diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 929632a6..67ce0d8b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,10 +11,16 @@ updates: # Note: there is no "pnpm" package-ecosystem value; pnpm is handled by "npm". - package-ecosystem: "npm" directory: "/" - # legacy/ holds archived snapshots of the pre-monorepo frontend (issue #150). + # legacy/frontend-* hold archived snapshots of the pre-monorepo frontend (issue #150). # They sit outside the pnpm workspace and are never built or deployed, but # each keeps its own npm/yarn lockfile as a reference for the track merge — # without this, Dependabot opens update PRs against code nothing runs. + # + # More broadly, ALL of legacy/ is the old system and is excluded from + # Dependabot version updates by the owner's decision of 2026-11-24; no other + # entry in this file covers any of it. That includes legacy/whatsapp, which + # is still built and deployed (spec 321) but gets no version-update PRs. + # Its security ALERTS are not affected by this file. exclude-paths: - "legacy/**" schedule: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be74e7a3..69ca066a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,6 +110,84 @@ jobs: - name: Build run: pnpm exec turbo run build --filter ansari-auth... + # TypeScript WhatsApp service (issue #358: apps/whatsapp). Mirrors the `auth` job. + # Its own id and name: the job named `whatsapp` below is the Python service in + # legacy/whatsapp, which stays until the staging cutover, and branch protection + # matches check names. `--filter ansari-whatsapp...` selects the app and its + # workspace deps (the two config packages, which define no tasks, so expect + # "3 packages in scope, 1 task" per step). Nothing in the tests reaches the + # network: every outside service is a fake or a mock. + whatsapp-service: + name: whatsapp service (lint, typecheck, test, build) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version-file: .nvmrc + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + - name: Install + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm exec turbo run lint --filter ansari-whatsapp... + + # Committed dummy env (apps/whatsapp/.env.ci): every value is deliberately + # fake, no repository secrets. Loaded so the service's configuration is + # valid wherever a task reads it. + - name: Load CI dummy env + run: grep -v '^#' apps/whatsapp/.env.ci >> "$GITHUB_ENV" + + - name: Typecheck + run: pnpm exec turbo run typecheck --filter ansari-whatsapp... + + - name: Test + run: pnpm exec turbo run test --filter ansari-whatsapp... + + - name: Build + run: pnpm exec turbo run build --filter ansari-whatsapp... + + # Model evaluation harness (issue #397: apps/eval). It runs apps/api's + # facilitator in process but is its own package, so that it is neither in the + # api image nor a reason to redeploy the api. No other job reaches it: + # `ansari-api...` does not, since apps/api must not depend on the harness. + # The suite needs no env and no secrets: it drives a scripted facilitator, and + # the api modules it loads read no config at import (#260). + eval: + name: eval (lint, typecheck, test) + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version-file: .nvmrc + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + # The full install, not `--filter ansari-eval...`: tsc and the tests follow + # `@/` into apps/api, whose imports resolve from apps/api/node_modules. + - name: Install + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm exec turbo run lint --filter ansari-eval... + + - name: Typecheck + run: pnpm exec turbo run typecheck --filter ansari-eval... + + - name: Test + run: pnpm exec turbo run test --filter ansari-eval... + frontend: # Emitted name deliberately unchanged (human decision, spec 48), even though # this job now also runs `test` and `build`. Check names are matched by @@ -191,6 +269,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + # Same uv as legacy/whatsapp/Dockerfile, so CI tests what ships. Change both together. + version: "0.9.13" - name: Install run: uv sync --frozen --extra dev diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 21e97d04..d21c4c1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,9 +34,10 @@ You need **Node 22** (22.18 or newer; `.nvmrc` pins the major for `nvm use`). environment contract, and [`apps/api/README.md`](apps/api/README.md) covers the backend in more depth. -This is a **pnpm workspace** (`apps/api/` + `apps/frontend/`) driven by -**[Turborepo](https://turborepo.com)**: install once at the repo root, then run -tasks from the root — `pnpm dev` brings up the whole stack (api, auth, frontend) at once. +This is a **pnpm workspace** (`apps/api/`, `apps/auth/`, `apps/frontend/`, `apps/mcp/`, the +model evaluation harness `apps/eval/`, and the shared `packages/*`) driven by **[Turborepo](https://turborepo.com)**: install once at the +repo root, then run tasks from the root — `pnpm dev` brings up the whole stack (api, auth, +frontend and the MCP server) at once. ```bash corepack enable # provides pnpm (version pinned in package.json) @@ -56,15 +57,29 @@ cp .env.example .env # DATABASE_URL = the ansari_auth owner URL; the service' pnpm db:migrate # applies packages/auth/drizzle/ to that DATABASE_URL cd ../.. -# Then, from the repo root: starts api (:3000), auth (:3100) and frontend together +# Then, from the repo root: starts api (:3000), auth (:3100), the frontend and the +# MCP server (:3001) together pnpm dev ``` +Both `.env` files need `ENVIRONMENT=development`. It has no default in any process +(#314); the `.env.example` files set it, but a `.env` copied before then lacks it, and +then api fails at its first config read and auth refuses to start, each naming +`ENVIRONMENT`. + `pnpm dev` includes `apps/auth`. Without its `.env`, auth's pane shows the env-validation error naming the missing variables and the other apps keep -running; `pnpm dev:no-auth` starts api + frontend only. The frontend talks to +running; `pnpm dev:no-auth` starts api + frontend only. + +`pnpm dev` also starts the MCP server (`apps/mcp`) on `:3001`, after a cached build +that shows as its own `ansari-mcp#build` row. A local api refuses MCP calls without +an `ansari-mcp` key, as a deployed one does: issue a development key and put +`ANSARI_API_AUTHORIZATION=Bearer ` in `apps/mcp/.env`, or run api with +`MCP_COMPLETE_KEY_MODE=log-only`. `pnpm mcp inspect` opens the MCP Inspector on it. The +steps are in [`apps/mcp/README.md`](apps/mcp/README.md), under "Local development". The frontend talks to **staging** unless `EXPO_PUBLIC_API_URL=http://localhost:3000` and -`EXPO_PUBLIC_AUTH_URL=http://localhost:3100` are set. +`EXPO_PUBLIC_AUTH_URL=http://localhost:3100` are set in `apps/frontend/.env.local` +(since SDK 58 a dev bundle lets that file win over the shell; see the frontend README). **Two databases.** Development and CI use two: the app database (`apps/api`, e.g. `ansari`) and the auth database (`apps/auth`, e.g. `ansari_auth`), each @@ -83,7 +98,8 @@ The test suites need neither database (they run on pglite). `pnpm dev` needs a real terminal: it runs Turbo's interactive UI so the Expo dev server keeps its keypress shortcuts (`i`, `a`, `w`, `r`) while sharing a console with the API and auth. To run one app on its own — or in a script or non-TTY shell — use -`pnpm api dev`, `pnpm auth dev` or `pnpm frontend start`. +`pnpm api dev`, `pnpm auth dev`, `pnpm frontend start` or, for the MCP server, +`pnpm mcp build && pnpm mcp dev` (`pnpm dev:mcp` does both, in a real terminal). **Use pnpm, not npm or yarn.** The single authoritative lockfile is the root `pnpm-lock.yaml`; there are deliberately no per-package lockfiles. Shared @@ -131,7 +147,11 @@ You can still target one package directly — `pnpm api lint`, `pnpm frontend we - CI must be green before a PR can merge. `develop` requires all five checks: `api (lint, typecheck, test, build)`, `auth (lint, typecheck, test, build)`, `frontend (lint, typecheck)`, `whatsapp (lint, format, test)`, and - `gitleaks (secret scan)`. The + `gitleaks (secret scan)`. `eval (lint, typecheck, test)` (the model evaluation + harness, `apps/eval/`) also runs on every pull request and is not a required + check. `whatsapp service (lint, typecheck, test, build)` (the TypeScript + service, `apps/whatsapp`) runs the same way and is not required until the + branch protection rule names it. The [Checks](#checks) above are the same tasks, so passing them locally is a good predictor. If the secret scan fails, see [Secret scanning](#secret-scanning). - Stage files explicitly (`git add path/to/file`). Please don't use `git add -A` diff --git a/README.md b/README.md index e05a161e..856766d9 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Alliance for Safe, Ethical, and Responsible AI). | [`apps/api/`](apps/api/) | The production backend: Next.js API, Gemini-powered facilitator, Islamic search tools | | [`apps/frontend/`](apps/frontend/) | The Ansari app: Expo / React Native (iOS, Android, and web via react-native-web) | | [`docs/`](docs/) | Documentation, including the [self-hosting guide](docs/self-hosting.md) | +| [`skills/`](skills/README.md) | The Ansari [agent skill](skills/ansari/SKILL.md), which answers Islamic questions through the Ansari MCP server; outside the pnpm workspace | This is a [pnpm workspace](https://pnpm.io/workspaces) driven by [Turborepo](https://turborepo.com): one `pnpm install` at the repo root installs diff --git a/RELEASE.md b/RELEASE.md index 358de981..e961e0b2 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -39,26 +39,37 @@ migration runbook were both proven in real releases on 2026-08-02. > | frontend (web) | `apps/frontend/Dockerfile.web` | > | auth | `apps/auth/Dockerfile` | > | whatsapp | `legacy/whatsapp/Dockerfile` | +> | mcp | `apps/mcp/Dockerfile` | +> | whatsapp-ts | `apps/whatsapp/Dockerfile` | > -> **Watch paths** — set these per service, or Railway rebuilds *both* on every push +> **Watch paths** — set these per service, or Railway rebuilds *every* service on every push > (any commit touches the root lockfile): > > ``` > backend: apps/api/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml > frontend: apps/frontend/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml > auth: apps/auth/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml -> whatsapp: legacy/whatsapp/** +> whatsapp: legacy/whatsapp/** .dockerignore +> whatsapp-ts: apps/whatsapp/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml .dockerignore +> mcp: apps/mcp/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml .dockerignore > ``` > > For backend, frontend and auth, `packages/**` is **not optional**. The shared config packages are copied into those > images, so a packages-only change alters the built artifact. Omit the pattern and > that change ships nothing — no rebuild, no deploy, and no error. The image simply -> drifts from the repo. **whatsapp is the exception:** it is a Python service outside the pnpm workspace, so its image contains nothing from +> drifts from the repo. **mcp watches it defensively:** its build stage copies `packages/` and installs from it, but +> its only workspace dependency is a devDependency (`@ansari/eslint-config`) and its final image is `dist` plus +> `package.json`, so today a packages-only change does not alter the shipped image. The pattern stays so that a future +> runtime dependency cannot ship silently. **whatsapp is the exception:** it is a Python service outside the pnpm workspace, so its image contains nothing from > `packages/`, the root lockfile or `package.json`; watching them would only rebuild it for changes it does not ship. +> **whatsapp-ts** (`apps/whatsapp`, the TypeScript port, #358) sits inside the pnpm workspace and copies `packages/`, so it watches +> the same shared paths as backend. Its record is named `whatsapp-ts` only until cutover, when it takes the `whatsapp` dashboard service. +> **This dashboard service has not been created yet.** The Dockerfile exposes port 3200; the service variable `PORT=3200` must be set when it is created. +> whatsapp and mcp add `.dockerignore`: their images build from the repo root, so that file decides what the build can see. > > **Deploy settings** — backend healthcheck `/api/health` (timeout 300s), frontend -> healthcheck `/`, whatsapp healthcheck `/`, auth healthcheck `/health` (200 only when the auth database -> answers; timeout 300s); restart ON_FAILURE, max 3 retries. +> healthcheck `/`, whatsapp healthcheck `/`, whatsapp-ts healthcheck `/` (timeout 300s), auth healthcheck `/health` (200 only when the auth database +> answers; timeout 300s), mcp healthcheck `/health` (timeout 300s); restart ON_FAILURE, max 3 retries. > > > **whatsapp service (spec 321, interim Python import; lives in `legacy/` because `apps/*` is reserved for the @@ -66,13 +77,34 @@ migration runbook were both proven in real releases on 2026-08-02. > Build: repo-root context, `legacy/whatsapp/Dockerfile`. Health check `/`. The Meta callback URL is > `https:///whatsapp/v2`, one Meta app per environment. Environment surface (full list in > `legacy/whatsapp/.env.example`): -> `DEPLOYMENT_TYPE` (required, `staging` or `production`), `BACKEND_SERVER_URL` (apps/api), +> `ENVIRONMENT` (required: `development`, `staging` or `production`; the same name apps/api and apps/auth use), `BACKEND_SERVER_URL` (apps/api), > `AUTH_SERVER_URL` and `AUTH_WHATSAPP_API_KEY` (apps/auth, issue #329), > `META_BUSINESS_PHONE_NUMBER_ID`, `META_ACCESS_TOKEN_FROM_SYS_USER`, `META_ANSARI_APP_SECRET` and > `META_WEBHOOK_VERIFY_TOKEN` (all four of the same Meta app, all required), > `SENTRY_DSN`, `WA_MAINTENANCE_MODE`, `WHATSAPP_CHAT_RETENTION_HOURS`, `LOGGING_LEVEL` (unset = `INFO`). +> **Prefix routing (issue #363):** one WhatsApp number can feed production, staging and a developer's machine. A message with no prefix is production's, `!s ` is staging's and `!d ` is development's; each environment ignores the others' and drops its own prefix before asking apps/api. On staging, testers must start every message with `!s `. +> **Order of the Meta steps:** subscribe the production WhatsApp account to the staging (or development) app only once the prefix code is running there. In the other order, staging answers every real user's plain message on the production number, and users get two answers. +> **`ENVIRONMENT=production` on the production service:** Sentry events are tagged `production` with 0.2 sample rates, and `/sentry-debug` is not mounted. +> > The service refuses to start if a secret above is missing, or if any `MOCK_*` switch is set outside -> `DEPLOYMENT_TYPE=local`. +> `ENVIRONMENT=development`. +> +> **mcp service (issue #364; staging only for now)** — one listener on `PORT` (3000): set `PORT=3000` as a +> service variable so Railway does not assign its own, and make the public domain's target port match. Build: repo-root context, `apps/mcp/Dockerfile`, which copies `package.json`, the lockfile, +> the workspace file and `packages/` and runs the root `mcp` script. Health check `/health`. Hosts connect at +> `https:///mcp`. Its settings are recorded in `apps/mcp/railway.toml`. Environment, for staging +> (`mcp-staging.askansari.ai`; full list in `apps/mcp/README.md`): +> +> | Variable | Value | +> |---|---| +> | `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai` (the server refuses any other Host on `/mcp`) | +> | `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai` (the default is production) | +> | `ANSARI_CLIENT` | `ansari-mcp-staging` | +> | `ANSARI_API_AUTHORIZATION` | `Bearer ansari_mcp_staging_<64 letters>`: the staging key, made in the staging auth shell with `--client-id ansari-mcp-staging` and set **before** apps/api staging deploys #314 (`docs/cutover/service-keys-runbook.md`) | +> | `ANSARI_RELEASE` | `${{RAILWAY_GIT_COMMIT_SHA}}`, a Railway reference variable: the commit is mapped here, in the dashboard, because the code reads no `RAILWAY_*` variable (#377). Unset, the release is the application version | +> +> `MCP_ALLOWED_ORIGINS` is left unset at first: it defaults to the allowed hosts, and requests without an Origin +> pass. The Cloudflare Workers path (`apps/mcp/wrangler.jsonc`) is not this deployment. > > **auth service (spec 300)** — one listener: the public domain > (`auth.askansari.ai`, `auth-staging.askansari.ai`) targets `PORT` (3100); set it as @@ -80,7 +112,8 @@ migration runbook were both proven in real releases on 2026-08-02. > client: no private-network hop, no shared secret (spec amendment H-1). > It has its OWN Railway Postgres, the auth database, with snapshots or PITR > enabled before its first real row, on Postgres 18 (C-4: the owner's service; in staging it -> already exists, empty; in production it is created or found, and checked empty in window step 1). +> already exists, empty; in production its schema is already applied, and window step 1 checks it +> holds no users and no accounts). > Its image is the service only: no Postgres client > and no migration SQL. The cutover runs from the owner's machine over the Tailscale route > (spec amendment H-8; the runbook's "operator environment"). The two operator scripts run from @@ -88,12 +121,47 @@ migration runbook were both proven in real releases on 2026-08-02. > `… scripts/ban-user.ts …`), or in the image from `/repo/apps/auth` with > `./node_modules/.bin/tsx scripts/…` (tsx directly: the image has no pnpm for its non-root user). > +> **`ENVIRONMENT` on `backend` and auth (#314 Amendment 3)** — the deployment label, also each +> service's Sentry environment and the environment in every service key's prefix. It has **no +> default in any process** (owner, 2026-11-12): every deployed service, every operator shell that +> runs an apps/auth script, and local dev (`development`) set it. Under `NODE_ENV=production` both +> services refuse to boot without it, or with `development`: +> +> | Service | staging | production | +> |---|---|---| +> | `backend` (apps/api) | `ENVIRONMENT=staging` | `ENVIRONMENT=production` | +> | auth (apps/auth) | `ENVIRONMENT=staging` | `ENVIRONMENT=production` | +> +> **Deploy order:** set `ENVIRONMENT` on `backend` and auth, in staging and in production, +> **before** the deploy that carries #314. A deploy without it fails its healthcheck and Railway +> keeps the previous deployment. +> > **frontend (web) build variables** — `Dockerfile.web` bakes `EXPO_PUBLIC_API_URL` -> and `EXPO_PUBLIC_AUTH_URL` into the bundle at build time, so both are set on the -> Railway service and a change needs a redeploy. They name the SAME environment: -> production `https://api.askansari.ai` + `https://auth.askansari.ai`, staging -> `https://api-staging.askansari.ai` + `https://auth-staging.askansari.ai` (the -> defaults when unset). The web app signs in at `EXPO_PUBLIC_AUTH_URL` (spec 300). +> and `EXPO_PUBLIC_AUTH_URL` into the bundle at build time, so a change needs a +> redeploy. **Both are mandatory on every web service built from +> `apps/frontend/Dockerfile.web`**: today that is staging web only, and a production +> `apps/frontend` service when one is created (#305). The image build fails at its guard +> (`apps/frontend/scripts/check-web-env.mjs`, #317) when either is unset or empty, +> naming the variable. They name the SAME environment: production +> `https://api.askansari.ai` + `https://auth.askansari.ai`, staging +> `https://api-staging.askansari.ai` + `https://auth-staging.askansari.ai`; a pair +> with one production host and not the other fails the build, showing both values. +> **Production web stays on `legacy/frontend-web` for now (#416):** it builds from its +> own `legacy/frontend-web/Dockerfile`, takes `EXPO_PUBLIC_API_V2_URL`, and has no such +> guard; neither variable above is needed on it. It also takes `MAINTENANCE_MODE` (PR #418): on +> for `true`, `True` or `1`, anything else or unset is off. When on, every route shows the +> maintenance screen and makes no api request. It is baked in at build time, so a change rebuilds +> and redeploys the service and takes effect only when that deployment is live; a tab that +> already loaded the app keeps its build until reloaded (`legacy/frontend-web/README.md`). Set it +> as a **service variable** of the legacy web service, never a shared variable: `backend`'s +> `MAINTENANCE_MODE` is a different switch, turned off at a different time. **The Railway +> variable is `MAINTENANCE_MODE`, and the value is `true` with no quotes.** An +> `EXPO_PUBLIC_MAINTENANCE_MODE` set on the service has no effect: only the `MAINTENANCE_MODE` +> build argument reaches the build, and the Dockerfile's `ENV` line sets the `EXPO_PUBLIC_` name +> from it (`legacy/frontend-web/Dockerfile:18,30`). A quoted `"true"` is not an on-value. +> The app's staging defaults (`DEFAULT_API_URL`, `DEFAULT_AUTH_URL`) serve local +> `expo start`/`expo export` only, never an image. The `apps/frontend` web app signs in at +> `EXPO_PUBLIC_AUTH_URL` (spec 300). > > **`apps/*/railway.toml` are not read by Railway here.** This project configures > deployment through the dashboard with a Dockerfile path (confirmed by the operator, @@ -108,6 +176,18 @@ migration runbook were both proven in real releases on 2026-08-02. root directory = repo root, dockerfile build from `apps/api/Dockerfile`, healthcheck `/api/health` with a 300s timeout, restart `ON_FAILURE` up to 3 times. `apps/api/railway.toml` records those same values in git. + > **Superseded 2026-11-21 (marker; the full reconciliation is pending):** `backend` did **not** + > auto-deploy on the 2026-11-21 push to `main`; the owner deployed it by hand. The cause is + > open. See [`docs/cutover/release-record.md`](docs/cutover/release-record.md), "the production + > window, as run". + The production `auth` service deploys from `develop` today (owner's statement, 2026-11-21), + and from `main` after the cutover window's step 16 switches it. + > **Superseded 2026-11-21 (marker; the full reconciliation is pending):** as of 2026-11-21, + > production `auth`, `mcp` and `whatsapp` deploy from `main`: the owner's statement for `auth`; + > for `mcp` and `whatsapp` inferred from their deployments of the promoted commit at 11:22:47Z, + > not confirmed. When the sources changed is not established. See + > [`docs/cutover/release-record.md`](docs/cutover/release-record.md), "the production window, + > as run". - **Promotion is a fast-forward, nothing else.** `main` is moved to `develop`'s tip with `--ff-only` — no merge commits, no cherry-picks, so `main` is always an exact prefix of `develop`'s history. @@ -132,6 +212,14 @@ migration runbook were both proven in real releases on 2026-08-02. force-push `main`. 5. **Watch the Railway auto-deploy** until the new deployment is live. + > **Superseded 2026-11-21 (marker; the full reconciliation is pending):** after the + > fast-forward push to `main` on 2026-11-21, Railway posted no status for any service for + > about five minutes, and `backend` got no deployment at all until it was deployed by hand from + > the dashboard; what started the other services' deployments at 11:22:47Z is not established. + > After a push to `main`, if Railway posts nothing for `backend` within a minute, deploy it + > manually at the pushed commit and check the deployed commit. See + > [`docs/cutover/release-record.md`](docs/cutover/release-record.md), "the production window, + > as run". `/api/health` is a real deploy gate: it returns 200 only when the database answers `SELECT 1` (within 2s) and 503 otherwise, so a deploy with a broken `DATABASE_URL` fails its healthcheck instead of going live broken. @@ -385,7 +473,9 @@ channel also names the EAS environment and the GitHub Environment. matches the commit it was published from. After any native change (a dependency with native code, a config plugin, `app.json` native fields), ship a new build first; an update alone reaches no one. The fingerprint contract - is tracked in #267. + is tracked in #267. An Expo SDK upgrade is always such a change: SDK 57 → 58 + changed both the iOS and the Android fingerprint (#428), so an update built + on the new SDK never reaches a binary built on the old one. - **Concurrent dispatches queue, they never cancel** (`queue: max`, so every pending run is kept). **Build** serializes the *dispatch* per profile/platform pair, not the EAS build. The dispatcher does not wait, so diff --git a/apps/api/.env.ci b/apps/api/.env.ci index f37c47d5..17c56627 100644 --- a/apps/api/.env.ci +++ b/apps/api/.env.ci @@ -7,3 +7,6 @@ DATABASE_URL=postgresql://placeholder-user:placeholder-not-a-real-password@local KALEMAT_API_KEY=placeholder-not-a-real-key USUL_API_TOKEN=placeholder-not-a-real-token GEMINI_API_KEY=placeholder-not-a-real-key + +# The deployment label (#314 Amendment 3). +ENVIRONMENT=development diff --git a/apps/api/.env.example b/apps/api/.env.example index bb6137f1..3a6e8012 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -73,9 +73,7 @@ USUL_BASE_URL=https://api.usul.ai/v1/vector-search # Sentry SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0 SENTRY_AUTH_TOKEN=sntrys_... # Optional — for source map uploads in production builds -# RAILWAY_ENVIRONMENT is auto-injected by Railway and used as the Sentry environment tag. -# Optional — falls back to NODE_ENV off-Railway; no need to set it manually. -# RAILWAY_ENVIRONMENT=production +# ENVIRONMENT (below) is the Sentry environment (#314). # IslamicMMLU leaderboard bearer token for /api/v1/chat/completions (Spec 19). # Optional — when unset the OpenAI-compat endpoint returns 503. Generate with `openssl rand -hex 32`. @@ -90,3 +88,17 @@ ANDROID_LATEST_BUILD_VERSION=1 # Environment NODE_ENV=development + +# How /api/v2/mcp-complete treats its service key (#314): enforce (default) or log-only. +# MCP_COMPLETE_KEY_MODE=enforce + +# Thread history limits (#400), in estimated tokens of the history a turn would send. +# From WARN the answer opens with a notice to start a new conversation; from BLOCK no +# model is called and the notice is the answer. WARN must be below BLOCK. +# THREAD_HISTORY_WARN_TOKENS=150000 +# THREAD_HISTORY_BLOCK_TOKENS=200000 + +# The deployment label (#314 Amendment 3): development, staging or production. The Sentry +# environment and the service-key prefix environment. Required everywhere, no default; staging or +# production when NODE_ENV=production. +ENVIRONMENT=development diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md index 8e8a10fa..e2e6dccc 100644 --- a/apps/api/AGENTS.md +++ b/apps/api/AGENTS.md @@ -46,6 +46,7 @@ database; generate + migrate. - `lib/ai/prompts/facilitator.ts` — the system prompt; changes need cited justification - `src/app/api/` — HTTP surface (`v2/*` product API, `v1/chat/completions` OpenAI-compat, `health`) - `tests/` — Vitest suites (`*.test.ts`); the full suite runs without external services +- Not here: the model evaluation harness is its own package, `apps/eval/` (`apps/eval/README.md`). It loads `lib/` and `db/` through `@/` and is typechecked against them in the `eval` CI job; nothing in this app may import it ## Conventions diff --git a/apps/api/CLAUDE.md b/apps/api/CLAUDE.md index 5a426e18..adbe6e8e 100644 --- a/apps/api/CLAUDE.md +++ b/apps/api/CLAUDE.md @@ -46,6 +46,7 @@ database; generate + migrate. - `lib/ai/prompts/facilitator.ts` — the system prompt; changes need cited justification - `src/app/api/` — HTTP surface (`v2/*` product API, `v1/chat/completions` OpenAI-compat, `health`) - `tests/` — Vitest suites (`*.test.ts`); the full suite runs without external services +- Not here: the model evaluation harness is its own package, `apps/eval/` (`apps/eval/README.md`). It loads `lib/` and `db/` through `@/` and is typechecked against them in the `eval` CI job; nothing in this app may import it ## Conventions diff --git a/apps/api/README.md b/apps/api/README.md index 3acd9eaf..dc640546 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -24,7 +24,7 @@ Responses stream over SSE, threads and messages persist to Postgres, and the sea | Feedback & prefs | `POST /api/v2/feedback`, `GET/POST /api/v2/preferences` | | App support | `GET /api/v2/app-check` (version/maintenance gate) | | OpenAI-compat | `POST /api/v1/chat/completions` (bearer-token gated, for evaluation harnesses) | -| MCP-style | `POST /api/v2/mcp-complete` (stateless completion for AI-skill integrations) | +| MCP-style | `POST /api/v2/mcp-complete` (stateless completion for AI-skill integrations; requires an `ansari-mcp` service key as `Authorization: Bearer `, verified at apps/auth, see `docs/self-hosting.md`) | | Admin | `GET /api/v2/admin/stats`, `/admin/analytics` dashboard | Auth is owned by `apps/auth` (Better Auth, spec 300): this service verifies its short-lived JWTs against the JWKS, and the `/v2/users/*` and password-reset routes are a compatibility layer over it with the legacy response shapes. No password, session or signing secret lives here. diff --git a/apps/api/db/schema/messages.ts b/apps/api/db/schema/messages.ts index 40064b4c..c44fee20 100644 --- a/apps/api/db/schema/messages.ts +++ b/apps/api/db/schema/messages.ts @@ -78,9 +78,11 @@ export type ModelProvider = 'gemini' | 'inkling'; * `tool_call_orphans`. With PRIMARY_BACKEND switching (#95), per-env Inkling * checkpoints (#90), and the #79 rescue, which model served a given answer is * runtime state — this makes it queryable per row instead of inferable from - * usage fingerprints or Sentry events. On the gemini path `modelId` is the - * request's configured primary model; the intra-Vertex 429 fast-failover (#45) - * stays within provider 'gemini' and is not distinguished here. + * usage fingerprints or Sentry events. On the gemini path `modelId` is the model + * that answered the turn's final call (issue #402): GEMINI_FALLBACK_MODEL when + * gemini-client failed over to it (#45), otherwise the configured or pinned model. + * A call that failed without a response names the model it asked for. Rows written + * before #402 name the configured primary even where the fallback answered. */ export interface ModelProvenance { provider: ModelProvider; diff --git a/apps/api/lib/ai/gemini-client.ts b/apps/api/lib/ai/gemini-client.ts index 9fe640e5..83bf7c78 100644 --- a/apps/api/lib/ai/gemini-client.ts +++ b/apps/api/lib/ai/gemini-client.ts @@ -216,6 +216,12 @@ export interface GeminiResponse { allParts: Part[]; /** Whether this response contains thinking parts */ hasThinking: boolean; + /** + * The model that wrote this response (issue #402). After a failover it is + * config.gemini.fallbackModel, not the model the call asked for, so provenance + * must be read from here and never from the configuration. + */ + modelId: string; /** Token usage metadata */ usage?: GeminiUsageMetadata; /** Duration in milliseconds */ @@ -256,6 +262,14 @@ export interface GeminiCallOptions { * Vertex pool); kept for future per-call routing. Omit for the configured default. */ model?: string; + /** + * Pin the call to its primary model (issue #393): never fail over to + * config.gemini.fallbackModel. A 429 then takes the bounded same-model retries, and a + * call that still fails surfaces its error instead of an answer written by another + * model. For evaluation runs, where an answer must be attributable to the model under + * test. Omit for the configured failover. + */ + noModelFallback?: boolean; /** Streaming callback for text chunks */ onTextChunk?: (text: string) => void | Promise; /** Callback for thinking parts (for logging, not display) */ @@ -372,6 +386,14 @@ function backoffDelayMs(attemptNum: number): number { const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); +/** + * No silent failover (issue #402): the "falling back" lines say a fallback was TRIED; + * this one says it ANSWERED. Model ids and the call label only. + */ +function logFallbackAnswered(label: string, primary: string, fallback: string): void { + console.warn(`[gemini] ${label}: answered by fallback ${fallback} (primary ${primary} did not answer)`); +} + /** * Run a Gemini establishment call with retry + model fallback. * @@ -388,10 +410,12 @@ async function withRetry( operation: (model: string) => Promise, label: string, // Per-call primary override (issue #70); see GeminiCallOptions.model. - primaryOverride?: string + primaryOverride?: string, + // Pinned call (issue #393); see GeminiCallOptions.noModelFallback. + noModelFallback = false ): Promise { const primary = primaryOverride ?? config.gemini.model; - const fallback = config.gemini.fallbackModel; + const fallback = noModelFallback ? undefined : config.gemini.fallbackModel; let lastError: unknown; for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { @@ -421,7 +445,9 @@ async function withRetry( `[gemini] ${label}: ${primary} exhausted after ${MAX_RETRIES + 1} attempts, falling back to ${fallback}` ); try { - return await operation(fallback); + const result = await operation(fallback); + logFallbackAnswered(label, primary, fallback); + return result; } catch (error) { lastError = error; } @@ -464,10 +490,12 @@ async function streamWithRetry( openStream: (model: string) => ReturnType, emit: (event: GeminiStreamEvent) => boolean | Promise, // Per-call primary override (issue #70); see GeminiCallOptions.model. - primaryOverride?: string + primaryOverride?: string, + // Pinned call (issue #393); see GeminiCallOptions.noModelFallback. + noModelFallback = false ): Promise { const primary = primaryOverride ?? config.gemini.model; - const fallback = config.gemini.fallbackModel; + const fallback = noModelFallback ? undefined : config.gemini.fallbackModel; // The fallback only buys us anything when it's a DIFFERENT model — it draws on a // separate Vertex capacity pool. GEMINI_FALLBACK_MODEL defaults to the same value // as GEMINI_MODEL (lib/config.ts), so this is commonly false; the 429 fast-failover @@ -652,6 +680,7 @@ async function streamWithRetry( rawPayload, allParts, hasThinking, + modelId: model, usage: finalUsage, durationMs: Date.now() - startTime, finishReason, @@ -701,7 +730,9 @@ async function streamWithRetry( console.warn(`[gemini] ${label}: falling back to ${fallback}`); for (let attemptNum = 0; attemptNum <= FALLBACK_MAX_RETRIES; attemptNum++) { try { - return await attempt(fallback); + const response = await attempt(fallback); + logFallbackAnswered(label, primary, fallback); + return response; } catch (error) { lastError = error; if (emitted || !isRetryableError(error)) throw error; @@ -799,7 +830,7 @@ function streamRawPayload(finalContent: Content | undefined, allParts: Part[]): /** * Parse a non-streaming response into GeminiResponse format */ -function parseResponse(response: GenerateContentResponse): GeminiResponse { +function parseResponse(response: GenerateContentResponse, modelId: string): GeminiResponse { const candidate = response.candidates?.[0]; if (!candidate || !candidate.content) { @@ -809,6 +840,7 @@ function parseResponse(response: GenerateContentResponse): GeminiResponse { rawPayload: { role: 'model', parts: [] }, allParts: [], hasThinking: false, + modelId, }; } @@ -820,6 +852,7 @@ function parseResponse(response: GenerateContentResponse): GeminiResponse { rawPayload: candidate.content, // Preserve exact format with thought signatures allParts: parts, hasThinking: hasThinkingParts(parts), + modelId, }; } @@ -850,15 +883,15 @@ export async function callGemini( ): Promise { const ai = getClient(); - const response = await withRetry((model) => { + const { response, model } = await withRetry(async (model) => { const chat: Chat = ai.chats.create({ model, config: buildConfig(options), history: options.history ?? [], }); - return chat.sendMessage({ message }); - }, 'callGemini', options.model); - return parseResponse(response); + return { response: await chat.sendMessage({ message }), model }; + }, 'callGemini', options.model, options.noModelFallback); + return parseResponse(response, model); } /** @@ -903,7 +936,8 @@ export async function callGeminiStreaming( return chat.sendMessageStream({ message }); }, emit, - options.model + options.model, + options.noModelFallback ); return await withTimeout(streamingOperation(), GEMINI_TIMEOUT_MS, 'Gemini streaming call'); @@ -980,7 +1014,8 @@ export async function* streamGemini( notify(); return true; }, - options.model + options.model, + options.noModelFallback ); queue.push({ type: 'done', response }); @@ -1142,7 +1177,8 @@ export async function continueWithToolResult( return chat.sendMessageStream({ message: TOOL_CONTINUATION_DIRECTIVE }); }, emit, - options.model + options.model, + options.noModelFallback ); return await withTimeout(streamingOperation(), GEMINI_TIMEOUT_MS, 'Gemini tool result call'); diff --git a/apps/api/lib/ai/inkling-client.ts b/apps/api/lib/ai/inkling-client.ts index e1222e2e..05d43ab9 100644 --- a/apps/api/lib/ai/inkling-client.ts +++ b/apps/api/lib/ai/inkling-client.ts @@ -24,6 +24,11 @@ * excluded from both `text` and `rawPayload`. * - temperature 0 is the evaluated configuration (100/100 BATIK, 0 malformed * tool calls, 0 empty finals). + * - The context window is 65,536 tokens for prompt PLUS max_tokens (measured on + * the Tinker endpoint, issue #399): at max_tokens 8192 the prompt — system + * prompt, tools and the whole thread history — must fit 57,344 tokens. A larger + * request is refused with HTTP 200 and one in-stream error frame, which this + * client surfaces; it does not trim history to fit. */ import * as Sentry from '@sentry/nextjs'; import { config } from '../config'; @@ -253,6 +258,27 @@ interface InklingStreamChunk { total_tokens?: number; completion_tokens_details?: { reasoning_tokens?: number }; } | null; + /** Present only on a provider error frame (issue #399); see describeStreamError. */ + error?: unknown; +} + +/** + * The provider's reason from an in-stream error frame (issue #399). Tinker answers a + * request it rejects with HTTP 200 and a single `data: {"error": {"type", "message"}}` + * frame, then closes without `[DONE]`: a prompt that with max_tokens exceeds Inkling's + * 65,536-token context window arrives this way. Only fields that are present are used; + * any other shape is reported as its JSON. + */ +function describeStreamError(error: unknown): string { + const { type, message } = (typeof error === 'object' && error !== null ? error : {}) as { + type?: unknown; + message?: unknown; + }; + const detail = + typeof message === 'string' + ? `${typeof type === 'string' ? type : 'error'}: ${message}` + : JSON.stringify(error); + return detail.slice(0, 500); } /** Extract the payload of a single SSE line, or null if it is not a `data:` line. */ @@ -380,6 +406,11 @@ export async function* streamInkling( } catch { throw new Error('[inkling] malformed SSE JSON chunk'); } + // An error frame carries no choices: read as an ordinary chunk it is dropped, and + // the stream is then misreported as truncated after 0 chars (issue #399). + if (chunk.error !== undefined && chunk.error !== null) { + throw new Error(`[inkling] provider error in stream — ${describeStreamError(chunk.error)}`); + } const choice = chunk.choices?.[0]; // choice.delta.reasoning_content is the hidden pass — intentionally dropped. if (typeof choice?.delta?.content === 'string' && choice.delta.content.length > 0) { @@ -444,6 +475,7 @@ export async function* streamInkling( // excluded above), so the complete-turn view equals the replay view. allParts: responseParts, hasThinking: false, + modelId: config.inkling.model, usage, durationMs: Date.now() - startTime, finishReason, diff --git a/apps/api/lib/ai/prompts/facilitator.ts b/apps/api/lib/ai/prompts/facilitator.ts index 6bb1b6e7..cfffae11 100644 --- a/apps/api/lib/ai/prompts/facilitator.ts +++ b/apps/api/lib/ai/prompts/facilitator.ts @@ -76,11 +76,7 @@ When using search tools, follow these strategies: 9. ALWAYS complete your response with a direct answer to the user's question, even if your research is incomplete 10. If a tool result says a source is "temporarily unavailable", do NOT retry that tool. Continue using the other tools and your own knowledge to give a complete, best-effort answer, and briefly note in your response that the source could not be consulted this time. -For questions outside Islamic knowledge domain: -1. Politely explain that you are specialized in Islamic topics -2. Suggest reformulating the question to relate to Islamic perspective if relevant -3. For purely secular topics, acknowledge the limits of your expertise -4. Avoid speculation on topics outside your knowledge base +Islam is an all-encompassing way of life, so consider the Islamic perspective on every question, whatever the topic. Requests for advice or guidance on everyday life (work, family, money, personal decisions) are not outside this domain: answer what was asked, fully and practically, in light of that perspective. Questions about hardship, trials, grief, loss, loneliness, anxiety, anger, doubt, oppression, or feeling distant from Allah are normal, sincere, and diff --git a/apps/api/lib/auth-service/client.ts b/apps/api/lib/auth-service/client.ts index 9e88aa08..7c7430fe 100644 --- a/apps/api/lib/auth-service/client.ts +++ b/apps/api/lib/auth-service/client.ts @@ -1,5 +1,6 @@ import { decodeJwt } from 'jose'; import { z } from 'zod'; +import { isMcpClientId } from '@ansari/types/attribution'; import { config } from '@/lib/config'; /** @@ -129,3 +130,60 @@ export async function deleteAuthUser(sub: string, jwt: string): Promise { const response = await authServiceFetch(ACCOUNT_PATH, { method: 'DELETE', bearer: jwt }); if (response.status !== 204) throw new AuthServiceUnavailableError(response.status); } + +/** + * apps/auth's service-key verify route (#314; apps/auth + * `routes/service-verify.ts`). Mounted at the public origin, it takes no + * credential of its own: the key in the body is the caller's. + */ +export const SERVICE_VERIFY_PATH = '/api/service/verify-key'; + +/** + * The longest service key apps/auth's verify route reads (apps/auth + * `VERIFY_KEY_MAX_LENGTH`). apps/auth answers 400 to a key outside + * `[\x21-\x7E]{1,256}`, and a 400 here is an outage (503), so a token outside + * that envelope must be refused before the call. The two bounds change together. + */ +export const SERVICE_KEY_MAX_LENGTH = 256; +const SERVICE_KEY_SHAPE = new RegExp(`^[\\x21-\\x7E]{1,${SERVICE_KEY_MAX_LENGTH}}$`); + +/** Whether `token` is inside the envelope apps/auth's verify route accepts (printable ASCII, 1–256 characters). */ +export function isServiceKeyShape(token: string): boolean { + return SERVICE_KEY_SHAPE.test(token); +} + +const verifyServiceKeySchema = z.union([ + z.object({ + valid: z.literal(true), + client_id: z.string().refine(isMcpClientId), + key_id: z.string().min(1), + }), + z.object({ valid: z.literal(false) }).strict(), +]); + +export type ServiceKeyVerdict = + | { valid: true; clientId: string; keyId: string } + | { valid: false }; + +/** + * Ask apps/auth whether `key` is a live service key holding `mcp: ['complete']`. + * `{ valid: false }` only when apps/auth said so in exactly that shape; any + * other answer (no response, a non-200, a body of the wrong shape, a client id + * off the `ansari-mcp` pattern) throws AuthServiceUnavailableError, and the + * caller fails closed. The key is never logged: it is the caller's secret. + * + * The refusal is pinned on both sides: apps/auth's tests assert the + * byte-identical body `{"valid":false}`, and this schema accepts that shape + * only. Adding any field to the refusal body on apps/auth turns every bad key + * into a 503 here, so the two change together. + */ +export async function verifyServiceKey(key: string): Promise { + const response = await authServiceFetch(SERVICE_VERIFY_PATH, { + body: { key, permissions: { mcp: ['complete'] } }, + }); + if (response.status !== 200) throw new AuthServiceUnavailableError(response.status); + const parsed = verifyServiceKeySchema.safeParse(await response.json().catch(() => undefined)); + if (!parsed.success) throw new AuthServiceUnavailableError(response.status); + if (!parsed.data.valid) return { valid: false }; + return { valid: true, clientId: parsed.data.client_id, keyId: parsed.data.key_id }; +} diff --git a/apps/api/lib/config.ts b/apps/api/lib/config.ts index 6509daf8..a42aabbd 100644 --- a/apps/api/lib/config.ts +++ b/apps/api/lib/config.ts @@ -1,3 +1,4 @@ +import { ENVIRONMENTS, environmentIssue } from '@ansari/types/environment'; import { z } from 'zod'; const AUTH_SERVICE_VARS = [ @@ -7,7 +8,7 @@ const AUTH_SERVICE_VARS = [ 'AUTH_LAYER_ORIGIN', ] as const; -const envSchema = z.object({ +export const envSchema = z.object({ // Database DATABASE_URL: z.string().min(1, 'DATABASE_URL is required'), @@ -113,6 +114,30 @@ const envSchema = z.object({ // against /v1/chat/completions with this bearer token. Optional in dev. LEADERBOARD_API_KEY: z.string().min(32).optional(), + // How /v2/mcp-complete treats its service key (#314): `log-only` verifies + // and records the verdict but serves anyway (the rollout week); `enforce` + // (the default when unset) refuses a missing or invalid key. Any other value + // fails validation, so a typo can never quietly open the route. Remove it + // and the log-only branch one week after enforcement; the follow-up issue + // is opened at enforce (rollout step 6). + MCP_COMPLETE_KEY_MODE: z.enum(['log-only', 'enforce']).optional(), + + // Thread history limits (issue #400), in estimated tokens of the history a + // turn would send (lib/facilitator/history-limit.ts). At WARN the answer + // opens with a notice to start a new conversation; at BLOCK no model is + // called and the notice is the answer. WARN must be below BLOCK (checked + // below); anything but a positive integer fails here, no clamping. + THREAD_HISTORY_WARN_TOKENS: z.coerce + .number() + .int('THREAD_HISTORY_WARN_TOKENS must be an integer') + .positive('THREAD_HISTORY_WARN_TOKENS must be positive') + .default(150000), + THREAD_HISTORY_BLOCK_TOKENS: z.coerce + .number() + .int('THREAD_HISTORY_BLOCK_TOKENS must be an integer') + .positive('THREAD_HISTORY_BLOCK_TOKENS must be positive') + .default(200000), + // App version control MAINTENANCE_MODE: z .enum(['true', 'false', 'True', 'False', '1', '0']) @@ -125,7 +150,14 @@ const envSchema = z.object({ // Optional NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), + // The deployment label (#314 Amendment 3): the Sentry environment. Required + // everywhere, no default (owner, 2026-11-12); staging or production under + // NODE_ENV=production (below). Checked at production boot + // (lib/boot-check.ts), at first config access elsewhere, never at build. + ENVIRONMENT: z.enum(ENVIRONMENTS), }).superRefine((env, ctx) => { + const environment = environmentIssue(env.NODE_ENV, env.ENVIRONMENT); + if (environment) ctx.addIssue({ code: 'custom', path: ['ENVIRONMENT'], message: environment }); if (env.NODE_ENV === 'production') { for (const name of AUTH_SERVICE_VARS) { if (!env[name]) { @@ -137,6 +169,13 @@ const envSchema = z.object({ } } } + if (env.THREAD_HISTORY_WARN_TOKENS >= env.THREAD_HISTORY_BLOCK_TOKENS) { + ctx.addIssue({ + code: 'custom', + path: ['THREAD_HISTORY_WARN_TOKENS'], + message: 'THREAD_HISTORY_WARN_TOKENS must be below THREAD_HISTORY_BLOCK_TOKENS', + }); + } // Fail fast at first config access, not at first chat request: an inkling // primary with no credential would otherwise serve a server whose every // completion fails. @@ -270,6 +309,20 @@ export const config = { }; }, + /** /v2/mcp-complete's key rollout mode (#314); `enforce` when unset. */ + get mcpCompleteKeyMode(): 'log-only' | 'enforce' { + return getEnv().MCP_COMPLETE_KEY_MODE ?? 'enforce'; + }, + + /** Thread history limits in estimated tokens (issue #400). */ + get threadHistory() { + const env = getEnv(); + return { + warnTokens: env.THREAD_HISTORY_WARN_TOKENS, + blockTokens: env.THREAD_HISTORY_BLOCK_TOKENS, + }; + }, + get appVersion() { return { maintenanceMode: getEnv().MAINTENANCE_MODE, diff --git a/apps/api/lib/facilitator/agent.ts b/apps/api/lib/facilitator/agent.ts index d1c0934c..e74cf6a3 100644 --- a/apps/api/lib/facilitator/agent.ts +++ b/apps/api/lib/facilitator/agent.ts @@ -18,6 +18,7 @@ import { } from '../ai/gemini-client'; import { streamInkling, isInklingConfigured } from '../ai/inkling-client'; import { FACILITATOR_SYSTEM_PROMPT, TOOL_CONTINUATION_DIRECTIVE } from '../ai/prompts/facilitator'; +import { convertToGeminiHistory } from './history'; import { config } from '../config'; import { createToolMap, getGeminiToolDescriptions } from '../tools'; import { citabilityOf, type ToolResult } from '../tools/types'; @@ -99,6 +100,24 @@ const EMPTY_ANSWER_ERROR_MESSAGE = const SAFETY_BLOCKED_ERROR_MESSAGE = 'The response was blocked by the provider. Please rephrase your question and try again.'; +// A model refused the request because the prompt exceeds its limit (issue #400): Gemini's +// 1,048,576-token input limit, or Inkling's 65,536-token window on a rescue of a thread it +// cannot fit. Recognised by each provider's own wording, since neither error carries a code +// that says so. The user is told in plain words; the provider's text goes to the log and +// Sentry only. An error that matches neither wording still surfaces with its own text. +const PROMPT_TOO_LARGE_ERRORS = [ + /input token count.{0,40}exceeds the maximum number of tokens/i, + /exceeds the model's context window/i, +]; +export const PROMPT_TOO_LARGE_MESSAGE = + 'Ansari could not answer because this conversation is too long. Please try again, or start a new conversation.'; + +/** What the user is told for a terminal model error: plain words for a prompt too large, else the error's own text. */ +export function userFacingModelError(error: unknown): string { + const message = error instanceof Error ? error.message : 'Unknown error'; + return PROMPT_TOO_LARGE_ERRORS.some((pattern) => pattern.test(message)) ? PROMPT_TOO_LARGE_MESSAGE : message; +} + // Degenerate-fragment detection (issue #66). Beyond a fully empty final (#60), Vertex's // capacity-cut family can end a turn with a real finishReason and a single trivial token as // the entire visible text — a lone '}', ']', '.', etc. That is never a valid facilitator @@ -329,63 +348,15 @@ export interface FacilitatorStreamEvent { * Set on every terminal event (`done` AND `error`) that a model call produced * (issue #99): the serving backend + model id of the call that produced — * or failed to produce — the final turn. A #79-rescued turn reports - * provider 'inkling' even though the request's primary was gemini, and the - * synthesis path reports the model that wrote the synthesis. Absent only + * provider 'inkling' even though the request's primary was gemini, a turn + * gemini-client served from GEMINI_FALLBACK_MODEL reports that model (#402), and + * the synthesis path reports the model that wrote the synthesis. Absent only * when no provider was ever engaged (e.g. no user message to process); * persist sites map absence to NULL. */ provenance?: ModelProvenance; } -/** - * Convert our message history to Gemini's Content[] format - * - * For assistant messages with rawPayload, uses the preserved Gemini Content - * which includes tool calls and thought signatures. Falls back to text-only - * for legacy messages without rawPayload. - */ -function convertToGeminiHistory(messages: Message[]): Content[] { - const history: Content[] = []; - - for (const msg of messages) { - if (msg.role === 'user') { - // Extract text from user messages - const textContent = msg.content - .filter((c): c is { type: 'text'; text: string } => c.type === 'text') - .map((c) => c.text) - .join('\n'); - - if (textContent) { - history.push({ - role: 'user', - parts: [{ text: textContent }], - }); - } - } else { - // For assistant messages, prefer rawPayload if available - // This preserves tool calls, citations, and thought signatures - if (msg.rawPayload) { - history.push(msg.rawPayload); - } else { - // Fallback for legacy messages without rawPayload - const textContent = msg.content - .filter((c): c is { type: 'text'; text: string } => c.type === 'text') - .map((c) => c.text) - .join(''); - - if (textContent) { - history.push({ - role: 'model', - parts: [{ text: textContent }], - }); - } - } - } - } - - return history; -} - /** * Format tool result for Gemini's functionResponse */ @@ -421,8 +392,26 @@ export async function* runFacilitator( * ladder rung and the #79 rescue. */ provider?: 'gemini' | 'inkling'; + /** + * Pin the whole request to one Gemini model (issue #393). EVALUATION ONLY: no + * route passes it. Every call of the request (tool-loop iterations, same-model + * retries, the synthesis pass) targets this model instead of config.gemini.model, + * and no other model may answer: the intra-Vertex 429 failover, the empty-final + * ladder's Inkling rung and the #79 Inkling rescue are all off, so a failure + * surfaces as a failure rather than as another model's answer under this model's + * name. Same reasoning as `provider: 'inkling'` above. Selects Gemini whatever + * PRIMARY_BACKEND says; combining it with `provider: 'inkling'` throws. + */ + model?: string; } ): AsyncGenerator { + const pinnedModel = options?.model; + if (pinnedModel !== undefined && options?.provider === 'inkling') { + throw new Error("runFacilitator: `model` pins a Gemini model and cannot be combined with provider 'inkling'"); + } + // Spread into every Gemini call's options; empty when the request is not pinned, so + // an unpinned request's calls are exactly what they were before the seam existed. + const pinnedCallOptions = pinnedModel !== undefined ? { model: pinnedModel, noModelFallback: true } : {}; const tools = getGeminiToolDescriptions(); const tracker: ToolUsageTracker = { history: [], callsWithArgs: [] }; @@ -487,7 +476,9 @@ export async function* runFacilitator( // `!useInklingRung` guard): rescuing an inkling-primary request with Inkling would // be meaningless, so inkling-primary failures fail loudly instead. The empty-final // ladder still applies, as same-model (Inkling) retries. - let useInklingRung = (options?.provider ?? config.primaryBackend) === 'inkling'; + const inklingPrimary = + pinnedModel === undefined && (options?.provider ?? config.primaryBackend) === 'inkling'; + let useInklingRung = inklingPrimary; // Terminal-Gemini-error rescue (#79): at most ONE Inkling rescue attempt per request // (cost guardrail), tracked separately from the ladder's emptyFinalRetries. let inklingRescueUsed = false; @@ -497,10 +488,15 @@ export async function* runFacilitator( // to produce) the final turn — after any ladder escalation or #79 rescue flipped // useInklingRung. config.gemini is only read on the gemini path (same lazy-read // rule as the ladder's model label: an inkling-only deployment's getter throws). + // On the gemini path the model is the one that ANSWERED the latest Gemini call (issue + // #402): gemini-client can fail over to config.gemini.fallbackModel inside a call, and + // only the response says so. Cleared before every call, so a call that fails without a + // response names the model it asked for. + let answeringGeminiModel: string | undefined; const currentProvenance = (): ModelProvenance => useInklingRung ? { provider: 'inkling', modelId: config.inkling.model } - : { provider: 'gemini', modelId: config.gemini.model }; + : { provider: 'gemini', modelId: answeringGeminiModel ?? pinnedModel ?? config.gemini.model }; // Overall request-time budget (Spec 49). softDeadline = when we stop starting new tool // work; the reserve between it and hardDeadline is the window for one synthesis pass. @@ -510,6 +506,22 @@ export async function* runFacilitator( const softDeadline = startTime + budgetMs - reserveMs; const hardDeadline = startTime + budgetMs; + // No silent escalation (issue #399): when a request that left Gemini for Inkling — the + // empty-final ladder's rung (#74) or the terminal-error rescue (#79), never an + // inkling-primary request — ends in an answer, name the model that wrote it. Engagement + // is logged where it happens; without this line an answered escalation leaves no trace, + // and the logs cannot tell it from one that never finished. No PII: provider, model id + // and counters only. + const logEscalatedAnswer = () => { + if (!useInklingRung || inklingPrimary) return; + console.warn('[facilitator] escalated request answered', { + ...currentProvenance(), + escalation: inklingRescueUsed ? 'terminal-error rescue' : 'empty-final ladder', + elapsedMs: Date.now() - startTime, + iterations, + }); + }; + // Token usage summed across every Gemini call in this turn (initial + tool-loop continuations). const totalUsage: GeminiUsageMetadata = { promptTokenCount: 0, @@ -591,6 +603,7 @@ export async function* runFacilitator( let synthText = ''; let synthResponse: GeminiResponse | null = null; + answeringGeminiModel = undefined; try { // Tools omitted → the model cannot emit a functionCall, so it must answer from context. // Once the request escalated to Inkling (#74/#79 — ladder rung or error rescue), @@ -608,13 +621,14 @@ export async function* runFacilitator( ...synthesisOptions, timeoutMs: Math.min(remainingMs, config.inkling.timeoutMs), }) - : streamGemini('', synthesisOptions); + : streamGemini('', { ...synthesisOptions, ...pinnedCallOptions }); for await (const event of stream) { if (event.type === 'text') { synthText += event.data; yield { type: 'text', data: event.data }; } else if (event.type === 'done') { synthResponse = event.response; + if (!useInklingRung) answeringGeminiModel = event.response.modelId; } } } catch (error) { @@ -664,6 +678,7 @@ export async function* runFacilitator( }); } logShortCircuit('done'); + logEscalatedAnswer(); yield { type: 'done', data: '', @@ -688,6 +703,7 @@ export async function* runFacilitator( // rescue: re-issuing a call whose text partially reached the client would duplicate // delivered tokens (the #42 rule) — such failures must still surface as errors. let visibleTextDelivered = false; + answeringGeminiModel = undefined; try { // Stream the model response with real-time event delivery. Bound the tool-gathering @@ -709,7 +725,7 @@ export async function* runFacilitator( ...callOptions, timeoutMs: Math.min(remainingToSoft, config.inkling.timeoutMs), }) - : streamGemini(currentQuery, callOptions); + : streamGemini(currentQuery, { ...callOptions, ...pinnedCallOptions }); const toolCallsCollected: GeminiToolCall[] = []; let response: GeminiResponse | null = null; @@ -765,6 +781,7 @@ export async function* runFacilitator( if (!response) { throw new Error('Stream ended without response'); } + if (!useInklingRung) answeringGeminiModel = response.modelId; addUsage(response.usage); @@ -789,10 +806,13 @@ export async function* runFacilitator( // config.gemini is never read AT ALL: on an inkling-only deployment (no // Gemini credentials) that getter throws, which would break the documented // same-model retry. - const currentModel = useInklingRung ? config.inkling.model : config.gemini.model; + const currentModel = useInklingRung + ? config.inkling.model + : (pinnedModel ?? config.gemini.model); // Rung 2 (#74/#79) runs on Inkling's separate (non-Vertex) infrastructure; // without TINKER_API_KEY the ladder is the single same-model retry. - const inklingAvailable = isInklingConfigured(); + // A pinned request (#393) never leaves its model: same-model retry only. + const inklingAvailable = pinnedModel === undefined && isInklingConfigured(); const maxRetries = inklingAvailable ? MAX_EMPTY_FINAL_RETRIES : 1; const summary = { degenerateKind, @@ -801,7 +821,8 @@ export async function* runFacilitator( iterations, toolCallCount: tracker.history.length, emptyFinalRetries, - model: currentModel, + // The model that wrote this final; `currentModel` is the one a retry asks for. + model: currentProvenance().modelId, }; if (RETRYABLE_EMPTY_FINISH_REASONS.has(finishReason) && emptyFinalRetries < maxRetries) { emptyFinalRetries++; @@ -867,6 +888,7 @@ export async function* runFacilitator( }); } + logEscalatedAnswer(); yield { type: 'done', data: '', @@ -1021,8 +1043,10 @@ export async function* runFacilitator( // delivered tokens would duplicate them), // - enough gathering budget remains for a real attempt (≥20s before the soft // deadline, which also keeps Spec 49's synthesis reserve intact), and - // - TINKER_API_KEY is configured. + // - TINKER_API_KEY is configured, and + // - the request is not pinned to one model (#393). if ( + pinnedModel === undefined && !useInklingRung && !inklingRescueUsed && !visibleTextDelivered && @@ -1057,7 +1081,7 @@ export async function* runFacilitator( Sentry.captureException(error); yield { type: 'error', - data: error instanceof Error ? error.message : 'Unknown error', + data: userFacingModelError(error), toolCalls: collectedToolCalls(), provenance: currentProvenance(), }; diff --git a/apps/api/lib/facilitator/history-limit.ts b/apps/api/lib/facilitator/history-limit.ts new file mode 100644 index 00000000..ada74da1 --- /dev/null +++ b/apps/api/lib/facilitator/history-limit.ts @@ -0,0 +1,133 @@ +/** + * Thread history limits (issue #400). + * + * Every turn sends the whole thread to the model, so a thread that grows without + * bound ends in prompts of a million tokens, 60 s hangs and refusals. Two thresholds + * (config.threadHistory, in estimated tokens) bound it: from `warnTokens` an answer + * opens with a notice to start a new conversation soon; from `blockTokens` no model + * is called and the notice is the answer. A single incoming message that is over + * `blockTokens` on its own is refused before it is stored, so one oversized paste + * does not end the thread it was sent to. + * + * The size is an ESTIMATE of the history about to be sent: the UTF-8 bytes of every + * text part `convertToGeminiHistory` produces, divided by BYTES_PER_TOKEN. It is not + * `messages.input_tokens`: that column is summed over every model call of a turn + * (each tool round re-sends the history), so it overstates the thread by a factor + * that changes from turn to turn, and it is absent on failed turns and old rows. + * Not counted: the system prompt and tool declarations (about 2,300 tokens, fixed) + * and thoughtSignature blobs in stored payloads. + */ +import { config } from '../config'; +import { convertToGeminiHistory } from './history'; +import type { FacilitatorStreamEvent, Message } from './agent'; + +/** + * Bytes, not characters: Arabic is two bytes a character and takes more tokens per + * character than English. The figure rests on issue #399's production threads (4.2 + * and 4.7 MB of text refused at Gemini's 1,048,576-token limit), which is no more + * precise than "about 4". The thresholds sit at a fifth of that limit, so an + * estimate a third off still blocks long before the failures it exists to prevent. + */ +export const BYTES_PER_TOKEN = 4; + +/** Opens an answer on a thread at or over the warn threshold. */ +export const HISTORY_WARNING_MESSAGE = + 'Note: this conversation is getting long. Please start a new conversation soon. Ansari cannot continue a conversation beyond a certain length.'; + +/** The whole answer on a thread at or over the block threshold. */ +export const HISTORY_BLOCK_MESSAGE = + 'This conversation has become too long for Ansari to continue. Please start a new conversation and ask your question there.'; + +/** + * The answer to one incoming message that is over the block threshold by itself. It + * does not suggest splitting the text: the parts would add up to the same size and + * block the thread on the last of them. + */ +export const HISTORY_MESSAGE_TOO_LONG_MESSAGE = + 'This message is too long for Ansari to read. Please send a shorter message.'; + +/** The 400 body on the stateless routes, whose callers send the history themselves. */ +export const HISTORY_REQUEST_TOO_LONG_MESSAGE = + 'The conversation in this request is too long. Send fewer or shorter messages.'; + +export type HistoryVerdict = 'ok' | 'warn' | 'block'; + +export interface HistoryAssessment { + verdict: HistoryVerdict; + estimatedTokens: number; +} + +/** Estimated tokens of the history `messages` would send, the newest message included. */ +export function estimateHistoryTokens(messages: Message[]): number { + let bytes = 0; + for (const content of convertToGeminiHistory(messages)) { + for (const part of content.parts ?? []) { + if (typeof part.text === 'string') bytes += Buffer.byteLength(part.text, 'utf8'); + } + } + return Math.ceil(bytes / BYTES_PER_TOKEN); +} + +/** + * Whether one incoming message is over the block threshold on its own. The thread + * routes ask this BEFORE storing the message: stored, it would count against the + * thread on every later turn and the thread could never be used again. A refused + * message is answered with HISTORY_MESSAGE_TOO_LONG_MESSAGE and nothing is saved. + */ +export function incomingMessageTooLong(text: string, threadId: string): boolean { + const estimatedTokens = Math.ceil(Buffer.byteLength(text, 'utf8') / BYTES_PER_TOKEN); + if (estimatedTokens < config.threadHistory.blockTokens) return false; + console.warn('[history-limit] incoming message refused', { threadId, estimatedTokens }); + return true; +} + +export function assessHistory(messages: Message[]): HistoryAssessment { + const estimatedTokens = estimateHistoryTokens(messages); + const { warnTokens, blockTokens } = config.threadHistory; + const verdict: HistoryVerdict = + estimatedTokens >= blockTokens ? 'block' : estimatedTokens >= warnTokens ? 'warn' : 'ok'; + return { verdict, estimatedTokens }; +} + +/** + * One turn of a stored thread, with the limits applied. `run` starts the facilitator + * and is never called on a blocked thread. + * + * The notices travel as ordinary `text` events, so the thread routes stream and store + * them like any answer. Stored, they survive the web app's re-read of the thread + * after `done`; streamed only, the block would be replaced there by a retry prompt. + * + * The warning is the answer's FIRST paragraph, sent just ahead of its first text. It + * cannot follow the answer: the web app cuts a "Citations" heading and everything + * after it from what it shows (apps/frontend/lib/citations.ts), which would take a + * trailing warning with it on every answer that cites a source. It is never the + * whole of an answer: an empty answer stays empty for the routes' own handling. + */ +export async function* limitThreadTurn( + messages: Message[], + threadId: string, + run: () => AsyncGenerator +): AsyncGenerator { + const { verdict, estimatedTokens } = assessHistory(messages); + if (verdict === 'ok') { + yield* run(); + return; + } + + console.warn('[history-limit] thread history over a threshold', { threadId, verdict, estimatedTokens }); + + if (verdict === 'block') { + yield { type: 'text', data: HISTORY_BLOCK_MESSAGE }; + yield { type: 'done', data: '' }; + return; + } + + let warned = false; + for await (const event of run()) { + if (!warned && event.type === 'text' && event.data.trim().length > 0) { + yield { type: 'text', data: `${HISTORY_WARNING_MESSAGE}\n\n` }; + warned = true; + } + yield event; + } +} diff --git a/apps/api/lib/facilitator/history.ts b/apps/api/lib/facilitator/history.ts new file mode 100644 index 00000000..80763adf --- /dev/null +++ b/apps/api/lib/facilitator/history.ts @@ -0,0 +1,51 @@ +import type { Content } from '../ai/gemini-client'; +import type { Message } from './agent'; + +/** + * Convert our message history to Gemini's Content[] format + * + * For assistant messages with rawPayload, uses the preserved Gemini Content + * which includes tool calls and thought signatures. Falls back to text-only + * for legacy messages without rawPayload. + */ +export function convertToGeminiHistory(messages: Message[]): Content[] { + const history: Content[] = []; + + for (const msg of messages) { + if (msg.role === 'user') { + // Extract text from user messages + const textContent = msg.content + .filter((c): c is { type: 'text'; text: string } => c.type === 'text') + .map((c) => c.text) + .join('\n'); + + if (textContent) { + history.push({ + role: 'user', + parts: [{ text: textContent }], + }); + } + } else { + // For assistant messages, prefer rawPayload if available + // This preserves tool calls, citations, and thought signatures + if (msg.rawPayload) { + history.push(msg.rawPayload); + } else { + // Fallback for legacy messages without rawPayload + const textContent = msg.content + .filter((c): c is { type: 'text'; text: string } => c.type === 'text') + .map((c) => c.text) + .join(''); + + if (textContent) { + history.push({ + role: 'model', + parts: [{ text: textContent }], + }); + } + } + } + } + + return history; +} diff --git a/apps/api/lib/tools/kalemat-response.ts b/apps/api/lib/tools/kalemat-response.ts new file mode 100644 index 00000000..ed6a6ff9 --- /dev/null +++ b/apps/api/lib/tools/kalemat-response.ts @@ -0,0 +1,27 @@ +import { ToolFetchError } from './resilience'; + +/** + * The items of a Kalimat `/search` 200 body, whichever of its two shapes it arrived in. + * + * Kalimat answers the same endpoint with a bare array of items or with an envelope + * `{ results: [...], total_results_num }`, and the caller does not choose which (issue #383): + * since 2026-11-05 every hadith search is enveloped, and a Quran search is enveloped when the + * query is a verse reference ("2:255") or a surah name and a bare array otherwise. The items + * themselves are the same in both. + * + * Any other body (an error object, `results` that is not an array, null) must NOT be waved + * through as "No results found": that would tell the model the source had nothing to say, + * invisibly to the degraded counter and Sentry (issue #2). It fails loudly as `invalid_body` + * through the tools' existing degraded path instead. + */ +export function kalematResults(body: unknown): T[] { + if (Array.isArray(body)) return body as T[]; + if (typeof body === 'object' && body !== null) { + const { results } = body as { results?: unknown }; + if (Array.isArray(results)) return results as T[]; + } + throw new ToolFetchError( + 'Kalemat API error: unexpected response shape (expected an array or { results: [...] })', + { errorClass: 'invalid_body' }, + ); +} diff --git a/apps/api/lib/tools/search-hadith.ts b/apps/api/lib/tools/search-hadith.ts index a5c3010a..8b60d70d 100644 --- a/apps/api/lib/tools/search-hadith.ts +++ b/apps/api/lib/tools/search-hadith.ts @@ -2,17 +2,18 @@ import { config } from '../config'; import type { ToolDescription, DocumentBlock, ToolResult, IslamicSearchTool } from './types'; import { trimCitationTitle } from './types'; import { fetchJsonWithTimeout, unavailableResult, reportDegradedTool, toolLabel, ToolFetchError } from './resilience'; +import { kalematResults } from './kalemat-response'; +// The fields this tool reads, as they appear in a real response (checked 2026-11-12, issue +// #383). The Arabic is in `text`; there is no `ar_text`. interface KalimatHadithResult { id: string; source_book: string; - chapter_number: string; + chapter_number: number; chapter_english: string; - section_number: string; - section_english: string; - hadith_number: string; + hadith_number: number; en_text: string; - ar_text: string; + text: string; grade_en: string; } @@ -60,7 +61,7 @@ Use this when the user asks about prophetic traditions or what the Prophet said indexes: '["sunnah_lk"]', }); - const data = await fetchJsonWithTimeout( + const body = await fetchJsonWithTimeout( `${this.baseUrl}?${params}`, { headers: { @@ -71,16 +72,7 @@ Use this when the user asks about prophetic traditions or what the Prophet said { errorPrefix: 'Kalemat API error' }, ); - // A 200 whose body is not the expected array (an error object, a shape change) must - // NOT be waved through as "No results found" — that would tell the model the source - // had nothing to say, invisibly to the degraded counter and Sentry (issue #2). Fail - // loudly through the existing degraded path instead. Note `!data.length` alone would - // read `undefined` on a non-array and silently degrade to the benign empty branch. - if (!Array.isArray(data)) { - throw new ToolFetchError('Kalemat API error: unexpected response shape (expected an array)', { - errorClass: 'invalid_body', - }); - } + const data = kalematResults(body); if (data.length === 0) { return { @@ -110,7 +102,7 @@ Use this when the user asks about prophetic traditions or what the Prophet said title = `${trimCitationTitle(title)} (LK id ${hadith.id})`; const content = JSON.stringify({ - ar: hadith.ar_text, + ar: hadith.text, en: hadith.en_text, grade: grade, collection: hadith.source_book, diff --git a/apps/api/lib/tools/search-quran.ts b/apps/api/lib/tools/search-quran.ts index 7a3f5705..ab82ef82 100644 --- a/apps/api/lib/tools/search-quran.ts +++ b/apps/api/lib/tools/search-quran.ts @@ -2,6 +2,7 @@ import { config } from '../config'; import type { ToolDescription, DocumentBlock, ToolResult, IslamicSearchTool } from './types'; import { trimCitationTitle } from './types'; import { fetchJsonWithTimeout, unavailableResult, reportDegradedTool, toolLabel, ToolFetchError } from './resilience'; +import { kalematResults } from './kalemat-response'; interface KalimatQuranResult { id: string; // e.g., "2:255" (Surah:Ayah) @@ -51,7 +52,7 @@ Use this when the user asks about Quranic verses, ayahs, or wants to know what t getText: '1', // 1 = Quran }); - const data = await fetchJsonWithTimeout( + const body = await fetchJsonWithTimeout( `${this.baseUrl}?${params}`, { headers: { @@ -62,16 +63,7 @@ Use this when the user asks about Quranic verses, ayahs, or wants to know what t { errorPrefix: 'Kalemat API error' }, ); - // A 200 whose body is not the expected array (an error object, a shape change) must - // NOT be waved through as "No results found" — that would tell the model the source - // had nothing to say, invisibly to the degraded counter and Sentry (issue #2). Fail - // loudly through the existing degraded path instead. Note `!data.length` alone would - // read `undefined` on a non-array and silently degrade to the benign empty branch. - if (!Array.isArray(data)) { - throw new ToolFetchError('Kalemat API error: unexpected response shape (expected an array)', { - errorClass: 'invalid_body', - }); - } + const data = kalematResults(body); if (data.length === 0) { return { diff --git a/apps/api/package.json b/apps/api/package.json index 6d901e44..d5bf7b56 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -34,12 +34,12 @@ "@sentry/nextjs": "^10.39.0", "drizzle-orm": "^0.45.2", "jose": "^6.2.9", - "next": "^15.5.25", + "next": "^15.5.29", "pg": "^8.17.2", - "react": "^19.2.4", - "react-dom": "^19.2.4", + "react": "^19.3.1", + "react-dom": "^19.3.1", "recharts": "^3.7.0", - "zod": "^4.3.5" + "zod": "^4.6.7" }, "devDependencies": { "@ansari/eslint-config": "workspace:*", @@ -51,17 +51,17 @@ "@types/bcrypt": "^6.0.0", "@types/node": "^25.0.10", "@types/pg": "^8.16.0", - "@types/react": "^19.2.9", - "@types/react-dom": "^19.2.3", - "@vitest/coverage-v8": "^4.1.11", - "dotenv": "^17.2.3", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitest/coverage-v8": "^5.1.1", + "dotenv": "^18.0.10", "drizzle-kit": "^0.31.8", "eslint": "catalog:", "eslint-config-next": "^15.5.22", "eslint-plugin-react-hooks": "^7.1.1", "tsx": "^4.21.0", "typescript": "catalog:", - "vitest": "^4.1.11", + "vitest": "^5.1.1", "yaml": "^2.9.1" } } diff --git a/apps/api/scripts/probes/environment-boot-probe.ts b/apps/api/scripts/probes/environment-boot-probe.ts new file mode 100644 index 00000000..92d9fc57 --- /dev/null +++ b/apps/api/scripts/probes/environment-boot-probe.ts @@ -0,0 +1,122 @@ +/** + * The production-shaped run for ENVIRONMENT (#314 Amendment 3; second review, + * finding 12): the BUILT apps/api started with `next start` and + * NODE_ENV=production, as Railway starts it, for each value of ENVIRONMENT. + * In-process tests (tests/boot-check.test.ts) call validateEnvAtBoot directly; + * this proves the rule on the real boot path, through instrumentation's + * register(). Operator-run, after `pnpm --filter ansari-api build`: + * + * pnpm --filter ansari-api exec tsx scripts/probes/environment-boot-probe.ts + * + * The database URL is an argument, never read from the environment, and + * should point at a port nothing listens on: the probe needs boot to get past + * the env check, not a database. Only the values below exist in the child. + * + * Next.js prints "Ready" even when register() throws, so the verdict is the + * healthcheck Railway runs: a refused boot answers /api/health 500 and logs + * the ENVIRONMENT rule (names only, no value); a good boot gets past the env + * check, answering 503 without a database (or 200 with one). Each case runs + * under a deadline (PASS or FAIL, never a hang). The output is pasted into the + * review (codev/reviews/314-*.md). + */ +import { spawn } from "node:child_process"; +import path from "node:path"; + +const databaseUrl = process.argv[2]; +if (!databaseUrl) { + console.error("usage: environment-boot-probe.ts "); + process.exit(2); +} + +const APP_DIR = path.resolve(__dirname, "../.."); +const PORT = "31996"; +const AUDIENCE = "ansari-api-probe-audience"; +const BASE: Record = { + PATH: process.env.PATH ?? "", + NODE_ENV: "production", + DATABASE_URL: databaseUrl, + KALEMAT_API_KEY: "probe", + USUL_API_TOKEN: "probe", + AUTH_URL: "https://auth.probe.test", + AUTH_JWT_ISSUER: "https://auth.probe.test", + AUTH_JWT_AUDIENCE: AUDIENCE, + AUTH_LAYER_ORIGIN: "https://api.probe.test", +}; + +type Outcome = { health: number | null; ruleLogged: boolean; leaked: boolean }; + +async function healthAfterReady( + output: () => string, + deadline: number, +): Promise { + while (Date.now() < deadline) { + if (/Ready in/.test(output())) { + try { + return (await fetch(`http://127.0.0.1:${PORT}/api/health`)).status; + } catch { + // not listening yet + } + } + await new Promise((r) => setTimeout(r, 250)); + } + return null; +} + +async function boot( + environment: string | undefined, + deadlineMs = 40_000, +): Promise { + const env = { + ...BASE, + ...(environment === undefined ? {} : { ENVIRONMENT: environment }), + }; + const child = spawn( + path.join(APP_DIR, "node_modules/.bin/next"), + ["start", "-p", PORT], + { + cwd: APP_DIR, + env, + }, + ); + let output = ""; + for (const stream of [child.stdout, child.stderr]) + stream.on("data", (chunk: Buffer) => (output += chunk.toString())); + const health = await healthAfterReady(() => output, Date.now() + deadlineMs); + await new Promise((r) => setTimeout(r, 300)); + child.kill("SIGTERM"); + await new Promise((r) => child.once("exit", r)); + return { + health, + // The validation failure names ENVIRONMENT: the production rule for an + // absent or `development` value, Zod's enum message for any other. + ruleLogged: /Environment validation failed[\s\S]*ENVIRONMENT/.test(output), + leaked: + output.includes(AUDIENCE) || + (environment !== undefined && output.includes(`"${environment}"`)), + }; +} + +async function main(): Promise { + let failed = 0; + for (const [environment, shouldBoot] of [ + [undefined, false], + ["development", false], + ["prod", false], + ["staging", true], + ["production", true], + ] as const) { + const outcome = await boot(environment); + const ok = shouldBoot + ? outcome.health !== null && outcome.health !== 500 && !outcome.ruleLogged + : outcome.health === 500 && outcome.ruleLogged && !outcome.leaked; + if (!ok) failed++; + console.log( + `${ok ? "PASS" : "FAIL"} NODE_ENV=production ENVIRONMENT=${environment ?? "(absent)"} → /api/health ${outcome.health ?? "no answer"}` + + `${outcome.ruleLogged ? ", ENVIRONMENT rule logged" : ""}`, + ); + } + return failed; +} + +// apps/api is CommonJS: no top-level await. +void main().then((failed) => process.exit(failed === 0 ? 0 : 1)); diff --git a/apps/api/sentry.server.config.ts b/apps/api/sentry.server.config.ts index 87e493ac..8d896877 100644 --- a/apps/api/sentry.server.config.ts +++ b/apps/api/sentry.server.config.ts @@ -5,7 +5,11 @@ import { SENTRY_REQUEST_PRIVACY } from "./lib/sentry-scrub"; Sentry.init({ dsn: process.env.SENTRY_DSN, enabled: process.env.NODE_ENV !== "test" && !process.env.VITEST, - environment: process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV, + // The deployment label (#314 Amendment 3), the same vocabulary as apps/auth + // (named after the legacy frontend's EXPO_PUBLIC_ENVIRONMENT; apps/frontend + // has no such variable). Required everywhere, no default (owner, 2026-11-12); + // validated at production boot (lib/boot-check.ts, right after this file). + environment: process.env.ENVIRONMENT, tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0, ...SENTRY_REQUEST_PRIVACY, }); diff --git a/apps/api/src/app/api/v1/chat/completions/route.ts b/apps/api/src/app/api/v1/chat/completions/route.ts index 06de5823..feaf45f7 100644 --- a/apps/api/src/app/api/v1/chat/completions/route.ts +++ b/apps/api/src/app/api/v1/chat/completions/route.ts @@ -28,6 +28,7 @@ import { type Message, type FacilitatorStreamEvent, } from '@/lib/facilitator/agent'; +import { assessHistory, HISTORY_REQUEST_TOO_LONG_MESSAGE } from '@/lib/facilitator/history-limit'; import { db } from '@/lib/db/index'; import { createThread, createMessage } from '@/lib/db/threads'; import { getOrCreateSystemUser } from '@/lib/db/users'; @@ -54,13 +55,31 @@ const MCQ_PATTERN = /\n\s*[ABCD][).]\s/; const LETTER_ANSWER_DIRECTIVE = '\n\nReply with only the single letter (A, B, C, or D) of the correct answer — no explanation, no markdown, no citations.'; +// Length caps per message, in characters (issue #403). An assistant message +// is one of Ansari's own answers sent back as history, and those run past +// 8,000, so it gets the larger cap; what the caller writes keeps 8,000. +// The message is written here because the 400 must name the message and the +// limit, whatever error text the validation library would produce. +const MAX_MESSAGE_CHARS = { system: 8000, user: 8000, assistant: 32000 } as const; + // OpenAI request body — accept the fields the leaderboard form sets and // ignore the rest. `messages` is the only required field that affects // behavior; everything else is metadata or a hint for letter-answer mode. -const messageSchema = z.object({ - role: z.enum(['system', 'user', 'assistant']), - content: z.string().min(1).max(8000), -}); +const messageSchema = z + .object({ + role: z.enum(['system', 'user', 'assistant']), + content: z.string().min(1, 'must not be empty'), + }) + .superRefine((m, ctx) => { + const limit = MAX_MESSAGE_CHARS[m.role]; + if (m.content.length > limit) { + ctx.addIssue({ + code: 'custom', + path: ['content'], + message: `this ${m.role} message is ${m.content.length} characters long; the limit for ${m.role} messages is ${limit}`, + }); + } + }); const requestSchema = z.object({ model: z.string().optional(), @@ -74,6 +93,12 @@ const requestSchema = z.object({ type OpenAIRequest = z.infer; +// The validation library's English messages, passed to the parse explicitly +// (issue #403). The library installs them as a default when it is imported, +// and the production bundle drops that step, so on a deployed server every +// message without wording of its own came out as "Invalid input". +const VALIDATION_MESSAGES = z.locales.en().localeError; + function openAIError( message: string, status: number, @@ -256,7 +281,7 @@ export async function POST(request: NextRequest): Promise { ); } - const parsed = requestSchema.safeParse(body); + const parsed = requestSchema.safeParse(body, { error: VALIDATION_MESSAGES }); if (!parsed.success) { return openAIError( parsed.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; '), @@ -319,6 +344,22 @@ export async function POST(request: NextRequest): Promise { const facilitatorMessages = toFacilitatorMessages(rewritten); + // Thread history limit (issue #400), before anything is saved: a request this + // long is refused as invalid input rather than sent to a model. + const history = assessHistory(facilitatorMessages); + if (history.verdict === 'block') { + console.warn('[history-limit] request refused', { + route: 'chat-completions', + estimatedTokens: history.estimatedTokens, + }); + return openAIError( + HISTORY_REQUEST_TOO_LONG_MESSAGE, + 400, + 'invalid_request_error', + 'context_length_exceeded' + ); + } + // Log to DB so we can observe leaderboard traffic in admin stats. // Failure to log is non-fatal — the caller still gets their answer. let threadId: string | undefined; diff --git a/apps/api/src/app/api/v2/mcp-complete/route.ts b/apps/api/src/app/api/v2/mcp-complete/route.ts index ab321d90..f45ed2aa 100644 --- a/apps/api/src/app/api/v2/mcp-complete/route.ts +++ b/apps/api/src/app/api/v2/mcp-complete/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'; import * as Sentry from '@sentry/nextjs'; import { z } from 'zod'; import { runFacilitator, type Message, type FacilitatorStreamEvent } from '@/lib/facilitator/agent'; +import { assessHistory, HISTORY_REQUEST_TOO_LONG_MESSAGE } from '@/lib/facilitator/history-limit'; import { toolCallsOrNull, type ContentBlock, @@ -11,14 +12,17 @@ import { import { db } from '@/lib/db/index'; import { getOrCreateSystemUser } from '@/lib/db/users'; import { createThread, createMessage, persistOrphanToolCalls } from '@/lib/db/threads'; -import { getClientId } from '@/lib/attribution'; +import { CLIENT_HEADER, getClientId } from '@/lib/attribution'; import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; +import { config } from '@/lib/config'; +import { AuthServiceUnavailableError, isServiceKeyShape, verifyServiceKey } from '@/lib/auth-service/client'; +import { parseClientId } from '@ansari/types/attribution'; const CONCISE_INSTRUCTION = 'Please provide a concise and brief answer. References are not required unless specifically asked for. Focus on delivering key information clearly and succinctly.'; const ATTRIBUTION = - '\n\n---\n**This information came from [ansari.chat](https://ansari.chat). Full references and citations are available upon request.**'; + '\n\n---\n**This information came from [askansari.ai](https://askansari.ai). Full references and citations are available upon request.**'; // Cached system user ID to avoid repeated DB lookups let cachedSystemUserId: string | null = null; @@ -64,6 +68,107 @@ function applyRateLimit(request: NextRequest): NextResponse | null { return null; } +/** + * What the key check found (#314), recorded on every request: + * - `valid`: apps/auth confirmed a live `ansari-mcp` key holding `mcp: complete`; + * - `missing`: no `Authorization: Bearer `, or a malformed one (no call made); + * - `refused`: apps/auth answered `{ valid: false }`; + * - `unverified`: apps/auth gave no usable answer (AuthServiceUnavailableError). + */ +type McpKeyVerdict = 'valid' | 'missing' | 'refused' | 'unverified'; + +/** + * The bearer token, or null when the header is absent or malformed + * (case-insensitive scheme, one token, no whitespace) or the token is outside + * the envelope apps/auth's verify route reads (printable ASCII, 1–256 + * characters). Such a token can never be a key; sent on, apps/auth would answer + * 400 and the request would get a 503 instead of the 401 it deserves. + */ +function bearerOf(request: NextRequest): string | null { + const header = request.headers.get('authorization'); + if (header === null) return null; + const token = /^Bearer ([^\s]+)$/i.exec(header)?.[1]; + return token !== undefined && isServiceKeyShape(token) ? token : null; +} + +/** + * On a valid key the thread belongs to the key's client (#320), never to the + * header or `?src=`. The header is parsed alone, so getClientId's own + * invalid-header warning never fires here; a header that is malformed or names + * another client raises one mismatch warning carrying ids only (never the raw + * value) and is otherwise ignored. + */ +function keyAttribution(request: NextRequest, keyClientId: string): string { + Sentry.setTag('client', keyClientId); + const header = parseClientId(request.headers.get(CLIENT_HEADER), null); + if (header.kind !== 'absent' && header.clientId !== keyClientId) { + Sentry.captureMessage('mcp-complete client mismatch', { + level: 'warning', + tags: { client: keyClientId, header_client: header.clientId }, + }); + } + return keyClientId; +} + +/** + * The key gate (#314), run after the per-IP cap and before the body or query + * is read. Resolves with the request's attribution, or with the response that + * ends it. In `enforce` mode a missing or refused key gets 401 and an apps/auth + * failure 503 (fail closed: nothing persisted, no Gemini call). In `log-only` + * mode every verdict is served. The verdict and key id are recorded; the key + * never is. Any error other than AuthServiceUnavailableError propagates to the + * route's own catch. + */ +async function authorizeMcpRequest( + request: NextRequest +): Promise<{ client: string | null } | { response: NextResponse }> { + const mode = config.mcpCompleteKeyMode; + const token = bearerOf(request); + + let verdict: McpKeyVerdict; + let key: { clientId: string; keyId: string } | null = null; + let unavailableStatus: number | null = null; + if (token === null) { + verdict = 'missing'; + } else { + try { + const result = await verifyServiceKey(token); + if (result.valid) { + verdict = 'valid'; + key = { clientId: result.clientId, keyId: result.keyId }; + } else { + verdict = 'refused'; + } + } catch (error) { + if (!(error instanceof AuthServiceUnavailableError)) throw error; + verdict = 'unverified'; + unavailableStatus = error.status; + } + } + + Sentry.setTag('mcp_key_verdict', verdict); + console.log('[ai-skill] mcp-complete key verdict', key ? { verdict, keyId: key.keyId } : { verdict }); + + if (key) return { client: keyAttribution(request, key.clientId) }; + + if (mode === 'enforce') { + if (verdict === 'unverified') { + console.warn('[ai-skill] mcp-complete key verify unavailable', { status: unavailableStatus }); + return { response: createErrorResponse('Authentication service unavailable', 503) }; + } + return { response: createErrorResponse('Unauthorized', 401) }; + } + + if (verdict === 'unverified') { + Sentry.captureMessage('mcp-complete key unverified (log-only)', { + level: 'warning', + tags: { mcp_key_verdict: verdict }, + extra: { status: unavailableStatus }, + }); + } + return { client: getClientId(request) }; +} + /** * Convert input messages to the facilitator's Message[] format, * prepending the concise instruction to the first user message's content. @@ -146,9 +251,23 @@ async function handleMcpComplete( const messages = prepareMessages(inputMessages); + // Thread history limit (issue #400), before anything is saved. The body caps + // above keep a request far below the default threshold; this holds the rule + // if they change. + const history = assessHistory(messages); + if (history.verdict === 'block') { + console.warn('[history-limit] request refused', { + route: 'mcp-complete', + estimatedTokens: history.estimatedTokens, + }); + return createErrorResponse(HISTORY_REQUEST_TOO_LONG_MESSAGE, 400); + } + // Log to DB: create system user, thread, and user messages. `source` stays - // 'ai-skill' (product surface); `client` is the per-request X-Ansari-Client - // attribution (spec 56), NULL when the header is absent. + // 'ai-skill' (product surface). `client` is the key's client_id whenever a + // valid key was presented (#314, #320); the X-Ansari-Client header or + // `?src=` (spec 56, #87) decides only in log-only mode without a valid key, + // and is NULL when neither was sent. const systemUserId = await getSystemUserId(); // Thread + inbound messages persist atomically (issue #20): a failed message @@ -249,6 +368,9 @@ export async function POST(request: NextRequest): Promise { if (rateLimitResponse) return rateLimitResponse; try { + const gate = await authorizeMcpRequest(request); + if ('response' in gate) return gate.response; + const body = await request.json(); const parseResult = postBodySchema.safeParse(body); if (!parseResult.success) { @@ -256,7 +378,7 @@ export async function POST(request: NextRequest): Promise { return createErrorResponse(errors, 400); } - return await handleMcpComplete(parseResult.data.messages, getClientId(request)); + return await handleMcpComplete(parseResult.data.messages, gate.client); } catch (error) { console.error('[ai-skill] mcp-complete POST error:', error); Sentry.captureException(error); @@ -271,6 +393,9 @@ export async function GET(request: NextRequest): Promise { if (rateLimitResponse) return rateLimitResponse; try { + const gate = await authorizeMcpRequest(request); + if ('response' in gate) return gate.response; + const q = request.nextUrl.searchParams.get('q'); if (!q || q.trim().length === 0) { return createErrorResponse('Query parameter "q" is required', 400); @@ -279,7 +404,7 @@ export async function GET(request: NextRequest): Promise { return createErrorResponse('Query parameter "q" must be at most 2000 characters', 400); } - return await handleMcpComplete([{ role: 'user', content: q.trim() }], getClientId(request)); + return await handleMcpComplete([{ role: 'user', content: q.trim() }], gate.client); } catch (error) { console.error('[ai-skill] mcp-complete GET error:', error); Sentry.captureException(error); diff --git a/apps/api/src/app/api/v2/threads/[id]/chat/route.ts b/apps/api/src/app/api/v2/threads/[id]/chat/route.ts index 7965748e..4e8f3d80 100644 --- a/apps/api/src/app/api/v2/threads/[id]/chat/route.ts +++ b/apps/api/src/app/api/v2/threads/[id]/chat/route.ts @@ -7,6 +7,7 @@ import { findThreadById, createMessage, findMessagesByThread, persistOrphanToolC import { getClientId } from '@/lib/attribution'; import { maybeGenerateThreadName } from '@/lib/ai/thread-naming'; import { runFacilitator, type Message } from '@/lib/facilitator/agent'; +import { HISTORY_MESSAGE_TOO_LONG_MESSAGE, incomingMessageTooLong, limitThreadTurn } from '@/lib/facilitator/history-limit'; import { startHeartbeat, SSE_HEARTBEAT } from '@/lib/streaming/heartbeat'; import { toolCallsOrNull, type ContentBlock } from '@/db/schema/messages'; @@ -18,6 +19,12 @@ const chatSchema = z.object({ message: z.string().min(1, 'Message is required'), }); +const SSE_HEADERS = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', +}; + // POST /api/v2/threads/[id]/chat - Send a message and get streaming response export async function POST(request: NextRequest, context: RouteContext) { try { @@ -45,6 +52,15 @@ export async function POST(request: NextRequest, context: RouteContext) { const { message } = parseResult.data; + // A message over the block threshold on its own is answered at once and NOT + // stored (issue #400): stored, it would block this thread for good. + if (incomingMessageTooLong(message, threadId)) { + const frames = [{ type: 'text', content: HISTORY_MESSAGE_TOO_LONG_MESSAGE }, { type: 'done' }]; + return new Response(frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join(''), { + headers: SSE_HEADERS, + }); + } + // Per-client attribution (spec 56). Capture before the stream — the // assistant message is written inside the async stream closure. const client = getClientId(request); @@ -103,7 +119,10 @@ export async function POST(request: NextRequest, context: RouteContext) { const heartbeat = startHeartbeat(() => safeEnqueue(encoder.encode(SSE_HEARTBEAT))); try { - for await (const event of runFacilitator(messageHistory)) { + // Thread history limits (issue #400): a long thread's answer opens with a + // notice, and a too-long thread gets the notice instead of a model call. + const turn = limitThreadTurn(messageHistory, threadId, () => runFacilitator(messageHistory)); + for await (const event of turn) { heartbeat.touch(); switch (event.type) { case 'text': @@ -213,13 +232,7 @@ export async function POST(request: NextRequest, context: RouteContext) { }, }); - return new Response(stream, { - headers: { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive', - }, - }); + return new Response(stream, { headers: SSE_HEADERS }); } catch (error) { console.error('Chat error:', error); Sentry.captureException(error); diff --git a/apps/api/src/app/api/v2/threads/[id]/route.ts b/apps/api/src/app/api/v2/threads/[id]/route.ts index c323ee71..4e83371d 100644 --- a/apps/api/src/app/api/v2/threads/[id]/route.ts +++ b/apps/api/src/app/api/v2/threads/[id]/route.ts @@ -16,6 +16,7 @@ import { getClientId } from '@/lib/attribution'; import { maybeGenerateThreadName } from '@/lib/ai/thread-naming'; import { toolCallsOrNull, type ContentBlock } from '@/db/schema/messages'; import { runFacilitator, type Message } from '@/lib/facilitator/agent'; +import { HISTORY_MESSAGE_TOO_LONG_MESSAGE, incomingMessageTooLong, limitThreadTurn } from '@/lib/facilitator/history-limit'; import { startHeartbeat, RAW_TEXT_HEARTBEAT, @@ -122,6 +123,12 @@ const chatSchema = z.object({ role: z.string().optional(), }); +const STREAM_HEADERS = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', +}; + // POST /api/v2/threads/[id] - Send a message and get streaming response // (Frontend calls this endpoint, not /threads/[id]/chat) export async function POST(request: NextRequest, context: RouteContext) { @@ -150,6 +157,12 @@ export async function POST(request: NextRequest, context: RouteContext) { const { content } = parseResult.data; + // A message over the block threshold on its own is answered at once and NOT + // stored (issue #400): stored, it would block this thread for good. + if (incomingMessageTooLong(content, threadId)) { + return new Response(HISTORY_MESSAGE_TOO_LONG_MESSAGE, { headers: STREAM_HEADERS }); + } + // Per-client attribution (spec 56). Capture the header value BEFORE the // stream starts — the assistant message is written inside the async stream // closure (seconds later), so we close over `client` here. @@ -228,7 +241,10 @@ export async function POST(request: NextRequest, context: RouteContext) { ); try { - for await (const event of runFacilitator(messageHistory)) { + // Thread history limits (issue #400): a long thread's answer opens with a + // notice, and a too-long thread gets the notice instead of a model call. + const turn = limitThreadTurn(messageHistory, threadId, () => runFacilitator(messageHistory)); + for await (const event of turn) { switch (event.type) { case 'text': heartbeat.stop(); @@ -319,13 +335,7 @@ export async function POST(request: NextRequest, context: RouteContext) { }, }); - return new Response(stream, { - headers: { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive', - }, - }); + return new Response(stream, { headers: STREAM_HEADERS }); } catch (error) { console.error('Chat error:', error); Sentry.captureException(error); diff --git a/apps/api/tests/auth/helpers.ts b/apps/api/tests/auth/helpers.ts index a3fdc3e7..dcd57120 100644 --- a/apps/api/tests/auth/helpers.ts +++ b/apps/api/tests/auth/helpers.ts @@ -48,6 +48,7 @@ export function setApiEnv(authUrl: string): void { process.env.DATABASE_URL = 'postgres://test:test@localhost:5432/test'; process.env.KALEMAT_API_KEY = 'placeholder'; process.env.USUL_API_TOKEN = 'placeholder'; + process.env.ENVIRONMENT = 'development'; process.env.AUTH_URL = authUrl; process.env.AUTH_JWT_ISSUER = TEST_ISSUER; process.env.AUTH_JWT_AUDIENCE = TEST_AUDIENCE; diff --git a/apps/api/tests/auth/verify-service-key.test.ts b/apps/api/tests/auth/verify-service-key.test.ts new file mode 100644 index 00000000..fffe0dc4 --- /dev/null +++ b/apps/api/tests/auth/verify-service-key.test.ts @@ -0,0 +1,157 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + AUTH_SERVICE_TIMEOUT_MS, + AuthServiceUnavailableError, + SERVICE_VERIFY_PATH, + verifyServiceKey, +} from '@/lib/auth-service/client'; +import { setApiEnv, TEST_LAYER_ORIGIN } from './helpers'; + +/** + * apps/api's client for apps/auth's service-key verify route (#314), against a + * stubbed fetch. Only an exact `{ valid: false }` is a refusal; every other + * answer apps/auth could give (or fail to give) throws + * AuthServiceUnavailableError so the route fails closed (503), never open. + */ + +const AUTH_URL = 'https://auth.verify-test.example'; +const KEY = 'ansari_mcp_test_key_value_0123456789'; + +let fetchMock: ReturnType; + +function answer(status: number, body: unknown, raw = false) { + fetchMock.mockResolvedValue( + new Response(raw ? (body as string) : JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }) + ); +} + +async function unavailable(promise: Promise) { + const err = await promise.then( + () => null, + (e: unknown) => e + ); + expect(err).toBeInstanceOf(AuthServiceUnavailableError); + return (err as AuthServiceUnavailableError).status; +} + +beforeEach(() => { + setApiEnv(AUTH_URL); + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('verifyServiceKey: the request', () => { + it('POSTs exactly { key, permissions: { mcp: [complete] } } to the verify path, with no Authorization', async () => { + answer(200, { valid: false }); + await verifyServiceKey(KEY); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit]; + expect(String(url)).toBe(`${AUTH_URL}${SERVICE_VERIFY_PATH}`); + expect(SERVICE_VERIFY_PATH).toBe('/api/service/verify-key'); + expect(init.method).toBe('POST'); + expect(JSON.parse(init.body as string)).toStrictEqual({ + key: KEY, + permissions: { mcp: ['complete'] }, + }); + const headers = init.headers as Record; + expect(Object.keys(headers).map((h) => h.toLowerCase())).not.toContain('authorization'); + expect(headers['content-type']).toBe('application/json'); + expect(headers.origin).toBe(TEST_LAYER_ORIGIN); + }); +}); + +describe('verifyServiceKey: the verdicts', () => { + it('a 200 valid answer maps to { valid, clientId, keyId }', async () => { + answer(200, { valid: true, client_id: 'ansari-mcp', key_id: 'key-1' }); + await expect(verifyServiceKey(KEY)).resolves.toStrictEqual({ + valid: true, + clientId: 'ansari-mcp', + keyId: 'key-1', + }); + }); + + it('a suffixed ansari-mcp client id is accepted', async () => { + answer(200, { valid: true, client_id: 'ansari-mcp-partner.v2', key_id: 'key-2' }); + await expect(verifyServiceKey(KEY)).resolves.toMatchObject({ clientId: 'ansari-mcp-partner.v2' }); + }); + + it('a 200 { valid: false } maps to { valid: false }', async () => { + answer(200, { valid: false }); + await expect(verifyServiceKey(KEY)).resolves.toStrictEqual({ valid: false }); + }); +}); + +describe('verifyServiceKey: everything else fails closed', () => { + it('a network error', async () => { + fetchMock.mockRejectedValue(new TypeError('fetch failed')); + expect(await unavailable(verifyServiceKey(KEY))).toBeNull(); + }); + + it(`an answer slower than ${AUTH_SERVICE_TIMEOUT_MS} ms aborts`, async () => { + vi.useFakeTimers(); + // Node's AbortSignal.timeout runs on an internal timer fake timers cannot + // drive, so stand in one built on setTimeout and check the delay it is given. + const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => { + const controller = new AbortController(); + setTimeout(() => controller.abort(new DOMException('timed out', 'TimeoutError')), ms); + return controller.signal; + }); + fetchMock.mockImplementation( + (_url: URL, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener('abort', () => reject(init.signal?.reason)); + }) + ); + + let settled = false; + const result = unavailable(verifyServiceKey(KEY)).finally(() => { + settled = true; + }); + await vi.advanceTimersByTimeAsync(AUTH_SERVICE_TIMEOUT_MS - 1); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(await result).toBeNull(); + expect(timeout).toHaveBeenCalledWith(3_000); + }); + + it.each([500, 429, 404, 401, 400, 204, 302])('a %i', async (status) => { + fetchMock.mockResolvedValue( + new Response(status === 204 ? null : JSON.stringify({ valid: false }), { status }) + ); + expect(await unavailable(verifyServiceKey(KEY))).toBe(status); + }); + + it('a 200 that is not JSON', async () => { + answer(200, 'not json', true); + expect(await unavailable(verifyServiceKey(KEY))).toBe(200); + }); + + it.each([ + ['valid: true without key_id', { valid: true, client_id: 'ansari-mcp' }], + ['valid: true without client_id', { valid: true, key_id: 'key-1' }], + ['valid: true with an empty key_id', { valid: true, client_id: 'ansari-mcp', key_id: '' }], + ['a client_id of claude-skill', { valid: true, client_id: 'claude-skill', key_id: 'key-1' }], + ['a client_id of askansari-whatsapp', { valid: true, client_id: 'askansari-whatsapp', key_id: 'key-1' }], + ['an upper-case client_id', { valid: true, client_id: 'ANSARI-MCP', key_id: 'key-1' }], + ['a client_id over 64 characters', { valid: true, client_id: `ansari-mcp-${'a'.repeat(54)}`, key_id: 'k' }], + ['valid: "true"', { valid: 'true', client_id: 'ansari-mcp', key_id: 'key-1' }], + ['valid: "false"', { valid: 'false' }], + ['valid: false with extra detail', { valid: false, reason: 'expired' }], + ['no valid field', { client_id: 'ansari-mcp', key_id: 'key-1' }], + ['null', null], + ['an array', [{ valid: false }]], + ])('a 200 with %s', async (_label, body) => { + answer(200, body); + expect(await unavailable(verifyServiceKey(KEY))).toBe(200); + }); +}); diff --git a/apps/api/tests/boot-check.test.ts b/apps/api/tests/boot-check.test.ts index 04d69345..4b7d11ea 100644 --- a/apps/api/tests/boot-check.test.ts +++ b/apps/api/tests/boot-check.test.ts @@ -16,6 +16,7 @@ const BASE_ENV = { DATABASE_URL: 'postgresql://user:pass@localhost:5432/db', KALEMAT_API_KEY: 'placeholder', USUL_API_TOKEN: 'placeholder', + ENVIRONMENT: 'development', }; const AUTH_ENV = { AUTH_URL: 'https://auth.askansari.ai', @@ -23,7 +24,7 @@ const AUTH_ENV = { AUTH_JWT_AUDIENCE: 'ansari-api-boot-check-value', AUTH_LAYER_ORIGIN: 'https://api.askansari.ai', }; -const SERVER = { NODE_ENV: 'production', NEXT_RUNTIME: 'nodejs' } as const; +const SERVER = { NODE_ENV: 'production', NEXT_RUNTIME: 'nodejs', ENVIRONMENT: 'production' } as const; let saved: NodeJS.ProcessEnv; beforeEach(() => { @@ -66,11 +67,50 @@ describe('validateEnvAtBoot', () => { expect(() => validateEnvAtBoot()).not.toThrow(); }); + it('a production boot with a bad MCP_COMPLETE_KEY_MODE throws, naming it (#314)', () => { + process.env = { ...process.env, ...BASE_ENV, ...AUTH_ENV, ...SERVER, MCP_COMPLETE_KEY_MODE: 'log_only' }; + expect(() => validateEnvAtBoot()).toThrow(/MCP_COMPLETE_KEY_MODE/); + resetEnvCache(); + process.env.MCP_COMPLETE_KEY_MODE = 'log-only'; + expect(() => validateEnvAtBoot()).not.toThrow(); + }); + + it('a production boot without ENVIRONMENT, or labelled development, throws naming it (#314 Amendment 3)', () => { + for (const environment of [undefined, 'development', 'prod', 'test']) { + resetEnvCache(); + process.env = { ...process.env, ...BASE_ENV, ...AUTH_ENV, ...SERVER }; + if (environment === undefined) delete process.env.ENVIRONMENT; + else process.env.ENVIRONMENT = environment; + expect(() => validateEnvAtBoot(), String(environment)).toThrow(/ENVIRONMENT/); + } + }); + + it.each(['staging', 'production'])('a production boot with ENVIRONMENT=%s boots', (environment) => { + process.env = { ...process.env, ...BASE_ENV, ...AUTH_ENV, ...SERVER, ENVIRONMENT: environment }; + expect(() => validateEnvAtBoot()).not.toThrow(); + }); + + it('next build never parses the env; outside a build ENVIRONMENT is required, with no default (owner, 2026-11-12)', async () => { + process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' }; + delete process.env.ENVIRONMENT; + expect(() => validateEnvAtBoot()).not.toThrow(); + process.env = { ...process.env, ...BASE_ENV, NODE_ENV: 'development' }; + delete process.env.NEXT_PHASE; // absent, not the string 'undefined' + resetEnvCache(); + const { getEnv } = await import('@/lib/config'); + expect(getEnv().ENVIRONMENT).toBe('development'); + // Absent in a dev process: the first config access fails, naming it. + delete process.env.ENVIRONMENT; + resetEnvCache(); + expect(() => getEnv()).toThrow(/ENVIRONMENT/); + }); + it('a build or a dev server never parses the env', () => { process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' }; delete process.env.DATABASE_URL; expect(() => validateEnvAtBoot()).not.toThrow(); - process.env = { ...process.env, NODE_ENV: 'development', NEXT_PHASE: undefined }; + process.env = { ...process.env, NODE_ENV: 'development' }; + delete process.env.NEXT_PHASE; // absent, not the string 'undefined' expect(() => validateEnvAtBoot()).not.toThrow(); }); }); diff --git a/apps/api/tests/config.test.ts b/apps/api/tests/config.test.ts index e366b1be..9ee7cc90 100644 --- a/apps/api/tests/config.test.ts +++ b/apps/api/tests/config.test.ts @@ -10,6 +10,7 @@ const REQUIRED_ENV: Record = { DATABASE_URL: 'postgresql://user:pass@localhost:5432/db', KALEMAT_API_KEY: 'placeholder-key', USUL_API_TOKEN: 'placeholder-token', + ENVIRONMENT: 'development', }; let savedEnv: NodeJS.ProcessEnv; @@ -280,6 +281,7 @@ describe('apps/auth config', () => { } setAuthEnv(); process.env.NODE_ENV = 'production'; + process.env.ENVIRONMENT = 'staging'; // required in production too (#314 Amendment 3) resetEnvCache(); expect(() => getEnv()).not.toThrow(); }); @@ -301,3 +303,80 @@ describe('apps/auth config', () => { } }); }); + +// #314: how /v2/mcp-complete treats its service key during the rollout. +// Absent means enforce (fail closed); only the two exact values parse, so a +// typo can never quietly put the route in log-only. +describe('MCP_COMPLETE_KEY_MODE (#314)', () => { + function withMode(value: string | undefined) { + if (value === undefined) delete process.env.MCP_COMPLETE_KEY_MODE; + else process.env.MCP_COMPLETE_KEY_MODE = value; + resetEnvCache(); + } + + it('absent → enforce', () => { + withMode(undefined); + expect(config.mcpCompleteKeyMode).toBe('enforce'); + }); + + it.each(['enforce', 'log-only'] as const)('%s → %s', (mode) => { + withMode(mode); + expect(config.mcpCompleteKeyMode).toBe(mode); + }); + + it.each(['log_only', 'LOG-ONLY', 'Enforce', '', ' enforce', 'off'])('%j fails validation', (value) => { + withMode(value); + expect(() => getEnv()).toThrow(/MCP_COMPLETE_KEY_MODE/); + expect(() => config.mcpCompleteKeyMode).toThrow(/Environment validation failed/); + }); +}); + +// Issue #400: the thread history thresholds are configuration with defaults. +// Anything but a positive integer, or a warn threshold that is not below the +// block threshold, fails at parse: a limit that silently never fires, or that +// blocks before it warns, must not boot. +describe('config.threadHistory (issue #400)', () => { + function withThresholds(warn: string | undefined, block: string | undefined) { + for (const [name, value] of [ + ['THREAD_HISTORY_WARN_TOKENS', warn], + ['THREAD_HISTORY_BLOCK_TOKENS', block], + ] as const) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + resetEnvCache(); + } + + it('defaults to warn at 150,000 and block at 200,000', () => { + withThresholds(undefined, undefined); + expect(config.threadHistory).toEqual({ warnTokens: 150000, blockTokens: 200000 }); + }); + + it('each threshold is overridable on its own', () => { + withThresholds('1000', undefined); + expect(config.threadHistory).toEqual({ warnTokens: 1000, blockTokens: 200000 }); + withThresholds(undefined, '900000'); + expect(config.threadHistory).toEqual({ warnTokens: 150000, blockTokens: 900000 }); + withThresholds('300', '600'); + expect(config.threadHistory).toEqual({ warnTokens: 300, blockTokens: 600 }); + }); + + it.each([ + ['200000', '200000'], + ['200001', '200000'], + ['150000', '100000'], + [undefined, '150000'], + ['250000', undefined], + ])('rejects warn %j with block %j: warn must be below block', (warn, block) => { + withThresholds(warn, block); + expect(() => getEnv()).toThrow(/THREAD_HISTORY_WARN_TOKENS must be below THREAD_HISTORY_BLOCK_TOKENS/); + expect(() => config.threadHistory).toThrow(/Environment validation failed/); + }); + + it.each(['0', '-5', '1500.5', 'many', '150k'])('rejects %j as a threshold', (value) => { + withThresholds(value, undefined); + expect(() => getEnv()).toThrow(/THREAD_HISTORY_WARN_TOKENS/); + withThresholds(undefined, value); + expect(() => getEnv()).toThrow(/THREAD_HISTORY_BLOCK_TOKENS/); + }); +}); diff --git a/apps/api/tests/contributor-docs.test.ts b/apps/api/tests/contributor-docs.test.ts index 5e8f84bb..d07ae47f 100644 --- a/apps/api/tests/contributor-docs.test.ts +++ b/apps/api/tests/contributor-docs.test.ts @@ -129,9 +129,10 @@ describe('CONTRIBUTING.md', () => { it('names required CI checks that the workflow actually emits', () => { const ci = parse(readFileSync(resolve(repoRoot, '.github/workflows/ci.yml'), 'utf8')); const emitted = Object.values(ci.jobs as Record).map((j) => j.name); - // All five jobs are required on `develop`, so the doc must name each one - // exactly as the workflow emits it — and notice when a job is added or renamed. - expect(emitted.length).toBe(5); + // The doc must name each job exactly as the workflow emits it, and notice + // when a job is added or renamed. Five are named as required on `develop`; + // `eval` (#397) and `whatsapp service` (#358) run on every PR and are named as not required. + expect(emitted.length).toBe(7); for (const check of emitted) { expect(doc).toContain(`\`${check}\``); } diff --git a/apps/api/tests/cutover-docs.test.ts b/apps/api/tests/cutover-docs.test.ts index ee90ab80..d7f38cba 100644 --- a/apps/api/tests/cutover-docs.test.ts +++ b/apps/api/tests/cutover-docs.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { limits, serviceUsers } from '../../../packages/auth/src'; @@ -17,12 +18,17 @@ const ROLLBACK = 'docs/cutover/rollback.md'; const SCRIPTS_DIR = 'apps/auth/scripts/cutover'; const SCRIPTS_README = `${SCRIPTS_DIR}/README.md`; const GUIDE = 'docs/cutover/deploy-guide.md'; -const DOCS = [RUNBOOK, ROLLBACK, GUIDE, 'docs/cutover/edge-check.md', 'docs/cutover/baselines.md', 'docs/cutover/rehearsal.md', SCRIPTS_README]; +const RECORD = 'docs/cutover/release-record.md'; +const DOCS = [RUNBOOK, ROLLBACK, GUIDE, RECORD, 'docs/cutover/edge-check.md', 'docs/cutover/baselines.md', 'docs/cutover/rehearsal.md', SCRIPTS_README]; /** Repo-relative paths a doc names in backticks or as a command argument. */ export function namedRepoPaths(doc: string): string[] { const found = new Set(); - for (const m of doc.matchAll(/(?:` citation (e.g. `origin/main:apps/api/...`) names a file at that ref, not in this + // checkout, so the `:` before the path excludes it (#416: step 7 cites origin/main's code). + // legacy/ is scanned too (#416: the runbook cites legacy/frontend-web), with .tsx and the route + // groups' parentheses, e.g. legacy/frontend-web/src/app/(public)/reset-password.tsx. + for (const m of doc.matchAll(/(? { [RUNBOOK, 8], [ROLLBACK, 1], ['docs/cutover/rehearsal.md', 2], + [RECORD, 4], ])('every repo path %s names exists', (rel, atLeast) => { const paths = namedRepoPaths(read(rel)); expect(paths.length).toBeGreaterThanOrEqual(atLeast); @@ -48,6 +55,11 @@ describe('cutover docs: every named file exists', () => { it('the path scan finds a planted missing file and ignores a near-miss', () => { const planted = 'run `apps/auth/scripts/cutover/99-missing.sql` then see https://example.com/apps/x.sql'; expect(namedRepoPaths(planted)).toEqual(['apps/auth/scripts/cutover/99-missing.sql']); + expect(namedRepoPaths('see `origin/main:apps/api/lib/auth/jwt.ts:47` and `apps/x/y.ts`')).toEqual(['apps/x/y.ts']); + expect(namedRepoPaths('page (`legacy/frontend-web/src/app/(public)/gone.tsx`) and (legacy/x.ts)')).toEqual([ + 'legacy/frontend-web/src/app/(public)/gone.tsx', + 'legacy/x.ts', + ]); expect(existsSync(resolve(repoRoot, 'apps/auth/scripts/cutover/99-missing.sql'))).toBe(false); }); @@ -85,11 +97,14 @@ describe('the window runbook', () => { }); it('applies every migration with both psql flags, naming the database', () => { - // The app window migrations by file; the auth journal by its loop, one file at a time (spec 329). + // The app window migrations by file; the auth journal by its loop, one file at a time (spec 329); + // and step 5's production single-file form for a journal file newer than the early apply (2026-11-21). const applies = doc.split('\n').filter((l) => /psql .*-f \S*drizzle\/\S+\.sql/.test(l) || /auth-journal\.mjs files/.test(l)); - expect(applies.length).toBe(4); + // + the named production procedure's loop (drop and re-apply, owner 2026-11-21). + expect(applies.length).toBe(6); for (const line of applies) { - expect(line).toMatch(/psql "\$(APP|AUTH)_DATABASE_URL" -X -v ON_ERROR_STOP=1 --single-transaction -f /); + // `-f `, or (the production procedure) the drop and every journal file piped into ONE psql. + expect(line).toMatch(/psql "\$(APP|AUTH)_DATABASE_URL" -X -v ON_ERROR_STOP=1 --single-transaction( -f |$)/); } }); @@ -113,12 +128,16 @@ describe('the window runbook', () => { expect(stepOf(title), String(title)).toBeLessThan(promote); } expect(stepOf(/The copy and the audits/)).toBe(promote - 4); - expect(stepOf(/The deploys: `auth`, `backend` and web/)).toBe(promote + 1); + expect(stepOf(/The deploys: `auth` and `backend`/)).toBe(promote + 1); expect(doc).toMatch(/\*\*Auto-deploy is ON for `backend`, the web service and `auth`, and stays on\*\*/); expect(doc).not.toMatch(/Auto-deploy is OFF|auto-deploy OFF on staging|Turn auto-deploy OFF on staging/); expect(doc).toMatch(/Steps 3 to 10 are \*\*one continuous session\*\*/); - expect(doc).toMatch(/main` is current except for spec 300/); - expect(doc).toMatch(/\*\*The web service has both build variables set before step 10\*\*/); + // #416: main is NOT current except for spec 300; the promotion is measured, and the web is untouched. + expect(doc).toMatch(/\*\*What the promotion carries is measured and recorded\*\*/); + expect(doc).toMatch(/git rev-list --count origin\/main\.\.origin\/develop/); + expect(doc).not.toMatch(/\*\*`main` is current except for spec 300\.\*\*/); + expect(doc).toMatch(/\*\*The web service needs no change\*\*/); + expect(doc).not.toMatch(/\*\*The web service has both build variables set before step 10\*\*/); }); it('step 10 checks the deployed tree is the checkout the scripts ran from (W5, M5)', () => { @@ -129,7 +148,7 @@ describe('the window runbook', () => { const before = step10.indexOf('echo develop-unchanged'); expect(before).toBeGreaterThan(0); expect(before).toBeLessThan(step10.indexOf('git push origin origin/develop:main')); - const step11 = steps[stepOf(/The deploys: `auth`, `backend` and web/) - 1] as string; + const step11 = steps[stepOf(/The deploys: `auth` and `backend`/) - 1] as string; expect(step11).toMatch(/first build and\s+deploy/); expect(step11).toMatch(/that is \[`rollback\.md`\]\(rollback\.md\) from step 1/); expect(doc).toMatch(/cutover\s+PR is brought current with `develop`/); @@ -154,12 +173,352 @@ describe('the window runbook', () => { expect(step7).toContain('eq(users.email, email.toLowerCase())'); }); - it('attaches the auth domain before the web swap (R4)', () => { - expect(stepOf(/Attach `auth\.askansari\.ai`/)).toBeLessThan(stepOf(/Replace legacy web/)); + it('attaches the auth domain before the web domain comes back (R4); there is no web swap (#416)', () => { + expect(stepOf(/Attach `auth\.askansari\.ai`/)).toBeLessThan(stepOf(/^\d+\. Web back$/)); + expect(stepOf(/Maintenance mode on, web off/)).toBeLessThan(stepOf(/^\d+\. Web back$/)); + expect(doc).not.toMatch(/Replace legacy web|legacy web retires in step 13|EXPO_PUBLIC_AUTH_URL=https/); + }); + + it('production web goes offline by legacy web\'s own flag, staging by the detach; the open-tab residual is stated (owner, 2026-11-21; #416)', () => { + const step3 = steps[stepOf(/Maintenance mode on, web off/) - 1] as string; + // backend's flag still does nothing for web: legacy web never asks app-check. + expect(step3).toContain('apps/api/src/app/api/v2/app-check/route.ts'); + expect(read('apps/api/src/app/api/v2/app-check/route.ts')).toMatch(/maintenanceMode/); + // Production: the legacy web service's own MAINTENANCE_MODE, service-scoped; staging keeps the detach. + expect(step3).toMatch(/\*\*Production: `MAINTENANCE_MODE=true` on the legacy web service\*\*/); + expect(step3).toMatch(/\*\*service variable of that service\*\*, never as a shared variable/); + expect(step3).toMatch(/\*\*Staging: detach the web domain from the staging web service\.\*\*/); + expect(step3).toMatch(/Wait until \*\*both\*\* are live/); + expect(step3.indexOf('Wait until **both** are live')).toBeLessThan(step3.indexOf('select now()')); + // The detach's old claim is gone; the residual is the same under both mechanisms. + expect(doc).not.toMatch(/only the detach stops web traffic|does not honour maintenance/); + expect(step3).toMatch(/\*\*Residual: a tab loaded before the maintenance build went live \(owner-accepted, 2026-11-21\)\.\*\*/); + expect(step3).toMatch(/\*\*The detach had the same residual\.\*\*/); + expect(step3).toMatch(/reset links and\s+shared links opened on web land on the maintenance screen/); + // The bundle check reads the flag the served bundle carries; its pattern matches the measured + // forms (ON, and both OFF forms) and not an unrelated getEnv entry. + const check = /MAINTENANCE_MODE:\(\)=>[A-Za-z_$][A-Za-z0-9_$]*\(("([^"\\]|\\.)*"|void 0)\)/; + expect(step3).toContain(String.raw`grep -oE 'MAINTENANCE_MODE:\(\)=>[A-Za-z_$][A-Za-z0-9_$]*\(("([^"\\]|\\.)*"|void 0)\)'`); + // Measured forms (#421): local builds (E), production with the flag off (t), and a quoted value, + // which the check must SHOW (it is OFF), not swallow into no output. + const measured: Array<[string, string]> = [ + ['RE:()=>!1,MAINTENANCE_MODE:()=>E("true")}', 'MAINTENANCE_MODE:()=>E("true")'], + ['MAINTENANCE_MODE:()=>E(void 0)}', 'MAINTENANCE_MODE:()=>E(void 0)'], + ['MAINTENANCE_MODE:()=>E("")}', 'MAINTENANCE_MODE:()=>E("")'], + ['MAINTENANCE_MODE:()=>t("")}', 'MAINTENANCE_MODE:()=>t("")'], + ['>!1,MAINTENANCE_MODE:()=>E("\\"true\\"")}', 'MAINTENANCE_MODE:()=>E("\\"true\\"")'], + ]; + for (const [bundle, printed] of measured) { + expect(bundle.match(check)?.[0], bundle).toBe(printed); + } + expect(check.test("const O=(0,S.default)('MAINTENANCE_MODE')")).toBe(false); + // ON and OFF are predicates that print a fixed token; neither printing means stop. + expect(step3).toMatch(/\*\*Neither printing means stop\*\*/); + expect(step3).toContain('production, flag off, measured by main on 2026-11-21, showed `t("")`'); + // The variable's name and value (an operator set EXPO_PUBLIC_MAINTENANCE_MODE, quoted, 2026-11-21). + for (const rel of [RUNBOOK, GUIDE, ROLLBACK, 'RELEASE.md']) { + expect(read(rel), rel).toMatch(/EXPO_PUBLIC_MAINTENANCE_MODE`\s+(?:set\s+)?on the\s+service has \*\*no effect\*\*|EXPO_PUBLIC_MAINTENANCE_MODE`\s+(?:set\s+)?on the\s+service has no effect/); + } + expect(read('legacy/frontend-web/Dockerfile')).not.toMatch(/ARG EXPO_PUBLIC_MAINTENANCE_MODE/); + expect((steps[0] as string)).toContain('**No `EXPO_PUBLIC_MAINTENANCE_MODE` variable is\n left on the service**'); + expect(step3).toMatch(/\*\*production:\*\* `MAINTENANCE_MODE=false` on the\s+legacy web service too/); + // The switch the runbook relies on exists in the tree. + expect(read('legacy/frontend-web/Dockerfile')).toMatch(/ENV EXPO_PUBLIC_MAINTENANCE_MODE=\$MAINTENANCE_MODE/); + expect(read('legacy/frontend-web/src/app/_layout.tsx')).toMatch(/if \(maintenanceMode\) \{\s*return fontsLoaded \? /); + // Step 1: the switch is ready, service-scoped, and the api origin is confirmed. + const step1 = steps[0] as string; + expect(step1).toContain('**Production: legacy web\'s maintenance switch is ready**'); + expect(step1).toContain('legacy/frontend-web/src/components/MaintenanceScreen.tsx && echo web-has-switch'); + expect(step1).toMatch(/\*\*Its `EXPO_PUBLIC_API_V2_URL` is an absolute api origin\*\*/); + }); + + it('the web flag ON and OFF checks discriminate every measured form, run as written in bash (#421 review)', () => { + const step3 = steps[stepOf(/Maintenance mode on, web off/) - 1] as string; + const block = step3.match(/```bash\n(web_flag\(\) \{[\s\S]*?)```/)?.[1]; + expect(block, 'the web_flag functions are in step 3').toBeDefined(); + // A stub curl stands in for the web domain: "/" serves an index naming one bundle, which holds BUNDLE. + const run = (bundle: string, fn: 'web_flag_on' | 'web_flag_off') => + spawnSync('bash', ['-c', `curl() { case "$2" in */) echo ''; + const res = await call(method, { clientHeader: raw }); + expect(res.status).toBe(200); + expect(captureMessage).toHaveBeenCalledTimes(1); + expect(captureMessage).toHaveBeenCalledWith('mcp-complete client mismatch', { + level: 'warning', + tags: { client: KEY_CLIENT, header_client: 'invalid' }, + }); + expect(messagesCaptured()).not.toContain('invalid X-Ansari-Client header'); + expect(JSON.stringify([captureMessage.mock.calls, setTag.mock.calls])).not.toContain('RAWMARKER'); + const threads = await client.query<{ client: string }>('SELECT client FROM threads'); + expect(threads.rows).toEqual([{ client: KEY_CLIENT }]); + }); + + it('scenario 5: a matching header (any case) → no event', async () => { + authAnswers(200, VALID); + const res = await call(method, { clientHeader: ' Ansari-MCP-Production ' }); + expect(res.status).toBe(200); + expect(captureMessage).not.toHaveBeenCalled(); + }); + + it("scenario 6: ?src=evil → the key's client, no event", async () => { + authAnswers(200, VALID); + const res = await call(method, { src: 'evil' }); + expect(res.status).toBe(200); + const threads = await client.query<{ client: string }>('SELECT client FROM threads'); + expect(threads.rows).toEqual([{ client: KEY_CLIENT }]); + expect(captureMessage).not.toHaveBeenCalled(); + expect(setTag).not.toHaveBeenCalledWith('client', 'evil'); + }); + + it.each([ + ['a 500', 500, { message: 'Internal error' }], + ['a 429', 429, { message: 'Too many requests' }], + ['a 200 that is not JSON', 200, 'proxy error'], + ['a 200 of the wrong shape', 200, { ok: true }], + ['valid: true missing key_id', 200, { valid: true, client_id: KEY_CLIENT }], + ['valid: true missing client_id', 200, { valid: true, key_id: KEY_ID }], + ['valid: true with an off-pattern client_id', 200, { valid: true, client_id: 'claude-skill', key_id: KEY_ID }], + ['a refusal carrying an extra field', 200, { valid: false, reason: 'revoked' }], + ])('scenario 7: %s → 503, no thread, no facilitator call', async (_label, status, body) => { + authAnswers(status, body); + const res = await call(method); + expect(res.status).toBe(503); + expect(res.json()).toStrictEqual(UNAVAILABLE); + await expectNothingPersisted(); + expect(verdictsRecorded()).toEqual(['unverified']); + expect(consoleSpies[1]).toHaveBeenCalledWith('[ai-skill] mcp-complete key verify unavailable', { status }); + // Enforce mode fails closed quietly: the warning is log-only's. + expect(captureMessage).not.toHaveBeenCalled(); + }); + + it('scenario 7: a network error → 503, the status null in the warning', async () => { + fetchMock.mockRejectedValue(new TypeError('fetch failed')); + const res = await call(method); + expect(res.status).toBe(503); + expect(res.json()).toStrictEqual(UNAVAILABLE); + await expectNothingPersisted(); + expect(consoleSpies[1]).toHaveBeenCalledWith('[ai-skill] mcp-complete key verify unavailable', { status: null }); + }); + + it(`scenario 7: apps/auth slower than ${AUTH_SERVICE_TIMEOUT_MS} ms → 503 at the timeout, not before`, async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + // Node's AbortSignal.timeout runs on an internal timer fake timers cannot + // drive, so stand in one built on setTimeout and check the delay it is given. + const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => { + const controller = new AbortController(); + setTimeout(() => controller.abort(new DOMException('timed out', 'TimeoutError')), ms); + return controller.signal; + }); + fetchMock.mockImplementation( + (_url: URL, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener('abort', () => reject(init.signal?.reason)); + }) + ); + + let settled = false; + const pending = call(method).finally(() => { + settled = true; + }); + await vi.advanceTimersByTimeAsync(AUTH_SERVICE_TIMEOUT_MS - 1); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + const res = await pending; + vi.useRealTimers(); + + expect(res.status).toBe(503); + expect(res.json()).toStrictEqual(UNAVAILABLE); + expect(timeout).toHaveBeenCalledWith(AUTH_SERVICE_TIMEOUT_MS); + await expectNothingPersisted(); + }); + + it('scenario 9: the per-IP cap answers 429 before any verify', async () => { + mockCheckRateLimit.mockReturnValue({ allowed: false, retryAfter: 17 }); + authAnswers(200, VALID); + const response = method === 'POST' ? await POST(postRequest()) : await GET(getRequest()); + expect(response.status).toBe(429); + expect(response.headers.get('Retry-After')).toBe('17'); + expect(fetchMock).not.toHaveBeenCalled(); + await expectNothingPersisted(); + }); + + it('an error other than apps/auth being unavailable falls into the route catch (500) and leaves no thread', async () => { + vi.stubEnv('AUTH_URL', ''); + resetEnvCache(); + const res = await call(method); + expect(res.status).toBe(500); + expect(fetchMock).not.toHaveBeenCalled(); + expect(captureException).toHaveBeenCalledTimes(1); + await expectNothingPersisted(); + }); +}); + +describe('scenario 8: the key is checked before the body', () => { + it('a valid key with an invalid POST body → 400', async () => { + authAnswers(200, VALID); + const res = await call('POST', { body: { messages: [] } }); + expect(res.status).toBe(400); + expect(fetchMock).toHaveBeenCalledTimes(1); + await expectNothingPersisted(); + }); + + it('a valid key with no ?q= → 400', async () => { + authAnswers(200, VALID); + const res = await call('GET', { query: null }); + expect(res.status).toBe(400); + await expectNothingPersisted(); + }); + + it('no key with an invalid POST body → 401 (the body is never read)', async () => { + const request = postRequest({ authorization: null, body: { messages: [] } }); + const read = vi.spyOn(request, 'json'); + const response = await POST(request); + expect(response.status).toBe(401); + expect(await response.json()).toStrictEqual(UNAUTHORIZED); + expect(read).not.toHaveBeenCalled(); + }); + + it('no key with no ?q= → 401', async () => { + const res = await call('GET', { authorization: null, query: null }); + expect(res.status).toBe(401); + expect(res.json()).toStrictEqual(UNAUTHORIZED); + }); +}); + +// --------------------------------------------------------------------------- +// Log-only mode (the rollout week) + +describe.each(['POST', 'GET'] as const)('%s, log-only mode (scenario 10)', (method) => { + beforeEach(() => { + setEnv('log-only'); + }); + + it('missing → served 200, verdict recorded, attributed by the header as today', async () => { + const res = await call(method, { authorization: null, clientHeader: 'muslimpedia' }); + expect(res.status).toBe(200); + expect(fetchMock).not.toHaveBeenCalled(); + expect(verdictsRecorded()).toEqual(['missing']); + expect(verdictLines()).toEqual([{ verdict: 'missing' }]); + const threads = await client.query<{ client: string | null }>('SELECT client FROM threads'); + expect(threads.rows).toEqual([{ client: 'muslimpedia' }]); + expect(captureMessage).not.toHaveBeenCalled(); + }); + + it('missing with ?src= → attributed by ?src= as today', async () => { + const res = await call(method, { authorization: null, src: 'jbprompt' }); + expect(res.status).toBe(200); + const threads = await client.query<{ client: string | null }>('SELECT client FROM threads'); + expect(threads.rows).toEqual([{ client: 'jbprompt' }]); + }); + + it('refused → served 200, verdict recorded, no warning', async () => { + authAnswers(200, { valid: false }); + const res = await call(method); + expect(res.status).toBe(200); + expect(verdictsRecorded()).toEqual(['refused']); + expect(verdictLines()).toEqual([{ verdict: 'refused' }]); + const threads = await client.query<{ client: string | null }>('SELECT client FROM threads'); + expect(threads.rows).toEqual([{ client: null }]); + expect(captureMessage).not.toHaveBeenCalled(); + }); + + it.each([ + ['a 500', () => authAnswers(500, { message: 'Internal error' }), 500], + ['a network error', () => fetchMock.mockRejectedValue(new TypeError('fetch failed')), null], + ])('unverified (%s) → served 200, verdict recorded, one Sentry warning', async (_label, script, status) => { + script(); + const res = await call(method); + expect(res.status).toBe(200); + expect(mockRunFacilitator).toHaveBeenCalledTimes(1); + expect(verdictsRecorded()).toEqual(['unverified']); + expect(verdictLines()).toEqual([{ verdict: 'unverified' }]); + expect(captureMessage).toHaveBeenCalledTimes(1); + expect(captureMessage).toHaveBeenCalledWith('mcp-complete key unverified (log-only)', { + level: 'warning', + tags: { mcp_key_verdict: 'unverified' }, + extra: { status }, + }); + }); + + it("valid → served, attributed by the key, a forged header still one mismatch warning", async () => { + authAnswers(200, VALID); + const res = await call(method, { clientHeader: 'claude-skill', src: 'evil' }); + expect(res.status).toBe(200); + expect(verdictsRecorded()).toEqual(['valid']); + expect(verdictLines()).toEqual([{ verdict: 'valid', keyId: KEY_ID }]); + const threads = await client.query<{ client: string }>('SELECT client FROM threads'); + expect(threads.rows).toEqual([{ client: KEY_CLIENT }]); + expect(messagesCaptured()).toEqual(['mcp-complete client mismatch']); + }); +}); + +describe('mode', () => { + it('MCP_COMPLETE_KEY_MODE=enforce enforces like the default', async () => { + setEnv('enforce'); + const res = await call('POST', { authorization: null }); + expect(res.status).toBe(401); + }); +}); + +// --------------------------------------------------------------------------- +// Scenario 12: no key material anywhere. Runs last, over every capture above. + +describe('scenario 12: the leak scan', () => { + it('negative control: the scan finds a window of the key in a known-bad line', () => { + const badLine = `verify failed for ${KEY.slice(0, PREFIX.length + 20)}`; + expect(leakedWindows(badLine).length).toBeGreaterThan(0); + expect(leakedWindows(KEY)).toHaveLength(64 - LEAK_WINDOW + 1); + }); + + it('near miss: the bare public prefix, and a 15-character fragment, are not a leak', () => { + expect(leakedWindows(`${PREFIX}… key prefix`)).toEqual([]); + expect(leakedWindows(KEY.slice(PREFIX.length, PREFIX.length + LEAK_WINDOW - 1))).toEqual([]); + }); + + it.each(['POST', 'GET'] as const)('%s: every verdict, in both modes, captures no key material', async (method) => { + const scripts: Array<[string | undefined, () => void]> = [ + [undefined, () => authAnswers(200, VALID)], + [undefined, () => authAnswers(200, { valid: false })], + [undefined, () => authAnswers(500, { message: 'Internal error' })], + [undefined, () => fetchMock.mockRejectedValue(new TypeError('fetch failed'))], + ['log-only', () => authAnswers(200, { valid: false })], + ['log-only', () => authAnswers(500, { message: 'Internal error' })], + ]; + for (const [mode, script] of scripts) { + setEnv(mode); + script(); + await call(method, { clientHeader: 'claude-skill' }); + } + // The request reached apps/auth (so the key was in play) on every run. + expect(fetchMock).toHaveBeenCalledTimes(scripts.length); + }); + + it('the scan over every console line, Sentry call and response body in this file finds nothing', () => { + const text = [...captures, ...responseBodies].join('\n'); + expect(captures.length).toBeGreaterThan(60); + expect(responseBodies.length).toBeGreaterThan(40); + expect(leakedWindows(text)).toEqual([]); + }); +}); diff --git a/apps/api/tests/mcp-complete.test.ts b/apps/api/tests/mcp-complete.test.ts index 80ae312f..88320d79 100644 --- a/apps/api/tests/mcp-complete.test.ts +++ b/apps/api/tests/mcp-complete.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { NextRequest } from 'next/server'; // Mock DB operations @@ -46,6 +46,21 @@ vi.mock('@/lib/rate-limit', () => ({ // Import route handlers after mocks import { GET, POST } from '../src/app/api/v2/mcp-complete/route'; +import { resetEnvCache } from '@/lib/config'; +import { installMcpKeyStub, MCP_TEST_CLIENT_ID, withMcpKey } from './helpers/mcp-key'; +import { HISTORY_REQUEST_TOO_LONG_MESSAGE } from '@/lib/facilitator/history-limit'; + +// Every request presents a valid key (#314); the gate itself is tested in +// mcp-complete-key.test.ts. +beforeEach(async () => { + await installMcpKeyStub(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + resetEnvCache(); +}); const SYSTEM_USER = { id: 'system-user-id', @@ -68,7 +83,7 @@ const MOCK_THREAD = { }; function makePostRequest(body: unknown, clientId?: string): NextRequest { - const headers: Record = { 'Content-Type': 'application/json' }; + const headers: Record = withMcpKey({ 'Content-Type': 'application/json' }); if (clientId !== undefined) headers['X-Ansari-Client'] = clientId; return new NextRequest('http://localhost/api/v2/mcp-complete', { method: 'POST', @@ -81,9 +96,9 @@ function makeGetRequest(query?: string, clientId?: string): NextRequest { const url = query ? `http://localhost/api/v2/mcp-complete?q=${encodeURIComponent(query)}` : 'http://localhost/api/v2/mcp-complete'; - const init: { method: string; headers?: Record } = { method: 'GET' }; - if (clientId !== undefined) init.headers = { 'X-Ansari-Client': clientId }; - return new NextRequest(url, init); + const headers = withMcpKey(); + if (clientId !== undefined) headers['X-Ansari-Client'] = clientId; + return new NextRequest(url, { method: 'GET', headers }); } /** Creates a mock async generator that yields facilitator events */ @@ -202,14 +217,16 @@ describe('POST /api/v2/mcp-complete', () => { expect(body.error).toBe('Gemini API timeout'); }); - it('does not require authentication', async () => { - // No Authorization header — should still work + it('requires a key (#314): no Authorization header → 401, the facilitator never runs', async () => { const request = makePostRequest({ messages: [{ role: 'user', content: 'Test' }], }); + request.headers.delete('authorization'); const response = await POST(request); - expect(response.status).toBe(200); + expect(response.status).toBe(401); + expect(await response.json()).toStrictEqual({ error: 'Unauthorized' }); + expect(mockRunFacilitator).not.toHaveBeenCalled(); }); it('creates thread and messages in DB', async () => { @@ -223,7 +240,7 @@ describe('POST /api/v2/mcp-complete', () => { { userId: SYSTEM_USER.id, source: 'ai-skill', - client: null, + client: MCP_TEST_CLIENT_ID, }, expect.anything() // tx executor (issue #20) ); @@ -382,11 +399,31 @@ describe('mcp-complete empty-answer backstop (issue #60)', () => { expect(response.status).toBe(200); const text = await response.text(); expect(text).toContain('Patience (sabr)'); - expect(text).toContain('ansari.chat'); + expect(text).toContain('askansari.ai'); + }); + + it('appends the exact askansari.ai attribution to the answer (issue #366)', async () => { + const response = await POST( + makePostRequest({ messages: [{ role: 'user', content: 'What is sabr?' }] }) + ); + expect(response.status).toBe(200); + expect(await response.text()).toBe( + 'Patience (sabr) is mentioned many times in the Quran.' + + '\n\n---\n**This information came from [askansari.ai](https://askansari.ai). Full references and citations are available upon request.**' + ); + const assistantCall = mockCreateMessage.mock.calls.find(([m]) => m.role === 'assistant'); + expect(assistantCall?.[0].content).toEqual([ + { + type: 'text', + text: + 'Patience (sabr) is mentioned many times in the Quran.' + + '\n\n---\n**This information came from [askansari.ai](https://askansari.ai). Full references and citations are available upon request.**', + }, + ]); }); }); -describe('mcp-complete client attribution (spec 56)', () => { +describe('mcp-complete client attribution (#314: the key decides)', () => { beforeEach(() => { vi.clearAllMocks(); setupSuccessfulMocks(); @@ -395,35 +432,112 @@ describe('mcp-complete client attribution (spec 56)', () => { mockCheckRateLimit.mockReturnValue({ allowed: true, retryAfter: 0 }); }); - it('POST attributes thread + all messages from X-Ansari-Client (source stays ai-skill)', async () => { + it("POST attributes thread + all messages to the key's client, not X-Ansari-Client (source stays ai-skill)", async () => { await POST(makePostRequest({ messages: [{ role: 'user', content: 'Q' }] }, 'muslimpedia')); expect(mockCreateThread).toHaveBeenCalledWith( - expect.objectContaining({ source: 'ai-skill', client: 'muslimpedia' }), + expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }), expect.anything() ); + expect(mockCreateMessage).toHaveBeenCalled(); for (const [arg] of mockCreateMessage.mock.calls) { - expect(arg).toEqual(expect.objectContaining({ source: 'ai-skill', client: 'muslimpedia' })); + expect(arg).toEqual(expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID })); } }); - it('GET attributes thread + messages from the header (distinct entrypoint from POST)', async () => { + it("GET attributes thread + messages to the key's client (distinct entrypoint from POST)", async () => { await GET(makeGetRequest('What is Islam?', 'muslimpedia')); expect(mockCreateThread).toHaveBeenCalledWith( - expect.objectContaining({ source: 'ai-skill', client: 'muslimpedia' }), + expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }), expect.anything() ); + expect(mockCreateMessage).toHaveBeenCalled(); for (const [arg] of mockCreateMessage.mock.calls) { - expect(arg).toEqual(expect.objectContaining({ client: 'muslimpedia' })); + expect(arg).toEqual(expect.objectContaining({ client: MCP_TEST_CLIENT_ID })); } }); - it('client is null when the header is absent (unchanged behavior)', async () => { + it("client is the key's when the header is absent", async () => { await POST(makePostRequest({ messages: [{ role: 'user', content: 'Q' }] })); expect(mockCreateThread).toHaveBeenCalledWith( - expect.objectContaining({ source: 'ai-skill', client: null }), + expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }), expect.anything() ); }); }); + +// Issue #400: a request whose history is at or over the block threshold is refused +// as invalid input, in the route's own error shape, before anything is saved and +// with no model call. There is no warning on this route: its caller sends the +// history itself and has no conversation to restart. +describe('mcp-complete thread history limit (issue #400)', () => { + const ANSWER = 'Patience (sabr) is mentioned many times in the Quran.'; + + function setThresholds(warn: number, block: number) { + vi.stubEnv('THREAD_HISTORY_WARN_TOKENS', String(warn)); + vi.stubEnv('THREAD_HISTORY_BLOCK_TOKENS', String(block)); + resetEnvCache(); + } + + beforeEach(() => { + vi.clearAllMocks(); + setupSuccessfulMocks(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('at the block threshold: 400 with the plain message, nothing saved, no model call', async () => { + setThresholds(100, 200); + const response = await POST(makePostRequest({ messages: [{ role: 'user', content: 'a'.repeat(800) }] })); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: HISTORY_REQUEST_TOO_LONG_MESSAGE }); + expect(mockRunFacilitator).not.toHaveBeenCalled(); + expect(mockCreateThread).not.toHaveBeenCalled(); + expect(mockCreateMessage).not.toHaveBeenCalled(); + expect(console.warn).toHaveBeenCalledWith('[history-limit] request refused', { + route: 'mcp-complete', + estimatedTokens: expect.any(Number), + }); + }); + + it('GET is held to the same limit', async () => { + setThresholds(100, 200); + const response = await GET(makeGetRequest('a'.repeat(800))); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: HISTORY_REQUEST_TOO_LONG_MESSAGE }); + expect(mockRunFacilitator).not.toHaveBeenCalled(); + }); + + it('between the warn and block thresholds: answered as usual, with no notice added', async () => { + setThresholds(100, 2000); + const response = await POST(makePostRequest({ messages: [{ role: 'user', content: 'a'.repeat(800) }] })); + + expect(response.status).toBe(200); + const text = await response.text(); + expect(text.startsWith(`${ANSWER}\n\n---\n`)).toBe(true); + expect(text).not.toMatch(/conversation is getting long/i); + expect(mockRunFacilitator).toHaveBeenCalledTimes(1); + }); + + it('at the default thresholds the largest body the route accepts is answered', async () => { + // 20 messages of 4,000 three-byte characters: the most bytes the body schema + // allows (its cap counts UTF-16 units, and no unit encodes to more than three + // bytes). About 60,000 estimated tokens, under the default warn threshold. + const largest = Array.from({ length: 20 }, (_, i) => ({ + role: i % 2 === 0 ? 'user' : 'assistant', + content: '\u4e2d'.repeat(4000), + })); + largest[19].role = 'user'; + const response = await POST(makePostRequest({ messages: largest })); + + expect(response.status).toBe(200); + expect(mockRunFacilitator).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/tests/model-provenance.test.ts b/apps/api/tests/model-provenance.test.ts index e596a8ce..f5a4dfc6 100644 --- a/apps/api/tests/model-provenance.test.ts +++ b/apps/api/tests/model-provenance.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; /** * Per-turn model provenance on the facilitator's terminal events (issue #99). @@ -7,6 +7,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; * `provenance: {provider, modelId}` describing the call that produced — or * failed to produce — the final turn: * - gemini-primary done → {gemini, config.gemini.model}; + * - a turn gemini-client served from GEMINI_FALLBACK_MODEL → {gemini, that model}, + * read from the response, per call (issue #402); * - forced provider 'inkling' → {inkling, config.inkling.model}; * - a #79-rescued turn reports inkling even though the primary was gemini — * this is what makes "rescued on Inkling" queryable, not just a Sentry event; @@ -38,8 +40,9 @@ const h = vi.hoisted(() => ({ inkling: { model: 'tinker://sft-dpo-bf16', timeoutMs: 180000 }, })); -function doneResponse(text: string, finishReason?: string) { +function doneResponse(text: string, finishReason?: string, modelId?: string) { return { + modelId, text, toolCalls: [], rawPayload: { role: 'model', parts: text ? [{ text }] : [] }, @@ -50,16 +53,18 @@ function doneResponse(text: string, finishReason?: string) { }; } -function textRound(text: string): () => AsyncGenerator { +// `modelId` is the model the client says answered (issue #402); omitted, the response +// names none, as in the suites written before the field existed. +function textRound(text: string, modelId?: string): () => AsyncGenerator { return async function* () { if (text) yield { type: 'text', data: text }; - yield { type: 'done', response: doneResponse(text, 'STOP') }; + yield { type: 'done', response: doneResponse(text, 'STOP', modelId) }; }; } -function emptyRound(finishReason?: string): () => AsyncGenerator { +function emptyRound(finishReason?: string, modelId?: string): () => AsyncGenerator { return async function* () { - yield { type: 'done', response: doneResponse('', finishReason) }; + yield { type: 'done', response: doneResponse('', finishReason, modelId) }; }; } @@ -145,6 +150,10 @@ beforeEach(() => { h.inkling = { model: 'tinker://sft-dpo-bf16', timeoutMs: 180000 }; }); +afterEach(() => { + vi.restoreAllMocks(); // the console spies some cases install +}); + describe('done-event provenance', () => { it('a gemini-primary turn reports {gemini, config.gemini.model}', async () => { h.scripts = [textRound('An answer.')]; @@ -186,6 +195,70 @@ describe('done-event provenance', () => { }); }); +describe('a turn served by GEMINI_FALLBACK_MODEL reports the fallback, not the primary (issue #402)', () => { + it('done: the model the response names', async () => { + h.scripts = [textRound('An answer.', 'gemini-fallback')]; + + const last = terminal(await collect(runFacilitator([userMessage('q')]))); + expect(last.type).toBe('done'); + expect(last.provenance).toEqual({ provider: 'gemini', modelId: 'gemini-fallback' }); + }); + + it('synthesis: the model the synthesis response names', async () => { + h.scripts = [textRound('Synthesized from context.', 'gemini-fallback')]; + + const last = terminal( + await collect(runFacilitator([userMessage('q')], undefined, { budgetMs: 5000, reserveMs: 5000 })) + ); + expect(last.type).toBe('done'); + expect(last.provenance).toEqual({ provider: 'gemini', modelId: 'gemini-fallback' }); + }); + + it('per call, not per request: a fallback-served empty final, then the primary answers the retry', async () => { + h.scripts = [emptyRound('STOP', 'gemini-fallback'), textRound('An answer.', 'gemini-3.7-flash')]; + + const last = terminal(await collect(runFacilitator([userMessage('q')]))); + expect(last.type).toBe('done'); + expect(last.provenance).toEqual({ provider: 'gemini', modelId: 'gemini-3.7-flash' }); + }); + + it('an empty final the fallback wrote is logged and reported under the fallback', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + h.scripts = [emptyRound('SAFETY', 'gemini-fallback')]; + + const last = terminal(await collect(runFacilitator([userMessage('q')]))); + + expect(last.type).toBe('error'); + expect(last.provenance).toEqual({ provider: 'gemini', modelId: 'gemini-fallback' }); + expect(error).toHaveBeenCalledWith( + '[facilitator] empty final completion — failing', + expect.objectContaining({ model: 'gemini-fallback' }) + ); + }); + + it('a later call that fails with no response names the model it asked for, not the earlier answerer', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + h.inklingConfigured = false; + h.scripts = [emptyRound('STOP', 'gemini-fallback'), errorRound('dual-pool 429 exhaustion')]; + + const last = terminal(await collect(runFacilitator([userMessage('q')]))); + expect(last.type).toBe('error'); + expect(last.provenance).toEqual({ provider: 'gemini', modelId: 'gemini-3.7-flash' }); + }); + + it('an Inkling-served turn is unaffected by what an earlier Gemini call named', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + h.scripts = [emptyRound('STOP', 'gemini-fallback'), emptyRound('STOP', 'gemini-fallback')]; + h.inklingScripts = [textRound('Ladder answer.', 'tinker://sft-dpo-bf16')]; + + const last = terminal(await collect(runFacilitator([userMessage('q')]))); + expect(last.type).toBe('done'); + expect(last.provenance).toEqual({ provider: 'inkling', modelId: 'tinker://sft-dpo-bf16' }); + }); +}); + describe('error-event provenance', () => { it('a terminal gemini error (rescue unavailable) reports the gemini provider that failed', async () => { h.inklingConfigured = false; diff --git a/apps/api/tests/openai-compat.test.ts b/apps/api/tests/openai-compat.test.ts index 0f3c3a7f..c0e2fa50 100644 --- a/apps/api/tests/openai-compat.test.ts +++ b/apps/api/tests/openai-compat.test.ts @@ -10,7 +10,7 @@ * - Response envelope matches OpenAI chat.completion shape and surfaces * token usage from the facilitator. */ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { NextRequest } from 'next/server'; const API_KEY = 'test-leaderboard-key-must-be-at-least-32-chars-long'; @@ -21,6 +21,7 @@ beforeEach(() => { process.env.GEMINI_API_KEY = 'test-gemini-key'; process.env.KALEMAT_API_KEY = 'test-kalemat-key'; process.env.USUL_API_TOKEN = 'test-usul-token'; + process.env.ENVIRONMENT = 'development'; process.env.LEADERBOARD_API_KEY = API_KEY; // Inkling (issue #74) is opt-in per test; default = unset. delete process.env.TINKER_API_KEY; @@ -318,6 +319,119 @@ describe('POST /v1/chat/completions', () => { }); }); +// Issue #403: the length cap is per role. An assistant message is one of Ansari's +// own answers replayed as history, and those run past 8,000 characters (taqwabench's +// JaleesBench run lost two conversations to the old flat cap), so it may be up to +// 32,000; user and system messages keep 8,000. The 400 names the message and the limit. +describe('message length caps (issue #403)', () => { + beforeEach(() => { + vi.clearAllMocks(); + setupSuccessfulMocks(); + }); + + const history = (assistantChars: number) => [ + { role: 'user', content: 'First question' }, + { role: 'assistant', content: 'a'.repeat(assistantChars) }, + { role: 'user', content: 'Follow-up' }, + ]; + + it.each([8001, 32000])('accepts an assistant message of %i characters and replays it whole', async (chars) => { + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const res = await POST(makeRequest({ messages: history(chars) }, AUTH)); + + expect(res.status).toBe(200); + const sent = mockRunFacilitator.mock.calls[0][0]; + expect(sent[1]).toEqual({ role: 'assistant', content: [{ type: 'text', text: 'a'.repeat(chars) }] }); + }); + + it('refuses an assistant message of 32,001 characters, naming the message and the limit', async () => { + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const res = await POST(makeRequest({ messages: history(32001) }, AUTH)); + + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ + error: { + message: + 'messages.1.content: this assistant message is 32001 characters long; the limit for assistant messages is 32000', + type: 'invalid_request_error', + code: 'invalid_body', + }, + }); + expect(mockRunFacilitator).not.toHaveBeenCalled(); + expect(mockCreateThread).not.toHaveBeenCalled(); + expect(mockCreateMessage).not.toHaveBeenCalled(); + }); + + it.each(['user', 'system'])('a %s message keeps the 8,000 cap: 8,000 passes, 8,001 is refused', async (role) => { + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const messages = (chars: number) => [ + { role, content: 'a'.repeat(chars) }, + { role: 'user', content: 'Question' }, + ]; + + expect((await POST(makeRequest({ messages: messages(8000) }, AUTH))).status).toBe(200); + + const res = await POST(makeRequest({ messages: messages(8001) }, AUTH)); + expect(res.status).toBe(400); + expect((await res.json()).error.message).toBe( + `messages.0.content: this ${role} message is 8001 characters long; the limit for ${role} messages is 8000` + ); + }); + + it('reports every over-long message, each with its own index and limit', async () => { + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const res = await POST( + makeRequest( + { + messages: [ + { role: 'user', content: 'a'.repeat(9000) }, + { role: 'assistant', content: 'a'.repeat(40000) }, + { role: 'user', content: 'Follow-up' }, + ], + }, + AUTH + ) + ); + + expect(res.status).toBe(400); + expect((await res.json()).error.message).toBe( + 'messages.0.content: this user message is 9000 characters long; the limit for user messages is 8000; ' + + 'messages.1.content: this assistant message is 40000 characters long; the limit for assistant messages is 32000' + ); + }); + + // The production bundle drops the step that installs the library's default + // messages, and every 400 without wording of its own then read "Invalid input" + // (seen on staging). The route passes the messages to the parse itself, so the + // text does not depend on that default. Removed here to stand in for the bundle. + it('says what is wrong with a field even when the library has no default messages', async () => { + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const { z } = await import('zod'); + const installed = z.config().localeError; + z.config({ localeError: () => undefined }); + try { + const bare = z.string().safeParse(1); + expect(bare.error?.issues[0].message).toBe('Invalid input'); + + const res = await POST(makeRequest({ messages: [{ role: 'tool', content: 'x' }] }, AUTH)); + expect(res.status).toBe(400); + expect((await res.json()).error.message).toBe( + 'messages.0.role: Invalid option: expected one of "system"|"user"|"assistant"' + ); + } finally { + z.config({ localeError: installed }); + } + }); + + it('refuses an empty message in plain words', async () => { + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const res = await POST(makeRequest({ messages: [{ role: 'user', content: '' }] }, AUTH)); + + expect(res.status).toBe(400); + expect((await res.json()).error.message).toBe('messages.0.content: must not be empty'); + }); +}); + describe('model routing (issue #74)', () => { beforeEach(() => { vi.clearAllMocks(); @@ -410,3 +524,74 @@ describe('GET /v1/chat/completions (health check)', () => { expect(body.name).toBe('ansari-facilitator'); }); }); + +// Issue #400: a request whose history is at or over the block threshold is refused +// as invalid input, in the OpenAI error shape, before anything is saved and with no +// model call. No warning is ever appended: it would corrupt a benchmark answer. +describe('thread history limit (issue #400)', () => { + async function withThresholds(warn: number, block: number) { + vi.stubEnv('THREAD_HISTORY_WARN_TOKENS', String(warn)); + vi.stubEnv('THREAD_HISTORY_BLOCK_TOKENS', String(block)); + (await import('@/lib/config')).resetEnvCache(); + } + + beforeEach(() => { + vi.clearAllMocks(); + setupSuccessfulMocks('B'); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(async () => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + (await import('@/lib/config')).resetEnvCache(); + }); + + it('at the block threshold: 400 context_length_exceeded, nothing saved, no model call', async () => { + await withThresholds(100, 200); + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const { HISTORY_REQUEST_TOO_LONG_MESSAGE } = await import('@/lib/facilitator/history-limit'); + const res = await POST(makeRequest({ messages: [{ role: 'user', content: 'a'.repeat(800) }] }, AUTH)); + + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ + error: { + message: HISTORY_REQUEST_TOO_LONG_MESSAGE, + type: 'invalid_request_error', + code: 'context_length_exceeded', + }, + }); + expect(mockRunFacilitator).not.toHaveBeenCalled(); + expect(mockCreateThread).not.toHaveBeenCalled(); + expect(mockCreateMessage).not.toHaveBeenCalled(); + }); + + it('system messages count: they are sent to the model with the first user message', async () => { + await withThresholds(100, 200); + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const res = await POST( + makeRequest( + { + messages: [ + { role: 'system', content: 'a'.repeat(800) }, + { role: 'user', content: 'Q' }, + ], + }, + AUTH + ) + ); + + expect(res.status).toBe(400); + expect((await res.json()).error.code).toBe('context_length_exceeded'); + }); + + it('between the warn and block thresholds: the answer is returned exactly, with no notice', async () => { + await withThresholds(100, 2000); + const { POST } = await import('../src/app/api/v1/chat/completions/route'); + const res = await POST(makeRequest({ messages: [{ role: 'user', content: 'a'.repeat(800) }] }, AUTH)); + + expect(res.status).toBe(200); + expect((await res.json()).choices[0].message.content).toBe('B'); + expect(mockRunFacilitator).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/tests/release-doc.test.ts b/apps/api/tests/release-doc.test.ts index 095622f0..d75fa16e 100644 --- a/apps/api/tests/release-doc.test.ts +++ b/apps/api/tests/release-doc.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -125,6 +125,70 @@ describe('RELEASE.md consistency', () => { expect(existsSync(resolve(apiDir, 'scripts/grant-admin.ts'))).toBe(false); }); + describe('Railway service records match the RELEASE.md block', () => { + // The tomls are not read by Railway; RELEASE.md and the tomls are two records of + // one dashboard, so each toml's Dockerfile, watch paths and health check must + // appear in RELEASE.md exactly. Service names are the RELEASE.md (dashboard) names. + const services: Record = { + backend: 'apps/api/railway.toml', + frontend: 'apps/frontend/railway.toml', + auth: 'apps/auth/railway.toml', + whatsapp: 'legacy/whatsapp/railway.toml', + // The TypeScript port (#358). It has its own name until cutover, because both services exist side by side until then. + 'whatsapp-ts': 'apps/whatsapp/railway.toml', + mcp: 'apps/mcp/railway.toml', + }; + + function readToml(rel: string) { + // Comments dropped first, so a commented-out pattern never counts. + const text = readFileSync(resolve(repoRoot, rel), 'utf8').replace(/#.*$/gm, ''); + const value = (key: string) => text.match(new RegExp(`^${key} = "([^"]*)"`, 'm'))?.[1]; + const block = text.match(/^watchPatterns = \[([\s\S]*?)\]/m)?.[1] ?? ''; + return { + dockerfilePath: value('dockerfilePath'), + healthcheckPath: value('healthcheckPath'), + watchPatterns: [...block.matchAll(/"([^"]+)"/g)].map((m) => m[1]), + restart: value('restartPolicyType'), + }; + } + + it('lists every railway.toml in the repo', () => { + const tomls = ['apps', 'legacy'] + .flatMap((dir) => readdirSync(resolve(repoRoot, dir)).map((name) => `${dir}/${name}/railway.toml`)) + .filter((rel) => existsSync(resolve(repoRoot, rel))); + expect(tomls.sort()).toEqual(Object.values(services).sort()); + }); + + for (const [service, rel] of Object.entries(services)) { + it(`${service}: Dockerfile row, watch-path line and health check match ${rel}`, () => { + const toml = readToml(rel); + expect(toml.dockerfilePath).toBeTruthy(); + expect(toml.restart).toBe('ON_FAILURE'); + const dockerfile = toml.dockerfilePath!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + expect(doc).toMatch(new RegExp(`^> \\| ${service}( \\(web\\))? \\| \`${dockerfile}\` \\|$`, 'm')); + + const line = doc.match(new RegExp(`^> ${service}:(.*)$`, 'm'))?.[1]; + expect(line, `no watch-path line for ${service}`).toBeDefined(); + expect(line!.trim().split(/\s+/)).toEqual(toml.watchPatterns); + + // The deploy-settings sentence wraps across quoted lines; read it as one line. + expect(doc.replace(/\n> /g, ' ')).toContain(`${service} healthcheck \`${toml.healthcheckPath}\``); + }); + } + + it('records the mcp staging environment (issue #364)', () => { + expect(doc).toContain('| `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai`'); + expect(doc).toContain('| `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai`'); + expect(doc).toContain('| `ANSARI_CLIENT` | `ansari-mcp-staging` |'); + // The release maps the platform's commit in the dashboard, never in code (#377). + expect(doc).toContain('| `ANSARI_RELEASE` | `${{RAILWAY_GIT_COMMIT_SHA}}`'); + expect(doc).not.toContain('`ANSARI_RELEASE` is **not** set'); + expect(doc).not.toContain('falls back to `RAILWAY_GIT_COMMIT_SHA`'); + expect(doc).toContain('`https:///mcp`'); + expect(doc.replace(/\n> /g, ' ')).toContain('set `PORT=3000` as a service variable so Railway does not assign its own'); + }); + }); + it('pins exactly the two production health-check domains', () => { expect(doc).toContain('https://api.askansari.ai/api/health'); expect(doc).toContain('https://api-35.ansari.chat/api/health'); diff --git a/apps/api/tests/route-persistence-rollback.test.ts b/apps/api/tests/route-persistence-rollback.test.ts index 1c90fd16..25442455 100644 --- a/apps/api/tests/route-persistence-rollback.test.ts +++ b/apps/api/tests/route-persistence-rollback.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; import { NextRequest } from 'next/server'; // Issue #20 (PR #26): the first real Executor consumers. Both ingestion routes @@ -43,9 +43,18 @@ vi.mock('@/lib/rate-limit', () => ({ })); const API_KEY = 'rollback-test-leaderboard-key-at-least-32-chars'; -vi.mock('@/lib/config', () => ({ - config: { leaderboard: { apiKey: 'rollback-test-leaderboard-key-at-least-32-chars' } }, -})); +vi.mock('@/lib/config', async () => { + // mcp-complete's key gate (#314) reads authService and mcpCompleteKeyMode. + const { MCP_KEY_CONFIG } = await import('./helpers/mcp-key'); + return { + config: { + leaderboard: { apiKey: 'rollback-test-leaderboard-key-at-least-32-chars' }, + // Both routes check the thread history limit (#400) before they persist. + threadHistory: { warnTokens: 150000, blockTokens: 200000 }, + ...MCP_KEY_CONFIG, + }, + }; +}); vi.mock('@/lib/ai/inkling-client', () => ({ isInklingConfigured: () => false, @@ -56,6 +65,7 @@ import { drizzle } from 'drizzle-orm/pglite'; import * as schema from '@/db/schema'; import { POST as mcpPost } from '../src/app/api/v2/mcp-complete/route'; import { POST as chatPost } from '../src/app/api/v1/chat/completions/route'; +import { installMcpKeyStub, withMcpKey } from './helpers/mcp-key'; let client: PGlite; @@ -114,6 +124,14 @@ afterAll(async () => { await client.close(); }); +beforeEach(async () => { + await installMcpKeyStub({ env: false }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + beforeEach(async () => { vi.clearAllMocks(); mockRunFacilitator.mockImplementation(() => facilitatorEmits('A fine answer.')); @@ -129,7 +147,7 @@ describe('POST /api/v2/mcp-complete — atomic inbound persistence', () => { function makeRequest(messages: Array<{ role: string; content: string }>): NextRequest { return new NextRequest('http://localhost/api/v2/mcp-complete', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: withMcpKey({ 'Content-Type': 'application/json' }), body: JSON.stringify({ messages }), }); } diff --git a/apps/api/tests/self-hosting-docs.test.ts b/apps/api/tests/self-hosting-docs.test.ts index 460dba7e..bc3713f1 100644 --- a/apps/api/tests/self-hosting-docs.test.ts +++ b/apps/api/tests/self-hosting-docs.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { existsSync, readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { limits } from '../../../packages/auth/src'; +import { envSchema } from '@/lib/config'; /** * docs/self-hosting.md against the code (issue #21; spec 300 amendment H-7). @@ -84,3 +85,12 @@ describe('self-hosting docs: service keys and the WhatsApp exchange (spec 329)', expect(doc).toMatch(/refuses to start when the auth database lacks `auth\.apikey`/); }); }); + +describe('self-hosting docs: the env surface', () => { + // Every variable apps/api's Zod schema reads is a documented one: a new + // setting (MCP_COMPLETE_KEY_MODE, #314) cannot ship without its docs row. + it('names every variable in the apps/api config schema', () => { + const undocumented = Object.keys(envSchema.shape).filter((name) => !doc.includes(`\`${name}\``)); + expect(undocumented).toEqual([]); + }); +}); diff --git a/apps/api/tests/sentry-environment.test.ts b/apps/api/tests/sentry-environment.test.ts new file mode 100644 index 00000000..d5bc2885 --- /dev/null +++ b/apps/api/tests/sentry-environment.test.ts @@ -0,0 +1,43 @@ +// apps/api's Sentry environment is ENVIRONMENT (#314 Amendment 3), as apps/auth's +// is (apps/auth/tests/environment.test.ts): never Railway's RAILWAY_ENVIRONMENT +// (owner directive: our own names only) and never NODE_ENV, which is +// `production` on staging too. The file is read as text: it is a side-effect +// module that calls Sentry.init, and boot-check.test.ts mocks it away. +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +import { describe, expect, it } from 'vitest'; + +const config = readFileSync(fileURLToPath(new URL('../sentry.server.config.ts', import.meta.url)), 'utf8'); + +/** A READ of a RAILWAY_* variable (a comment naming one is fine). */ +const RAILWAY_READ = /process\.env\.RAILWAY_|process\.env\[\s*['"`]RAILWAY_/; + +/** The problems with a Sentry server config's environment; empty when it is right. */ +function environmentProblems(source: string): string[] { + const line = source.split('\n').find((l) => /^\s*environment\s*:/.test(l)); + const problems: string[] = []; + if (line === undefined) return ['no environment line']; + if (!line.includes('process.env.ENVIRONMENT')) problems.push('environment is not process.env.ENVIRONMENT'); + if (/NODE_ENV/.test(line)) problems.push('environment reads NODE_ENV'); + if (RAILWAY_READ.test(source)) problems.push('reads a RAILWAY_* variable'); + return problems; +} + +describe('sentry.server.config.ts environment', () => { + it('is process.env.ENVIRONMENT, with no NODE_ENV and no RAILWAY_* read', () => { + expect(environmentProblems(config)).toEqual([]); + }); + + it('the check bites on planted configs, and passes a comment that names the old variable', () => { + const planted = (environment: string, extra = '') => `Sentry.init({\n${extra} environment: ${environment},\n});\n`; + expect(environmentProblems(planted('process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV'))).toEqual([ + 'environment is not process.env.ENVIRONMENT', + 'environment reads NODE_ENV', + 'reads a RAILWAY_* variable', + ]); + expect(environmentProblems(planted('process.env.NODE_ENV'))).toContain('environment reads NODE_ENV'); + expect(environmentProblems(planted("process.env['RAILWAY_ENVIRONMENT']"))).toContain('reads a RAILWAY_* variable'); + expect(environmentProblems(planted('process.env.ENVIRONMENT', ' // not RAILWAY_ENVIRONMENT (#314)\n'))).toEqual([]); + }); +}); diff --git a/apps/api/tests/skill-docs.test.ts b/apps/api/tests/skill-docs.test.ts new file mode 100644 index 00000000..fec5f4a6 --- /dev/null +++ b/apps/api/tests/skill-docs.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest'; +import { existsSync, readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { parse } from 'yaml'; + +/** + * skills/ansari/SKILL.md, the public Ansari agent skill (#409). It must call the + * MCP server (mcp.askansari.ai/mcp), which holds the ansari-mcp key, and never + * apps/api's /api/v2/mcp-complete, which refuses a keyless call once it + * enforces (#314). A skill is public, so it can never carry a key either. + * skills/ stays outside the pnpm workspace. + * + * The checks are one function so the known-bad case below proves each fails. + */ + +const repoRoot = resolve(__dirname, '../../..'); +const skillDir = resolve(repoRoot, 'skills/ansari'); +const MCP_URL = 'https://mcp.askansari.ai/mcp'; + +function skillProblems(text: string, dirName: string): string[] { + const problems: string[] = []; + const match = /^---\n([\s\S]*?)\n---\n/.exec(text); + if (!match) return ['no frontmatter']; + let fm: Record; + try { + fm = parse(match[1]) as Record; + } catch { + return ['frontmatter is not YAML']; + } + const body = text.slice(match[0].length); + + // Agent Skills specification (agentskills.io/specification). + const name = fm.name; + if (typeof name !== 'string' || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name) || name.length > 64) problems.push('invalid name'); + if (name !== dirName) problems.push('name does not match its directory'); + const description = fm.description; + if (typeof description !== 'string' || description.trim().length === 0 || description.length > 1024) problems.push('invalid description'); + if (fm.compatibility !== undefined && (typeof fm.compatibility !== 'string' || fm.compatibility.length > 500)) problems.push('invalid compatibility'); + const metadata = fm.metadata; + if (metadata !== undefined && (typeof metadata !== 'object' || metadata === null || Object.values(metadata).some((v) => typeof v !== 'string'))) { + problems.push('metadata values must be strings'); + } + + // The one host it may reach is the MCP server. + const runtime = fm.runtime as { network?: { allowed_domains?: unknown } } | undefined; + if (JSON.stringify(runtime?.network?.allowed_domains) !== JSON.stringify(['mcp.askansari.ai'])) problems.push('allowed_domains is not exactly mcp.askansari.ai'); + if (!body.includes(`curl -sS --max-time 90 -X POST '${MCP_URL}'`)) problems.push('no curl to the MCP endpoint'); + if (!body.includes("-H 'Accept: application/json, text/event-stream'")) problems.push('no Accept header for both response types'); + if (!body.includes('answer_islamic_question')) problems.push('does not name the MCP tool'); + if (/api\.askansari\.ai|mcp-staging\.askansari\.ai/.test(text)) problems.push('names another host'); + // Owner's decision (2026-11-25): askansari.ai only, so no ansari.chat host anywhere (api., mcp. or the site). + if (/ansari\.chat/.test(text)) problems.push('names an ansari.chat host'); + if (/mcp-complete|\/api\/v2\//.test(text)) problems.push('calls apps/api'); + + // No authentication claims, no attribution header the MCP server drops, no credentials. + if (/no authentication|requires no auth|no api key is needed/i.test(text)) problems.push('claims no authentication'); + if (/x-ansari-client/i.test(text)) problems.push('sends X-Ansari-Client'); + if (/ansari_[a-z]+_(development|staging|production)_|authorization:|bearer /i.test(text)) problems.push('carries a credential'); + + // The question goes in through a quoted heredoc only, never into the command. + if (!body.includes("<<'ANSARI_QUESTION_END' |\nQUESTION GOES HERE\nANSARI_QUESTION_END\n")) problems.push('question is not passed through the quoted heredoc'); + return problems; +} + +describe('Ansari agent skill (skills/ansari)', () => { + const skill = readFileSync(resolve(skillDir, 'SKILL.md'), 'utf8'); + + it('is a valid skill that calls only the MCP server, with no credential or no-auth claim', () => { + expect(skillProblems(skill, 'ansari')).toEqual([]); + }); + + it('the checks fail on the old skill text (api.askansari.ai/api/v2/mcp-complete, no authentication)', () => { + const old = [ + '---', + 'name: ansari', + 'description: Islamic questions.', + 'metadata:', + ' version: 3.4', + ' website: https://ansari.chat', + 'runtime:', + ' network:', + ' allowed_domains:', + ' - api.askansari.ai', + '---', + 'Answer Islamic questions by calling the Ansari API. The API requires no authentication.', + "curl -s -X POST 'https://api.askansari.ai/api/v2/mcp-complete' \\", + " -H 'X-Ansari-Client: ansari-skill' \\", + ` -d '{"messages": [{"role": "user", "content": "USER_QUESTION_HERE"}]}'`, + '', + ].join('\n'); + expect(skillProblems(old, 'ansari')).toEqual([ + 'metadata values must be strings', + 'allowed_domains is not exactly mcp.askansari.ai', + 'no curl to the MCP endpoint', + 'no Accept header for both response types', + 'does not name the MCP tool', + 'names another host', + 'names an ansari.chat host', + 'calls apps/api', + 'claims no authentication', + 'sends X-Ansari-Client', + 'question is not passed through the quoted heredoc', + ]); + // Each near-miss is caught on its own. + expect(skillProblems(skill.replace(/mcp\.askansari\.ai/g, 'mcp.ansari.chat'), 'ansari')).toContain('names an ansari.chat host'); + expect(skillProblems(skill.replace('(https://askansari.ai)', '(https://ansari.chat)'), 'ansari')).toEqual(['names an ansari.chat host']); + expect(skillProblems(skill + '\nhttps://mcp-staging.askansari.ai/mcp\n', 'ansari')).toEqual(['names another host']); + expect(skillProblems(skill + '\nPOST /api/v2/mcp-complete\n', 'ansari')).toContain('calls apps/api'); + expect(skillProblems(skill + '\nAuthorization: Bearer x\n', 'ansari')).toContain('carries a credential'); + expect(skillProblems(skill + '\nThe API requires no authentication.\n', 'ansari')).toEqual(['claims no authentication']); + expect(skillProblems(skill, 'ansari-skill')).toContain('name does not match its directory'); + expect(skillProblems(skill.replace('---\nname: ansari', '---\nname: [ansari'), 'ansari')).toEqual(['frontmatter is not YAML']); + }); + + it('stays outside the pnpm workspace', () => { + expect(existsSync(resolve(repoRoot, 'skills/package.json'))).toBe(false); + expect(existsSync(resolve(skillDir, 'package.json'))).toBe(false); + const workspace = parse(readFileSync(resolve(repoRoot, 'pnpm-workspace.yaml'), 'utf8')) as { packages: string[] }; + expect(workspace.packages.every((p) => !p.startsWith('skills'))).toBe(true); + }); +}); diff --git a/apps/api/tests/source-scan/facilitator-model-pin.test.ts b/apps/api/tests/source-scan/facilitator-model-pin.test.ts new file mode 100644 index 00000000..bc9720e9 --- /dev/null +++ b/apps/api/tests/source-scan/facilitator-model-pin.test.ts @@ -0,0 +1,275 @@ +// Source scan for issue #393. `runFacilitator` takes a `model` option that pins a request +// to one Gemini model with cross-model failover and Inkling escalation switched off. It +// exists for the evaluation harness (apps/eval) only. A route that passed it would +// take a user's request out of the production failover path, so no route may. +// +// The scan reads code through the TypeScript parser (comments and strings never count), +// is proven on planted lines and near-misses before it is trusted on the tree, and +// asserts a floor on what it walked, so an empty walk or a renamed function cannot pass. +import { describe, expect, it } from 'vitest'; +import ts from 'typescript'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { REPO_ROOT, readSource, sourceFiles } from './scan'; + +function parse(source: string): ts.SourceFile { + return ts.createSourceFile('scan.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +} + +/** Every name `runFacilitator` goes by in a file: itself, and any `import { runFacilitator as x }`. */ +function facilitatorNames(file: ts.SourceFile): Set { + const names = new Set(['runFacilitator']); + const visit = (node: ts.Node): void => { + if (ts.isImportSpecifier(node) && node.propertyName?.text === 'runFacilitator') names.add(node.name.text); + ts.forEachChild(node, visit); + }; + visit(file); + return names; +} + +const propertyName = (name: ts.PropertyName): string | null => + ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name) + ? name.text + : ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression) + ? name.expression.text + : null; + +export interface FacilitatorCallScan { + /** How many `runFacilitator(...)` calls the file makes. */ + calls: number; + /** Why a call is refused, one entry per offending call. */ + hits: string[]; +} + +/** + * Calls of `runFacilitator` whose options could carry `model`. The rule is strict so that + * it fails loudly: the third argument must be absent, or an object literal written at the + * call, with no `model` key, no spread and no key the scan cannot read. Options built + * elsewhere (a variable, a spread) are refused, because the scan cannot see inside them. + */ +export function facilitatorModelHits(source: string): FacilitatorCallScan { + const file = parse(source); + const names = facilitatorNames(file); + const out: FacilitatorCallScan = { calls: 0, hits: [] }; + const visit = (node: ts.Node): void => { + if (ts.isCallExpression(node)) { + const callee = node.expression; + const called = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : null; + if (called !== null && names.has(called)) { + out.calls++; + const options = node.arguments[2]; + const text = node.getText(file).replace(/\s+/g, ' ').slice(0, 120); + if (node.arguments.some((a) => ts.isSpreadElement(a))) { + out.hits.push(`spread arguments: ${text}`); + } else if (options !== undefined) { + if (!ts.isObjectLiteralExpression(options)) { + out.hits.push(`options are not written at the call: ${text}`); + } else { + for (const property of options.properties) { + if (ts.isSpreadAssignment(property)) { + out.hits.push(`options spread another object: ${text}`); + continue; + } + const key = property.name ? propertyName(property.name) : null; + if (key === null) out.hits.push(`an option key the scan cannot read: ${text}`); + else if (key === 'model') out.hits.push(`passes \`model\`: ${text}`); + } + } + } + } + } + ts.forEachChild(node, visit); + }; + visit(file); + return out; +} + +/** + * Import or require specifiers that reach into the evaluation harness: a path with an + * `eval` directory in it (apps/eval is `../../eval` from apps/api/lib), or the harness's + * package name, `ansari-eval`. + */ +export function evalImportHits(source: string): string[] { + const hits: string[] = []; + const inEval = (specifier: string) => /(^|\/)(ansari-)?eval(\/|$)/.test(specifier); + const visit = (node: ts.Node): void => { + if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + if (inEval(node.moduleSpecifier.text)) hits.push(node.moduleSpecifier.text); + } else if ( + ts.isCallExpression(node) && + (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === 'require')) && + node.arguments.length > 0 && + ts.isStringLiteralLike(node.arguments[0]) && + inEval(node.arguments[0].text) + ) { + hits.push(node.arguments[0].text); + } + ts.forEachChild(node, visit); + }; + visit(parse(source)); + return hits; +} + +/** A file of the harness, where it lives since issue #397. */ +const HARNESS_FILE = 'apps/eval/lib/score.ts'; + +/** Would this Docker COPY source or deploy watch pattern take in a file of the harness? */ +export function reachesHarness(pattern: string): boolean { + const glob = pattern.replace(/^(\.?\/)+/, '').replace(/\/+$/, ''); + if (glob === '' || glob === '.') return true; + const body = glob + .replace(/[.+^${}()|[\]\\]/g, '\\$&') + .replace(/\*\*/g, '\0') + .replace(/\*/g, '[^/]*') + .replace(/\0/g, '.*'); + return new RegExp(`^${body}(/.*)?$`).test(HARNESS_FILE); +} + +const IMPORT = "import { runFacilitator } from '@/lib/facilitator/agent';\n"; + +describe('no route pins a request to a model (issue #393)', () => { + it('catches planted lines', () => { + for (const bad of [ + "for await (const e of runFacilitator(history, undefined, { model: 'gemini-4-argon' })) {}", + 'runFacilitator(history, undefined, { model });', + 'runFacilitator(history, onMessage, { provider, model: body.model });', + "runFacilitator(history, undefined, { 'model': chosen });", + "runFacilitator(history, undefined, { ['model']: chosen });", + // Options the scan cannot see inside are refused too. + 'runFacilitator(history, undefined, { ...requestOptions });', + 'runFacilitator(history, undefined, options);', + 'runFacilitator(history, undefined, { [key]: value });', + 'runFacilitator(...args);', + // Called through a namespace, and under another name. + "facilitator.runFacilitator(history, undefined, { model: 'x' });", + ]) { + const scan = facilitatorModelHits(IMPORT + bad); + expect(scan.calls, bad).toBe(1); + expect(scan.hits, bad).toHaveLength(1); + } + const aliased = "import { runFacilitator as run } from '@/lib/facilitator/agent';\nrun(history, undefined, { model: 'x' });"; + expect(facilitatorModelHits(aliased)).toMatchObject({ calls: 1, hits: [expect.stringContaining('passes `model`')] }); + }); + + it('passes near-misses', () => { + for (const fine of [ + // The calls the routes make today. + 'for await (const event of runFacilitator(messageHistory)) {}', + 'for await (const event of runFacilitator(messages, undefined, { provider })) {}', + "runFacilitator(messages, onMessage, { provider: 'inkling' });", + // `model` somewhere else: another function's options, another key, a variable. + "streamGemini(contents, { model: 'gemini-3.7-flash' }); runFacilitator(messages);", + 'const model = config.gemini.model; runFacilitator(messages, undefined, { provider });', + 'runFacilitator(messages, undefined, { modelFamily, provider });', + // In a comment or a string, it is not code. + "// runFacilitator(history, undefined, { model: 'x' })\nrunFacilitator(history);", + 'const doc = "runFacilitator(history, undefined, { model })"; runFacilitator(history);', + ]) { + const scan = facilitatorModelHits(IMPORT + fine); + expect(scan.calls, fine).toBe(1); + expect(scan.hits, fine).toEqual([]); + } + // A file that never calls it has nothing to report. + expect(facilitatorModelHits('export const model = 1;')).toEqual({ calls: 0, hits: [] }); + }); + + it('holds on apps/api/src: every runFacilitator call is found, and none can carry `model`', () => { + const files = sourceFiles('apps/api/src'); + const routes = files.filter((f) => f.split('\\').join('/').startsWith('apps/api/src/app/api/')); + let calls = 0; + const hits: Record = {}; + for (const file of files) { + const scan = facilitatorModelHits(readSource(file)); + calls += scan.calls; + if (scan.hits.length > 0) hits[file] = scan.hits; + } + console.info( + `[source-scan] facilitator model pin: ${Object.values(hits).flat().length} hits, ${calls} runFacilitator calls, ${files.length} files (${routes.length} under src/app/api)`, + ); + // Floors: the walk reached the routes, and the scan recognised the calls they make + // (chat, thread, mcp-complete and the OpenAI-compatible route). If runFacilitator is + // renamed or wrapped, this fails rather than passing on zero calls. + expect(routes.length).toBeGreaterThanOrEqual(20); + expect(calls).toBeGreaterThanOrEqual(4); + expect(hits).toEqual({}); + }); +}); + +describe('the app does not import the evaluation harness (issues #393, #397)', () => { + it('catches planted lines', () => { + for (const bad of [ + // By path. The harness is apps/eval: `../../eval` from apps/api/lib or db, deeper from src. + "import { scoreRun } from '../../eval/lib/score';", + "import { scoreRun } from '@/eval/lib/score';", + "export { runJobs } from '../eval/lib/runner';", + "const { scoreRun } = await import('../../../eval/lib/score');", + "const prices = require('../../eval/models.json');", + "import { scoreRun } from '../../../../apps/eval/lib/score';", + // By package name. + "import { scoreRun } from 'ansari-eval/lib/score';", + "const harness = await import('ansari-eval');", + ]) { + expect(evalImportHits(bad), bad).toHaveLength(1); + } + }); + + it('passes near-misses', () => { + for (const fine of [ + "import { evaluate } from '@/lib/evaluation/rules';", + "import { retrieval } from './retrieval';", + "import medieval from 'medieval-names';", + "import { rules } from 'ansari-evaluation';", + "import { rules } from '@/lib/ansari-evals/rules';", + "// import { scoreRun } from '../../eval/lib/score';", + "const path = '../../eval/lib/score';", + ]) { + expect(evalImportHits(fine), fine).toEqual([]); + } + }); + + it('holds on apps/api/src, lib and db', () => { + const files = [...sourceFiles('apps/api/src'), ...sourceFiles('apps/api/lib'), ...sourceFiles('apps/api/db')]; + const hits: Record = {}; + for (const file of files) { + const found = evalImportHits(readSource(file)); + if (found.length > 0) hits[file] = found; + } + console.info(`[source-scan] eval imports: ${Object.values(hits).flat().length} hits in ${files.length} files`); + expect(files.length).toBeGreaterThanOrEqual(60); + expect(hits).toEqual({}); + }); + + // Issue #397: the harness left apps/api so that it is not in the api image + // (`COPY apps/api apps/api`) and an eval-only edit does not redeploy the api + // (watch pattern `apps/api/**`). The Dockerfile decides the first. For the second, + // railway.toml is the reviewable record; the live patterns are in the Railway dashboard. + it('tells a COPY source or watch pattern that takes in the harness from one that does not', () => { + for (const bad of ['.', './', 'apps', './apps/', 'apps/eval', 'apps/eval/', 'apps/**', 'apps/*', '**', 'apps/eval/lib/*.ts']) { + expect(reachesHarness(bad), bad).toBe(true); + } + for (const fine of ['apps/api', 'apps/api/**', 'apps/api/package.json', 'packages', 'packages/**', 'package.json', 'apps/evaluation/**', 'eval/**']) { + expect(reachesHarness(fine), fine).toBe(false); + } + }); + + it('is outside what the api image copies and what the api deploy watches', () => { + expect(existsSync(path.join(REPO_ROOT, 'apps/api/eval'))).toBe(false); + expect(existsSync(path.join(REPO_ROOT, HARNESS_FILE))).toBe(true); + const manifest = JSON.parse(readSource('apps/api/package.json')) as Record | undefined>; + expect({ ...manifest.dependencies, ...manifest.devDependencies }).not.toHaveProperty('ansari-eval'); + + // The COPY reader takes one line per instruction. A continued or heredoc COPY + // would be read in part, so it is refused rather than half-checked. + const dockerfile = readSource('apps/api/Dockerfile'); + expect(dockerfile).not.toMatch(/^COPY\b.*(\\|<<)/m); + const copied = [...dockerfile.matchAll(/^COPY\s+(.+)$/gm)].flatMap((m) => m[1].trim().split(/\s+/).slice(0, -1)); + const watchList = readSource('apps/api/railway.toml').match(/^watchPatterns = \[([\s\S]*?)^\]/m); + const watched = [...(watchList?.[1] ?? '').matchAll(/^\s*"([^"]+)"/gm)].map((m) => m[1]); + const reaching = [...copied, ...watched].filter(reachesHarness); + console.info(`[source-scan] api image: ${reaching.length} of ${copied.length} COPY sources and ${watched.length} watch patterns take in apps/eval`); + // Floors: both lists were read, and each still names the app itself. + expect(copied).toContain('apps/api'); + expect(watched).toContain('apps/api/**'); + expect(reaching).toEqual([]); + }); +}); diff --git a/apps/api/tests/source-scan/history-limit-coverage.test.ts b/apps/api/tests/source-scan/history-limit-coverage.test.ts new file mode 100644 index 00000000..c4929b0c --- /dev/null +++ b/apps/api/tests/source-scan/history-limit-coverage.test.ts @@ -0,0 +1,162 @@ +// Source scan for issue #400. The thread history limit is applied by the routes, not +// inside `runFacilitator` (lib/facilitator/history-limit.ts says why), so a route that +// called the facilitator without it would send an unbounded history to the model again. +// Every `runFacilitator(...)` call under apps/api/src must therefore be covered, one of +// two ways: +// - it is made inside a `limitThreadTurn(...)` call (the thread routes: warn and block +// arrive as part of the answer), or +// - its file also calls `assessHistory(...)` (the stateless routes: 400 on block). +// +// The scan reads code through the TypeScript parser (comments and strings never count), +// is proven on planted lines and near-misses before it is trusted on the tree, and +// asserts floors on what it walked, so an empty walk or a renamed function cannot pass. +import { describe, expect, it } from 'vitest'; +import ts from 'typescript'; +import { readSource, sourceFiles } from './scan'; + +function parse(source: string): ts.SourceFile { + return ts.createSourceFile('scan.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +} + +const AGENT_FUNCTION = 'runFacilitator'; +const LIMIT_FUNCTIONS = ['limitThreadTurn', 'assessHistory'] as const; +type LimitFunction = (typeof LIMIT_FUNCTIONS)[number]; + +/** Every name the three functions go by in a file: themselves, and any `import { x as y }`. */ +function localNames(file: ts.SourceFile): Map { + const names = new Map([AGENT_FUNCTION, ...LIMIT_FUNCTIONS].map((name) => [name, name])); + const visit = (node: ts.Node): void => { + if (ts.isImportSpecifier(node) && node.propertyName && names.has(node.propertyName.text)) { + names.set(node.name.text, node.propertyName.text); + } + ts.forEachChild(node, visit); + }; + visit(file); + return names; +} + +export interface HistoryLimitScan { + /** `runFacilitator(...)` calls made inside a `limitThreadTurn(...)` call. */ + wrapped: number; + /** `runFacilitator(...)` calls outside one, in a file that calls `assessHistory(...)`. */ + assessed: number; + /** `runFacilitator(...)` calls with neither: one entry per offending call. */ + uncovered: string[]; +} + +export function historyLimitScan(source: string): HistoryLimitScan { + const file = parse(source); + const names = localNames(file); + const calledName = (node: ts.CallExpression): string | undefined => { + const callee = node.expression; + const text = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : null; + return text === null ? undefined : names.get(text); + }; + + const bare: string[] = []; + let wrapped = 0; + let assesses = false; + const visit = (node: ts.Node, insideLimit: boolean): void => { + if (ts.isCallExpression(node)) { + const called = calledName(node); + if (called === AGENT_FUNCTION) { + if (insideLimit) wrapped++; + else bare.push(node.getText(file).replace(/\s+/g, ' ').slice(0, 120)); + } else if ((called as LimitFunction) === 'assessHistory') { + assesses = true; + } else if ((called as LimitFunction) === 'limitThreadTurn') { + // Only the arguments are inside it: `limitThreadTurn(...)(runFacilitator())` is not. + visit(node.expression, insideLimit); + for (const argument of node.arguments) visit(argument, true); + return; + } + } + ts.forEachChild(node, (child) => visit(child, insideLimit)); + }; + visit(file, false); + + return assesses + ? { wrapped, assessed: bare.length, uncovered: [] } + : { wrapped, assessed: 0, uncovered: bare }; +} + +const IMPORTS = + "import { runFacilitator } from '@/lib/facilitator/agent';\n" + + "import { assessHistory, limitThreadTurn } from '@/lib/facilitator/history-limit';\n"; + +describe('every route that runs the facilitator applies the thread history limit (issue #400)', () => { + it('catches planted lines', () => { + for (const bad of [ + // The thread routes as they were before the limit. + 'for await (const event of runFacilitator(messageHistory)) {}', + 'for await (const event of runFacilitator(messages, undefined, { provider })) {}', + // The limit named but not applied: imported only, in a comment, in a string. + '// assessHistory(messages)\nrunFacilitator(messages);', + 'const doc = "limitThreadTurn(messages, id, () => runFacilitator(messages))"; runFacilitator(messages);', + // The wrapper called beside the facilitator rather than around it. + 'limitThreadTurn(messages, threadId, () => other()); for await (const e of runFacilitator(messages)) {}', + 'limitThreadTurn(messages, threadId, run)(runFacilitator(messages));', + // Through a namespace. + 'for await (const e of facilitator.runFacilitator(messages)) {}', + ]) { + const scan = historyLimitScan(IMPORTS + bad); + expect(scan.uncovered, bad).toHaveLength(1); + expect(scan.wrapped + scan.assessed, bad).toBe(0); + } + const aliased = "import { runFacilitator as run } from '@/lib/facilitator/agent';\nfor await (const e of run(messages)) {}"; + expect(historyLimitScan(aliased).uncovered).toHaveLength(1); + }); + + it('passes the covered forms', () => { + for (const fine of [ + // The thread routes. + 'const turn = limitThreadTurn(messageHistory, threadId, () => runFacilitator(messageHistory));', + 'for await (const e of limitThreadTurn(messages, id, function () { return runFacilitator(messages); })) {}', + ]) { + expect(historyLimitScan(IMPORTS + fine), fine).toEqual({ wrapped: 1, assessed: 0, uncovered: [] }); + } + for (const fine of [ + // The stateless routes: the verdict is checked, then the facilitator runs. + "if (assessHistory(messages).verdict === 'block') return refuse(); for await (const e of runFacilitator(messages)) {}", + 'const history = assessHistory(messages); runFacilitator(messages, undefined, { provider });', + ]) { + expect(historyLimitScan(IMPORTS + fine), fine).toEqual({ wrapped: 0, assessed: 1, uncovered: [] }); + } + const aliased = + "import { runFacilitator as run } from '@/lib/facilitator/agent';\n" + + "import { limitThreadTurn as limit } from '@/lib/facilitator/history-limit';\n" + + 'limit(messages, id, () => run(messages));'; + expect(historyLimitScan(aliased)).toEqual({ wrapped: 1, assessed: 0, uncovered: [] }); + // A file that never runs the facilitator has nothing to cover. + expect(historyLimitScan('export const limitThreadTurn = 1;')).toEqual({ wrapped: 0, assessed: 0, uncovered: [] }); + }); + + it('holds on apps/api/src: every runFacilitator call is covered', () => { + const files = sourceFiles('apps/api/src'); + const uncovered: Record = {}; + const wrappedIn: string[] = []; + const assessedIn: string[] = []; + for (const file of files) { + const scan = historyLimitScan(readSource(file)); + const posix = file.split('\\').join('/'); + if (scan.uncovered.length > 0) uncovered[posix] = scan.uncovered; + if (scan.wrapped > 0) wrappedIn.push(posix); + if (scan.assessed > 0) assessedIn.push(posix); + } + console.info( + `[source-scan] history limit: ${Object.values(uncovered).flat().length} uncovered, ` + + `${wrappedIn.length} files wrapped, ${assessedIn.length} files assessed, ${files.length} files`, + ); + // Floors: the scan recognised the calls the four routes make. If runFacilitator or + // the limit is renamed or moved, this fails rather than passing on zero calls. + expect(wrappedIn.sort()).toEqual([ + 'apps/api/src/app/api/v2/threads/[id]/chat/route.ts', + 'apps/api/src/app/api/v2/threads/[id]/route.ts', + ]); + expect(assessedIn.sort()).toEqual([ + 'apps/api/src/app/api/v1/chat/completions/route.ts', + 'apps/api/src/app/api/v2/mcp-complete/route.ts', + ]); + expect(uncovered).toEqual({}); + }); +}); diff --git a/apps/api/tests/source-scan/scan.ts b/apps/api/tests/source-scan/scan.ts index 12fbbe16..3033c23e 100644 --- a/apps/api/tests/source-scan/scan.ts +++ b/apps/api/tests/source-scan/scan.ts @@ -1,7 +1,7 @@ // Source scans for spec 300 (plan phase 9): the legacy auth model is gone from // runtime code and stays gone. The scanner reads code through the TypeScript // parser, so comments never count: a column named in a comment is not a query. -import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import path from 'node:path'; import ts from 'typescript'; @@ -173,3 +173,43 @@ export function whatsappHits(files: readonly { path: string; source: string }[]) } return hits; } + +// ── Scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12) ── + +/** + * Our code reads only our own names; the hosting platform's are mapped in its + * dashboard (owner, 2026-11-12, via main, #314). Any `RAILWAY_*` name in code + * counts, whatever the access path (`process.env.X`, `process.env['X']`, or a + * helper taking the name as a string, as apps/mcp's `setting(env, 'X')` does); + * comments do not, since docs explaining the rule name the variables. + */ +const RAILWAY_NAME = /\bRAILWAY_[A-Z0-9_]+\b/g; + +/** Each RAILWAY_* name the code (comments removed) mentions, in order. */ +export function railwayEnvHits(source: string): string[] { + return codeWithoutComments(source).match(RAILWAY_NAME) ?? []; +} + +/** + * The trees scan 6 covers (#377): every app's `src/` and `lib/`, and every + * package under `packages/`. A directory that does not exist is skipped, so + * a new app or package joins the scan without an edit here. + */ +export function railwayScanDirs(): string[] { + const dirs = (parent: string) => + readdirSync(path.join(REPO_ROOT, parent)) + .map((name) => path.join(parent, name)) + .filter((rel) => statSync(path.join(REPO_ROOT, rel)).isDirectory()); + const apps = dirs('apps').flatMap((app) => [path.join(app, 'src'), path.join(app, 'lib')]); + return [...apps, ...dirs('packages')].filter((rel) => existsSync(path.join(REPO_ROOT, rel))); +} + +/** Each file whose code names a RAILWAY_* variable, with the names it names. No file is exempt. */ +export function railwayTreeHits(files: readonly { path: string; source: string }[]): Record { + const hits: Record = {}; + for (const file of files) { + const found = railwayEnvHits(file.source); + if (found.length > 0) hits[file.path] = found; + } + return hits; +} diff --git a/apps/api/tests/source-scan/source-scan.test.ts b/apps/api/tests/source-scan/source-scan.test.ts index 71e03e5b..d40a0164 100644 --- a/apps/api/tests/source-scan/source-scan.test.ts +++ b/apps/api/tests/source-scan/source-scan.test.ts @@ -12,6 +12,9 @@ import { databaseUrlHits, isExcludedFromDatabaseUrlScan, legacySqlHits, + railwayEnvHits, + railwayScanDirs, + railwayTreeHits, readSource, removedHopHits, removedHopTextHits, @@ -284,3 +287,67 @@ describe('scan 5: apps/api has no WhatsApp-specific code (spec 329)', () => { expect(hits).toEqual({}); }); }); + +describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12, #314, #377)', () => { + // Every app's src/ and lib/ and every package (#377), plus the operator + // scripts and config files apps/api and apps/auth run: a script reading + // RAILWAY_* breaks the rule just as well (codex). + const SCAN_DIRS = railwayScanDirs(); + const FILES = [ + ...new Set([ + ...SCAN_DIRS.flatMap((dir) => sourceFiles(dir)), + ...API_RUNTIME, + ...sourceFiles('apps/api/scripts'), + ...AUTH_RUNTIME, + ]), + ]; + const tree = () => FILES.map((file) => ({ path: file, source: readSource(file) })); + + it('catches planted lines, whatever the access path', () => { + for (const bad of [ + 'const env = process.env.RAILWAY_ENVIRONMENT;', + "const name = process.env['RAILWAY_ENVIRONMENT_NAME'];", + 'const sha = process.env[`RAILWAY_GIT_COMMIT_SHA`];', + "const release = setting(env, 'RAILWAY_GIT_COMMIT_SHA');", + "Sentry.init({ environment: process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV });", + ]) { + expect(railwayEnvHits(bad), bad).not.toEqual([]); + } + }); + + it('ignores near-misses', () => { + for (const fine of [ + '// Railway injects RAILWAY_ENVIRONMENT; we read ENVIRONMENT instead', + '/* RAILWAY_GIT_COMMIT_SHA is not read */ const x = 1;', + "const host = 'postgres.railway.internal';", + "const file = 'apps/api/railway.toml';", + 'const environment = process.env.ENVIRONMENT;', + "const name = 'MY_RAILWAY';", + ]) { + expect(railwayEnvHits(fine), fine).toEqual([]); + } + }); + + it('covers every app src/lib and every package', () => { + for (const dir of ['apps/api/src', 'apps/api/lib', 'apps/auth/src', 'apps/frontend/src', 'apps/frontend/lib', 'apps/mcp/src', 'packages/auth', 'packages/types']) { + expect(SCAN_DIRS, dir).toContain(dir); + } + for (const dir of ['apps/mcp', 'packages']) { + expect(FILES.some((file) => file.startsWith(`${dir}/`)), dir).toBe(true); + } + expect(FILES.length).toBeGreaterThan(200); + }); + + it('fails on a planted read in the tree, and passes once it is removed', () => { + const planted = { path: 'apps/mcp/src/planted.ts', source: 'export const sha = process.env.RAILWAY_X;\n' }; + expect(railwayTreeHits([...tree(), planted])).toEqual({ 'apps/mcp/src/planted.ts': ['RAILWAY_X'] }); + expect(railwayTreeHits(tree())).toEqual({}); + }); + + it('the tree has no hits, and no file is exempt', () => { + const hits = railwayTreeHits(tree()); + report('RAILWAY_* reads (apps/*/src + apps/*/lib + packages/* + api/auth scripts)', FILES, hits); + expect(hits).toEqual({}); + }); +}); + diff --git a/apps/api/tests/threads-token-persistence.test.ts b/apps/api/tests/threads-token-persistence.test.ts index 5532c91e..fea02a82 100644 --- a/apps/api/tests/threads-token-persistence.test.ts +++ b/apps/api/tests/threads-token-persistence.test.ts @@ -102,6 +102,7 @@ beforeEach(() => { process.env.GEMINI_API_KEY = 'test-gemini-key'; process.env.KALEMAT_API_KEY = 'test-kalemat-key'; process.env.USUL_API_TOKEN = 'test-usul-token'; + process.env.ENVIRONMENT = 'development'; process.env.GEMINI_MODEL = 'gemini-primary'; process.env.GEMINI_FALLBACK_MODEL = 'gemini-primary'; sdk.scripts = []; diff --git a/apps/api/tests/tool-citability.test.ts b/apps/api/tests/tool-citability.test.ts index 3d0ff329..a838ae27 100644 --- a/apps/api/tests/tool-citability.test.ts +++ b/apps/api/tests/tool-citability.test.ts @@ -24,6 +24,7 @@ beforeEach(() => { process.env.GEMINI_API_KEY = 'test-gemini-key'; process.env.KALEMAT_API_KEY = 'test-kalemat-key'; process.env.USUL_API_TOKEN = 'test-usul-token'; + process.env.ENVIRONMENT = 'development'; }); let originalFetch: typeof globalThis.fetch; @@ -47,13 +48,13 @@ const QURAN = { id: '2:153', text: 'يَٰٓأَيُّهَا ٱلَّذِينَ' const HADITH = { id: 'h1', source_book: 'Sahih Muslim', - chapter_number: '1', + chapter_number: 1, chapter_english: 'Patience', - section_number: '1', + section_number: 1, section_english: 'Patience', - hadith_number: '2999', + hadith_number: 2999, en_text: 'How wonderful is the affair of the believer', - ar_text: 'عَجَبًا لأَمْرِ الْمُؤْمِنِ', + text: 'عَجَبًا لأَمْرِ الْمُؤْمِنِ', grade_en: 'Sahih', }; const USUL = { diff --git a/apps/api/tests/toolcalls-routes.test.ts b/apps/api/tests/toolcalls-routes.test.ts index 2bd150b8..67cadd9d 100644 --- a/apps/api/tests/toolcalls-routes.test.ts +++ b/apps/api/tests/toolcalls-routes.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; import { NextRequest } from 'next/server'; /** @@ -81,6 +81,8 @@ import { SSE_HEARTBEAT } from '@/lib/streaming/heartbeat'; import { POST as threadPost } from '../src/app/api/v2/threads/[id]/route'; import { POST as chatPost } from '../src/app/api/v2/threads/[id]/chat/route'; import { POST as mcpPost } from '../src/app/api/v2/mcp-complete/route'; +import { resetEnvCache } from '@/lib/config'; +import { installMcpKeyStub, MCP_TEST_CLIENT_ID, withMcpKey } from './helpers/mcp-key'; let client: PGlite; let db: ReturnType>; @@ -166,6 +168,17 @@ afterAll(async () => { await client.close(); }); +// mcp-complete requires a valid key (#314): every mcpReq presents one. +beforeEach(async () => { + await installMcpKeyStub(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + resetEnvCache(); +}); + beforeEach(async () => { vi.clearAllMocks(); mockAuthenticateRequest.mockResolvedValue({ user: { id: USER_ID } }); @@ -198,7 +211,7 @@ function chatReq(message: string): NextRequest { function mcpReq(content: string): NextRequest { return new NextRequest('http://localhost/api/v2/mcp-complete', { method: 'POST', - headers: { 'Content-Type': 'application/json', 'X-Ansari-Client': 'ai-skill-v1' }, + headers: withMcpKey({ 'Content-Type': 'application/json' }), body: JSON.stringify({ messages: [{ role: 'user', content }] }), }); } @@ -433,7 +446,7 @@ describe('POST /api/v2/mcp-complete (ai-skill)', () => { expect(await assistantRows()).toHaveLength(0); const orphans = await orphanRows(); expect(orphans).toHaveLength(1); - expect(orphans[0]).toMatchObject({ reason: 'error', source: 'ai-skill', client: 'ai-skill-v1' }); + expect(orphans[0]).toMatchObject({ reason: 'error', source: 'ai-skill', client: MCP_TEST_CLIENT_ID }); expect(orphans[0].toolCalls).toEqual(RECORDS); // The orphan is attached to the thread this request created. const threadRows = await db.select().from(threads).where(eq(threads.id, orphans[0].threadId)); diff --git a/apps/api/tests/tools.test.ts b/apps/api/tests/tools.test.ts index 7c68f243..6be54201 100644 --- a/apps/api/tests/tools.test.ts +++ b/apps/api/tests/tools.test.ts @@ -14,6 +14,7 @@ beforeEach(() => { process.env.GEMINI_API_KEY = 'test-gemini-key'; process.env.KALEMAT_API_KEY = 'test-kalemat-key'; process.env.USUL_API_TOKEN = 'test-usul-token'; + process.env.ENVIRONMENT = 'development'; }); describe('Islamic Tools', () => { diff --git a/apps/api/tests/turbo-coverage-inputs.test.ts b/apps/api/tests/turbo-coverage-inputs.test.ts new file mode 100644 index 00000000..8f82d332 --- /dev/null +++ b/apps/api/tests/turbo-coverage-inputs.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'fs'; +import { resolve } from 'path'; + +// Pin for issue #381: CI runs `test:coverage`, not `test`, and turbo has no way +// to share an `inputs` list between tasks, so apps/api/turbo.json repeats it. +// The two lists drifted (#330, #314, #377 each patched one entry), and every +// file `test` lists but `test:coverage` misses left ansari-api#test:coverage at +// the same hash when only that file changed, so a warm cache replayed a stale +// green doc or scan result. This file is under apps/api, so it is in its own +// task hash: editing either list reruns it. + +const turboJson = resolve(__dirname, '../turbo.json'); + +// turbo.json is JSONC. Strip // and /* */ comments outside strings only: the +// inputs hold globs like "apps/*/src/**", whose `/*` a regex over the whole +// file would take for a block comment. +function stripJsonComments(source: string): string { + let out = ''; + let i = 0; + while (i < source.length) { + const ch = source[i]; + if (ch === '"') { + const start = i; + i++; + while (i < source.length && source[i] !== '"') i += source[i] === '\\' ? 2 : 1; + i++; + out += source.slice(start, i); + } else if (ch === '/' && source[i + 1] === '/') { + while (i < source.length && source[i] !== '\n') i++; + } else if (ch === '/' && source[i + 1] === '*') { + const end = source.indexOf('*/', i + 2); + if (end === -1) throw new Error('unterminated block comment'); + i = end + 2; + } else { + out += ch; + i++; + } + } + return out; +} + +type TurboTask = { inputs?: string[] }; + +function readTasks(): Record { + const parsed = JSON.parse(stripJsonComments(readFileSync(turboJson, 'utf8'))) as { + tasks: Record; + }; + return parsed.tasks; +} + +describe('apps/api turbo inputs', () => { + it('strips comments but keeps globs inside strings', () => { + const src = '{\n // a comment\n "a": ["$TURBO_ROOT$/apps/*/src/**"], /* block */ "b": "x//y"\n}'; + expect(JSON.parse(stripJsonComments(src))).toEqual({ + a: ['$TURBO_ROOT$/apps/*/src/**'], + b: 'x//y', + }); + }); + + it('test:coverage lists exactly the inputs test lists', () => { + const tasks = readTasks(); + const test = tasks['test']?.inputs; + const coverage = tasks['test:coverage']?.inputs; + + // Loud if either list vanishes: two missing lists would compare equal. + expect(test, 'test.inputs').toBeDefined(); + expect(coverage, 'test:coverage.inputs').toBeDefined(); + expect(test!.length).toBeGreaterThan(1); + + const testSet = new Set(test); + const coverageSet = new Set(coverage); + expect({ + missingFromCoverage: [...testSet].filter((i) => !coverageSet.has(i)).sort(), + extraInCoverage: [...coverageSet].filter((i) => !testSet.has(i)).sort(), + }).toEqual({ missingFromCoverage: [], extraInCoverage: [] }); + }); +}); diff --git a/apps/api/tests/usul-retry.test.ts b/apps/api/tests/usul-retry.test.ts index 4a5890bd..4d7451ea 100644 --- a/apps/api/tests/usul-retry.test.ts +++ b/apps/api/tests/usul-retry.test.ts @@ -16,6 +16,7 @@ beforeEach(() => { process.env.GEMINI_API_KEY = 'test-gemini-key'; process.env.KALEMAT_API_KEY = 'test-kalemat-key'; process.env.USUL_API_TOKEN = 'test-usul-token'; + process.env.ENVIRONMENT = 'development'; }); const BASE_URL = 'https://api.usul.ai/v1/vector-search/book/version'; diff --git a/apps/api/turbo.json b/apps/api/turbo.json index b72610cd..c40f364f 100644 --- a/apps/api/turbo.json +++ b/apps/api/turbo.json @@ -19,33 +19,80 @@ // The root package.json is here for root-test-script.test.ts (issue #330), // which pins the root `test` script's worker cap: without it, removing the // cap left this task at the same hash and a warm cache replayed the pin green. + // + // Every app's src/ and lib/ and every package are here for source-scan 6 + // (#314, widened by #377), which reads them for RAILWAY_* names: without + // them a RAILWAY_ read added there left this task at the same hash and a + // warm cache replayed the scan green. (apps/auth/scripts, also scanned, is + // listed above.) + // + // The railway tomls are here for release-doc.test.ts (issue #364), which + // checks each one against RELEASE.md: without them a toml-only edit left this + // task at the same hash and a warm cache replayed the check green. + // + // skills/ is here for skill-docs.test.ts (issue #409), which checks the public + // agent skill (skills/ansari/SKILL.md) calls only the MCP server and carries no + // credential. skills/ is outside the workspace, so without it a skill-only edit + // left this task at the same hash and a warm cache replayed the check green. "test": { "inputs": [ "$TURBO_DEFAULT$", ".env.ci", - "$TURBO_ROOT$/apps/auth/src/**", "$TURBO_ROOT$/apps/auth/scripts/**", + "$TURBO_ROOT$/apps/*/src/**", + "$TURBO_ROOT$/apps/*/lib/**", + "$TURBO_ROOT$/packages/**", "$TURBO_ROOT$/apps/auth/tests/helpers/**", "$TURBO_ROOT$/packages/auth/drizzle/**", "$TURBO_ROOT$/packages/auth/tests/helpers/**", "$TURBO_ROOT$/RELEASE.md", "$TURBO_ROOT$/CONTRIBUTING.md", "$TURBO_ROOT$/README.md", + "$TURBO_ROOT$/skills/**", "$TURBO_ROOT$/docs/**", "$TURBO_ROOT$/.github/ISSUE_TEMPLATE/**", "$TURBO_ROOT$/.github/scripts/**", "$TURBO_ROOT$/.github/workflows/**", "$TURBO_ROOT$/.gitleaksignore", "$TURBO_ROOT$/.gitleaks.toml", - "$TURBO_ROOT$/package.json" + "$TURBO_ROOT$/package.json", + "$TURBO_ROOT$/apps/*/railway.toml", + "$TURBO_ROOT$/legacy/*/railway.toml" ] }, - // CI runs the same pin through test:coverage, so it needs the root - // package.json too. Overriding `inputs` replaces the root task's list, so - // the inherited entries are repeated. + // CI runs this task, not `test`, so it lists EXACTLY the same inputs: + // overriding `inputs` replaces the root task's list, and turbo cannot share + // one between tasks, so the list is repeated. Every entry `test` has and + // this lacked left ansari-api#test:coverage at the same hash when only that + // file changed, and a warm cache replayed a stale doc or scan result (#381; + // patched one entry at a time before by #330, #314, #377). + // tests/turbo-coverage-inputs.test.ts fails if the two lists differ. "test:coverage": { - "inputs": ["$TURBO_DEFAULT$", ".env.ci", "$TURBO_ROOT$/package.json"] + "inputs": [ + "$TURBO_DEFAULT$", + ".env.ci", + "$TURBO_ROOT$/apps/auth/scripts/**", + "$TURBO_ROOT$/apps/*/src/**", + "$TURBO_ROOT$/apps/*/lib/**", + "$TURBO_ROOT$/packages/**", + "$TURBO_ROOT$/apps/auth/tests/helpers/**", + "$TURBO_ROOT$/packages/auth/drizzle/**", + "$TURBO_ROOT$/packages/auth/tests/helpers/**", + "$TURBO_ROOT$/RELEASE.md", + "$TURBO_ROOT$/CONTRIBUTING.md", + "$TURBO_ROOT$/README.md", + "$TURBO_ROOT$/skills/**", + "$TURBO_ROOT$/docs/**", + "$TURBO_ROOT$/.github/ISSUE_TEMPLATE/**", + "$TURBO_ROOT$/.github/scripts/**", + "$TURBO_ROOT$/.github/workflows/**", + "$TURBO_ROOT$/.gitleaksignore", + "$TURBO_ROOT$/.gitleaks.toml", + "$TURBO_ROOT$/package.json", + "$TURBO_ROOT$/apps/*/railway.toml", + "$TURBO_ROOT$/legacy/*/railway.toml" + ] } } } diff --git a/apps/auth/.env.ci b/apps/auth/.env.ci index 7249123a..07ec761a 100644 --- a/apps/auth/.env.ci +++ b/apps/auth/.env.ci @@ -16,3 +16,6 @@ RESEND_API_KEY=re_placeholder-not-a-real-key FRONTEND_URL=http://localhost:8081 PORT=3100 NODE_ENV=test + +# The deployment label (#314 Amendment 3). +ENVIRONMENT=development diff --git a/apps/auth/.env.example b/apps/auth/.env.example index 311e2a13..8cf6a2be 100644 --- a/apps/auth/.env.example +++ b/apps/auth/.env.example @@ -33,3 +33,8 @@ FRONTEND_URL=http://localhost:8081 # The one listener. apps/api reaches it here too (its AUTH_URL). PORT=3100 + +# The deployment label (#314 Amendment 3): development, staging or production. The Sentry +# environment and the service-key prefix environment. Required everywhere, no default; staging or +# production when NODE_ENV=production. +ENVIRONMENT=development diff --git a/apps/auth/package.json b/apps/auth/package.json index 7e2f808f..d61a9fd4 100644 --- a/apps/auth/package.json +++ b/apps/auth/package.json @@ -23,7 +23,7 @@ "bcrypt": "^6.0.0", "better-auth": "1.7.7", "cors": "^2.8.5", - "dotenv": "^17.2.3", + "dotenv": "^18.0.10", "express": "^5.1.0", "jose": "^6.2.9" }, @@ -38,6 +38,6 @@ "tsx": "^4.21.0", "typescript": "catalog:", "typescript-eslint": "catalog:", - "vitest": "^4.1.11" + "vitest": "^5.1.1" } } diff --git a/apps/auth/scripts/cutover/README.md b/apps/auth/scripts/cutover/README.md index 18c63950..d8b35809 100644 --- a/apps/auth/scripts/cutover/README.md +++ b/apps/auth/scripts/cutover/README.md @@ -42,7 +42,8 @@ because it is the one place both databases are named. **Dry run: `copy.sh --dry-run`.** The same copy, guards and audits, with nothing committed: `02`'s transaction ends in `ROLLBACK` after printing the auth-side audit from inside it (another session cannot see uncommitted rows). If the auth database has no schema yet (staging and -production before runbook step 5), the **whole auth journal**, in `_journal.json` order +production before runbook step 5; **production, 2026-11-21:** its journal is already applied, +see `docs/cutover/release-record.md`, so no baseline is added there), the **whole auth journal**, in `_journal.json` order (`auth-journal.mjs sql`: every migration, then an assertion that each one is present), is applied inside the same transaction and rolled back with it, so the dry run proves the copy against the schema production will have, and step 1's empty-database check still holds afterwards. The SQL diff --git a/apps/auth/scripts/probes/environment-boot-probe.ts b/apps/auth/scripts/probes/environment-boot-probe.ts new file mode 100644 index 00000000..458f9aef --- /dev/null +++ b/apps/auth/scripts/probes/environment-boot-probe.ts @@ -0,0 +1,92 @@ +/** + * The production-shaped run for ENVIRONMENT (#314 Amendment 3; second review, + * finding 12): the BUILT apps/auth (`dist/index.mjs`) started as its own + * process with NODE_ENV=production, as Railway starts it, for each value of + * ENVIRONMENT. In-process tests mutate process.env; this proves the rule on + * the real boot path. Operator-run, after `pnpm --filter ansari-auth build`: + * + * pnpm --filter ansari-auth exec tsx scripts/probes/environment-boot-probe.ts + * + * The database URL is an argument, never read from the environment, and + * should point at a port nothing listens on (e.g. 127.0.0.1:1): the probe + * needs boot to get past the env check, not a database (apps/auth starts on + * an unreachable database, by design). No .env is loaded (DOTENV_CONFIG_PATH + * is /dev/null), so only the values below exist. + * + * Expected: absent, `development` and `prod` refuse to boot, naming + * ENVIRONMENT and no value; `staging` and `production` listen. Each case runs + * under a deadline (PASS or FAIL, never a hang). The output is pasted into the + * review (codev/reviews/314-*.md). + */ +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const databaseUrl = process.argv[2]; +if (!databaseUrl) { + console.error('usage: environment-boot-probe.ts '); + process.exit(2); +} + +const APP_DIR = fileURLToPath(new URL('../..', import.meta.url)); +const SECRET = 'probe-secret-'.padEnd(40, 'x'); +const BASE: Record = { + PATH: process.env.PATH ?? '', + DOTENV_CONFIG_PATH: '/dev/null', + NODE_ENV: 'production', + DATABASE_URL: databaseUrl, + BETTER_AUTH_SECRET: SECRET, + BETTER_AUTH_URL: 'https://auth.probe.test', + CORS_ORIGIN: 'https://app.probe.test', + AUTH_LAYER_ORIGIN: 'https://api.probe.test', + AUTH_JWT_ISSUER: 'https://auth.probe.test', + AUTH_JWT_AUDIENCE: 'ansari-api', + RESEND_API_KEY: 'r'.repeat(20), + FRONTEND_URL: 'https://app.probe.test', + PORT: '31997', +}; + +type Outcome = { listened: boolean; refusedOn: string | null; leaked: boolean }; + +function boot(environment: string | undefined, deadlineMs = 20_000): Promise { + const env = { ...BASE, ...(environment === undefined ? {} : { ENVIRONMENT: environment }) }; + return new Promise((resolve) => { + const child = spawn(process.execPath, ['dist/index.mjs'], { cwd: APP_DIR, env }); + let output = ''; + const finish = () => { + clearTimeout(timer); + child.kill('SIGTERM'); + const refused = /env validation failed for: ([A-Z_, ]+)\./.exec(output); + resolve({ + listened: /listening on port/.test(output), + refusedOn: refused?.[1] ?? null, + leaked: output.includes(SECRET) || (environment !== undefined && environment !== '' && output.includes(`ENVIRONMENT=${environment}`)), + }); + }; + const timer = setTimeout(finish, deadlineMs); + for (const stream of [child.stdout, child.stderr]) { + stream.on('data', (chunk: Buffer) => { + output += chunk.toString(); + if (/listening on port|env validation failed/.test(output)) setTimeout(finish, 200); + }); + } + child.on('exit', () => setTimeout(finish, 50)); + }); +} + +let failed = 0; +for (const [environment, shouldBoot] of [ + [undefined, false], + ['development', false], + ['prod', false], + ['staging', true], + ['production', true], +] as const) { + const outcome = await boot(environment); + const ok = shouldBoot + ? outcome.listened && outcome.refusedOn === null + : !outcome.listened && outcome.refusedOn === 'ENVIRONMENT' && !outcome.leaked; + if (!ok) failed++; + const what = outcome.listened ? 'listened' : outcome.refusedOn ? `refused (names: ${outcome.refusedOn})` : 'no answer'; + console.log(`${ok ? 'PASS' : 'FAIL'} NODE_ENV=production ENVIRONMENT=${environment ?? '(absent)'} → ${what}`); +} +process.exit(failed === 0 ? 0 : 1); diff --git a/apps/auth/scripts/probes/service-keys-demo.ts b/apps/auth/scripts/probes/service-keys-demo.ts index 57f3f0dd..99b97e88 100644 --- a/apps/auth/scripts/probes/service-keys-demo.ts +++ b/apps/auth/scripts/probes/service-keys-demo.ts @@ -41,6 +41,7 @@ async function main(): Promise { console.log(`\n$ tsx scripts/service-keys.ts ${argv.join(' ')}`); const { lines, exitCode } = await serviceKeys(argv, { databaseUrl, + environment: 'development', connect: () => ({ db, auth }), recorder, print: (line) => console.log(line), @@ -61,7 +62,7 @@ async function main(): Promise { await step(['create-service', 'whatsapp', '--confirm', 'whatsapp']); const shown = await step(['create-key', 'whatsapp', ...LIMITS, '--client-id', 'whatsapp-service']); const userId = idIn(shown, /^ {2}id {10}([0-9a-f-]{36})$/); - const first = idIn(await step(['create-key', 'whatsapp', ...LIMITS, '--client-id', 'whatsapp-service', '--confirm', userId]), /^Created key ([0-9a-f-]{36})/); + const first = idIn(await step(['create-key', 'whatsapp', ...LIMITS, '--client-id', 'whatsapp-service', '--confirm', userId]), /^Created \w+ key ([0-9a-f-]{36})/); await step(['list', 'whatsapp']); await step(['rotate', 'whatsapp', ...LIMITS, '--confirm', userId]); await step(['update-limits', 'whatsapp', '--key', first, '--rate-max', '120', '--rate-window', '60', '--daily', '6000', '--confirm', first]); @@ -75,7 +76,7 @@ async function main(): Promise { const text = transcript.join('\n'); const { username, password, pathname, protocol } = new URL(databaseUrl); const leaks = [databaseUrl, `${username}:${password}@`, `${pathname}`, `${protocol}//`].filter((s) => text.includes(s)); - const keys = text.match(/ansari_wa_[A-Za-z]{64}/g) ?? []; + const keys = text.match(/ansari_wa_development_[A-Za-z]{64}/g) ?? []; console.log(`\nCHECK database printed as hostname:port only: ${leaks.length === 0 ? 'PASS' : `FAIL (${leaks.join(', ')})`}`); console.log(`CHECK two keys created, each printed once: ${keys.length === 2 && new Set(keys).size === 2 ? 'PASS' : `FAIL (${keys.length})`}`); process.exit(leaks.length === 0 && keys.length === 2 ? 0 : 1); diff --git a/apps/auth/scripts/service-keys.ts b/apps/auth/scripts/service-keys.ts index 3036b16d..9cd2284a 100644 --- a/apps/auth/scripts/service-keys.ts +++ b/apps/auth/scripts/service-keys.ts @@ -23,10 +23,17 @@ * name for create-service, which has no user yet. A mismatch writes nothing * and exits 2. `--name` and `--client-id` take 1 to 64 letters, digits, * spaces, dots, underscores and hyphens, and never a key-shaped value: both - * are printed by list and sent to Sentry. + * are printed by list and sent to Sentry. For `ansari-mcp`, `--client-id` is + * required and must be `ansari-mcp` or `ansari-mcp-` (#314): it is the + * thread attribution apps/api stores for every request the key makes. * * - It prints the database as `hostname:port` only, never the URL. - * - Permissions and the key prefix are fixed per service (SERVICES); limits are + * - The script reads `ENVIRONMENT` (development, staging or production; #314 + * Amendment 3) from its process env and refuses to run without it. It is + * printed under the database line before anything connects, and a new key's + * prefix carries it (`ansari___`); the routes refuse a + * key labelled for another environment. + * - Permissions and the base key prefix are fixed per service (SERVICES); limits are * required flags with no defaults, checked against limits.ts's bounds. The * budget is daily and always refills: a budget without a refill deletes the * key the first time it is exhausted. There is no expiry option: a key lives @@ -44,14 +51,18 @@ import * as Sentry from '@sentry/node'; import { createAuth, createDb, + ENVIRONMENTS, getEnv, + isMcpClientId, limits, serviceAddress, serviceUsers, type Auth, type Db, + type Environment, } from '@ansari/auth'; + import { urlHostPort } from './url-host'; type ServiceName = serviceUsers.ServiceName; @@ -75,8 +86,16 @@ export const USAGE = [ ' tsx scripts/service-keys.ts update-limits --key --rate-max --rate-window --daily [--confirm ]', ' tsx scripts/service-keys.ts revoke --key [--confirm ]', `Services: ${Object.keys(serviceUsers.SERVICES).join(', ')}`, + `ENVIRONMENT (${ENVIRONMENTS.join(', ')}) must be set, as on the auth service: a new key's prefix carries it`, + '(ansari___), and each environment\'s routes refuse a key labelled for another. Check it against the', + 'database line before --confirm.', ].join('\n'); +/** The refusal when ENVIRONMENT is absent or not one of ENVIRONMENTS: fixed words, never the value. */ +export const ENVIRONMENT_RULE = `ENVIRONMENT is not set to one of ${ENVIRONMENTS.join(', ')} (set it as on the auth service). Refusing to run.`; + +const isEnvironment = (value: string): value is Environment => (ENVIRONMENTS as readonly string[]).includes(value); + /** The exit code of a run that wrote nothing on purpose (show step, confirm mismatch). */ export const EXIT_NOTHING_WRITTEN = 2; /** The exit code of a write whose Sentry record could not be sent. */ @@ -139,7 +158,6 @@ function limitsFrom(flags: Map): KeyLimits { }; } -/** Parses the command line; throws RefusedError with the reason when it is not a valid command. */ /** A key name or client id: printed by list and sent to Sentry, so a bounded, inert charset. */ const LABEL = /^[A-Za-z0-9 ._-]{1,64}$/; @@ -164,6 +182,24 @@ function label(flag: string, value: string | undefined): string | null { return value; } +/** The refusal for an `ansari-mcp` key without a valid client id: fixed words, never the value. */ +export const MCP_CLIENT_ID_RULE = + 'ansari-mcp keys need --client-id: ansari-mcp, or ansari-mcp- and a suffix of lowercase letters, digits, dots, underscores and hyphens (64 characters at most). Nothing was written.'; + +/** + * The client id a new key of `service` carries. An `ansari-mcp` key must name + * its caller with an `ansari-mcp*` id (isMcpClientId), since apps/auth and + * apps/api refuse a key without one; other services default to their name. + * The value is never echoed back. + */ +export function clientIdFor(service: ServiceName, clientId: string | null): string { + if (service === 'ansari-mcp') { + if (!isMcpClientId(clientId)) throw new RefusedError(MCP_CLIENT_ID_RULE); + return clientId; + } + return clientId ?? service; +} + export function parseArgs(argv: readonly string[]): ServiceKeysCommand { const [kind, service, ...rest] = argv; if (!isKind(kind) || service === undefined || service.startsWith('--')) throw new RefusedError(USAGE); @@ -195,15 +231,18 @@ export function parseArgs(argv: readonly string[]): ServiceKeysCommand { case 'list': return { kind, service }; case 'create-key': - case 'rotate': + case 'rotate': { + const clientId = label('--client-id', flags.get('--client-id')); + clientIdFor(service, clientId); return { kind, service, confirm, limits: limitsFrom(flags), name: label('--name', flags.get('--name')), - clientId: label('--client-id', flags.get('--client-id')), + clientId, }; + } case 'update-limits': return { kind, service, keyId: keyId(), limits: limitsFrom(flags), confirm }; case 'revoke': @@ -249,7 +288,8 @@ export type KeyEvent = { export type ScriptResult = { lines: string[]; exitCode: number; events: KeyEvent[] }; -export type ScriptContext = { db: Db; auth: Auth; now?: Date }; +/** `environment` is the validated ENVIRONMENT: a new key's prefix names it. */ +export type ScriptContext = { db: Db; auth: Auth; environment: Environment; now?: Date }; const describeLimits = (l: { rateLimitMax: number | null; @@ -268,6 +308,7 @@ function keyLines(key: serviceUsers.ServiceKey): string[] { ` name ${key.name ?? ''}`, ` prefix ${key.prefix ?? ''}`, ` permissions ${key.permissions ?? ''}`, + ` client_id ${serviceUsers.clientIdOf(key.metadata) ?? ''}`, ` enabled ${key.enabled}`, ` limits ${describeLimits(key)}; remaining ${key.remaining}`, ` created ${iso(key.createdAt)}`, @@ -318,7 +359,8 @@ async function createKey( flags: KeyFlags ): Promise<{ id: string; key: string; name: string }> { const checked = checkKeyLimits(service, flags.limits); - const { permissions, prefix } = serviceUsers.SERVICES[service]; + const { permissions } = serviceUsers.SERVICES[service]; + const prefix = serviceUsers.keyPrefix(service, ctx.environment); // Default name: the service and the minute it was created, so a rotation's two keys differ. const name = flags.name ?? `${service} ${(ctx.now ?? new Date()).toISOString().slice(0, 16)}Z`; const created = await ctx.auth.api.createApiKey({ @@ -327,7 +369,7 @@ async function createKey( prefix, name, permissions: Object.fromEntries(Object.entries(permissions).map(([k, v]) => [k, [...v]])), - metadata: { clientId: flags.clientId ?? service }, + metadata: { clientId: clientIdFor(service, flags.clientId) }, rateLimitEnabled: true, rateLimitTimeWindow: checked.rateLimitTimeWindow, rateLimitMax: checked.rateLimitMax, @@ -392,6 +434,7 @@ export async function runServiceKeys(ctx: ScriptContext, cmd: ServiceKeysCommand if (cmd.kind === 'create-key' || cmd.kind === 'rotate') { checkKeyLimits(cmd.service, cmd.limits); + clientIdFor(cmd.service, cmd.clientId); const live = keys.filter((k) => k.enabled); if (cmd.kind === 'rotate' && live.length === 0) { throw new RefusedError(`Service "${cmd.service}" has no live key to rotate; use create-key.`); @@ -404,7 +447,8 @@ export async function runServiceKeys(ctx: ScriptContext, cmd: ServiceKeysCommand ...userLines(cmd.service, user), `${live.length} live key(s): ${live.map((k) => k.id).join(', ') || 'none'}`, `This would create a key with ${describeLimits(cmd.limits)}.`, - 'Nothing was written. If this is the service you mean, run:', + ` environment ${ctx.environment} (prefix ${serviceUsers.keyPrefix(cmd.service, ctx.environment)})`, + 'Nothing was written. If this is the service and environment you mean, run:', command(`${cmd.kind} ${cmd.service} ${flagsText(cmd.limits)}${extra ? ` ${extra}` : ''} --confirm ${user.id}`), ]); } @@ -421,7 +465,7 @@ export async function runServiceKeys(ctx: ScriptContext, cmd: ServiceKeysCommand : []; return { lines: [ - `Created key ${created.id} (${created.name}) for ${cmd.service}: ${describeLimits(cmd.limits)}.`, + `Created ${ctx.environment} key ${created.id} (${created.name}) for ${cmd.service}: ${describeLimits(cmd.limits)}.`, ...rawKeyLines(created.key), ...rotated, ], @@ -511,10 +555,28 @@ export const unrecordedRecorder: Recorder = { reason: 'SENTRY_DSN is not set: no record was attempted.', }; +/** + * The script's Sentry init: its events carry ENVIRONMENT, like apps/auth's own + * (#314 Amendment 3), never NODE_ENV, which is `production` on staging too. An + * absent or unknown ENVIRONMENT never gets here: main() refuses it first. + */ +export function scriptSentryInit(dsn: string, environment: Environment) { + return { dsn, environment, ...SCRIPT_SENTRY_OPTIONS }; +} + +/** + * The validated ENVIRONMENT, or null when it is absent or not one of + * ENVIRONMENTS. main() checks it before scriptRecorder, so Sentry is never + * initialised under an operator's typo (second review, finding 8). + */ +export function validEnvironment(value: string | undefined): Environment | null { + return value !== undefined && isEnvironment(value) ? value : null; +} + /** The script's recorder: Sentry when a DSN is set (initialised here), otherwise none. */ -export function scriptRecorder(dsn: string | undefined): Recorder { +export function scriptRecorder(dsn: string | undefined, environment: Environment): Recorder { if (!dsn) return unrecordedRecorder; - Sentry.init({ dsn, environment: process.env.NODE_ENV ?? 'development', ...SCRIPT_SENTRY_OPTIONS }); + Sentry.init(scriptSentryInit(dsn, environment)); return sentryRecorder; } @@ -540,7 +602,9 @@ export function scriptError(err: unknown): string { export type ScriptDeps = { databaseUrl: string | undefined; - connect: () => ScriptContext; + /** ENVIRONMENT as the process has it, unvalidated: the script refuses an absent or unknown value. */ + environment: string | undefined; + connect: () => Omit; recorder: Recorder; /** Prints one line at once (console.log in the script). */ print: (line: string) => void; @@ -571,10 +635,16 @@ export async function serviceKeys(argv: readonly string[], deps: ScriptDeps): Pr return { lines, exitCode: 1 }; } emit(`Auth database: ${host}`); + const environment = deps.environment; + if (environment === undefined || !isEnvironment(environment)) { + emit(ENVIRONMENT_RULE); + return { lines, exitCode: 1 }; + } + emit(`Environment: ${environment} (a new key's prefix carries it: ansari__${environment}_)`); let result: ScriptResult; try { const cmd = parseArgs(argv); - result = await runServiceKeys(deps.connect(), cmd); + result = await runServiceKeys({ ...deps.connect(), environment }, cmd); } catch (err) { emit(`service-keys refused: ${scriptError(err)}`); return { lines, exitCode: 1 }; @@ -612,9 +682,15 @@ export function printLine(line: string): void { } async function main(): Promise { - const recorder = scriptRecorder(process.env.SENTRY_DSN); + const environment = validEnvironment(process.env.ENVIRONMENT); + if (environment === null) { + printLine(ENVIRONMENT_RULE); + process.exit(1); + } + const recorder = scriptRecorder(process.env.SENTRY_DSN, environment); const { exitCode } = await serviceKeys(process.argv.slice(2), { databaseUrl: process.env.DATABASE_URL, + environment, // validated above: one validation connect: () => { try { getEnv(); diff --git a/apps/auth/src/alerts.ts b/apps/auth/src/alerts.ts index b0d08cd8..34ccc6da 100644 --- a/apps/auth/src/alerts.ts +++ b/apps/auth/src/alerts.ts @@ -7,7 +7,9 @@ // identifier in a Sentry event. A per-key alert names the key by its id (a // plugin-made UUID that identifies a credential, not a person, and that `list` // prints), so the operator can act on it. The one personal id an operator -// needs, an ineligible user's, goes only in a server log line. +// needs, an ineligible user's, goes only in a server log line. The MCP verify +// route (#314) raises the same per-key kinds through the same factory, with +// its own thresholds, message and tags. import { limits } from '@ansari/auth'; import * as Sentry from '@sentry/node'; @@ -132,18 +134,40 @@ export type ExchangeAlert = export type KeyRefusalCode = 'USAGE_EXCEEDED' | 'RATE_LIMITED'; +/** The kinds every key-holding route raises: the exchange's, less `ineligible-user`. */ +export type KeyAlert = Exclude; + +/** + * Every alert the MCP verify route (#314) raises, on the same terms as the + * exchange's, with MCP thresholds: a refusal is a `valid: false` answer, and + * the service user is `ansari-mcp`'s. `client-id-invalid` is a key the plugin + * accepted whose `client_id` is missing or not `ansari-mcp*` (a key created + * outside the script); the caller saw `valid: false`. It names the first such + * key in its window. + */ +export type McpVerifyAlert = KeyAlert | { kind: 'client-id-invalid'; keyId: string; windowSeconds: number }; + export const EXCHANGE_ALERT_MESSAGE = 'auth: WhatsApp exchange alert'; +export const MCP_VERIFY_ALERT_MESSAGE = 'auth: MCP key verify alert'; -/** One Sentry event (plus a log line with the same fields). */ -export function sendExchangeAlert(alert: ExchangeAlert): void { - console.warn(EXCHANGE_ALERT_MESSAGE, alert); - Sentry.captureMessage(`${EXCHANGE_ALERT_MESSAGE}: ${alert.kind}`, { - level: 'warning', - tags: { alert: `whatsapp-exchange-${alert.kind}` }, - extra: { ...alert }, - }); +/** One Sentry event per alert (plus a log line with the same fields), under `message` and the tag `-`. */ +export function keyAlertSender(message: string, tagPrefix: string): (alert: A) => void { + return (alert) => { + console.warn(message, alert); + Sentry.captureMessage(`${message}: ${alert.kind}`, { + level: 'warning', + tags: { alert: `${tagPrefix}-${alert.kind}` }, + extra: { ...alert }, + }); + }; } +/** One Sentry event (plus a log line with the same fields). */ +export const sendExchangeAlert: (alert: ExchangeAlert) => void = keyAlertSender(EXCHANGE_ALERT_MESSAGE, 'whatsapp-exchange'); + +/** One Sentry event (plus a log line with the same fields). */ +export const sendMcpVerifyAlert: (alert: McpVerifyAlert) => void = keyAlertSender(MCP_VERIFY_ALERT_MESSAGE, 'mcp-verify'); + /** The fields of a verified key the per-key alerts read, as `verifyApiKey` returns them. */ export type VerifiedKeyUsage = { id: string; @@ -155,37 +179,57 @@ export type VerifiedKeyUsage = { createdAt: Date | string; }; -/** What the exchange route reports; each call is one request, the alerts decide when to send. */ -export type ExchangeAlerts = { +/** What a key-holding route reports; each call is one request, the alerts decide when to send. */ +export type KeyAlerts = { keyVerified(key: VerifiedKeyUsage): void; keyRefused(code: KeyRefusalCode): void; unauthorized(): void; - ineligibleUser(userId: string, reason: string): void; serviceUserUnresolvable(serviceUsers: number): void; }; -export const INELIGIBLE_USER_MESSAGE = 'whatsapp exchange: ineligible user refused (repair per the service-keys runbook)'; +/** A service's alert thresholds: per key per rate-limit window, per key per refill period, and refusals per EXCHANGE_ALERT_WINDOW. */ +export type KeyAlertThresholds = { keyWindow: number; daily: number; unauthorized: number }; -export type ExchangeAlertOptions = { - send?: (alert: ExchangeAlert) => void; +export type KeyAlertOptions = { + thresholds: KeyAlertThresholds; + /** + * The shortest gap between two window-volume alerts for one key, in ms. A + * key's alert otherwise repeats once per its own rate-limit window; the MCP + * route sets EXCHANGE_ALERT_WINDOW so every MCP kind fires at most once per + * alert window (spec 314 §1). 0 keeps the exchange's behaviour (spec 329). + */ + keyWindowFloorMs?: number; + send: (alert: A) => void; now?: () => number; }; +/** The shared core, plus the fixed-window tally a service's own kinds use. */ +type KeyAlertCore = KeyAlerts & { + /** Count one event in `name`'s fixed window; true the first time the count reaches `threshold`. */ + tally(name: string, threshold: number): boolean; +}; + /** - * The exchange's alerts, deduplicated in process. The per-key counts come - * from the key's own row (the plugin keeps them durably and resets them with - * the window and the refill); a key's window alert fires once per window and - * its daily alert once per refill period. The rest count in fixed + * A key-holding route's alerts, deduplicated in process. The per-key counts + * come from the key's own row (the plugin keeps them durably and resets them + * with the window and the refill); a key's window alert fires once per window + * and its daily alert once per refill period. The rest count in fixed * EXCHANGE_ALERT_WINDOW windows and fire once per window. A restart can * re-fire once, which errs loud. */ -export function createExchangeAlerts({ send = sendExchangeAlert, now = Date.now }: ExchangeAlertOptions = {}): ExchangeAlerts { +function createKeyAlerts({ + thresholds, + keyWindowFloorMs = 0, + send: sendAlert, + now = Date.now, +}: KeyAlertOptions): KeyAlertCore { + // Every KeyAlert is an A for both callers; the cast keeps the core generic. + const send = sendAlert as unknown as (alert: KeyAlert) => void; const windowMs = limits.EXCHANGE_ALERT_WINDOW * 1000; const keyWindowFiredAt = new Map(); const keyDailyFiredFor = new Map(); const windows = new Map(); - /** Count one event in `name`'s fixed window; true the first time the count reaches `threshold`. */ function tally(name: string, threshold: number): boolean { const at = now(); let window = windows.get(name); @@ -202,43 +246,106 @@ export function createExchangeAlerts({ send = sendExchangeAlert, now = Date.now const windowSeconds = limits.EXCHANGE_ALERT_WINDOW; return { + tally, keyVerified(key) { const keyWindowMs = key.rateLimitTimeWindow ?? 0; const firedAt = keyWindowFiredAt.get(key.id); - if ( - key.requestCount >= limits.WHATSAPP_EXCHANGE_KEY_ALERT && - (firedAt === undefined || now() - firedAt >= keyWindowMs) - ) { + const gapMs = Math.max(keyWindowMs, keyWindowFloorMs); + if (key.requestCount >= thresholds.keyWindow && (firedAt === undefined || now() - firedAt >= gapMs)) { keyWindowFiredAt.set(key.id, now()); send({ kind: 'key-window-volume', keyId: key.id, requests: key.requestCount, windowSeconds: keyWindowMs / 1000, - threshold: limits.WHATSAPP_EXCHANGE_KEY_ALERT, + threshold: thresholds.keyWindow, }); } if (key.refillAmount === null || key.remaining === null) return; const used = key.refillAmount - key.remaining; const period = new Date(key.lastRefillAt ?? key.createdAt).toISOString(); - if (used >= limits.WHATSAPP_EXCHANGE_DAILY_ALERT && keyDailyFiredFor.get(key.id) !== period) { + if (used >= thresholds.daily && keyDailyFiredFor.get(key.id) !== period) { keyDailyFiredFor.set(key.id, period); - send({ kind: 'key-daily-volume', keyId: key.id, requests: used, threshold: limits.WHATSAPP_EXCHANGE_DAILY_ALERT }); + send({ kind: 'key-daily-volume', keyId: key.id, requests: used, threshold: thresholds.daily }); } }, keyRefused(code) { if (tally(`refused:${code}`, 1)) send({ kind: 'key-refused', code, windowSeconds }); }, unauthorized() { - const { max } = limits.EXCHANGE_UNAUTHORIZED_ALERT; - if (tally('unauthorized', max)) send({ kind: 'unauthorized-volume', windowSeconds, threshold: max }); + if (tally('unauthorized', thresholds.unauthorized)) { + send({ kind: 'unauthorized-volume', windowSeconds, threshold: thresholds.unauthorized }); + } + }, + serviceUserUnresolvable(serviceUsers) { + if (tally('service-user', 1)) send({ kind: 'service-user-unresolvable', serviceUsers, windowSeconds }); }, + }; +} + +/** What the exchange route reports. */ +export type ExchangeAlerts = KeyAlerts & { + ineligibleUser(userId: string, reason: string): void; +}; + +export const INELIGIBLE_USER_MESSAGE = 'whatsapp exchange: ineligible user refused (repair per the service-keys runbook)'; + +export type ExchangeAlertOptions = { + send?: (alert: ExchangeAlert) => void; + now?: () => number; +}; + +/** The WhatsApp exchange's alerts (spec 329): its thresholds, message and `whatsapp-exchange-*` tags. */ +export function createExchangeAlerts({ send = sendExchangeAlert, now = Date.now }: ExchangeAlertOptions = {}): ExchangeAlerts { + const core = createKeyAlerts({ + thresholds: { + keyWindow: limits.WHATSAPP_EXCHANGE_KEY_ALERT, + daily: limits.WHATSAPP_EXCHANGE_DAILY_ALERT, + unauthorized: limits.EXCHANGE_UNAUTHORIZED_ALERT.max, + }, + send, + now, + }); + const { tally, ...alerts } = core; + return { + ...alerts, ineligibleUser(userId, reason) { console.warn(INELIGIBLE_USER_MESSAGE, { userId, reason }); - if (tally('ineligible', 1)) send({ kind: 'ineligible-user', windowSeconds }); + if (tally('ineligible', 1)) send({ kind: 'ineligible-user', windowSeconds: limits.EXCHANGE_ALERT_WINDOW }); }, - serviceUserUnresolvable(serviceUsers) { - if (tally('service-user', 1)) send({ kind: 'service-user-unresolvable', serviceUsers, windowSeconds }); + }; +} + +/** What the MCP verify route reports. */ +export type McpVerifyAlerts = KeyAlerts & { + /** A key the plugin accepted carries no `ansari-mcp*` client id; its id names it. */ + clientIdInvalid(keyId: string): void; +}; + +export type McpVerifyAlertOptions = { + send?: (alert: McpVerifyAlert) => void; + now?: () => number; +}; + +/** The MCP verify route's alerts (#314): MCP thresholds, its message and `mcp-verify-*` tags. */ +export function createMcpVerifyAlerts({ send = sendMcpVerifyAlert, now = Date.now }: McpVerifyAlertOptions = {}): McpVerifyAlerts { + const core = createKeyAlerts({ + thresholds: { + keyWindow: limits.MCP_VERIFY_KEY_ALERT, + daily: limits.MCP_VERIFY_DAILY_ALERT, + unauthorized: limits.MCP_VERIFY_UNAUTHORIZED_ALERT.max, + }, + keyWindowFloorMs: limits.EXCHANGE_ALERT_WINDOW * 1000, + send, + now, + }); + const { tally, ...alerts } = core; + return { + ...alerts, + clientIdInvalid(keyId) { + if (tally('client-id-invalid', 1)) { + send({ kind: 'client-id-invalid', keyId, windowSeconds: limits.EXCHANGE_ALERT_WINDOW }); + } }, }; } diff --git a/apps/auth/src/app.ts b/apps/auth/src/app.ts index c96b461b..f5b60767 100644 --- a/apps/auth/src/app.ts +++ b/apps/auth/src/app.ts @@ -5,8 +5,9 @@ // /api/auth/* Better Auth's router (its JWKS at /api/auth/jwks included) // /api/account/* the account endpoints, bound to the caller's own JWT // /api/whatsapp/session the WhatsApp token exchange, bound to a service key +// /api/service/verify-key the MCP key verify route (#314), for apps/api // /health and the diag route -import { createAuth, getEnv, type Auth, type Db, type Mailer } from '@ansari/auth'; +import { createAuth, getEnv, type Auth, type Db, type Environment, type Mailer } from '@ansari/auth'; import { toNodeHandler } from 'better-auth/node'; import express, { type Express, type Request, type Response } from 'express'; @@ -18,6 +19,7 @@ import { corsFor, mergeExposedHeaders } from './middleware/cors'; import { ACCOUNT_PATH, accountRouter } from './routes/account'; import { clientIpDiag, DIAG_PATH } from './routes/diag'; import { health } from './routes/health'; +import { SERVICE_VERIFY_PATH, serviceVerifyRouter, type VerifyOptions } from './routes/service-verify'; import { WHATSAPP_SESSION_PATH, whatsappRouter, type ExchangeOptions } from './routes/whatsapp'; export type ServiceDeps = { auth: Auth; db: Db }; @@ -26,6 +28,10 @@ export type AppOptions = { production?: boolean; /** The WhatsApp exchange's alerts and clock; the defaults in production. */ exchange?: ExchangeOptions; + /** The MCP verify route's alerts and clock; the defaults in production. */ + verify?: VerifyOptions; + /** This deployment's ENVIRONMENT for both key routes (#314 Amendment 3); defaults to getEnv(). */ + environment?: Environment; }; const AUTH_ROUTE = '/api/auth{/*path}'; @@ -65,9 +71,12 @@ export function createApp({ auth, db }: ServiceDeps, options: AppOptions = {}): app.disable('x-powered-by'); // Ahead of corsFor (spec 329): corsFor decides by origin alone and answers // OPTIONS itself, so a route after it would get CORS for the configured - // origin. The router answers every request to its path, so nothing reaches - // corsFor; a browser can never read a response from it. - app.use(WHATSAPP_SESSION_PATH, whatsappRouter({ auth, db }, options.exchange)); + // origin. Each router answers every request to its path, so nothing reaches + // corsFor; a browser can never read a response from either. + // The one environment knob for both key routes (second review, finding 7). + const environment = options.environment ?? getEnv().ENVIRONMENT; + app.use(WHATSAPP_SESSION_PATH, whatsappRouter({ auth, db }, options.exchange ?? {}, environment)); + app.use(SERVICE_VERIFY_PATH, serviceVerifyRouter({ auth, db }, options.verify ?? {}, environment)); app.use(corsFor(getEnv().CORS_ORIGIN)); app.use(mergeExposedHeaders); app.use(blockedPaths); diff --git a/apps/auth/src/index.ts b/apps/auth/src/index.ts index 2d4aa069..05611425 100644 --- a/apps/auth/src/index.ts +++ b/apps/auth/src/index.ts @@ -11,7 +11,7 @@ import { createApp, createServiceAuth } from './app'; import { assertSchema } from './boot'; const env = getEnv(); -initSentry(env.SENTRY_DSN, env.NODE_ENV); +initSentry(env.SENTRY_DSN, env.ENVIRONMENT); // No admin check at boot (owner amendment 2026-10-17): admin is the role in // auth.users alone, granted by scripts/grant-admin.ts, and the window audits it diff --git a/apps/auth/src/routes/apikey-relation.ts b/apps/auth/src/routes/apikey-relation.ts new file mode 100644 index 00000000..f88d6cb3 --- /dev/null +++ b/apps/auth/src/routes/apikey-relation.ts @@ -0,0 +1,19 @@ +// The outage check the key-holding routes (the WhatsApp exchange, the MCP +// verify route) run on every plugin refusal. The plugin reports a database +// failure (an outage, `auth.apikey` missing) as INVALID_API_KEY, the code of +// an unknown key. A query on `auth.apikey` itself (not `select 1`, which +// passes with the relation gone) tells them apart; a success is trusted for +// APIKEY_RELATION_CHECK_TTL, so an outage that starts inside that window is +// still read as a refusal (the accepted residual, spec 329). +import { limits, schema, type Db } from '@ansari/auth'; + +/** A check bound to one route's cache; it throws when `auth.apikey` cannot be read. */ +export function createApiKeyRelationCheck(db: Db, now: () => number = Date.now): () => Promise { + let checkedAt: number | null = null; + return async function checkApiKeyRelation(): Promise { + const at = now(); + if (checkedAt !== null && at - checkedAt < limits.APIKEY_RELATION_CHECK_TTL) return; + await db.select({ id: schema.apikey.id }).from(schema.apikey).limit(1); + checkedAt = at; + }; +} diff --git a/apps/auth/src/routes/service-verify.ts b/apps/auth/src/routes/service-verify.ts new file mode 100644 index 00000000..b4fc8c8e --- /dev/null +++ b/apps/auth/src/routes/service-verify.ts @@ -0,0 +1,163 @@ +// The MCP key verify route (#314): apps/api asks whether the key an MCP caller +// presented is a good `ansari-mcp` key, and learns its `client_id`. +// +// POST /api/service/verify-key +// Content-Type: application/json +// { "key": "", "permissions": { "mcp": ["complete"] } } +// +// 200 { valid: true, client_id, key_id } +// 200 { valid: false } every refusal, one body: unknown, disabled, expired, +// exhausted, rate limited, wrong permission, another owner, a missing or +// off-pattern client_id +// 400 Invalid request not JSON, over the byte limit, a key out of bounds, or +// a permission set other than the one the route serves; no key is touched +// 500 Internal error the database, `auth.apikey`, or the service user +// +// The permission set is closed: the route serves exactly `{ mcp: ['complete'] }` +// for the `ansari-mcp` service user, so it cannot verify or spend a WhatsApp +// key under the WhatsApp permission. The key is the only credential; there is +// no shared secret. Each verify spends one unit of the key's budget and one +// rate-limit slot (the plugin's own throttle). No response, log line or Sentry +// event carries the key or the body; errors log `{name, code}` only. +// +// Like the WhatsApp exchange, the router answers every request to its path +// itself (any other method is a bare 404) and is mounted ahead of `corsFor`, +// so no response carries an `Access-Control-*` header. It is outside Better +// Auth's handler path, so no router per-IP rule applies: apps/api calls from +// its egress IP. +import { isMcpClientId, limits, redactError, serviceUsers, type Environment } from '@ansari/auth'; +import express, { Router, type NextFunction, type Request, type Response } from 'express'; + +import { createMcpVerifyAlerts, type KeyRefusalCode, type McpVerifyAlerts } from '../alerts'; +import type { ServiceDeps } from '../app'; +import { createApiKeyRelationCheck } from './apikey-relation'; + +export const SERVICE_VERIFY_PATH = '/api/service/verify-key'; + +const SERVICE = 'ansari-mcp'; +const SERVED_RESOURCE = 'mcp'; +const SERVED_ACTIONS: readonly string[] = serviceUsers.SERVICES[SERVICE].permissions.mcp; + +/** Printable ASCII with no space: sanity bounds only (a real key is 75 characters). */ +const KEY = new RegExp(`^[\\x21-\\x7E]{1,${limits.VERIFY_KEY_MAX_LENGTH}}$`); + +const KEY_REFUSAL_CODES: readonly string[] = ['USAGE_EXCEEDED', 'RATE_LIMITED'] satisfies KeyRefusalCode[]; + +export type VerifyOptions = { + alerts?: McpVerifyAlerts; + /** The clock for the relation-check cache; tests advance it. */ + now?: () => number; +}; + +/** True only for exactly `{ mcp: ['complete'] }`: no other resource, action, order or repeat. */ +function isServedPermissionSet(value: unknown): boolean { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false; + const entries = Object.entries(value); + if (entries.length !== 1) return false; + const [[resource, actions]] = entries as [[string, unknown]]; + return ( + resource === SERVED_RESOURCE && + Array.isArray(actions) && + actions.length === SERVED_ACTIONS.length && + actions.every((action, i) => action === SERVED_ACTIONS[i]) + ); +} + +/** The key, when the body is within bounds and asks for the served set; null otherwise. Other fields are ignored. */ +function presentedKey(body: unknown): string | null { + if (!body || typeof body !== 'object' || Array.isArray(body)) return null; + const { key, permissions } = body as Record; + if (typeof key !== 'string' || !KEY.test(key)) return null; + if (!isServedPermissionSet(permissions)) return null; + return key; +} + +const REFUSED = { valid: false } as const; +const invalidRequest = (res: Response) => res.status(400).json({ message: 'Invalid request' }); +const internalError = (res: Response) => res.status(500).json({ message: 'Internal error' }); + +/** + * `environment` is this deployment's ENVIRONMENT (#314 Amendment 3): only a key + * whose stored prefix names it is served. `ansari-mcp` has no legacy window + * (LEGACY_PREFIXES['ansari-mcp'] is empty). createApp passes it; it is the one place it is set. + */ +export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOptions, environment: Environment): Router { + const alerts = options.alerts ?? createMcpVerifyAlerts(); + const checkApiKeyRelation = createApiKeyRelationCheck(db, options.now ?? Date.now); + const permissions = { [SERVED_RESOURCE]: [...SERVED_ACTIONS] }; + const router = Router(); + + function refuse(res: Response): void { + alerts.unauthorized(); + res.status(200).json(REFUSED); + } + + function fail(res: Response, err: unknown): void { + console.error('mcp key verify failed:', err instanceof Error ? redactError(err) : { name: 'unknown' }); + if (!res.headersSent) internalError(res); + } + + /** body-parser 2.x skips a body it does not handle instead of raising, so the media type is checked here. */ + function requireJson(req: Request, res: Response, next: NextFunction): void { + if (req.is('application/json') !== 'application/json') return void invalidRequest(res); + next(); + } + + /** The parser's errors (malformed JSON, over the limit, a bad charset) → the one 400, never Express's error page. */ + // Express recognizes an error handler by its four parameters, so `_next` stays. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function parseFailure(_err: unknown, _req: Request, res: Response, _next: NextFunction): void { + invalidRequest(res); + } + + async function verify(req: Request, res: Response): Promise { + try { + const key = presentedKey(req.body); + if (!key) return void invalidRequest(res); + + const verified = await auth.api.verifyApiKey({ body: { key, permissions } }); + if (!verified.valid || !verified.key) { + const code = verified.error?.code; + if (typeof code === 'string' && KEY_REFUSAL_CODES.includes(code)) { + alerts.keyRefused(code as KeyRefusalCode); + } + // An outage reads as INVALID_API_KEY; it must be a 500, not a refusal. + await checkApiKeyRelation(); + return refuse(res); + } + + // Only after the plugin accepts: no state of the service user makes a refused key valid. + const owner = await serviceUsers.findServiceUser(db, SERVICE); + if (owner.kind !== 'one') { + alerts.serviceUserUnresolvable(owner.kind === 'many' ? owner.ids.length : 0); + return fail(res, new Error('ansari-mcp service user unresolvable')); + } + if (verified.key.referenceId !== owner.user.id) return refuse(res); + // A key whose stored prefix is not this service's and this environment's + // (another environment's label, another service's, a hand-made one) is + // the same refusal (#314 Amendment 3). No legacy prefix is accepted here: + // the MCP window is closed (second external review, finding 1). + if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res); + + const clientId = serviceUsers.clientIdOf(verified.key.metadata); + if (clientId === null || !isMcpClientId(clientId)) { + alerts.clientIdInvalid(verified.key.id); + return refuse(res); + } + // Counted only for a key that is served: a wrong owner or a bad client id + // is a refusal, already counted by refuse() (security architect, #314). + alerts.keyVerified(verified.key); + res.status(200).json({ valid: true, client_id: clientId, key_id: verified.key.id }); + } catch (err) { + fail(res, err); + } + } + + router.post('/', requireJson, express.json({ limit: limits.VERIFY_BODY_LIMIT }), parseFailure, verify); + // Every other method (OPTIONS included) and every sub-path ends here, so + // nothing falls through to corsFor. + router.use((_req: Request, res: Response) => { + res.status(404).end(); + }); + return router; +} diff --git a/apps/auth/src/routes/whatsapp.ts b/apps/auth/src/routes/whatsapp.ts index daa7115f..9e60532c 100644 --- a/apps/auth/src/routes/whatsapp.ts +++ b/apps/auth/src/routes/whatsapp.ts @@ -26,14 +26,7 @@ // Better Auth's handler path, so no router per-IP rule applies: the WhatsApp // service calls from one egress IP, and the key's own limits and the per-user // budget are the throttle. -import { - consumeWindow, - limits, - redactError, - schema, - serviceUsers, - whatsapp, -} from '@ansari/auth'; +import { consumeWindow, limits, redactError, serviceUsers, whatsapp, type Environment } from '@ansari/auth'; import express, { Router, type NextFunction, type Request, type Response } from 'express'; import { @@ -43,6 +36,7 @@ import { type KeyRefusalCode, } from '../alerts'; import type { ServiceDeps } from '../app'; +import { createApiKeyRelationCheck } from './apikey-relation'; export { WHATSAPP_SESSION_PATH }; @@ -93,25 +87,17 @@ const unauthorized = (res: Response) => res.status(401).json({ message: 'Unautho const invalidRequest = (res: Response) => res.status(400).json({ message: 'Invalid request' }); const internalError = (res: Response) => res.status(500).json({ message: 'Internal error' }); -export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptions = {}): Router { +/** + * `environment` is this deployment's ENVIRONMENT (#314 Amendment 3): only a key + * whose stored prefix names it, or a legacy prefix while the window is open, is + * served. createApp passes it; it is the one place it is set. + */ +export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptions, environment: Environment): Router { const alerts = options.alerts ?? createExchangeAlerts(); const now = options.now ?? Date.now; const router = Router(); - let relationCheckedAt: number | null = null; - - /** - * The plugin reports a database failure (an outage, `auth.apikey` missing) - * as INVALID_API_KEY, the code of an unknown key. A query on `auth.apikey` - * itself (not `select 1`, which passes with the relation gone) tells them - * apart; a success is trusted for APIKEY_RELATION_CHECK_TTL. Throws on failure. - */ - async function checkApiKeyRelation(): Promise { - const at = now(); - if (relationCheckedAt !== null && at - relationCheckedAt < limits.APIKEY_RELATION_CHECK_TTL) return; - await db.select({ id: schema.apikey.id }).from(schema.apikey).limit(1); - relationCheckedAt = at; - } + const checkApiKeyRelation = createApiKeyRelationCheck(db, now); function refuse(res: Response): void { alerts.unauthorized(); @@ -137,13 +123,21 @@ export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptio await checkApiKeyRelation(); return refuse(res); } - alerts.keyVerified(verified.key); const owner = await serviceUsers.findServiceUser(db, SERVICE); if (owner.kind !== 'one') { alerts.serviceUserUnresolvable(owner.kind === 'many' ? owner.ids.length : 0); return fail(res, new Error('whatsapp service user unresolvable')); } if (verified.key.referenceId !== owner.user.id) return refuse(res); + // A key whose stored prefix is not this service's and this environment's + // (another environment's label, another service's, a hand-made one) is + // the same refusal (#314 Amendment 3). The legacy prefixes (`ansari_wa_`, `wa_`) are accepted + // while serviceUsers.LEGACY_UNLABELLED_KEYS holds. + if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res); + // Counted only for a key that is served, as on the verify route: a wrong + // owner or prefix is a refusal, already counted by refuse() (second + // review, finding 6; supersedes leaving the exchange's order as it was). + alerts.keyVerified(verified.key); next(); } catch (err) { fail(res, err); diff --git a/apps/auth/tests/blocked-paths.test.ts b/apps/auth/tests/blocked-paths.test.ts index 89f05354..180d4293 100644 --- a/apps/auth/tests/blocked-paths.test.ts +++ b/apps/auth/tests/blocked-paths.test.ts @@ -5,7 +5,7 @@ // session, so a pass cannot come from a missing or non-admin session. import { request } from 'node:http'; -import { API_KEY_PATHS, BLOCKED_AUTH_PATHS } from '@ansari/auth'; +import { API_KEY_ENDPOINT_COUNT, API_KEY_PATHS, BLOCKED_AUTH_PATHS } from '@ansari/auth'; import { admin } from 'better-auth/plugins'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; @@ -142,6 +142,26 @@ describe('the api-key surface, from the installed package', () => { } }); + // The plugin-upgrade guard (#314, owner request 2026-11-11). The plugin's + // docs advertise `POST /api-key/verify`, but no published version routes it + // (1.7.7, 1.7.20 and 1.8.0-beta.7 all mark verifyApiKey serverOnly). The MCP + // verify route calls it in process; if a plugin bump ever gives it a path, + // these fail loudly, and the blocked-path prefix rule must still refuse it. + // Re-check both on every @better-auth/api-key upgrade. + it('verifyApiKey stays server-only: no path, 7 endpoints, 5 routed', () => { + const endpoint = service.auth.api.verifyApiKey as unknown as ApiEndpoint; + expect(endpoint.path).toBeUndefined(); + expect(API_KEY_ENDPOINT_COUNT).toBe(7); + expect(API_KEY_PATHS).toHaveLength(5); + expect(API_KEY_PATHS).not.toContain('/api-key/verify'); + }); + + it('POST /api/auth/api-key/verify and its case and trailing-slash variants are refused today', async () => { + for (const variant of [...variants('/api-key/verify'), '/api/auth/API-KEY/VERIFY', '/api/auth/api-key/verify/']) { + await expectBlocked(service.publicUrl, variant, 'POST'); + } + }); + it('a path that only starts with "api-key" is not blocked', () => { expect(isBlockedPath('/api/auth/api-keys')).toBe(false); expect(isBlockedPath('/api/auth/api-key-x')).toBe(false); diff --git a/apps/auth/tests/environment.test.ts b/apps/auth/tests/environment.test.ts new file mode 100644 index 00000000..16e2a123 --- /dev/null +++ b/apps/auth/tests/environment.test.ts @@ -0,0 +1,85 @@ +// ENVIRONMENT (#314 Amendment 3, owner 2026-11-12): the deployment label, the +// Sentry environment and the service-key prefix's environment. Under +// NODE_ENV=production it is required and must be staging or production, so a +// deployed apps/auth without it refuses to boot (src/index.ts calls getEnv() +// before anything else) and names the variable, never a value. It has no +// default (owner, 2026-11-12): every process sets it. Nothing reads it at build time: the +// image build runs tsc/tsdown, which never executes getEnv(). +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +import { envSchema, getEnv, resetEnvCache } from '@ansari/auth/env'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const COMPLETE = { + DATABASE_URL: 'postgres://u:p@localhost:5432/auth', + BETTER_AUTH_SECRET: 'x'.repeat(32), + BETTER_AUTH_URL: 'https://auth.example.test', + CORS_ORIGIN: 'https://app.example.test', + AUTH_LAYER_ORIGIN: 'https://api.example.test', + AUTH_JWT_ISSUER: 'https://auth.example.test', + AUTH_JWT_AUDIENCE: 'ansari-api', + RESEND_API_KEY: 'r'.repeat(20), + FRONTEND_URL: 'https://app.example.test', +}; + +const issuesOf = (env: Record) => { + const result = envSchema.safeParse(env); + return result.success ? [] : result.error.issues.map((i) => String(i.path[0])); +}; + +describe('ENVIRONMENT in the schema', () => { + it.each([[undefined], ['development'], ['prod'], ['test']])( + 'NODE_ENV=production with ENVIRONMENT %j is refused, on ENVIRONMENT only', + (environment) => { + expect(issuesOf({ ...COMPLETE, NODE_ENV: 'production', ENVIRONMENT: environment })).toEqual(['ENVIRONMENT']); + } + ); + + it.each([['staging'], ['production']])('NODE_ENV=production with ENVIRONMENT=%s parses', (environment) => { + const result = envSchema.safeParse({ ...COMPLETE, NODE_ENV: 'production', ENVIRONMENT: environment }); + expect(result.success && result.data.ENVIRONMENT).toBe(environment); + }); + + it.each([['development'], ['test'], [undefined]])( + 'NODE_ENV=%s without ENVIRONMENT is refused too: no default anywhere (owner, 2026-11-12)', + (nodeEnv) => { + expect(issuesOf({ ...COMPLETE, NODE_ENV: nodeEnv })).toEqual(['ENVIRONMENT']); + } + ); + + it.each([['development'], ['staging'], ['production']])('NODE_ENV=development with ENVIRONMENT=%s parses', (environment) => { + const result = envSchema.safeParse({ ...COMPLETE, NODE_ENV: 'development', ENVIRONMENT: environment }); + expect(result.success && result.data.ENVIRONMENT).toBe(environment); + }); +}); + +describe('the boot path (getEnv, first call in src/index.ts)', () => { + let saved: NodeJS.ProcessEnv; + beforeEach(() => { + saved = { ...process.env }; + resetEnvCache(); + }); + afterEach(() => { + process.env = saved; + resetEnvCache(); + }); + + it('refuses a production boot without ENVIRONMENT, naming it and no value', () => { + process.env = { ...process.env, ...COMPLETE, NODE_ENV: 'production' }; + delete process.env.ENVIRONMENT; + expect(() => getEnv()).toThrow(/env validation failed for: ENVIRONMENT\./); + try { + getEnv(); + } catch (err) { + expect(String(err)).not.toContain(COMPLETE.BETTER_AUTH_SECRET); + } + }); + + it('boots with ENVIRONMENT=staging, and the value reaches Sentry init', () => { + process.env = { ...process.env, ...COMPLETE, NODE_ENV: 'production', ENVIRONMENT: 'staging' }; + expect(getEnv().ENVIRONMENT).toBe('staging'); + const index = readFileSync(fileURLToPath(new URL('../src/index.ts', import.meta.url)), 'utf8'); + expect(index).toContain('initSentry(env.SENTRY_DSN, env.ENVIRONMENT);'); + }); +}); diff --git a/apps/auth/tests/helpers/leak-scan.ts b/apps/auth/tests/helpers/leak-scan.ts new file mode 100644 index 00000000..5d547640 --- /dev/null +++ b/apps/auth/tests/helpers/leak-scan.ts @@ -0,0 +1,32 @@ +// The key-material scan (#314): a raw key, or any 16-character window of its +// random part, in some text. The public prefix (`ansari_mcp__`, stored in +// `apikey.prefix` and published as the secret-scanning pattern) is exempt, so +// the scan never keys on it. Negative-tested in service-verify.test.ts against +// a known-bad line and the bare prefix (a verification pattern is code). +import { ENVIRONMENTS, serviceUsers } from '@ansari/auth'; + +export const LEAK_WINDOW = 16; + +// Longest first, so `ansari_mcp_staging_` is stripped whole, never just `ansari_mcp_`. +const PREFIXES = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]) + .flatMap((name) => [ + serviceUsers.SERVICES[name].prefix, + ...serviceUsers.LEGACY_PREFIXES[name], + ...ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env)), + ]) + .sort((a, b) => b.length - a.length); + +/** Every 16-character window of the key's random part (the part after its prefix, environment included). */ +export function keyWindows(key: string): string[] { + const prefix = PREFIXES.find((p) => key.startsWith(p)) ?? ''; + const random = key.slice(prefix.length); + if (random.length < LEAK_WINDOW) throw new Error('not a key: its random part is shorter than the scan window'); + return Array.from({ length: random.length - LEAK_WINDOW + 1 }, (_, i) => random.slice(i, i + LEAK_WINDOW)); +} + +/** The windows of `keys` that `text` contains; empty when it carries no key material. */ +export function leakedWindows(text: string, keys: Iterable): string[] { + const found: string[] = []; + for (const key of keys) for (const window of keyWindows(key)) if (text.includes(window)) found.push(window); + return found; +} diff --git a/apps/auth/tests/helpers/service.ts b/apps/auth/tests/helpers/service.ts index 81b3fbd0..8c89edd5 100644 --- a/apps/auth/tests/helpers/service.ts +++ b/apps/auth/tests/helpers/service.ts @@ -15,6 +15,7 @@ import { } from '../../../../packages/auth/tests/helpers/auth-db'; import type { FailedSignInAlert, ListWalkAlert } from '../../src/alerts'; import { createApp, createServiceAuth } from '../../src/app'; +import type { VerifyOptions } from '../../src/routes/service-verify'; import type { ExchangeOptions } from '../../src/routes/whatsapp'; export { TEST_ADMIN_EMAIL } from '../../../../packages/auth/tests/helpers/auth-db'; @@ -40,6 +41,8 @@ export type ServiceOptions = { mailer?: Mailer; /** The WhatsApp exchange's alerts and clock. */ exchange?: ExchangeOptions; + /** The MCP verify route's alerts and clock. */ + verify?: VerifyOptions; }; function listen(app: { listen: (port: number, cb: () => void) => Server }): Promise { @@ -55,6 +58,12 @@ function listen(app: { listen: (port: number, cb: () => void) => Server }): Prom const urlOf = (server: Server) => `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +/** Serves another app (e.g. over the same db with other options) on an ephemeral port; close it when done. */ +export async function serveApp(app: { listen: (port: number, cb: () => void) => Server }): Promise<{ url: string; close: () => Promise }> { + const server = await listen(app); + return { url: urlOf(server), close: () => new Promise((resolve) => server.close(() => resolve())) }; +} + export async function startService(options: ServiceOptions = {}): Promise { setAuthEnv(BASE); const client = await migrate(); @@ -68,7 +77,7 @@ export async function startService(options: ServiceOptions = {}): Promise { warn.mockRestore(); }); }); + +describe('ansari-mcp key limits (#314): the numbers and how they relate', () => { + it('initial caps: 120 per minute (apps/api per-IP cap), 5,000 a day, refilled daily', () => { + expect(limits.MCP_KEY_INITIAL).toEqual({ + rateLimitMax: 120, + rateLimitTimeWindow: 60_000, + refillAmount: 5000, + refillInterval: limits.KEY_REFILL_INTERVAL, + }); + }); + + it('alerts sit at one third of the caps, so a surge is seen before anything is refused', () => { + expect(limits.MCP_VERIFY_KEY_ALERT).toBe(Math.floor(limits.MCP_KEY_INITIAL.rateLimitMax / 3)); + expect(limits.MCP_VERIFY_DAILY_ALERT).toBe(Math.floor(limits.MCP_KEY_INITIAL.refillAmount / 3)); + expect(limits.MCP_VERIFY_UNAUTHORIZED_ALERT).toEqual({ window: limits.EXCHANGE_ALERT_WINDOW, max: 20 }); + }); + + it("bounds are MCP's own constant, as wide as WhatsApp's, and admit the initial values", () => { + expect(limits.MCP_KEY_BOUNDS).not.toBe(limits.WHATSAPP_KEY_BOUNDS); + expect(limits.MCP_KEY_BOUNDS).toEqual(limits.WHATSAPP_KEY_BOUNDS); + const { rateLimitMax, rateLimitTimeWindow, refillAmount } = limits.MCP_KEY_BOUNDS; + const initial = limits.MCP_KEY_INITIAL; + expect(initial.rateLimitMax).toBeGreaterThanOrEqual(rateLimitMax.min); + expect(initial.rateLimitMax).toBeLessThanOrEqual(rateLimitMax.max); + expect(initial.rateLimitTimeWindow).toBeGreaterThanOrEqual(rateLimitTimeWindow.min); + expect(initial.rateLimitTimeWindow).toBeLessThanOrEqual(rateLimitTimeWindow.max); + expect(initial.refillAmount).toBeGreaterThanOrEqual(refillAmount.min); + expect(initial.refillAmount).toBeLessThanOrEqual(refillAmount.max); + }); + + it('the verify body holds a maximal key with room to spare', () => { + expect(limits.VERIFY_KEY_MAX_LENGTH).toBe(256); + expect(limits.VERIFY_BODY_LIMIT).toBe(1024); + const body = JSON.stringify({ key: 'k'.repeat(limits.VERIFY_KEY_MAX_LENGTH), permissions: { mcp: ['complete'] } }); + expect(Buffer.byteLength(body)).toBeLessThan(limits.VERIFY_BODY_LIMIT); + }); +}); diff --git a/apps/auth/tests/service-keys-no-dsn.test.ts b/apps/auth/tests/service-keys-no-dsn.test.ts index 6f830aff..ee5aa19a 100644 --- a/apps/auth/tests/service-keys-no-dsn.test.ts +++ b/apps/auth/tests/service-keys-no-dsn.test.ts @@ -3,9 +3,9 @@ // test shows the unrecorded path is taken on purpose, not because an // uninitialised Sentry's flush happens to answer false. import * as Sentry from '@sentry/node'; -import { afterAll, beforeAll, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; -import { EXIT_UNRECORDED, scriptRecorder, serviceKeys, unrecordedRecorder } from '../scripts/service-keys'; +import { EXIT_UNRECORDED, scriptRecorder, scriptSentryInit, serviceKeys, unrecordedRecorder, validEnvironment } from '../scripts/service-keys'; import { startService, type Service } from './helpers/service'; let service: Service; @@ -21,6 +21,7 @@ async function run(argv: string[], recorder: ReturnType) const lines: string[] = []; const result = await serviceKeys(argv, { databaseUrl: 'postgres://db.example:6543/auth', + environment: 'staging', connect: () => ({ db: service.db, auth: service.auth }), recorder, print: (line) => lines.push(line), @@ -30,7 +31,7 @@ async function run(argv: string[], recorder: ReturnType) it('no DSN: nothing is captured or flushed; the write stands, the banner names the key id, exit 3', async () => { expect(Sentry.getClient()).toBeUndefined(); - const recorder = scriptRecorder(undefined); + const recorder = scriptRecorder(undefined, 'staging'); expect(recorder).toBe(unrecordedRecorder); expect(Sentry.getClient()).toBeUndefined(); @@ -46,7 +47,7 @@ it('no DSN: nothing is captured or flushed; the write stands, the banner names t recorder ); expect(keyed.exitCode, keyed.text).toBe(EXIT_UNRECORDED); - const keyId = /Created key ([0-9a-f-]{36})/.exec(keyed.text)![1]!; + const keyId = /Created \w+ key ([0-9a-f-]{36})/.exec(keyed.text)![1]!; const banner = keyed.text.slice(keyed.text.indexOf('THE SENTRY RECORD')); expect(banner).toContain('SENTRY_DSN is not set: no record was attempted.'); expect(banner).toContain(`key ${keyId}`); @@ -58,3 +59,20 @@ it('no DSN: nothing is captured or flushed; the write stands, the banner names t // the old implicit path (an uninitialised flush answering false) never printed. expect(Sentry.getClient()).toBeUndefined(); }); + +describe('the script\'s Sentry environment (#314 Amendment 3, codex)', () => { + it('is ENVIRONMENT, never NODE_ENV', () => { + const before = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + try { + expect(scriptSentryInit('https://public@o0.ingest.sentry.io/0', 'staging').environment).toBe('staging'); + expect(scriptSentryInit('https://public@o0.ingest.sentry.io/0', 'production').environment).toBe('production'); + // main() validates before scriptRecorder: a typo never reaches Sentry.init. + for (const bad of [undefined, '', 'prod', 'Production', 'test']) expect(validEnvironment(bad), String(bad)).toBeNull(); + for (const good of ['development', 'staging', 'production']) expect(validEnvironment(good)).toBe(good); + } finally { + process.env.NODE_ENV = before; + } + }); +}); + diff --git a/apps/auth/tests/service-keys-sentry.test.ts b/apps/auth/tests/service-keys-sentry.test.ts index a0ac7c73..35dfc6a0 100644 --- a/apps/auth/tests/service-keys-sentry.test.ts +++ b/apps/auth/tests/service-keys-sentry.test.ts @@ -53,12 +53,13 @@ beforeEach(() => { async function createKey(print: (line: string) => void) { const result = await serviceKeys(['create-key', 'whatsapp', ...LIMIT_FLAGS, '--confirm', userId], { databaseUrl: DB_URL, + environment: 'staging', connect: () => ({ db: service.db, auth: service.auth }), recorder: sentryRecorder, print, }); expect(result.exitCode).toBe(0); - const key = result.lines.find((l) => /^ansari_wa_[A-Za-z]{64}$/.test(l)); + const key = result.lines.find((l) => /^ansari_wa_staging_[A-Za-z]{64}$/.test(l)); if (!key) throw new Error('no key in the output'); return key; } diff --git a/apps/auth/tests/service-keys.test.ts b/apps/auth/tests/service-keys.test.ts index 9b95df0a..06fd461d 100644 --- a/apps/auth/tests/service-keys.test.ts +++ b/apps/auth/tests/service-keys.test.ts @@ -3,19 +3,24 @@ // posture, against the auth database on pglite. Script functions are driven // directly; Sentry through a spy transport. import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; import * as Sentry from '@sentry/node'; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { limits, serviceUsers } from '@ansari/auth'; +import { ENVIRONMENTS, limits, serviceUsers } from '@ansari/auth'; import { checkKeyLimits, EXIT_NOTHING_WRITTEN, EXIT_UNRECORDED, KEY_EVENT_MESSAGE, + ENVIRONMENT_RULE, + MCP_CLIENT_ID_RULE, parseArgs, RefusedError, + runServiceKeys, sentryRecorder, serviceKeys, type KeyEvent, @@ -34,7 +39,15 @@ const DB_URL_DISTINCT = 'postgres://opsname-zq:pw-zq-9@db.example:6543/authdb-zq const INITIAL = limits.WHATSAPP_KEY_INITIAL; const LIMIT_FLAGS = ['--rate-max', '60', '--rate-window', '60', '--daily', '3000']; -const WA_KEY = /ansari_wa_[A-Za-z]{64}/g; +const WA_KEY = /ansari_wa_staging_[A-Za-z]{64}/g; +/** An ansari-mcp key's flags: its initial limits and the client id it must carry (#314). */ +const MCP_INITIAL = limits.MCP_KEY_INITIAL; +const MCP_FLAGS = [ + '--rate-max', String(MCP_INITIAL.rateLimitMax), + '--rate-window', String(MCP_INITIAL.rateLimitTimeWindow / 1000), + '--daily', String(MCP_INITIAL.refillAmount), + '--client-id', 'ansari-mcp-production', +]; let service: Service; @@ -66,13 +79,17 @@ function memoryRecorder(flushed = true): Recorder & { events: KeyEvent[]; flushe }; } -type RunOptions = { url?: string | undefined; recorder?: Recorder; flushTimeoutMs?: number }; +type RunOptions = { url?: string | undefined; environment?: string | undefined; recorder?: Recorder; flushTimeoutMs?: number }; + +/** The ENVIRONMENT these tests run the script under, unless a test says otherwise. */ +const SCRIPT_ENVIRONMENT = 'staging'; async function run(argv: string[], opts: RunOptions = {}) { const connect = vi.fn(() => ({ db: service.db, auth: service.auth })); const print = vi.fn<(line: string) => void>(); const result = await serviceKeys(argv, { databaseUrl: 'url' in opts ? opts.url : DB_URL, + environment: 'environment' in opts ? opts.environment : SCRIPT_ENVIRONMENT, connect, recorder: opts.recorder ?? memoryRecorder(), print, @@ -100,7 +117,7 @@ async function createKey(kind: 'create-key' | 'rotate' = 'create-key', flags = L expect(result.exitCode, result.text).toBe(0); const prefix = serviceUsers.SERVICES[name as serviceUsers.ServiceName].prefix; const key = result.lines.find((l) => l.startsWith(prefix) && l.length > prefix.length + 60); - const id = /Created key ([0-9a-f-]{36})/.exec(result.text)?.[1]; + const id = /Created \w+ key ([0-9a-f-]{36})/.exec(result.text)?.[1]; if (!key || !id) throw new Error('no key in the output'); return { ...result, key, id, userId }; } @@ -307,7 +324,7 @@ describe('every subcommand', () => { const userId = await createService(); const first = await createKey(); if (name === 'create-key') { - expect(first.text).toContain(`Created key ${first.id}`); + expect(first.text).toContain(`Created staging key ${first.id}`); return; } const argv = @@ -320,7 +337,7 @@ describe('every subcommand', () => { const { text, exitCode } = await run([...argv, '--confirm', confirm]); expect(exitCode).toBe(0); expect(text).toContain(first.id); - if (name === 'rotate') expect(text).toMatch(/Created key [0-9a-f-]{36}/); + if (name === 'rotate') expect(text).toMatch(/Created staging key [0-9a-f-]{36}/); }); }); @@ -511,7 +528,7 @@ describe('create-key', () => { expect(text).not.toContain(row!.key as string); expect(row).toMatchObject({ reference_id: userId, - prefix: 'ansari_wa_', + prefix: 'ansari_wa_staging_', start: null, enabled: true, rate_limit_enabled: true, @@ -550,6 +567,88 @@ describe('create-key', () => { }); }); +describe('ansari-mcp keys: the client id (#314, scenario 14)', () => { + const NO_CLIENT = MCP_FLAGS.slice(0, -2); + const KEY = `ansari_mcp_${'Q'.repeat(64)}`; + + it.each([ + ['no --client-id', []], + ['another client', ['--client-id', 'claude-skill']], + ['upper case', ['--client-id', 'ANSARI-MCP']], + ['an underscore after the name', ['--client-id', 'ansari-mcp_x']], + ['no separator', ['--client-id', 'ansari-mcpx']], + ['an empty suffix', ['--client-id', 'ansari-mcp-']], + ['a prefix before the name', ['--client-id', 'x-ansari-mcp']], + ['65 characters', ['--client-id', `ansari-mcp-${'a'.repeat(54)}`]], + ['a key', ['--client-id', KEY]], + ['a key body', ['--client-id', `ansari-mcp-${'q'.repeat(40)}`]], + ] as [string, string[]][])('create-key and rotate refuse %s, write nothing and record nothing', async (_case, extra) => { + const userId = await createService('ansari-mcp'); + for (const kind of ['create-key', 'rotate']) { + const before = await rowCounts(); + const recorder = memoryRecorder(); + const result = await run([kind, 'ansari-mcp', ...NO_CLIENT, ...extra, '--confirm', userId], { recorder }); + expect(result.exitCode, result.text).toBe(1); + expect(result.text).toContain('--client-id'); + // The value is never echoed (the fixed rule text itself names `ansari-mcp-`). + if (extra[1] !== undefined) expect(result.text.replace(MCP_CLIENT_ID_RULE, '')).not.toContain(extra[1]); + expect(await rowCounts()).toEqual(before); + expect(recorder.events).toEqual([]); + } + }); + + it('refuses a command built without the parser (runServiceKeys checks again)', async () => { + const userId = await createService('ansari-mcp'); + for (const clientId of [null, 'claude-skill']) { + await expect( + runServiceKeys( + { db: service.db, auth: service.auth, environment: 'staging' }, + { kind: 'create-key', service: 'ansari-mcp', confirm: userId, limits: MCP_INITIAL, name: null, clientId } + ) + ).rejects.toBeInstanceOf(RefusedError); + } + expect((await rowCounts())?.keys).toBe(0); + }); + + it.each([['ansari-mcp'], ['ansari-mcp-production'], ['ansari-mcp-beta.2_x'], [`ansari-mcp-${'ab1-'.repeat(13)}x`]])( + 'accepts %s, stores it as metadata.clientId, and list shows it', + async (clientId) => { + await createService('ansari-mcp'); + const { id, key } = await createKey('create-key', [...NO_CLIENT, '--client-id', clientId], 'ansari-mcp'); + const row = await keyRow(id); + expect(JSON.parse(row!.metadata as string)).toEqual({ clientId }); + expect(JSON.parse(row!.permissions as string)).toEqual({ mcp: ['complete'] }); + expect((await verify(key, { mcp: ['complete'] })).valid).toBe(true); + const { exitCode, text } = await run(['list', 'ansari-mcp']); + expect(exitCode).toBe(0); + expect(text).toContain(`client_id ${clientId}`); + } + ); + + it('rotate needs the client id too, and keeps both keys live', async () => { + await createService('ansari-mcp'); + const old = await createKey('create-key', MCP_FLAGS, 'ansari-mcp'); + const fresh = await createKey('rotate', MCP_FLAGS, 'ansari-mcp'); + expect(JSON.parse((await keyRow(fresh.id))!.metadata as string)).toEqual({ clientId: 'ansari-mcp-production' }); + expect((await verify(old.key, { mcp: ['complete'] })).valid).toBe(true); + expect((await verify(fresh.key, { mcp: ['complete'] })).valid).toBe(true); + }); + + it('a whatsapp key still defaults its client id to the service name', async () => { + await createService(); + const { id } = await createKey(); + expect(JSON.parse((await keyRow(id))!.metadata as string)).toEqual({ clientId: 'whatsapp' }); + }); + + it('checkKeyLimits uses MCP_KEY_BOUNDS for ansari-mcp', () => { + expect(serviceUsers.SERVICES['ansari-mcp'].bounds).toBe(limits.MCP_KEY_BOUNDS); + expect(checkKeyLimits('ansari-mcp', MCP_INITIAL)).toEqual(MCP_INITIAL); + expect(() => + checkKeyLimits('ansari-mcp', { ...MCP_INITIAL, rateLimitMax: limits.MCP_KEY_BOUNDS.rateLimitMax.max + 1 }) + ).toThrow(/Out of bounds/); + }); +}); + describe('list', () => { it('prints id, name, prefix, permissions, enabled, limits and dates per key; never a key or a hash', async () => { await createService(); @@ -565,7 +664,7 @@ describe('list', () => { expect(text).not.toContain(key.slice(3, 20)); expect(text).not.toContain((await keyRow(id))!.key as string); } - for (const field of ['name wa-a', 'name wa-b', 'prefix ansari_wa_', 'permissions {"whatsapp":["mint"]}', 'enabled true', 'limits 60 per 60 s; budget 3000 per 24 h', 'created 20', 'last request 20', 'last request never']) { + for (const field of ['name wa-a', 'name wa-b', 'prefix ansari_wa_', 'permissions {"whatsapp":["mint"]}', 'client_id whatsapp', 'enabled true', 'limits 60 per 60 s; budget 3000 per 24 h', 'created 20', 'last request 20', 'last request never']) { expect(text).toContain(field); } expect(text.match(WA_KEY)).toBeNull(); @@ -623,7 +722,7 @@ describe('revoke', () => { it("refuses a key that is not the service's", async () => { await createService(); await createService('ansari-mcp'); - const mcp = await createKey('create-key', LIMIT_FLAGS, 'ansari-mcp'); + const mcp = await createKey('create-key', MCP_FLAGS, 'ansari-mcp'); const { exitCode, text } = await run(['revoke', 'whatsapp', '--key', mcp.id, '--confirm', mcp.id]); expect(exitCode).toBe(1); expect(text).toMatch(/not a key of this service/); @@ -690,7 +789,7 @@ describe('SECRET_SCANNING_PATTERNS', () => { await createService('whatsapp'); await createService('ansari-mcp'); const wa = (await createKey('create-key', LIMIT_FLAGS, 'whatsapp')).key; - const mcp = (await createKey('create-key', LIMIT_FLAGS, 'ansari-mcp')).key; + const mcp = (await createKey('create-key', MCP_FLAGS, 'ansari-mcp')).key; const { whatsapp, 'ansari-mcp': amcp } = serviceUsers.SECRET_SCANNING_PATTERNS; const { rows } = await service.client.query<{ token: string }>('select token from auth.session limit 1'); const sessionToken = rows[0]?.token ?? (await import('better-auth/crypto')).generateRandomString(32); @@ -713,6 +812,123 @@ describe('SECRET_SCANNING_PATTERNS', () => { }); expect(hits.filter(Boolean)).toHaveLength(2); }); + + const NAMES = Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]; + const BODY = 'Q'.repeat(64); + + // Both states of the legacy window are live code (second review, finding 2): + // the builders take the state, and every assertion below runs for both, so + // closing the window (LEGACY_UNLABELLED_KEYS = false) breaks nothing here. + describe.each([true, false])('the legacy window open: %s', (legacy) => { + it('the main pattern catches every labelled prefix, and the bare prefix only where the window accepts it', () => { + for (const name of NAMES) { + const pattern = serviceUsers.scanningPatternFor(name, legacy); + for (const env of ENVIRONMENTS) expect(pattern.test(`${serviceUsers.keyPrefix(name, env)}${BODY}`), `${name} ${env}`).toBe(true); + const bare = serviceUsers.SERVICES[name].prefix; + expect(pattern.test(`${bare}${BODY}`), `${name} bare`).toBe(legacy && serviceUsers.LEGACY_PREFIXES[name].includes(bare)); + expect(pattern.test(`${bare}qa_${BODY}`)).toBe(false); + } + }); + + it('every prefix a route accepts, in every environment, is caught by the main or a legacy pattern (codex, PR #372)', () => { + for (const name of NAMES) { + const patterns = [serviceUsers.scanningPatternFor(name, legacy), ...serviceUsers.legacyScanningPatternsFor(name, legacy)]; + for (const env of ENVIRONMENTS) { + for (const prefix of serviceUsers.acceptedKeyPrefixesFor(name, env, legacy)) { + expect(patterns.some((p) => p.test(`${prefix}${BODY}`)), `${name} ${env} ${prefix}`).toBe(true); + } + } + } + }); + + it('accepts exactly its own environment\'s prefix, plus the legacy prefixes only while open', () => { + for (const name of NAMES) { + for (const env of ENVIRONMENTS) { + expect(serviceUsers.acceptedKeyPrefixesFor(name, env, legacy)).toEqual( + legacy ? [serviceUsers.keyPrefix(name, env), ...serviceUsers.LEGACY_PREFIXES[name]] : [serviceUsers.keyPrefix(name, env)] + ); + } + if (!legacy) expect(serviceUsers.legacyScanningPatternsFor(name, legacy)).toEqual([]); + } + }); + }); + + it('the window today: WhatsApp keeps ansari_wa_ and wa_, ansari-mcp has none (second review, finding 1)', () => { + expect(serviceUsers.LEGACY_PREFIXES).toEqual({ whatsapp: ['ansari_wa_', 'wa_'], 'ansari-mcp': [] }); + expect(serviceUsers.legacyScanningPatternsFor('whatsapp', true).map((p) => p.source)).toEqual(['wa_[A-Za-z]{64}']); + expect(serviceUsers.legacyScanningPatternsFor('ansari-mcp', true)).toEqual([]); + // The exported constants are the builders under the current state, whatever it is. + for (const name of NAMES) { + expect(serviceUsers.SECRET_SCANNING_PATTERNS[name].source).toBe( + serviceUsers.scanningPatternFor(name, serviceUsers.LEGACY_UNLABELLED_KEYS).source + ); + } + }); + + it('the runbook names every legacy pattern by its source', () => { + const runbook = readFileSync(fileURLToPath(new URL('../../../docs/cutover/service-keys-runbook.md', import.meta.url)), 'utf8'); + for (const pattern of Object.values(serviceUsers.LEGACY_SCANNING_PATTERNS).flat()) { + expect(runbook).toContain(`\`${pattern.source}\``); + } + }); + + it('keyPrefix is ansari___ for every service and environment, all distinct', () => { + const all = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]).flatMap((name) => + ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env)) + ); + for (const prefix of all) expect(prefix).toMatch(/^ansari_[a-z]+_(development|staging|production)_$/); + expect(new Set(all).size).toBe(all.length); + }); +}); + +describe('ENVIRONMENT (#314 Amendment 3)', () => { + it.each([[undefined], [''], ['prod'], ['live'], ['Production'], ['test']])( + 'absent or not one of development, staging, production (%j) → refused before anything connects', + async (environment) => { + for (const argv of [['list', 'whatsapp'], ['create-key', 'whatsapp', ...LIMIT_FLAGS]]) { + const { exitCode, text, connect } = await run(argv, { environment }); + expect(exitCode).toBe(1); + expect(text).toContain(ENVIRONMENT_RULE); + if (environment) expect(text.replace(ENVIRONMENT_RULE, '')).not.toContain(` ${environment} `); + expect(connect).not.toHaveBeenCalled(); + } + } + ); + + it('--env is no longer an option: the environment comes from the process alone', () => { + expect(() => parseArgs(['create-key', 'whatsapp', '--env', 'production', ...LIMIT_FLAGS])).toThrow(/not an option/); + }); + + it.each(ENVIRONMENTS.map((environment) => [environment]))( + 'under %s: printed under the database line, named with its prefix in the show step', + async (environment) => { + await createService(); + const { exitCode, lines, text } = await run(['create-key', 'whatsapp', ...LIMIT_FLAGS], { environment }); + expect(exitCode).toBe(2); + const at = lines.findIndex((l) => l.startsWith('Auth database: ')); + expect(lines[at + 1]).toBe(`Environment: ${environment} (a new key's prefix carries it: ansari__${environment}_)`); + expect(text).toContain(`environment ${environment} (prefix ansari_wa_${environment}_)`); + } + ); + + it('a created key carries ENVIRONMENT in its prefix, the row and list', async () => { + const userId = await createService(); + const result = await run(['create-key', 'whatsapp', ...LIMIT_FLAGS, '--confirm', userId], { environment: 'production' }); + expect(result.exitCode, result.text).toBe(0); + expect(result.lines.some((l) => /^ansari_wa_production_[A-Za-z]{64}$/.test(l))).toBe(true); + const id = /Created production key ([0-9a-f-]{36})/.exec(result.text)?.[1]; + expect((await keyRow(id!))!.prefix).toBe('ansari_wa_production_'); + expect((await run(['list', 'whatsapp'])).text).toContain('prefix ansari_wa_production_'); + }); + + it('a pasted labelled key is refused in --name, without echoing it', async () => { + const userId = await createService(); + const pasted = `ansari_wa_production_${'k'.repeat(40)}`; // within the 64-character label bound, so the key-shape check decides + const result = await run(['create-key', 'whatsapp', ...LIMIT_FLAGS, '--name', pasted, '--confirm', userId]); + expect(result.exitCode).toBe(1); + expect(result.text).toMatch(/looks like a key/); + expect(result.text).not.toContain(pasted); + }); }); describe('the durable record', () => { @@ -747,12 +963,12 @@ describe('the durable record', () => { recorder: sentryRecorder, }); const key1 = first.lines.find((l) => l.startsWith('ansari_wa_'))!; - const id1 = /Created key ([0-9a-f-]{36})/.exec(first.text)![1]!; + const id1 = /Created \w+ key ([0-9a-f-]{36})/.exec(first.text)![1]!; const rotated = await run(['rotate', 'whatsapp', ...LIMIT_FLAGS, '--name', 'wa-2', '--confirm', userId], { recorder: sentryRecorder, }); const key2 = rotated.lines.find((l) => l.startsWith('ansari_wa_'))!; - const id2 = /Created key ([0-9a-f-]{36})/.exec(rotated.text)![1]!; + const id2 = /Created \w+ key ([0-9a-f-]{36})/.exec(rotated.text)![1]!; await run(['update-limits', 'whatsapp', '--key', id2, ...LIMIT_FLAGS, '--confirm', id2], { recorder: sentryRecorder }); await run(['revoke', 'whatsapp', '--key', id1, '--confirm', id1], { recorder: sentryRecorder }); await run(['list', 'whatsapp'], { recorder: sentryRecorder }); @@ -810,7 +1026,7 @@ describe('the durable record', () => { expect(exitCode).not.toBe(0); expect(text).toMatch(/SENTRY RECORD OF THIS ACTION WAS NOT SENT/); expect(text).toMatch(/runbook's key log/); - const id = /Created key ([0-9a-f-]{36})/.exec(text)![1]!; + const id = /Created \w+ key ([0-9a-f-]{36})/.exec(text)![1]!; expect(text).toMatch(new RegExp(`action create-key, service whatsapp, user ${userId}, key ${id}`)); // The write stands, and the key was still shown once (it is not stored anywhere else). expect(await keyRow(id)).toMatchObject({ enabled: true }); diff --git a/apps/auth/tests/service-verify-sentry.test.ts b/apps/auth/tests/service-verify-sentry.test.ts new file mode 100644 index 00000000..7eda528a --- /dev/null +++ b/apps/auth/tests/service-verify-sentry.test.ts @@ -0,0 +1,102 @@ +// The MCP verify route under the service's own Sentry options (#314: no Sentry +// event or log line carries the key, any 16-character window of its random +// part, or the request body). Default integrations stay on, as in production; +// only the transport is a spy. Its own file: the Console integration patches +// `console` for the whole process. +import { inspect } from 'node:util'; + +import * as Sentry from '@sentry/node'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { getEnv, limits, serviceUsers } from '@ansari/auth'; + +import { MCP_VERIFY_ALERT_MESSAGE, SERVICE_SENTRY_OPTIONS } from '../src/alerts'; +import { SERVICE_VERIFY_PATH } from '../src/routes/service-verify'; +import { leakedWindows } from './helpers/leak-scan'; +import { startService, type Service } from './helpers/service'; + +const MCP = { mcp: ['complete'] }; +const envelopes: unknown[] = []; +const logged: unknown[][] = []; +const rawKeys: string[] = []; +let service: Service; + +beforeAll(async () => { + Sentry.init({ + dsn: 'https://public@o0.ingest.sentry.io/0', + environment: 'test', + ...SERVICE_SENTRY_OPTIONS, + transport: () => ({ + send: async (envelope) => { + envelopes.push(envelope); + return {}; + }, + flush: async () => true, + }), + }); + // After Sentry.init, so the Console integration's patch sits underneath. + for (const level of ['log', 'info', 'warn', 'error', 'debug'] as const) { + vi.spyOn(console, level).mockImplementation((...args: unknown[]) => { + logged.push(args); + }); + } + service = await startService(); +}); + +afterAll(async () => { + vi.restoreAllMocks(); + await Sentry.close(); + await service?.close(); +}); + +async function mcpKey(userId: string, metadata: unknown = { clientId: 'ansari-mcp-production' }) { + const { key } = await service.auth.api.createApiKey({ + body: { userId, prefix: serviceUsers.keyPrefix('ansari-mcp', getEnv().ENVIRONMENT), permissions: MCP, metadata, rateLimitEnabled: false }, + }); + rawKeys.push(key); + return key; +} + +const post = (body: unknown) => + fetch(`${service.publicUrl}${SERVICE_VERIFY_PATH}`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); + +describe('Sentry events and logs from the verify route', () => { + it('carry no key, no window of its random part and no body, across the alerting cases', async () => { + const owner = await serviceUsers.createServiceUser(service.db, 'ansari-mcp'); + const good = await mcpKey(owner.id); + const offPattern = await mcpKey(owner.id, { clientId: 'claude-skill' }); + const unknown = `${serviceUsers.keyPrefix('ansari-mcp', getEnv().ENVIRONMENT)}${'Z'.repeat(64)}`; + rawKeys.push(unknown); + + expect((await post({ key: good, permissions: MCP })).status).toBe(200); + // client-id-invalid, while the request (with its body) is in flight. + expect(await (await post({ key: offPattern, permissions: MCP })).text()).toBe('{"valid":false}'); + // Refusal volume. + for (let i = 0; i < limits.MCP_VERIFY_UNAUTHORIZED_ALERT.max; i++) { + expect((await post({ key: unknown, permissions: MCP })).status).toBe(200); + } + // A 400 with a key in the body. + expect((await post({ key: good, permissions: { whatsapp: ['mint'] } })).status).toBe(400); + // service-user-unresolvable: the owner loses its `service` row; a 500. + await service.client.query('delete from auth.account where user_id = $1', [owner.id]); + expect((await post({ key: good, permissions: MCP })).status).toBe(500); + await Sentry.flush(2000); + + const serialized = JSON.stringify(envelopes); + for (const kind of ['client-id-invalid', 'unauthorized-volume', 'service-user-unresolvable']) { + expect(serialized).toContain(`${MCP_VERIFY_ALERT_MESSAGE}: ${kind}`); + expect(serialized).toContain(`mcp-verify-${kind}`); + } + expect(leakedWindows(serialized, rawKeys)).toEqual([]); + expect(serialized).not.toContain('"permissions"'); + expect(serialized).not.toContain('claude-skill'); + + const consoleText = logged.map((args) => args.map((a) => inspect(a, { depth: 8 })).join(' ')).join('\n'); + expect(consoleText).toContain(MCP_VERIFY_ALERT_MESSAGE); + expect(leakedWindows(consoleText, rawKeys)).toEqual([]); + }); +}); diff --git a/apps/auth/tests/service-verify.test.ts b/apps/auth/tests/service-verify.test.ts new file mode 100644 index 00000000..6b046534 --- /dev/null +++ b/apps/auth/tests/service-verify.test.ts @@ -0,0 +1,764 @@ +// POST /api/service/verify-key (#314, plan phase 2), over HTTP through +// startService on pglite built from the auth journal, with the real api-key +// plugin. Keys are made through the service-keys script's own path +// (parseArgs → runServiceKeys), except the ones the script refuses to make, +// which are created in process the way a key made outside the script would be. +// Spec 314's apps/auth scenarios 1–10, 12, 13 and 15 are here; 11 is in +// blocked-paths.test.ts, 14 in service-keys.test.ts, and the Sentry leg of 12 +// in service-verify-sentry.test.ts. +import { inspect } from 'node:util'; + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { ENVIRONMENTS, getEnv, limits, serviceUsers } from '@ansari/auth'; + +import { createMcpVerifyAlerts, EXCHANGE_ALERT_MESSAGE, MCP_VERIFY_ALERT_MESSAGE, type McpVerifyAlert } from '../src/alerts'; +import { createApp } from '../src/app'; +import { SERVICE_VERIFY_PATH } from '../src/routes/service-verify'; +import { WHATSAPP_SESSION_PATH } from '../src/routes/whatsapp'; +import { parseArgs, runServiceKeys } from '../scripts/service-keys'; +import { keyWindows, leakedWindows } from './helpers/leak-scan'; +import { BASE, serveApp, signUpTokens, startService, type Service } from './helpers/service'; + +const MCP = { mcp: ['complete'] }; + +/** Every console line written while this file runs, for the leak scan at the end. */ +const logged: unknown[][] = []; +const consoleSpies = (['log', 'info', 'warn', 'error', 'debug'] as const).map((level) => + vi.spyOn(console, level).mockImplementation((...args: unknown[]) => { + logged.push(args); + }) +); + +/** Every raw key this file made: none may reach a response or a log. */ +const rawKeys = new Set(); +const remember = (key: string) => { + rawKeys.add(key); + return key; +}; + +class Clock { + at = Date.now(); + now = () => this.at; + advance(ms: number) { + this.at += ms; + } +} + +const clock = new Clock(); +const alerts: McpVerifyAlert[] = []; +const alertsOf = (kind: McpVerifyAlert['kind']) => alerts.filter((a) => a.kind === kind); +/** A fresh alert window, so one test's counts never reach the next. */ +const nextAlertWindow = () => clock.advance(limits.EXCHANGE_ALERT_WINDOW * 1000); + +/** The tracker of the service started last, so a test can spy on what it is told. */ +let verifyAlerts: ReturnType; +/** The tracker of the suite's main `service` (later services each get their own). */ +let serviceAlerts: ReturnType; + +function startVerifyService(): Promise { + verifyAlerts = createMcpVerifyAlerts({ send: (alert) => alerts.push(alert), now: clock.now }); + return startService({ verify: { alerts: verifyAlerts, now: clock.now } }); +} + +type ServiceName = serviceUsers.ServiceName; + +const LIMIT_FLAGS: Record = { + 'ansari-mcp': [ + '--rate-max', String(limits.MCP_KEY_INITIAL.rateLimitMax), + '--rate-window', String(limits.MCP_KEY_INITIAL.rateLimitTimeWindow / 1000), + '--daily', String(limits.MCP_KEY_INITIAL.refillAmount), + '--client-id', 'ansari-mcp-production', + ], + whatsapp: ['--rate-max', '60', '--rate-window', '60', '--daily', '3000'], +}; + +async function serviceUserOf(on: Service, name: ServiceName): Promise { + const found = await serviceUsers.findServiceUser(on.db, name); + if (found.kind === 'one') return found.user.id; + if (found.kind === 'many') throw new Error(`more than one ${name} service user`); + return (await serviceUsers.createServiceUser(on.db, name)).id; +} + +/** A key made by the service-keys script's create-key, as an operator would; returns the raw key and its id. */ +async function scriptKey(name: ServiceName = 'ansari-mcp', on: Service = service, flags = LIMIT_FLAGS[name]) { + const userId = await serviceUserOf(on, name); + // The script issues under the same ENVIRONMENT the app under test serves (getEnv(): development here). + const environment = getEnv().ENVIRONMENT; + const result = await runServiceKeys({ db: on.db, auth: on.auth, environment }, parseArgs(['create-key', name, ...flags, '--confirm', userId])); + expect(result.exitCode).toBe(0); + const prefix = serviceUsers.keyPrefix(name, environment); + const raw = result.lines.find((l) => l.startsWith(prefix) && l.length > prefix.length + 60); + const id = /Created \w+ key ([0-9a-f-]{36})/.exec(result.lines.join('\n'))?.[1]; + if (!raw || !id) throw new Error('no key in the script output'); + return { key: remember(raw), id }; +} + +/** A key the script would refuse to make (a key created outside it): in process, owned by `userId`. */ +async function outsideKey(userId: string, body: Record = {}, on: Service = service) { + const created = await on.auth.api.createApiKey({ + // This environment's label by default, so the other checks are what the tests reach. + body: { userId, prefix: serviceUsers.keyPrefix('ansari-mcp', getEnv().ENVIRONMENT), name: 'outside', permissions: MCP, rateLimitEnabled: false, ...body }, + }); + return { key: remember(created.key), id: created.id }; +} + +type KeyRow = { remaining: number | null; request_count: number; last_request: string | null; enabled: boolean }; + +async function keyRow(id: string, on: Service = service): Promise { + const { rows } = await on.client.query( + 'select remaining, request_count, last_request, enabled from auth.apikey where id = $1', + [id] + ); + return rows[0]; +} + +type PostOptions = { contentType?: string | null; headers?: Record; method?: string; path?: string; on?: Service }; +type Answer = { status: number; text: string; headers: Headers }; + +/** A raw request to the route. Every response is checked for every key this file has made. */ +async function post(body: unknown, opts: PostOptions = {}): Promise { + const headers: Record = { ...opts.headers }; + if (opts.contentType !== null) headers['content-type'] = opts.contentType ?? 'application/json'; + const res = await fetch(`${(opts.on ?? service).publicUrl}${opts.path ?? SERVICE_VERIFY_PATH}`, { + method: opts.method ?? 'POST', + headers, + body: typeof body === 'string' ? body : JSON.stringify(body), + }); + const text = await res.text(); + expect(leakedWindows(text, rawKeys)).toEqual([]); + return { status: res.status, text, headers: res.headers }; +} + +const verify = (key: string, opts: PostOptions = {}) => post({ key, permissions: MCP }, opts); + +const REFUSED = '{"valid":false}'; +const INVALID = '{"message":"Invalid request"}'; +const INTERNAL = '{"message":"Internal error"}'; + +function expectRefused(res: Answer): void { + expect(res.status).toBe(200); + expect(res.text).toBe(REFUSED); + expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8'); + expect(res.headers.get('content-length')).toBe(String(REFUSED.length)); +} + +let service: Service; +let mcpUserId: string; +let key: string; +let keyId: string; + +beforeAll(async () => { + service = await startVerifyService(); + serviceAlerts = verifyAlerts; + mcpUserId = await serviceUserOf(service, 'ansari-mcp'); + ({ key, id: keyId } = await scriptKey()); +}); + +afterAll(async () => { + await service?.close(); + for (const spy of consoleSpies) spy.mockRestore(); +}); + +describe('the leak scan itself (a verification pattern is code)', () => { + it('catches a line holding one 16-character window of a key, and never flags the bare prefix', () => { + const sample = `ansari_mcp_${'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl'}`; + expect(keyWindows(sample)).toHaveLength(64 - 16 + 1); + const bad = `upstream said: ${sample.slice(30, 46)} (truncated)`; + expect(leakedWindows(bad, [sample])).toEqual([sample.slice(30, 46)]); + // Fifteen characters of the random part is a near miss, not a window. + expect(leakedWindows(`x ${sample.slice(11, 26)} y`, [sample])).toEqual([]); + expect(leakedWindows('key ansari_mcp_ (prefix only), ansari_mcp_ again', [sample])).toEqual([]); + expect(leakedWindows(`full key ${sample}`, [sample]).length).toBe(49); + }); +}); + +describe('a valid ansari-mcp key', () => { + it('→ 200 { valid: true, client_id, key_id }, and remaining drops by exactly 1', async () => { + const before = await keyRow(keyId); + const res = await verify(key); + expect(res.status).toBe(200); + expect(JSON.parse(res.text)).toEqual({ valid: true, client_id: 'ansari-mcp-production', key_id: keyId }); + expect(Object.keys(JSON.parse(res.text) as object)).toEqual(['valid', 'client_id', 'key_id']); + const after = await keyRow(keyId); + expect(after?.remaining).toBe((before?.remaining ?? 0) - 1); + expect(after?.request_count).toBe((before?.request_count ?? 0) + 1); + }); + + it('every client id the script accepts is served as stored', async () => { + for (const clientId of ['ansari-mcp', 'ansari-mcp-beta', 'ansari-mcp-dev.1_x']) { + const flags = [...LIMIT_FLAGS['ansari-mcp'].slice(0, -1), clientId]; + const made = await scriptKey('ansari-mcp', service, flags); + const res = await verify(made.key); + expect(JSON.parse(res.text)).toEqual({ valid: true, client_id: clientId, key_id: made.id }); + } + }); + + it('extra fields in the body are ignored', async () => { + const res = await post({ key, permissions: MCP, client_id: 'ansari-mcp-forged', extra: [1, 2] }); + expect(JSON.parse(res.text)).toMatchObject({ valid: true, client_id: 'ansari-mcp-production' }); + }); + + it('the plugin returns metadata as an object here, and clientIdOf reads it (scenario 15)', async () => { + const made = await scriptKey(); + const verified = await service.auth.api.verifyApiKey({ body: { key: made.key, permissions: MCP } }); + expect(verified.valid).toBe(true); + expect(verified.key?.metadata).toEqual({ clientId: 'ansari-mcp-production' }); + expect(serviceUsers.clientIdOf(verified.key?.metadata)).toBe('ansari-mcp-production'); + // The stored form is JSON text; clientIdOf reads that too. + const { rows } = await service.client.query<{ metadata: string }>('select metadata from auth.apikey where id = $1', [made.id]); + expect(typeof rows[0]?.metadata).toBe('string'); + expect(serviceUsers.clientIdOf(rows[0]?.metadata)).toBe('ansari-mcp-production'); + }); +}); + +describe('refusals: one byte-identical { valid: false }', () => { + /** A script-made key whose row `sql` then changes (the hash's id is $1). */ + async function seeded(sql: string) { + const made = await scriptKey(); + await service.client.query(sql, [made.id]); + return made; + } + + const cases: [string, () => Promise<{ key: string; id: string | null; kept: boolean }>][] = [ + ['an unknown key', async () => ({ key: remember(`ansari_mcp_${'Q'.repeat(64)}`), id: null, kept: false })], + ['a disabled key', async () => ({ ...(await seeded('update auth.apikey set enabled = false where id = $1')), kept: true })], + [ + // The plugin deletes an expired key when it is presented: its behaviour, not the route's. + 'an expired key', + async () => ({ ...(await seeded(`update auth.apikey set expires_at = now() - interval '1 minute' where id = $1`)), kept: false }), + ], + [ + 'an exhausted key (refilled daily)', + async () => ({ ...(await seeded('update auth.apikey set remaining = 0, last_refill_at = now() where id = $1')), kept: true }), + ], + [ + 'a rate-limited key', + async () => ({ + ...(await seeded('update auth.apikey set request_count = rate_limit_max, last_request = now() where id = $1')), + kept: true, + }), + ], + ['a key with no permissions', async () => ({ ...(await seeded('update auth.apikey set permissions = null where id = $1')), kept: true })], + ]; + + it.each(cases)('%s', async (_name, make) => { + const made = await make(); + expectRefused(await verify(made.key)); + if (!made.id) return; + // Spec 314 amendment 1: the plugin deletes an expired key when it is + // presented; every other refused row is kept. A plugin bump that changes + // either fails here. + if (made.kept) expect(await keyRow(made.id)).toBeDefined(); + else expect(await keyRow(made.id)).toBeUndefined(); + }); + + it('USAGE_EXCEEDED and RATE_LIMITED each raised one key-refused alert in the window', () => { + const codes = alertsOf('key-refused').map((a) => (a.kind === 'key-refused' ? a.code : null)); + expect(codes.sort()).toEqual(['RATE_LIMITED', 'USAGE_EXCEEDED']); + }); + + it('an exhausted key is kept, and served again after its daily refill', async () => { + const made = await seeded('update auth.apikey set remaining = 0, last_refill_at = now() where id = $1'); + expectRefused(await verify(made.key)); + await service.client.query( + `update auth.apikey set last_refill_at = now() - interval '1 day' - interval '1 minute' where id = $1`, + [made.id] + ); + expect(JSON.parse((await verify(made.key)).text)).toMatchObject({ valid: true, key_id: made.id }); + }); +}); + +describe('a WhatsApp key (wrong permission, wrong owner)', () => { + it('→ the same { valid: false }, with remaining, request_count and last_request untouched', async () => { + const wa = await scriptKey('whatsapp'); + // Used once by its own route, so last_request and request_count are not their initial values. + await service.client.query(`update auth.apikey set request_count = 3, last_request = now() - interval '1 hour' where id = $1`, [wa.id]); + const before = await keyRow(wa.id); + expectRefused(await verify(wa.key)); + expect(await keyRow(wa.id)).toEqual(before); + }); +}); + +describe('a permission set other than { mcp: [complete] } → 400 before any key is touched', () => { + const requests: [string, (key: string) => unknown][] = [ + ['whatsapp: mint', (k) => ({ key: k, permissions: { whatsapp: ['mint'] } })], + ['an empty object', (k) => ({ key: k, permissions: {} })], + ['an extra permission', (k) => ({ key: k, permissions: { mcp: ['complete'], whatsapp: ['mint'] } })], + ['an extra action', (k) => ({ key: k, permissions: { mcp: ['complete', 'admin'] } })], + ['a repeated action', (k) => ({ key: k, permissions: { mcp: ['complete', 'complete'] } })], + ['no action', (k) => ({ key: k, permissions: { mcp: [] } })], + ['an action as a string', (k) => ({ key: k, permissions: { mcp: 'complete' } })], + ['a differently cased resource', (k) => ({ key: k, permissions: { MCP: ['complete'] } })], + ['permissions as an array', (k) => ({ key: k, permissions: [['mcp', ['complete']]] })], + ['permissions null', (k) => ({ key: k, permissions: null })], + ['permissions missing', (k) => ({ key: k })], + ]; + + it.each(requests)('%s → the one 400, no plugin call, the key row unchanged', async (_name, body) => { + const made = await scriptKey(); + const before = await keyRow(made.id); + const spy = vi.spyOn(service.auth.api, 'verifyApiKey'); + try { + const res = await post(body(made.key)); + expect(res.status).toBe(400); + expect(res.text).toBe(INVALID); + expect(res.text).not.toMatch(/mcp|whatsapp|permission|complete|mint/i); + expect(spy).not.toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + expect(await keyRow(made.id)).toEqual(before); + }); + + it('the spy sees the plugin call for the served set (so the cases above are not vacuous)', async () => { + const spy = vi.spyOn(service.auth.api, 'verifyApiKey'); + try { + expect((await verify(key)).status).toBe(200); + expect(spy).toHaveBeenCalledTimes(1); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('the owner and the client id', () => { + it('a key carrying mcp: complete owned by a non-service user → { valid: false }', async () => { + const member = await signUpTokens(service, 'mcp-member@example.com'); + const made = await outsideKey(member.id, { metadata: { clientId: 'ansari-mcp-production' } }); + expectRefused(await verify(made.key)); + }); + + it("a key carrying mcp: complete owned by the WhatsApp service user → { valid: false }", async () => { + const waUser = await serviceUserOf(service, 'whatsapp'); + const made = await outsideKey(waUser, { metadata: { clientId: 'ansari-mcp-production' } }); + expectRefused(await verify(made.key)); + }); + + it.each([ + ['no metadata', {}], + ['metadata without clientId', { metadata: { other: 'x' } }], + ['an off-pattern clientId (claude-skill)', { metadata: { clientId: 'claude-skill' } }], + ['a clientId that only starts with ansari-mcp', { metadata: { clientId: 'ansari-mcpx' } }], + ['an upper-case clientId', { metadata: { clientId: 'ansari-mcp-PROD' } }], + ['a non-string clientId', { metadata: { clientId: 42 } }], + ])('%s → { valid: false }, and one client-id-invalid alert per window naming the key', async (_name, body) => { + nextAlertWindow(); + const sent = alertsOf('client-id-invalid').length; + const first = await outsideKey(mcpUserId, body); + const second = await outsideKey(mcpUserId, body); + for (const made of [first, second, first]) expectRefused(await verify(made.key)); + expect(alertsOf('client-id-invalid').slice(sent)).toEqual([ + { kind: 'client-id-invalid', keyId: first.id, windowSeconds: limits.EXCHANGE_ALERT_WINDOW }, + ]); + }); +}); + +describe('the stored prefix (#314 Amendments 2 and 3)', () => { + const served = { metadata: { clientId: 'ansari-mcp-production' } }; + const here = getEnv().ENVIRONMENT; + + it.each([["this environment's label", serviceUsers.keyPrefix('ansari-mcp', here)]])('%s → served', async (_name, prefix) => { + const made = await outsideKey(mcpUserId, { ...served, prefix }); + expect(made.key.startsWith(prefix)).toBe(true); + expect(JSON.parse((await verify(made.key)).text)).toEqual({ + valid: true, + client_id: 'ansari-mcp-production', + key_id: made.id, + }); + }); + + it('the longest prefix the table produces fits the plugin (created with it, not a cited limit)', async () => { + const all = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]).flatMap((name) => + ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env)) + ); + const longest = all.reduce((a, b) => (b.length > a.length ? b : a)); + expect(longest).toBe('ansari_mcp_development_'); + const made = await outsideKey(mcpUserId, { ...served, prefix: longest }); + expect(made.key.startsWith(longest)).toBe(true); + }); + + it.each([ + ...ENVIRONMENTS.filter((e) => e !== here).map((e) => [`another environment's label (${e})`, `ansari_mcp_${e}_`]), + ['a foreign prefix', 'evil_'], + ["a WhatsApp prefix for this environment", serviceUsers.keyPrefix('whatsapp', here)], + ["WhatsApp's pre-rename legacy prefix", 'wa_'], + // No MCP window (second review, finding 1): no unlabelled MCP key can exist. + ['the bare ansari_mcp_ prefix', 'ansari_mcp_'], + ['an unknown environment', 'ansari_mcp_qa_'], + ['no prefix', undefined], + ])('%s → the same { valid: false }', async (_name, prefix) => { + const made = await outsideKey(mcpUserId, { ...served, prefix }); + expectRefused(await verify(made.key)); + }); + + it('a staging-labelled key is refused by a production-configured app, and served by a staging one', async () => { + const made = await outsideKey(mcpUserId, { ...served, prefix: 'ansari_mcp_staging_' }); + for (const [environment, valid] of [['production', false], ['staging', true]] as const) { + const app = await serveApp(createApp({ auth: service.auth, db: service.db }, { environment, production: false })); + try { + const res = await fetch(`${app.url}${SERVICE_VERIFY_PATH}`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ key: made.key, permissions: MCP }), + }); + expect(res.status).toBe(200); + expect(((await res.json()) as { valid: boolean }).valid, environment).toBe(valid); + } finally { + await app.close(); + } + } + }); +}); + +describe('the service user (scenario 7)', () => { + it('missing: a valid key → 500 and one alert per window; an unknown key → { valid: false }', async () => { + const lone = await startVerifyService(); + try { + nextAlertWindow(); + const sent = alertsOf('service-user-unresolvable').length; + const made = await scriptKey('ansari-mcp', lone); + const owner = await serviceUserOf(lone, 'ansari-mcp'); + await lone.client.query(`delete from auth.account where user_id = $1`, [owner]); + for (let i = 0; i < 3; i++) { + const res = await verify(made.key, { on: lone }); + expect(res.status).toBe(500); + expect(res.text).toBe(INTERNAL); + } + expect(alertsOf('service-user-unresolvable').slice(sent)).toEqual([ + { kind: 'service-user-unresolvable', serviceUsers: 0, windowSeconds: limits.EXCHANGE_ALERT_WINDOW }, + ]); + expectRefused(await verify(remember(`ansari_mcp_${'R'.repeat(64)}`), { on: lone })); + } finally { + await lone.close(); + } + }); + + it('duplicated by a forced second row: a valid key → 500 and an alert; an unknown key → { valid: false }', async () => { + const dup = await startVerifyService(); + try { + nextAlertWindow(); + const sent = alertsOf('service-user-unresolvable').length; + const made = await scriptKey('ansari-mcp', dup); + await dup.client.exec(` + alter table auth.account drop constraint account_provider_id_account_id_unique; + with second as ( + insert into auth.users (name, email, role, registered_via) + values ('service-ansari-mcp', 'second-mcp@example.com', 'user', 'service') returning id + ) + insert into auth.account (account_id, provider_id, user_id, updated_at) + select 'ansari-mcp', 'service', id, now() from second; + `); + const res = await verify(made.key, { on: dup }); + expect(res.status).toBe(500); + expect(res.text).toBe(INTERNAL); + expect(alertsOf('service-user-unresolvable').slice(sent)).toEqual([ + { kind: 'service-user-unresolvable', serviceUsers: 2, windowSeconds: limits.EXCHANGE_ALERT_WINDOW }, + ]); + expectRefused(await verify(remember(`ansari_mcp_${'S'.repeat(64)}`), { on: dup })); + } finally { + await dup.close(); + } + }); +}); + +describe('outages are 500, never { valid: false } (scenario 8)', () => { + it('auth.apikey dropped → 500 for a valid and an unknown key once the check window has passed', async () => { + const outage = await startVerifyService(); + try { + const made = await scriptKey('ansari-mcp', outage); + const unknown = remember(`ansari_mcp_${'T'.repeat(64)}`); + // An unknown key while the relation is there: refused, and the check is cached. + expectRefused(await verify(unknown, { on: outage })); + await outage.client.exec('drop table auth.apikey'); + // Inside the window, the stated residual: still refused. + expectRefused(await verify(unknown, { on: outage })); + clock.advance(limits.APIKEY_RELATION_CHECK_TTL); + for (const presented of [made.key, unknown]) { + const res = await verify(presented, { on: outage }); + expect(res.status).toBe(500); + expect(res.text).toBe(INTERNAL); + } + } finally { + await outage.close(); + } + }); + + it('the database stopped under the running app → 500 for a valid and an unknown key', async () => { + const stopped = await startVerifyService(); + const made = await scriptKey('ansari-mcp', stopped); + clock.advance(limits.APIKEY_RELATION_CHECK_TTL); + await stopped.client.close(); + for (const presented of [made.key, remember(`ansari_mcp_${'U'.repeat(64)}`)]) { + const res = await verify(presented, { on: stopped }); + expect(res.status).toBe(500); + expect(res.text).toBe(INTERNAL); + } + await stopped.close().catch(() => undefined); + }); +}); + +describe('the body → the one 400 (scenario 9)', () => { + const cases: [string, () => string, string | null][] = [ + ['malformed JSON', () => '{"key":', 'application/json'], + ['a text/plain body', () => JSON.stringify({ key, permissions: MCP }), 'text/plain'], + ['no Content-Type', () => JSON.stringify({ key, permissions: MCP }), null], + ['over the byte limit', () => JSON.stringify({ key, permissions: MCP, pad: 'x'.repeat(limits.VERIFY_BODY_LIMIT) }), 'application/json'], + ['a JSON string', () => JSON.stringify(key), 'application/json'], + ['a JSON array', () => JSON.stringify([key, MCP]), 'application/json'], + ['key missing', () => JSON.stringify({ permissions: MCP }), 'application/json'], + ['key not a string', () => JSON.stringify({ key: 12345, permissions: MCP }), 'application/json'], + ['key empty', () => JSON.stringify({ key: '', permissions: MCP }), 'application/json'], + ['key over 256 characters', () => JSON.stringify({ key: `ansari_mcp_${'A'.repeat(246)}`, permissions: MCP }), 'application/json'], + ['key with a space', () => JSON.stringify({ key: `${key.slice(0, 20)} ${key.slice(20)}`, permissions: MCP }), 'application/json'], + ['key with a tab', () => JSON.stringify({ key: `${key}\t`, permissions: MCP }), 'application/json'], + ['key with a non-ASCII character', () => JSON.stringify({ key: `${key.slice(0, 74)}é`, permissions: MCP }), 'application/json'], + ]; + + it.each(cases)('%s → the exact 400, no plugin call', async (_name, body, contentType) => { + const before = await keyRow(keyId); + const spy = vi.spyOn(service.auth.api, 'verifyApiKey'); + try { + const res = await post(body(), { contentType }); + expect(res.status).toBe(400); + expect(res.text).toBe(INVALID); + expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8'); + expect(spy).not.toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + expect(await keyRow(keyId)).toEqual(before); + }); + + it('a key of exactly 256 printable characters is in bounds (refused as unknown, not a 400)', async () => { + expectRefused(await verify(remember(`ansari_mcp_${'V'.repeat(245)}`))); + }); +}); + +describe('transport (scenario 10)', () => { + const ORIGINS: [string, string | undefined][] = [ + ['the configured CORS_ORIGIN', BASE], + ['null', 'null'], + ['https://evil.example', 'https://evil.example'], + ['no Origin', undefined], + ]; + const corsHeaders = (headers: Headers) => [...headers.keys()].filter((h) => h.startsWith('access-control-')); + + it.each(ORIGINS)('no Access-Control-* header on POST or OPTIONS (%s)', async (_name, origin) => { + const originHeader: Record = origin ? { origin } : {}; + for (const presented of [key, `ansari_mcp_${'W'.repeat(64)}`]) { + const res = await verify(presented, { headers: originHeader }); + expect(res.status).toBe(200); + expect(corsHeaders(res.headers)).toEqual([]); + } + const invalid = await post('{', { headers: originHeader }); + expect(invalid.status).toBe(400); + expect(corsHeaders(invalid.headers)).toEqual([]); + const preflight = await fetch(`${service.publicUrl}${SERVICE_VERIFY_PATH}`, { + method: 'OPTIONS', + headers: { ...originHeader, 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type' }, + }); + expect(preflight.status).toBe(404); + expect(corsHeaders(preflight.headers)).toEqual([]); + }); + + it.each(['GET', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'])('%s → 404 with an empty body and no Access-Control-* header', async (method) => { + const res = await fetch(`${service.publicUrl}${SERVICE_VERIFY_PATH}`, { method, headers: { origin: BASE } }); + expect(res.status).toBe(404); + expect(await res.text()).toBe(''); + expect(corsHeaders(res.headers)).toEqual([]); + }); + + it('a sub-path → 404 with no Access-Control-* header', async () => { + const res = await verify(key, { path: `${SERVICE_VERIFY_PATH}/extra`, headers: { origin: BASE } }); + expect(res.status).toBe(404); + expect(corsHeaders(res.headers)).toEqual([]); + }); + + it('is mounted before corsFor, beside the exchange', () => { + const app = createApp({ auth: service.auth, db: service.db }); + type Layer = { name: string; matchers: ((path: string) => unknown)[] }; + const stack = (app as unknown as { router: { stack: Layer[] } }).router.stack; + const at = (path: string) => stack.findIndex((l) => l.name === 'router' && l.matchers.some((m) => m(path))); + const corsAt = stack.findIndex((l) => l.name === 'corsMiddleware'); + expect(at(SERVICE_VERIFY_PATH)).toBeGreaterThanOrEqual(0); + expect(at(WHATSAPP_SESSION_PATH)).toBeGreaterThanOrEqual(0); + expect(corsAt).toBeGreaterThan(at(SERVICE_VERIFY_PATH)); + }); + + it('is not reachable under /api/auth/*', async () => { + for (const path of ['/api/auth/service/verify-key', '/api/auth/api/service/verify-key']) { + const before = await keyRow(keyId); + const res = await verify(key, { path, headers: { 'x-real-ip': '198.51.100.9', origin: BASE } }); + expect(res.status).toBe(404); + expect(await keyRow(keyId)).toEqual(before); + } + }); +}); + +describe('alerts (scenario 13)', () => { + it('only a served key counts toward the volume alerts: a wrong owner or a bad client id is a refusal', async () => { + const member = await signUpTokens(service, 'mcp-volume-member@example.com'); + const wrongOwner = await outsideKey(member.id, { metadata: { clientId: 'ansari-mcp-production' } }); + const badClientId = await outsideKey(mcpUserId, { metadata: { clientId: 'claude-skill' } }); + const served = await scriptKey(); + const counted = vi.spyOn(serviceAlerts, 'keyVerified'); + try { + expectRefused(await verify(wrongOwner.key)); + expectRefused(await verify(badClientId.key)); + expect(counted).not.toHaveBeenCalled(); + expect((await verify(served.key)).status).toBe(200); + expect(counted).toHaveBeenCalledTimes(1); + expect(counted.mock.calls[0][0]).toMatchObject({ id: served.id }); + } finally { + counted.mockRestore(); + } + }); + + it('per-key window volume: one alert at MCP_VERIFY_KEY_ALERT, counts and the key id only', async () => { + const made = await scriptKey(); + const sent = alertsOf('key-window-volume').length; + for (let i = 0; i < limits.MCP_VERIFY_KEY_ALERT + 5; i++) expect((await verify(made.key)).status).toBe(200); + expect(alertsOf('key-window-volume').slice(sent)).toEqual([ + { + kind: 'key-window-volume', + keyId: made.id, + requests: limits.MCP_VERIFY_KEY_ALERT, + windowSeconds: limits.MCP_KEY_INITIAL.rateLimitTimeWindow / 1000, + threshold: limits.MCP_VERIFY_KEY_ALERT, + }, + ]); + }); + + it('per-key daily volume: one alert at MCP_VERIFY_DAILY_ALERT since the refill', async () => { + const made = await scriptKey(); + const daily = limits.MCP_KEY_INITIAL.refillAmount; + await service.client.query(`update auth.apikey set remaining = $1, last_refill_at = now() where id = $2`, [ + daily - (limits.MCP_VERIFY_DAILY_ALERT - 1), + made.id, + ]); + const sent = alertsOf('key-daily-volume').length; + for (let i = 0; i < 3; i++) expect((await verify(made.key)).status).toBe(200); + expect(alertsOf('key-daily-volume').slice(sent)).toEqual([ + { kind: 'key-daily-volume', keyId: made.id, requests: limits.MCP_VERIFY_DAILY_ALERT, threshold: limits.MCP_VERIFY_DAILY_ALERT }, + ]); + }); + + it('refusal volume: one alert per window at MCP_VERIFY_UNAUTHORIZED_ALERT, and again in the next window', async () => { + const { max } = limits.MCP_VERIFY_UNAUTHORIZED_ALERT; + const unknown = remember(`ansari_mcp_${'X'.repeat(64)}`); + for (let round = 0; round < 2; round++) { + nextAlertWindow(); + const sent = alertsOf('unauthorized-volume').length; + for (let i = 0; i < max + 5; i++) expectRefused(await verify(unknown)); + expect(alertsOf('unauthorized-volume').slice(sent)).toEqual([ + { kind: 'unauthorized-volume', windowSeconds: limits.EXCHANGE_ALERT_WINDOW, threshold: max }, + ]); + } + }); + + it('USAGE_EXCEEDED fires once per window, and again in the next', async () => { + const made = await scriptKey(); + await service.client.query('update auth.apikey set remaining = 0, last_refill_at = now() where id = $1', [made.id]); + for (let round = 0; round < 2; round++) { + nextAlertWindow(); + const sent = alertsOf('key-refused').length; + for (let i = 0; i < 3; i++) expectRefused(await verify(made.key)); + expect(alertsOf('key-refused').slice(sent)).toEqual([ + { kind: 'key-refused', code: 'USAGE_EXCEEDED', windowSeconds: limits.EXCHANGE_ALERT_WINDOW }, + ]); + } + }); + + it('every alert carries numbers, its kind, a refusal code or a key id, and nothing else', () => { + expect(new Set(alerts.map((a) => a.kind))).toEqual( + new Set(['key-window-volume', 'key-daily-volume', 'key-refused', 'unauthorized-volume', 'service-user-unresolvable', 'client-id-invalid']) + ); + for (const alert of alerts) { + for (const [field, value] of Object.entries(alert)) { + if (field === 'kind') continue; + if (field === 'keyId') expect(value).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); + else if (field === 'code') expect(['USAGE_EXCEEDED', 'RATE_LIMITED']).toContain(value); + else expect(typeof value, field).toBe('number'); + } + } + }); +}); + +describe('MCP alert dedup (unit, injected clock)', () => { + it('each fire-once kind sends once per EXCHANGE_ALERT_WINDOW, and again in the next window', () => { + const sent: McpVerifyAlert[] = []; + const fake = new Clock(); + const tracker = createMcpVerifyAlerts({ send: (a) => sent.push(a), now: fake.now }); + const windowMs = limits.EXCHANGE_ALERT_WINDOW * 1000; + const round = () => { + for (let i = 0; i < 5; i++) { + tracker.clientIdInvalid(`00000000-0000-4000-8000-00000000000${i}`); + tracker.keyRefused('USAGE_EXCEEDED'); + tracker.serviceUserUnresolvable(0); + } + for (let i = 0; i < limits.MCP_VERIFY_UNAUTHORIZED_ALERT.max + 5; i++) tracker.unauthorized(); + }; + round(); + fake.advance(windowMs - 1); + round(); + const kinds = () => sent.map((a) => a.kind).sort(); + const once = ['client-id-invalid', 'key-refused', 'service-user-unresolvable', 'unauthorized-volume']; + expect(kinds()).toEqual(once); + expect(sent.find((a) => a.kind === 'client-id-invalid')).toMatchObject({ keyId: '00000000-0000-4000-8000-000000000000' }); + fake.advance(1); + round(); + expect(kinds()).toEqual([...once, ...once].sort()); + }); + + it('a key over MCP_VERIFY_KEY_ALERT in every 60 s key window alerts once per EXCHANGE_ALERT_WINDOW, not once per key window', () => { + const sent: McpVerifyAlert[] = []; + const fake = new Clock(); + const tracker = createMcpVerifyAlerts({ send: (a) => sent.push(a), now: fake.now }); + const keyWindowMs = limits.MCP_KEY_INITIAL.rateLimitTimeWindow; + const usage = { + id: '00000000-0000-4000-8000-0000000000aa', + requestCount: limits.MCP_VERIFY_KEY_ALERT, + rateLimitTimeWindow: keyWindowMs, + remaining: null, + refillAmount: null, + lastRefillAt: null, + createdAt: new Date(fake.at).toISOString(), + }; + const alertWindowMs = limits.EXCHANGE_ALERT_WINDOW * 1000; + expect(alertWindowMs / keyWindowMs).toBeGreaterThanOrEqual(2); + // Every key window inside one alert window crosses the threshold. + for (let t = 0; t < alertWindowMs; t += keyWindowMs) { + tracker.keyVerified(usage); + fake.advance(keyWindowMs); + } + expect(sent.filter((a) => a.kind === 'key-window-volume')).toHaveLength(1); + // The next alert window may fire again. + tracker.keyVerified(usage); + expect(sent.filter((a) => a.kind === 'key-window-volume')).toHaveLength(2); + }); + + it('sends under the MCP message and mcp-verify- tags, never the WhatsApp ones', () => { + expect(MCP_VERIFY_ALERT_MESSAGE).toBe('auth: MCP key verify alert'); + expect(EXCHANGE_ALERT_MESSAGE).not.toBe(MCP_VERIFY_ALERT_MESSAGE); + }); +}); + +describe('key material at rest and in logs (scenario 12)', () => { + it("the apikey rows hold no window of any key's random part outside the hash", async () => { + const { rows } = await service.client.query<{ row: Record }>('select row_to_json(t) as row from auth.apikey t'); + expect(rows.length).toBeGreaterThan(10); + const text = JSON.stringify(rows.map(({ row }) => ({ ...row, key: undefined }))); + expect(text).toContain('ansari_mcp_'); // the public prefix is stored, and exempt + expect(leakedWindows(text, rawKeys)).toEqual([]); + }); + + it('the console carries no window of any key, no key hash and no driver error object', async () => { + expect(logged.length).toBeGreaterThan(0); + const text = logged.map((args) => args.map((a) => inspect(a, { depth: 8 })).join(' ')).join('\n'); + expect(leakedWindows(text, rawKeys)).toEqual([]); + const { rows } = await service.client.query<{ key: string }>('select key from auth.apikey'); + for (const { key: hash } of rows) expect(text).not.toContain(hash); + for (const args of logged) for (const arg of args) expect(arg).not.toBeInstanceOf(Error); + }); +}); diff --git a/apps/auth/tests/whatsapp-session.test.ts b/apps/auth/tests/whatsapp-session.test.ts index 3c085c90..5c94a1d6 100644 --- a/apps/auth/tests/whatsapp-session.test.ts +++ b/apps/auth/tests/whatsapp-session.test.ts @@ -11,7 +11,7 @@ import { inspect } from 'node:util'; import { createLocalJWKSet, jwtVerify } from 'jose'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; -import { limits, serviceUsers } from '@ansari/auth'; +import { ENVIRONMENTS, getEnv, limits, serviceUsers, type Environment } from '@ansari/auth'; import { TEST_JWT_AUDIENCE, TEST_JWT_ISSUER } from '../../../packages/auth/tests/helpers/auth-db'; import { @@ -24,6 +24,9 @@ import { createApp } from '../src/app'; import { exchangeLimitKey, WHATSAPP_SESSION_PATH } from '../src/routes/whatsapp'; import { BASE, rateLimitRow, send, signUpTokens, startService, type Service } from './helpers/service'; +/** The ENVIRONMENT the app under test runs as (the test env sets none, so the default); pinned in beforeAll. */ +const HERE: Environment = 'development'; + const WHATSAPP = { whatsapp: ['mint'] }; /** The plugin's key hash: SHA-256, base64url (packages/auth's probe 1 pins it to defaultKeyHasher). */ @@ -67,17 +70,17 @@ let key: string; /** A fresh exchange-alert window, so one test's counts never reach the next. */ const nextAlertWindow = () => clock.advance(limits.EXCHANGE_ALERT_WINDOW * 1000); +/** The alerts object of the service last started here, so a test can spy on what the route calls. */ +let exchangeAlerts: ReturnType; + function startExchangeService(): Promise { - return startService({ - exchange: { - alerts: createExchangeAlerts({ send: (alert) => alerts.push(alert), now: clock.now }), - now: clock.now, - }, - }); + exchangeAlerts = createExchangeAlerts({ send: (alert) => alerts.push(alert), now: clock.now }); + return startService({ exchange: { alerts: exchangeAlerts, now: clock.now } }); } beforeAll(async () => { service = await startExchangeService(); + expect(getEnv().ENVIRONMENT).toBe(HERE); serviceUserId = (await serviceUsers.createServiceUser(service.db, 'whatsapp')).id; key = await createKey(); }); @@ -92,7 +95,9 @@ type KeyBody = Record; /** A key created in process, as the service-keys script does, owned by `userId`. */ async function createKey(body: KeyBody = {}, on: Service = service, userId = serviceUserId) { const created = await on.auth.api.createApiKey({ - body: { userId, prefix: 'ansari_wa_', name: 'test', permissions: WHATSAPP, rateLimitEnabled: false, ...body }, + // This environment's label by default (second review, finding 2); the legacy + // prefixes have their own dedicated tests. + body: { userId, prefix: serviceUsers.keyPrefix('whatsapp', HERE), name: 'test', permissions: WHATSAPP, rateLimitEnabled: false, ...body }, }); remember(keyHash(created.key)); return remember(created.key); @@ -219,6 +224,14 @@ describe('key refusals: one byte-identical 401, no rows', () => { ], ['a key with mcp: complete only', async () => ({ bearer: await createKey({ permissions: { mcp: ['complete'] } }) })], ['a key with no permissions', async () => ({ bearer: await seededKey('update auth.apikey set permissions = null where key = $1') })], + // #314 Amendment 3: a stored prefix that is not this service's and this environment's. + ...ENVIRONMENTS.filter((e) => e !== HERE).map( + (e) => [`a key labelled for ${e}`, async () => ({ bearer: await createKey({ prefix: `ansari_wa_${e}_` }) })] as [string, () => Promise] + ), + ['a key with a foreign prefix', async () => ({ bearer: await createKey({ prefix: 'evil_' }) })], + ['a key with an MCP prefix', async () => ({ bearer: await createKey({ prefix: serviceUsers.keyPrefix('ansari-mcp', HERE) }) })], + ['a key with an unknown environment', async () => ({ bearer: await createKey({ prefix: 'ansari_wa_qa_' }) })], + ['a key with no prefix', async () => ({ bearer: await createKey({ prefix: undefined }) })], [ "another service's whatsapp: mint key", async () => { @@ -274,6 +287,45 @@ describe('key refusals: one byte-identical 401, no rows', () => { }); describe('the exchange', () => { + it('keyVerified counts only a served key: never one refused for its prefix (second review, finding 6)', async () => { + const spy = vi.spyOn(exchangeAlerts, 'keyVerified'); + try { + for (const prefix of [ + ...ENVIRONMENTS.filter((e) => e !== HERE).map((e) => `ansari_wa_${e}_`), + 'evil_', + serviceUsers.keyPrefix('ansari-mcp', HERE), + ]) { + const refused = await createKey({ prefix }); + expect((await exchange(newBsuid(), newPhone(), { bearer: refused })).status, prefix).toBe(401); + } + expect(spy).not.toHaveBeenCalled(); + expect((await exchange(newBsuid(), newPhone(), { bearer: await createKey() })).status).toBe(200); + expect(spy).toHaveBeenCalledTimes(1); + } finally { + spy.mockRestore(); + } + }); + + it('a bare ansari_wa_ key (issued before #314) still exchanges during the compatibility window', async () => { + const legacy = await createKey({ prefix: 'ansari_wa_' }); + expect((await exchange(newBsuid(), newPhone(), { bearer: legacy })).status).toBe(200); + }); + + it('a pre-rename wa_ key (issued before 2026-10-30) still exchanges during the compatibility window (codex, PR #372)', async () => { + const legacy = await createKey({ prefix: 'wa_' }); + expect(legacy.startsWith('wa_')).toBe(true); + expect((await exchange(newBsuid(), newPhone(), { bearer: legacy })).status).toBe(200); + }); + + it.each([...serviceUsers.acceptedKeyPrefixes('whatsapp', HERE)])( + 'a key with the accepted prefix %s → 200 (this environment\'s label and, while legacy keys live, the bare and pre-rename wa_ prefixes)', + async (prefix) => { + const labelled = await createKey({ prefix }); + expect(labelled.startsWith(prefix)).toBe(true); + expect((await exchange(newBsuid(), newPhone(), { bearer: labelled })).status).toBe(200); + } + ); + it('a new BSUID → 200 with a JWT for a new WhatsApp user and its one session', async () => { const bsuid = newBsuid(); const before = await rowCounts(); @@ -659,7 +711,7 @@ describe('alerts', () => { const id = (await service.auth.api.createApiKey({ body: { userId: serviceUserId, - prefix: 'ansari_wa_', + prefix: serviceUsers.keyPrefix('whatsapp', HERE), name: 'volume', permissions: WHATSAPP, rateLimitEnabled: true, @@ -688,7 +740,7 @@ describe('alerts', () => { const created = await service.auth.api.createApiKey({ body: { userId: serviceUserId, - prefix: 'ansari_wa_', + prefix: serviceUsers.keyPrefix('whatsapp', HERE), name: 'daily', permissions: WHATSAPP, rateLimitEnabled: false, diff --git a/apps/eval/README.md b/apps/eval/README.md new file mode 100644 index 00000000..bf66023a --- /dev/null +++ b/apps/eval/README.md @@ -0,0 +1,197 @@ +# Model evaluation harness + +Runs a versioned question set through the **real facilitator** (its prompt, tools, retries +and budgets) once per model, scores every answer with code, and writes a results file and +a comparison report. Built for issue #393; meant to be re-run whenever a new model appears. + +It is its own workspace package, `ansari-eval`, in `apps/eval/` (issue #397). It calls +apps/api's `runFacilitator` in process, so `@/` here means what it means in apps/api: +`tsconfig.json` (read by tsx and tsc) and `vitest.config.ts` map `@/lib`, `@/db` and `@/` +to `../api/lib`, `../api/db` and `../api/src`. It is never deployed. The api image copies +`apps/api`, `packages` and the root manifests, so the harness and its results are not in +it. The api service's recorded watch patterns (`apps/api/railway.toml`) are `apps/api/**`, +`packages/**` and the root manifests, so a new question or a results file does not +redeploy the api. Two limits on that: Railway reads its dashboard, not the toml, so the +live patterns are whatever the dashboard holds; and `pnpm-lock.yaml` is a watched file, so +adding or bumping a dependency of this package does redeploy the api. + +Three rules keep it out of production, all enforced by +`apps/api/tests/source-scan/facilitator-model-pin.test.ts`: nothing under apps/api's +`src/`, `lib/` or `db/` imports the harness, by path or as `ansari-eval`; no route passes +`model` to `runFacilitator`; and no `COPY` source in the api Dockerfile or watch pattern +recorded in the api `railway.toml` takes in `apps/eval`. + +## Run it + +From the repo root, with an env file that holds real credentials: + +```bash +pnpm --filter ansari-eval exec -- tsx --env-file=.env.eval.local run.ts \ + --models gemini-3.7-flash,gemini-4-hydrogen,gemini-4-argon +``` + +The `--` after `exec` is required: without it pnpm takes `--env-file` for itself and the +run stops with `node: .env.eval.local: not found`. pnpm runs the command in `apps/eval/`, +so the env file path and `run.ts` are relative to it. That is also what makes `@/` +resolve: tsx reads the `tsconfig.json` of the directory it starts in. + +The first model is the baseline the others are compared against. The run prints one line +per conversation and ends with the two paths it wrote, under `apps/eval/results/`: + +- `.json`: inputs, model ids, git revision, dates, every raw answer, the tool-call + records, the looked-up verses and the scores. +- `.md`: the comparison report. + +`--dry-run` prints the plan and the number of calls without calling anything. A full run +of question set v1 over three models is 138 facilitator requests, roughly 280 to 550 model +calls. Other options: `--repeats ` (samples per question), `--only `, `--concurrency ` (default 4), `--questions `, `--out `, +`--verbose`. + +### The env file + +`apps/eval/.env.eval.local` (git ignores `.env.*.local`). The harness reads the same +variables the app does, through apps/api's `lib/config.ts`: + +```bash +# Vertex AI: the models under test are called here. +GOOGLE_CLOUD_PROJECT= +GOOGLE_CLOUD_LOCATION=global +GOOGLE_APPLICATION_CREDENTIALS=/absolute/path/to/service-account.json # or gcloud ADC +# The search tools. +KALEMAT_API_KEY= +USUL_API_TOKEN= +# Required by config validation; the harness never opens a database connection. +DATABASE_URL=postgresql://unused:unused@localhost:5432/unused +ENVIRONMENT=development +``` + +`GEMINI_MODEL`, `GEMINI_FALLBACK_MODEL`, `PRIMARY_BACKEND` and `TINKER_API_KEY` do not +affect a run: each request is pinned to the model under test (see below). + +If the first four conversations all fail, the run stops and prints the error: a wrong +credential or model id should not produce a file of 138 errors. + +## What "the real facilitator path" means here + +`runFacilitator(history, undefined, { model })`. The `model` option pins the request: +every Gemini call targets that model, the cross-model 429 failover is off, and the request +never escalates to Inkling. Same-model retries, tool calls, budgets and the synthesis pass +all run as in production. So an answer recorded under a model's name was written by that +model, and a model that cannot answer shows up as an error, not as another model's answer. + +Follow-up turns replay history the way the chat route does: each earlier answer's text +with the final model turn's raw payload. + +## What is scored + +All by code; the functions are in `lib/` and each file's header states its rules. + +| Measure | How | +|---|---| +| Quran quote matches its source | Every run of Arabic is compared with the retrieved text of the verse it is labelled with (`score-quran.ts`). Letters only, at three levels (`arabic.ts`): as written, in standard spelling, and ignoring alefs. A reference the answer names that no search returned is looked up, so a quote written from memory is still checked. Arabic a tafsir, fiqh or hadith search returned, and Arabic in a citation entry not headed with a Quran reference, is that source's text and is set aside. | +| The reference is right | A quote whose text is a different verse than the reference on its own line (or heading its citation entry) is `wrong_reference`; a question can also list the references its answer should quote (`expectRefs`). | +| Hadith `LK id` came from a search | Every `LK id` token is looked up among the ids `search_hadith` returned in that turn, an earlier turn, or nowhere (`fabricated`). Also: hadith citations with no id, and stated grades that contradict the search result (`score-hadith.ts`). | +| Answer is in the question's language | Script share of the prose, then function words or script-specific letters (`score-language.ts`). | +| Searched before quoting | Per quote: the verse (or the quoted words, inside a tafsir or hadith result) came from a search in this turn, an earlier turn, or none. Per turn: scripture quoted with no result from the matching search tool. | +| Latency, tokens, cost, tools, failures | Time to first event and first visible text, total time; tokens summed over the turn's model calls; cost per answer and per 1,000 answers from `models.json` (see Prices); tool calls and how many returned no source; errors, budget syntheses and retries (read from the facilitator's own log lines, attributed per request). | + +The report states counts and lists every failed quote with its diff, every fabricated id, +every answer in the wrong language and every error. A quote fails only when it is labelled: +a reference on its own line, or in its paragraph when the text is plainly an attempt at a +verse in hand. Two buckets are for a human to read, not for the gate: quotes that differ +from their source only by an alef, and `suspect` Arabic (text near a reference that +matches nothing, text resembling a verse with no reference at all, or one verse's text in +a paragraph that names only another). + +### Limits, stated + +- A Quran quote with no reference near it and no matching verse in hand is not scored. +- In an answer written in Arabic script, only Arabic that is quoted (`﴿ ﴾`, `« »`, `" "`) + or vowelled is read as a quote; unvowelled, unquoted scripture inside Arabic prose is + missed. +- Spelling the checker does not fold (open ta for ta marbuta, a silent letter standard + spelling drops, a dropped hamza) shows up as a mismatch or an alef-only difference, with + its diff, for a human to judge. +- An errored turn reports no token usage, so it adds nothing to cost. +- One sample per question. Zero failures in n answers bounds the true rate below about + 3/n. Use `--repeats` for more. + +## Rescore without calling a model + +```bash +pnpm --filter ansari-eval exec -- tsx rescore.ts results/.json +``` + +Recomputes every score from what the file recorded and rewrites the report. Use it after +correcting a scorer or adding a price to `models.json`. + +## Check that a clean result means something + +```bash +pnpm --filter ansari-eval exec -- tsx selfcheck.ts results/.json +``` + +"No failed quotes" is only good news if a failed quote would have been seen. This takes +each answer in the results file that quotes a verse correctly, corrupts that quote two ways +(swaps two words, drops a word), scores it again, and reports how many corruptions the +scorer failed, how many it only listed for reading, and how many it missed. No model is +called. Run it on every results file before believing its Quran numbers. + +## Add a model + +1. Pass its id in `--models`. Nothing else is needed to run it. +2. For cost, add its price to `models.json` (US dollars per million input and output + tokens, with where the number came from). A model without a price reports cost as n/a. + +### Prices + +The report's Cost section gives, per model, the price inputs, the cost per answer and per +1,000 answers, and the ratio to the baseline. Each entry in `models.json` carries: + +- `confirmed`: `true` only after a person has checked the numbers against the + [Vertex AI pricing page](https://cloud.google.com/vertex-ai/generative-ai/pricing). The + report marks every figure for an unconfirmed model. Put the date you checked in `source`. +- `checked` (optional): a weaker check in a few words, such as "Developer API page, Vertex + unconfirmed". It is shown beside the NO; the price still counts as not confirmed. +- `next` (optional): an announced price change, `{ "from": "2026-12-01", "inputPerMTok": + 4, "outputPerMTok": 20 }`. The report then also costs the run at that price, because an + introductory rate that ends next month is not the price a decision should rest on. + +After editing prices, run `rescore.ts` on the results file: no model is called. + +What the cost figure is: model tokens only, at the full input price (the facilitator does +not report cached-input tokens, so a caching discount makes the real bill lower), averaged +over this question set, which is not production's mix of questions. + +## Add or change a question + +Question sets are files in `questions/`, validated on load (`lib/question-set.ts`). + +```json +{ + "id": "near-in-our-eyes", + "category": "near-identical", + "language": "en", + "note": "Why it is in the set.", + "turns": [{ "text": "The question.", "expectRefs": ["52:48"] }] +} +``` + +- More than one entry in `turns` makes a follow-up conversation. +- `language` is the language the answer must be in. +- `expectRefs` is optional: the Quran references the answer should quote. + +A released set is not edited: copy it to `v2.json`, raise `version`, and change that. The +results file records the set's version and hash, so two runs are comparable only when +both match. Write questions yourself. Do not copy a user's conversation out of a database. + +## Tests + +`pnpm --filter ansari-eval test`, from the repo root; no env or credentials are needed. +The suite is in `tests/`, and CI runs it with lint and typecheck in the `eval` job. Each +scorer is tested against a known-bad answer it must fail and a near-miss it must pass; +the staging misquote (بِعَيْنِنَا for بِأَعْيُنِنَا, labelled 68:48) is one of the fixtures. The +runner, scoring and report are tested end to end against a scripted facilitator. +`tests/run-command.test.ts` starts the run command itself under tsx, and loads the api +modules a real run needs through `@/` under both tsx and vitest. diff --git a/apps/eval/eslint.config.mjs b/apps/eval/eslint.config.mjs new file mode 100644 index 00000000..a9097d41 --- /dev/null +++ b/apps/eval/eslint.config.mjs @@ -0,0 +1,18 @@ +import tseslint from 'typescript-eslint'; +import ansari from '@ansari/eslint-config/base'; + +// Same shape as packages/types: the shared base is ignores-only, and ESLint 9 +// flat config does not match `.ts` files without an explicit `files` glob and +// a TypeScript parser, so both are spelled out. `results/` is run output. +export default [ + ...ansari, + { ignores: ['results/**'] }, + ...tseslint.configs.recommended, + { + files: ['**/*.ts'], + languageOptions: { + parser: tseslint.parser, + parserOptions: { projectService: false, sourceType: 'module' }, + }, + }, +]; diff --git a/apps/eval/lib/answer.ts b/apps/eval/lib/answer.ts new file mode 100644 index 00000000..bdb26847 --- /dev/null +++ b/apps/eval/lib/answer.ts @@ -0,0 +1,261 @@ +/** + * Reading the structure of a facilitator answer: the prose, the Citations section and + * its numbered entries, the `[n]` markers, and the runs of Arabic a quote can live in. + * + * The shapes are the ones apps/frontend already parses out of real answers + * (`lib/citations.ts`, `lib/document-citations.ts`); the heading and entry patterns are + * copied from there, with the heading widened to the other languages a model may title + * the section in. + */ +import { findRefs, type RefOccurrence } from './quran-refs'; + +const HEADING_WORDS = [ + 'citations', 'references', 'sources', 'références', 'referencias', 'citas', 'kutipan', 'sitasi', + 'referensi', 'rujukan', 'kaynaklar', 'kaynakça', 'alıntılar', 'المراجع', 'المصادر', 'الاستشهادات', + 'الاقتباسات', 'التوثيق', 'حوالہ جات', 'حوالے', +].join('|'); + +/** A line that is only the citations heading, however it is decorated. */ +const CITATIONS_HEADING = new RegExp( + `^[ \\t]*(?:#{1,6}[ \\t]*)?(?:\\*\\*|__)?[ \\t]*(?:${HEADING_WORDS})[ \\t]*:?[ \\t]*(?:\\*\\*|__)?[ \\t]*:?[ \\t]*$`, + 'imu', +); + +/** A line that opens a numbered entry: `[1] …`, `1. …`, `- **[1]** …`. */ +const ENTRY_LINE = /^[ \t]*(?:[-*][ \t]+)?(?:\*\*|__)?(?:\[(\d{1,4})\]|(\d{1,4})[.)])(?:\*\*|__)?[ \t]*(.*)$/; + +/** An inline source marker, not a Markdown link label. */ +const INLINE_MARKER = /\[(\d{1,4})\](?!\()/g; + +export interface CitationEntry { + number: number; + /** Offsets of the entry in the whole answer. */ + start: number; + end: number; + text: string; +} + +export interface ParsedAnswer { + answer: string; + /** The prose: everything before the citations heading (the whole answer if none). */ + body: string; + /** Offset where the citations section starts; `answer.length` when there is none. */ + citationsStart: number; + entries: CitationEntry[]; +} + +export function parseAnswer(answer: string): ParsedAnswer { + const heading = CITATIONS_HEADING.exec(answer); + if (!heading) return { answer, body: answer, citationsStart: answer.length, entries: [] }; + + const citationsStart = heading.index; + const sectionStart = heading.index + heading[0].length; + const entries: CitationEntry[] = []; + let offset = sectionStart; + let open: CitationEntry | null = null; + for (const line of answer.slice(sectionStart).split('\n')) { + const m = ENTRY_LINE.exec(line); + if (m) { + if (open) entries.push(open); + open = { number: Number(m[1] ?? m[2]), start: offset, end: offset + line.length, text: line }; + } else if (open) { + open.end = offset + line.length; + open.text += `\n${line}`; + } + offset += line.length + 1; + } + if (open) entries.push(open); + return { answer, body: answer.slice(0, citationsStart), citationsStart, entries }; +} + +// ── Arabic runs ────────────────────────────────────────────────────────────── + +/** + * Arabic letters (tatweel included), not digits or punctuation. The presentation-forms + * block is split around U+FD3E and U+FD3F: those are the ornate brackets ﴿ ﴾, and a + * bracket must end a run, or `﴿verse﴾ الآية` reads as one quote with a wrong last word. + */ +const LETTERS = + '\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0750-\\u077F\\u08A0-\\u08B4\\uFB50-\\uFD3D\\uFD40-\\uFDFB\\uFE70-\\uFEFC'; +/** Vowel marks and Quranic annotation signs. */ +const MARKS = '\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u08D3-\\u08FF'; +/** What may sit between the letters of one run: spaces on a line, joiners, ۞ and ۩. */ +const INNER = ' \\t\\u00A0\\u200C\\u200D\\u06DE\\u06E9'; + +/** + * A run of Arabic: letters and marks with only spaces between them, on one line. Digits + * (a verse number), punctuation, brackets, Latin text and line breaks all end a run, so a + * verse is one run and prose splits into clauses. Quran text carries no punctuation. + */ +const ARABIC_RUN = new RegExp(`[${LETTERS}${MARKS}](?:[${LETTERS}${MARKS}${INNER}]*[${LETTERS}${MARKS}])?`, 'g'); +const LETTER = new RegExp(`[${LETTERS.replace('\\u0620-\\u064A', '\\u0620-\\u063F\\u0641-\\u064A')}]`, 'g'); +const HARAKA = /[ً-ْ]/g; + +/** Paired marks a quotation is written between. */ +const DELIMITED = [ + /﴿[^﴾\n]{1,3000}﴾/g, + /«[^»\n]{1,3000}»/g, + /“[^”\n]{1,3000}”/g, + /"[^"\n]{1,3000}"/g, + /\{[^}\n]{1,3000}\}/g, +]; + +export interface ArabicSegment { + /** Offsets in the whole answer. */ + start: number; + end: number; + text: string; + words: number; + letters: number; + /** Vowel marks per letter. Quoted scripture is usually vowelled; prose is not. */ + vowelDensity: number; + /** Written between quotation marks or ﴿ ﴾. */ + delimited: boolean; + /** Where the segment sits. */ + where: 'body' | 'citation'; + /** The citation entry it sits in, when `where` is 'citation'. */ + entry?: number; +} + +/** Every run of Arabic in the answer with at least two words. */ +export function arabicSegments(parsed: ParsedAnswer): ArabicSegment[] { + const { answer } = parsed; + const spans: Array<[number, number]> = []; + for (const pattern of DELIMITED) { + for (const m of answer.matchAll(pattern)) spans.push([m.index, m.index + m[0].length]); + } + const out: ArabicSegment[] = []; + for (const m of answer.matchAll(ARABIC_RUN)) { + const text = m[0]; + const start = m.index; + const end = start + text.length; + const words = text.trim().split(/\s+/u).length; + const letters = text.match(LETTER)?.length ?? 0; + if (words < 2 || letters < 6) continue; + const entry = parsed.entries.find((e) => start >= e.start && end <= e.end); + out.push({ + start, + end, + text, + words, + letters, + vowelDensity: (text.match(HARAKA)?.length ?? 0) / letters, + delimited: spans.some(([s, e]) => start >= s && end <= e), + where: start >= parsed.citationsStart ? 'citation' : 'body', + entry: entry?.number, + }); + } + return out; +} + +// ── Labels ─────────────────────────────────────────────────────────────────── + +/** How near a label is to the text it is read against, nearest first. */ +export type LabelScope = 'line' | 'paragraph' | 'near'; + +export interface Label extends RefOccurrence { + /** The reference was written here, or reached through a `[n]` marker written here. */ + via: 'direct' | 'marker'; +} + +export interface AnswerLabels { + /** Labels in the prose, by position: written references and `[n]` markers resolved. */ + body: Label[]; + /** + * The references each citation entry is headed with, by entry number: the ones on its + * first line (`[1] Quran 2:286`). An entry headed with none is not a Quran entry: a + * hadith, a tafsir or a fiqh source, whose Arabic is that source's text. A reference + * further down such an entry (a tafsir saying "when 2:284 was revealed") is not a label. + */ + byEntry: Map; + /** Every distinct reference the answer names, anywhere. */ + all: RefOccurrence[]; +} + +export function answerLabels(parsed: ParsedAnswer): AnswerLabels { + const byEntry = new Map(); + const all: RefOccurrence[] = []; + for (const entry of parsed.entries) { + const refs = findRefs(entry.text).map((r) => ({ ...r, start: r.start + entry.start, end: r.end + entry.start })); + const headerEnd = entry.start + (entry.text.indexOf('\n') === -1 ? entry.text.length : entry.text.indexOf('\n')); + // The first entry with a number wins, as it does for a reader. + if (!byEntry.has(entry.number)) byEntry.set(entry.number, refs.filter((r) => r.end <= headerEnd)); + all.push(...refs); + } + + const body: Label[] = findRefs(parsed.body).map((r) => ({ ...r, via: 'direct' as const })); + all.push(...body); + for (const m of parsed.body.matchAll(INLINE_MARKER)) { + for (const ref of byEntry.get(Number(m[1])) ?? []) { + body.push({ ...ref, start: m.index, end: m.index + m[0].length, via: 'marker' }); + } + } + body.sort((a, b) => a.start - b.start); + return { body, byEntry, all }; +} + +function lineBounds(text: string, start: number, end: number): [number, number] { + const from = text.lastIndexOf('\n', start - 1) + 1; + const to = text.indexOf('\n', end); + return [from, to === -1 ? text.length : to]; +} + +function paragraphBounds(text: string, start: number, end: number): [number, number] { + const before = text.slice(0, start); + const blank = /\n[ \t]*\n/g; + let from = 0; + for (const m of before.matchAll(blank)) from = m.index + m[0].length; + const after = /\n[ \t]*\n/.exec(text.slice(end)); + return [from, after ? end + after.index : text.length]; +} + +/** The end of a sentence: a full stop, question or exclamation mark, any closing marks, then a space. */ +const SENTENCE_END = /[.!?؟。]["'»”)\]*_`]*\s/u; + +/** How far after / before a segment a label still counts as `near`. */ +const NEAR_AFTER = 400; +const NEAR_BEFORE = 200; + +/** + * The labels a segment is read against, nearest scope first: the labels on its own line + * (those after it, only within its sentence); failing that, in its paragraph; failing + * that, the closest one shortly after or before. + * A segment inside a citation entry is read against the references that entry is headed + * with, and against nothing when it is headed with none. + */ +export function labelsFor( + segment: ArabicSegment, + parsed: ParsedAnswer, + labels: AnswerLabels, +): { scope: LabelScope | null; labels: RefOccurrence[] } { + if (segment.where === 'citation') { + const refs = segment.entry === undefined ? [] : (labels.byEntry.get(segment.entry) ?? []); + return { scope: refs.length > 0 ? 'line' : null, labels: refs }; + } + const within = ([from, to]: [number, number]) => labels.body.filter((l) => l.start >= from && l.end <= to); + + // A label after the quote labels it only within the same sentence: in + // `In «quote», the words show no case ending. In 5:69, …` the reference opens the next + // sentence and is about something else. A label before the quote keeps the whole line + // (`Quran 68:48. «quote»`). + const sameSentence = (l: RefOccurrence) => l.start < segment.end || !SENTENCE_END.test(parsed.body.slice(segment.end, l.start)); + const onLine = within(lineBounds(parsed.body, segment.start, segment.end)).filter(sameSentence); + if (onLine.length > 0) return { scope: 'line', labels: onLine }; + const inParagraph = within(paragraphBounds(parsed.body, segment.start, segment.end)); + if (inParagraph.length > 0) return { scope: 'paragraph', labels: inParagraph }; + + const gap = (l: RefOccurrence) => (l.start >= segment.end ? l.start - segment.end : segment.start - l.end); + const near = labels.body + .filter((l) => (l.start >= segment.end ? gap(l) <= NEAR_AFTER : l.end <= segment.start && gap(l) <= NEAR_BEFORE)) + .sort((a, b) => gap(a) - gap(b)); + if (near.length === 0) return { scope: null, labels: [] }; + // The closest label, and any others written at the same spot (a marker with two refs). + return { scope: 'near', labels: near.filter((l) => l.start === near[0].start) }; +} + +/** The share of a text's letters that are Arabic script (0 when it has no letters). */ +export function arabicShare(text: string): number { + const letters = text.match(/\p{L}/gu)?.length ?? 0; + if (letters === 0) return 0; + return (text.match(/(?=\p{L})\p{Script=Arabic}/gu)?.length ?? 0) / letters; +} diff --git a/apps/eval/lib/arabic.ts b/apps/eval/lib/arabic.ts new file mode 100644 index 00000000..2760cf98 --- /dev/null +++ b/apps/eval/lib/arabic.ts @@ -0,0 +1,300 @@ +/** + * Arabic text normalization for comparing a quoted Quran passage with its source. + * + * The source (Kalimat) is Uthmani script with full marks: `ٱلصَّلَوٰةَ`, `ٱلسَّمَـٰوَٰتِ`. + * A model may copy it, drop the marks, or retype it in standard spelling: `الصلاة`, + * `السماوات`. A raw comparison would call all of those misquotes, so the comparison runs + * on letters only, at three levels. Each level is a pure function of the text; a quote + * matches a verse at a level when its normalized letters are a contiguous substring of the + * verse's normalized letters. + * + * - `verbatim`: marks removed, nothing respelled. Passes when the quote carries the same + * letters as the source. This is what a copy of the search result gives. + * - `standard`: the documented Uthmani-to-standard spelling rules below. Passes for a + * correct quote retyped in standard spelling. THIS is the level that decides a pass. + * - `skeleton`: `standard` with every plain alef removed. Passes when the only remaining + * difference is whether an alef is written. It can hide a real error (قال / قل), so a + * quote that matches only here is reported for a human to read, not counted as exact. + * + * `standard` rules, applied word by word so no rule can reach across a word boundary + * (a quote may begin or end anywhere in a verse): + * 1. Remove vowel marks, tanwin, shadda, sukun, madda, Quranic pause and annotation + * signs, tatweel, and everything that is not an Arabic letter. + * 2. Alef wasla ٱ and alef madda آ are alef. Hamza on any seat (أ إ ؤ ئ, or the hamza + * mark on a tatweel) is a bare hamza ء; the seat is not kept, because the two + * spellings seat it differently (يَـُٔودُهُ / يؤوده). + * 3. ى and Farsi ی are ي; ک is ك. + * 4. Dagger alef (U+0670) is a written alef (ٱلْكِتَـٰبُ → الكتاب), except: on a waw that + * carries no vowel of its own the pair is one alef (ٱلصَّلَوٰةَ → الصلاة); on a final ى + * it is dropped (عَلَىٰ → علي); on a ى inside a word the pair is one alef + * (ٱلتَّوْرَىٰةَ → التوراة). + * 5. Small waw ۥ is dropped. Small ya ۦ is dropped after ه (بِهِۦ) and is ي elsewhere + * (يُحْىِۦ → يحيي). Small high ya ۧ is ي; small high noon ۨ is ن. + * 6. Inside a word, ءا is ا (ءَامَنُوا / آمنوا) and a run of alefs is one alef. + * 7. The few words standard spelling writes without the alef the dagger stands for, and + * the lam words Uthmani writes with one lam, are folded to one form (WORD_FOLDS). + * + * Known residue, which lands in `skeleton` or as a mismatch and is listed in the report + * for a human: open ta for ta marbuta (رحمت / رحمة), a silent letter standard spelling + * drops (مِا۟ئَةَ / مئة), and a hamza dropped by the writer (باعيننا for بأعيننا). + */ + +const FATHA = 0x064e; +const DAMMA = 0x064f; +const KASRA = 0x0650; +const SHADDA = 0x0651; +const SUKUN = 0x0652; +const HAMZA_ABOVE = 0x0654; +const HAMZA_BELOW = 0x0655; +const DAGGER_ALEF = 0x0670; +const SMALL_HIGH_YEH = 0x06e7; +const SMALL_HIGH_NOON = 0x06e8; +const TATWEEL = 0x0640; +const SMALL_WAW = 0x06e5; +const SMALL_YEH = 0x06e6; + +const ALEF = 'ا'; +const HAMZA = 'ء'; +const WAW = 'و'; +const YEH = 'ي'; +const HEH = 'ه'; + +/** A combining mark (Unicode category M). Every Arabic vowel and annotation sign is one. */ +const MARK = /\p{M}/u; +/** An Arabic-script letter, as opposed to an Arabic digit, mark or punctuation sign. */ +const ARABIC_LETTER = /(?=\p{L})\p{Script=Arabic}/u; +const ARABIC_LETTER_G = /(?=\p{L})\p{Script=Arabic}/gu; + +export function isArabicLetter(ch: string): boolean { + return ARABIC_LETTER.test(ch); +} + +/** How many Arabic letters a text holds (marks, digits and punctuation not counted). */ +export function arabicLetterCount(text: string): number { + return text.match(ARABIC_LETTER_G)?.length ?? 0; +} + +/** Letter-level folds shared by every level. */ +function foldLetter(ch: string): string { + switch (ch) { + case 'ٱ': // alef wasla + return ALEF; + case 'ى': // alef maqsura + case 'ی': // Farsi yeh + return YEH; + case 'ک': // keheh + return 'ك'; + default: + return ch; + } +} + +/** + * `verbatim`: the text's Arabic letters as written, marks removed. NFC first, so a + * decomposed أ (alef + hamza mark) and a precomposed one compare equal. + */ +export function normalizeVerbatim(text: string): string { + let out = ''; + for (const ch of text.normalize('NFC')) { + const cp = ch.codePointAt(0)!; + if (cp === TATWEEL || cp === SMALL_WAW || cp === SMALL_YEH) continue; + if (!isArabicLetter(ch)) continue; + out += foldLetter(ch); + } + return out; +} + +/** Rule 7. Applied to a single normalized word, so it cannot reach across a boundary. */ +const WORD_FOLDS: ReadonlyArray = [ + ['هاذا', 'هذا'], + ['هاذه', 'هذه'], + ['هاذان', 'هذان'], + ['هاءلاء', 'هءلاء'], + ['ذالك', 'ذلك'], + ['لاكن', 'لكن'], + ['ءولاءك', 'ءولءك'], + ['الرحمان', 'الرحمن'], + ['ءلاه', 'ءله'], + ['الليل', 'اليل'], + ['اللاتي', 'الاتي'], + ['اللاءي', 'الاءي'], +]; + +interface Cluster { + base: string; + marks: number[]; +} + +/** One word (no whitespace) as base characters, each with the marks that follow it. */ +function clusters(word: string): Cluster[] { + const out: Cluster[] = []; + for (const ch of word.normalize('NFD')) { + if (MARK.test(ch)) { + if (out.length > 0) out[out.length - 1].marks.push(ch.codePointAt(0)!); + continue; + } + out.push({ base: ch, marks: [] }); + } + return out; +} + +function hasOwnVowel(marks: number[]): boolean { + return marks.some((m) => m === FATHA || m === DAMMA || m === KASRA || m === SHADDA || m === SUKUN); +} + +function normalizeStandardWord(word: string): string { + const cs = clusters(word); + let out = ''; + for (let i = 0; i < cs.length; i++) { + const { base, marks } = cs[i]; + const cp = base.codePointAt(0)!; + const hamza = marks.includes(HAMZA_ABOVE) || marks.includes(HAMZA_BELOW); + const dagger = marks.includes(DAGGER_ALEF); + const tail = + (marks.includes(SMALL_HIGH_YEH) ? YEH : '') + (marks.includes(SMALL_HIGH_NOON) ? 'ن' : ''); + + if (cp === TATWEEL) { + // A tatweel only carries what is written above it. + out += (hamza ? HAMZA : '') + (dagger ? ALEF : '') + tail; + continue; + } + if (cp === SMALL_WAW) continue; + if (cp === SMALL_YEH) { + if (!out.endsWith(HEH)) out += YEH; + continue; + } + if (!isArabicLetter(base)) continue; + + const letter = foldLetter(base); + if (hamza && (letter === ALEF || letter === WAW || letter === YEH)) { + // Rule 2: the seat is not kept. + out += HAMZA + (dagger ? ALEF : '') + tail; + continue; + } + if (dagger && letter === WAW && !hasOwnVowel(marks)) { + out += ALEF + tail; // rule 4: ٱلصَّلَوٰةَ + continue; + } + if (dagger && (base === 'ى' || base === 'ی')) { + const moreLetters = cs.slice(i + 1).some((c) => isArabicLetter(c.base)); + out += (moreLetters ? ALEF : YEH) + tail; // rule 4: ٱلتَّوْرَىٰةَ / عَلَىٰ + continue; + } + out += letter + (hamza ? HAMZA : '') + (dagger ? ALEF : '') + tail; + } + + out = out.replace(/ءا/g, ALEF).replace(/ا{2,}/g, ALEF); // rule 6 + for (const [from, to] of WORD_FOLDS) { + if (out.includes(from)) out = out.split(from).join(to); + } + return out; +} + +/** The `standard` form of each whitespace-separated word, empty words dropped. */ +export function standardWords(text: string): string[] { + return text + .split(/\s+/u) + .map(normalizeStandardWord) + .filter((w) => w.length > 0); +} + +/** `standard`: see the rules at the top of this file. */ +export function normalizeStandard(text: string): string { + return standardWords(text).join(''); +} + +/** `skeleton`: `standard` with every plain alef removed. */ +export function normalizeSkeleton(text: string): string { + return normalizeStandard(text).split(ALEF).join(''); +} + +export type MatchLevel = 'verbatim' | 'standard' | 'skeleton'; + +export interface NormalizedText { + verbatim: string; + standard: string; + skeleton: string; +} + +export function normalizeAll(text: string): NormalizedText { + const standard = normalizeStandard(text); + return { + verbatim: normalizeVerbatim(text), + standard, + skeleton: standard.split(ALEF).join(''), + }; +} + +/** + * The strictest level at which `quote` is a contiguous part of `source`, or null. A quote + * with no letters at a level cannot match at that level. + */ +export function matchLevel(quote: NormalizedText, source: NormalizedText): MatchLevel | null { + if (quote.verbatim && source.verbatim.includes(quote.verbatim)) return 'verbatim'; + if (quote.standard && source.standard.includes(quote.standard)) return 'standard'; + if (quote.skeleton && source.skeleton.includes(quote.skeleton)) return 'skeleton'; + return null; +} + +/** + * The share of `quote`'s 4-letter windows (at `skeleton`) that occur in `source`. Used + * only to name the verse a failed quote was probably attempting; never to pass one. + */ +export function overlap(quote: NormalizedText, source: NormalizedText): number { + const q = quote.skeleton; + const s = source.skeleton; + if (q.length < 4) return 0; + let hit = 0; + const total = q.length - 3; + for (let i = 0; i < total; i++) { + if (s.includes(q.slice(i, i + 4))) hit++; + } + return hit / total; +} + +/** + * Where a quote departs from its source, word by word at `standard`: `extra` is the + * quote's words that are not in the source in order; `missing` is the source's words the + * quote should have had in their place (the words it skipped between its matched words, + * and as many source words before its first and after its last matched word as it has + * unmatched words there). For the report; a human reads it. + */ +export function wordDiff(quoteText: string, sourceText: string): { extra: string[]; missing: string[] } { + const q = standardWords(quoteText); + const s = standardWords(sourceText); + // Longest common subsequence over words. + const lcs: number[][] = Array.from({ length: q.length + 1 }, () => new Array(s.length + 1).fill(0)); + for (let i = q.length - 1; i >= 0; i--) { + for (let j = s.length - 1; j >= 0; j--) { + lcs[i][j] = q[i] === s[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + } + const matchedQuote: number[] = []; + const matchedSource: number[] = []; + let i = 0; + let j = 0; + while (i < q.length && j < s.length) { + if (q[i] === s[j]) { + matchedQuote.push(i++); + matchedSource.push(j++); + } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { + i++; + } else { + j++; + } + } + const inQuote = new Set(matchedQuote); + const extra = q.filter((_, k) => !inQuote.has(k)); + if (matchedSource.length === 0) return { extra, missing: [] }; + + const inSource = new Set(matchedSource); + const first = matchedSource[0]; + const last = matchedSource[matchedSource.length - 1]; + const leading = matchedQuote[0]; + const trailing = q.length - 1 - matchedQuote[matchedQuote.length - 1]; + const missing: string[] = []; + for (let k = Math.max(0, first - leading); k <= Math.min(s.length - 1, last + trailing); k++) { + if (!inSource.has(k)) missing.push(s[k]); + } + return { extra, missing }; +} diff --git a/apps/eval/lib/capture.ts b/apps/eval/lib/capture.ts new file mode 100644 index 00000000..52f5d4a6 --- /dev/null +++ b/apps/eval/lib/capture.ts @@ -0,0 +1,50 @@ +/** + * Attributing the facilitator's own log lines to the request that wrote them. + * + * The facilitator reports an empty-final retry, a transient-error retry, a repetition cut + * and a budget short-circuit only through console.warn / console.error. Those are what + * "degraded outcomes" are made of, and with several requests in flight a shared console + * cannot say whose line is whose. AsyncLocalStorage can: each request runs inside its own + * store, and a line written anywhere in that request's async work lands in that store. + * + * Only the first argument's text and the message of any Error argument are kept, cut to + * a fixed length: a log line is a label, not a place for content. + */ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { LogEvent } from './types'; + +const store = new AsyncLocalStorage(); +const MAX_MESSAGE = 300; +let installed = false; + +function render(args: unknown[]): string { + const parts = args + .filter((a) => typeof a === 'string' || a instanceof Error) + .map((a) => (a instanceof Error ? a.message : (a as string))); + return parts.join(' ').slice(0, MAX_MESSAGE); +} + +/** + * Route console.warn and console.error into the active request's store. Outside a + * request they print as before. With `echo`, captured lines are printed too. + */ +export function installLogCapture(options: { echo?: boolean } = {}): void { + if (installed) return; + installed = true; + for (const level of ['warn', 'error'] as const) { + const original = console[level].bind(console); + console[level] = (...args: unknown[]) => { + const events = store.getStore(); + if (!events) return original(...args); + events.push({ level, message: render(args) }); + if (options.echo) original(...args); + }; + } +} + +/** Run `work`, returning its result and the log lines written while it ran. */ +export async function withLogCapture(work: () => Promise): Promise<{ result: T; log: LogEvent[] }> { + const log: LogEvent[] = []; + const result = await store.run(log, work); + return { result, log }; +} diff --git a/apps/eval/lib/question-set.ts b/apps/eval/lib/question-set.ts new file mode 100644 index 00000000..273ece20 --- /dev/null +++ b/apps/eval/lib/question-set.ts @@ -0,0 +1,57 @@ +/** + * Loading a question set and failing loudly on a malformed one: a set that silently + * dropped a question would make two runs look comparable when they are not. + */ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { z } from 'zod'; +import { parseRef } from './quran-refs'; +import { LANGUAGES } from './score-language'; +import type { QuestionSet } from './types'; + +const turnSchema = z.strictObject({ + text: z.string().min(1), + expectRefs: z + .array(z.string().refine((r) => parseRef(r) !== null, 'must be a Quran reference like 52:48 or 94:5-6')) + .optional(), +}); + +const questionSchema = z.strictObject({ + id: z.string().regex(/^[a-z0-9-]+$/, 'ids are lowercase letters, digits and hyphens'), + category: z.string().min(1), + language: z.enum(LANGUAGES), + turns: z.array(turnSchema).min(1), + note: z.string().optional(), +}); + +const setSchema = z + .strictObject({ + id: z.string().min(1), + version: z.number().int().positive(), + description: z.string(), + questions: z.array(questionSchema).min(1), + }) + .superRefine((set, ctx) => { + const seen = new Set(); + for (const q of set.questions) { + if (seen.has(q.id)) ctx.addIssue({ code: 'custom', message: `duplicate question id "${q.id}"` }); + seen.add(q.id); + } + }); + +export interface LoadedQuestionSet { + set: QuestionSet; + /** sha256 of the file's bytes: two runs with the same hash asked the same questions. */ + sha256: string; +} + +export function parseQuestionSet(json: string): QuestionSet { + const result = setSchema.safeParse(JSON.parse(json)); + if (!result.success) throw new Error(`Question set is not valid:\n${result.error.toString()}`); + return result.data; +} + +export function loadQuestionSet(path: string): LoadedQuestionSet { + const text = readFileSync(path, 'utf8'); + return { set: parseQuestionSet(text), sha256: createHash('sha256').update(text).digest('hex') }; +} diff --git a/apps/eval/lib/quran-refs.ts b/apps/eval/lib/quran-refs.ts new file mode 100644 index 00000000..e82e26fd --- /dev/null +++ b/apps/eval/lib/quran-refs.ts @@ -0,0 +1,252 @@ +/** + * Finding Quran references in an answer: `2:255`, `94:5-6`, `٢:٢٥٥`, `[الطور: 48]`, + * `سورة البقرة، الآية 255`, `Surah At-Tur, verse 48`. + * + * A reference is only accepted when the surah exists and the ayah is within that surah's + * length, which is what keeps `10:30` the time and `Muslim 8:3371` from being read as one. + */ + +/** Ayah count per surah, index 0 = surah 1. The total is 6236; a test holds that. */ +export const AYAH_COUNTS: readonly number[] = [ + 7, 286, 200, 176, 120, 165, 206, 75, 129, 109, 123, 111, 43, 52, 99, 128, 111, 110, 98, 135, + 112, 78, 118, 64, 77, 227, 93, 88, 69, 60, 34, 30, 73, 54, 45, 83, 182, 88, 75, 85, + 54, 53, 89, 59, 37, 35, 38, 29, 18, 45, 60, 49, 62, 55, 78, 96, 29, 22, 24, 13, + 14, 11, 11, 18, 12, 12, 30, 52, 52, 44, 28, 28, 20, 56, 40, 31, 50, 40, 46, 42, + 29, 19, 36, 25, 22, 17, 19, 26, 30, 20, 15, 21, 11, 8, 8, 19, 5, 8, 8, 11, + 11, 8, 3, 9, 5, 4, 7, 3, 6, 3, 5, 4, 5, 6, +]; + +/** Arabic surah names, index 0 = surah 1. */ +const ARABIC_NAMES: readonly string[] = [ + 'الفاتحة', 'البقرة', 'آل عمران', 'النساء', 'المائدة', 'الأنعام', 'الأعراف', 'الأنفال', 'التوبة', 'يونس', + 'هود', 'يوسف', 'الرعد', 'إبراهيم', 'الحجر', 'النحل', 'الإسراء', 'الكهف', 'مريم', 'طه', + 'الأنبياء', 'الحج', 'المؤمنون', 'النور', 'الفرقان', 'الشعراء', 'النمل', 'القصص', 'العنكبوت', 'الروم', + 'لقمان', 'السجدة', 'الأحزاب', 'سبأ', 'فاطر', 'يس', 'الصافات', 'ص', 'الزمر', 'غافر', + 'فصلت', 'الشورى', 'الزخرف', 'الدخان', 'الجاثية', 'الأحقاف', 'محمد', 'الفتح', 'الحجرات', 'ق', + 'الذاريات', 'الطور', 'النجم', 'القمر', 'الرحمن', 'الواقعة', 'الحديد', 'المجادلة', 'الحشر', 'الممتحنة', + 'الصف', 'الجمعة', 'المنافقون', 'التغابن', 'الطلاق', 'التحريم', 'الملك', 'القلم', 'الحاقة', 'المعارج', + 'نوح', 'الجن', 'المزمل', 'المدثر', 'القيامة', 'الإنسان', 'المرسلات', 'النبأ', 'النازعات', 'عبس', + 'التكوير', 'الانفطار', 'المطففين', 'الانشقاق', 'البروج', 'الطارق', 'الأعلى', 'الغاشية', 'الفجر', 'البلد', + 'الشمس', 'الليل', 'الضحى', 'الشرح', 'التين', 'العلق', 'القدر', 'البينة', 'الزلزلة', 'العاديات', + 'القارعة', 'التكاثر', 'العصر', 'الهمزة', 'الفيل', 'قريش', 'الماعون', 'الكوثر', 'الكافرون', 'النصر', + 'المسد', 'الإخلاص', 'الفلق', 'الناس', +]; + +/** + * English surah names as keys: lowercase, no diacritics, no article, no punctuation. + * `englishKey` reduces what a model writes ("Aṭ-Ṭūr", "al-Baqarah") to the same form. + */ +const ENGLISH_KEYS: readonly string[] = [ + 'fatihah', 'baqarah', 'imran', 'nisa', 'maidah', 'anam', 'araf', 'anfal', 'tawbah', 'yunus', + 'hud', 'yusuf', 'rad', 'ibrahim', 'hijr', 'nahl', 'isra', 'kahf', 'maryam', 'taha', + 'anbiya', 'hajj', 'muminun', 'nur', 'furqan', 'shuara', 'naml', 'qasas', 'ankabut', 'rum', + 'luqman', 'sajdah', 'ahzab', 'saba', 'fatir', 'yasin', 'saffat', 'sad', 'zumar', 'ghafir', + 'fussilat', 'shura', 'zukhruf', 'dukhan', 'jathiyah', 'ahqaf', 'muhammad', 'fath', 'hujurat', 'qaf', + 'dhariyat', 'tur', 'najm', 'qamar', 'rahman', 'waqiah', 'hadid', 'mujadilah', 'hashr', 'mumtahanah', + 'saff', 'jumuah', 'munafiqun', 'taghabun', 'talaq', 'tahrim', 'mulk', 'qalam', 'haqqah', 'maarij', + 'nuh', 'jinn', 'muzzammil', 'muddaththir', 'qiyamah', 'insan', 'mursalat', 'naba', 'naziat', 'abasa', + 'takwir', 'infitar', 'mutaffifin', 'inshiqaq', 'buruj', 'tariq', 'ala', 'ghashiyah', 'fajr', 'balad', + 'shams', 'layl', 'duha', 'sharh', 'tin', 'alaq', 'qadr', 'bayyinah', 'zalzalah', 'adiyat', + 'qariah', 'takathur', 'asr', 'humazah', 'fil', 'quraysh', 'maun', 'kawthar', 'kafirun', 'nasr', + 'masad', 'ikhlas', 'falaq', 'nas', +]; + +export const SURAH_COUNT = 114; + +export interface QuranRef { + surah: number; + /** First ayah. */ + ayah: number; + /** Last ayah of a range; equals `ayah` for a single verse. */ + ayahEnd: number; +} + +export interface RefOccurrence extends QuranRef { + /** Offsets of the reference in the text it was found in. */ + start: number; + end: number; + /** How it was written: `2:255`, or by surah name. */ + form: 'numeric' | 'named'; +} + +export function refKey(surah: number, ayah: number): string { + return `${surah}:${ayah}`; +} + +/** Every verse key a reference covers, e.g. 94:5-6 → ['94:5', '94:6']. */ +export function refVerses(ref: QuranRef): string[] { + const out: string[] = []; + for (let a = ref.ayah; a <= ref.ayahEnd; a++) out.push(refKey(ref.surah, a)); + return out; +} + +export function formatRef(ref: QuranRef): string { + return ref.ayahEnd > ref.ayah ? `${ref.surah}:${ref.ayah}-${ref.ayahEnd}` : `${ref.surah}:${ref.ayah}`; +} + +/** Parse `52:48` or `94:5-6`; null when it is not a valid reference. */ +export function parseRef(text: string): QuranRef | null { + const m = /^(\d{1,3}):(\d{1,3})(?:-(\d{1,3}))?$/.exec(text.trim()); + if (!m) return null; + return validRef(Number(m[1]), Number(m[2]), m[3] === undefined ? undefined : Number(m[3])); +} + +function validRef(surah: number, ayah: number, ayahEnd?: number): QuranRef | null { + if (!Number.isInteger(surah) || surah < 1 || surah > SURAH_COUNT) return null; + const count = AYAH_COUNTS[surah - 1]; + if (ayah < 1 || ayah > count) return null; + if (ayahEnd === undefined || ayahEnd === ayah) return { surah, ayah, ayahEnd: ayah }; + if (ayahEnd < ayah || ayahEnd > count) return null; + return { surah, ayah, ayahEnd }; +} + +/** Arabic-Indic and Persian digits as ASCII, one character for one, so offsets hold. */ +export function asciiDigits(text: string): string { + return text.replace(/[٠-٩۰-۹]/g, (d) => { + const cp = d.charCodeAt(0); + return String(cp >= 0x06f0 ? cp - 0x06f0 : cp - 0x0660); + }); +} + +/** An Arabic name with marks and hamza seats folded, so `الإسراء` and `الاسراء` agree. */ +function arabicNameKey(name: string): string { + return name + .normalize('NFD') + .replace(/\p{M}/gu, '') + .replace(/[ٱأإآ]/g, 'ا') + .replace(/ى/g, 'ي') + .replace(/[ةہۃ]/g, 'ه') + .replace(/\s+/g, ' ') + .trim(); +} + +const ARTICLE = /^(?:al|an|ar|as|ash|at|ath|ad|adh|az|aal|ali|el)[-\s'’]+/; + +/** Reduce an English surah name to its key; see ENGLISH_KEYS. */ +export function englishKey(name: string): string { + let key = name + .normalize('NFD') + .replace(/\p{M}/gu, '') + .toLowerCase() + .replace(/[ʿʾ`]/g, "'") + .trim(); + key = key.replace(/^(?:surah|surat|sura|sourate|sure|surah\s+al)\s+/, ''); + for (let i = 0; i < 2; i++) key = key.replace(ARTICLE, ''); + key = key.replace(/[^a-z]/g, ''); + // Spelling variants a model produces for the same name. + key = key.replace(/aa/g, 'a').replace(/ee/g, 'i').replace(/oo/g, 'u'); + return key; +} + +const ENGLISH_ALIASES: Readonly> = { + fatiha: 'fatihah', baqara: 'baqarah', aliimran: 'imran', maida: 'maidah', tawba: 'tawbah', + tauba: 'tawbah', anaam: 'anam', yaseen: 'yasin', yasin: 'yasin', sajda: 'sajdah', + jathiya: 'jathiyah', waqia: 'waqiah', mujadila: 'mujadilah', mumtahana: 'mumtahanah', + juma: 'jumuah', jumua: 'jumuah', haqqa: 'haqqah', qiyama: 'qiyamah', ghashiya: 'ghashiyah', + bayyina: 'bayyinah', zalzala: 'zalzalah', qaria: 'qariah', humaza: 'humazah', inshirah: 'sharh', + kafirun: 'kafirun', kafiroon: 'kafirun', muminoon: 'muminun', munafiqoon: 'munafiqun', + toor: 'tur', noor: 'nur', room: 'rum', hood: 'hud', nooh: 'nuh', teen: 'tin', feel: 'fil', + layl: 'layl', lail: 'layl', duhaa: 'duha', quraish: 'quraysh', kauthar: 'kawthar', kausar: 'kawthar', + ikhlaas: 'ikhlas', naas: 'nas', asr: 'asr', isra: 'isra', israa: 'isra', taha: 'taha', +}; + +const ARABIC_NAME_TO_SURAH = new Map( + ARABIC_NAMES.map((name, i) => [arabicNameKey(name), i + 1]), +); +const ENGLISH_KEY_TO_SURAH = new Map(ENGLISH_KEYS.map((key, i) => [key, i + 1])); + +export function surahByArabicName(name: string): number | null { + const key = arabicNameKey(name); + return ARABIC_NAME_TO_SURAH.get(key) ?? ARABIC_NAME_TO_SURAH.get(`ال${key}`) ?? null; +} + +export function surahByEnglishName(name: string): number | null { + const key = englishKey(name); + if (!key) return null; + const direct = ENGLISH_KEY_TO_SURAH.get(key) ?? ENGLISH_KEY_TO_SURAH.get(ENGLISH_ALIASES[key] ?? ''); + if (direct) return direct; + // A trailing h is optional in transliteration (Baqara / Baqarah). + return ENGLISH_KEY_TO_SURAH.get(`${key}h`) ?? ENGLISH_KEY_TO_SURAH.get(key.replace(/h$/, '')) ?? null; +} + +/** + * `surah:ayah` and `surah:ayah-ayah`. Not preceded by a digit, colon or underscore (an + * `LK id 1_23_42`, a time), and not followed by another `:digit` or by an underscore. + */ +const NUMERIC_REF = /(? b.length - a.length) + // The keys are folded (arabicNameKey); widen each folded letter back to what a model + // may write, so `المؤمنون`, `المائدة` and `الإسراء` are found as written. + .map((name) => + [...name] + .map((ch, i) => { + if (ch === 'ا') return '[اأإآٱ]'; + if (ch === 'و') return '[وؤ]'; + if (ch === 'ي') return '[يئى]'; + if (ch === 'ه' && i === name.length - 1) return '[هةہ]'; + return ch; + }) + .join(''), + ) + .join('|'); + +/** + * A surah named in Arabic, then an ayah number: `سورة الطور: 48`, `[الطور: 48]`, + * `(البقرة، الآية 255)`. Short names are ordinary words (ص, ق, محمد), so the name must + * follow سورة or open a bracket. + */ +const ARABIC_NAMED_REF = new RegExp( + `(?:(?:سورة|سورۃ)\\s+|[\\[\\(﴿])(${ARABIC_NAME_ALT})\\s*[:،,]?\\s*(?:${AYAH_WORD}\\s*[:]?\\s*)?(\\d{1,3})(?:\\s?[-–—]\\s?(\\d{1,3}))?`, + 'gu', +); + +/** + * A surah named in Latin script, then an ayah number: `Surah At-Tur, verse 48`, + * `Sourate Al-Baqara, verset 255`, `Surah Ash-Sharh (94), Verse 6`, `Surah Al-Baqarah: 255`, + * `QS. Al-Baqarah [2]: 255`. The word for "surah" (or QS) is required, and then either a + * word for "verse" or a colon before the number. + */ +const LATIN_NAMED_REF = new RegExp( + `\\b(?:surah|surat|sura|sourate|sure|qs\\.?)\\s+([\\p{L}'’ʿʾ\`-]+(?:[\\s-][\\p{L}'’ʿʾ\`-]+)?)\\s*(?:[\\[(]\\d{1,3}[\\])])?\\s*(?:[,(]?\\s*${AYAH_WORD}\\s*:?|:)\\s*(\\d{1,3})(?:\\s?[-–—]\\s?(\\d{1,3}))?`, + 'giu', +); + +/** Every Quran reference in `text`, in order of appearance, overlapping finds merged. */ +export function findRefs(text: string): RefOccurrence[] { + const ascii = asciiDigits(text); + const found: RefOccurrence[] = []; + + for (const m of ascii.matchAll(NUMERIC_REF)) { + const ref = validRef(Number(m[1]), Number(m[2]), m[3] === undefined ? undefined : Number(m[3])); + // An out-of-range end (`2:255-300`) is not a range; keep the first verse. + const single = ref ?? (m[3] !== undefined ? validRef(Number(m[1]), Number(m[2])) : null); + if (single) found.push({ ...single, start: m.index, end: m.index + m[0].length, form: 'numeric' }); + } + + for (const m of ascii.matchAll(ARABIC_NAMED_REF)) { + const surah = surahByArabicName(m[1]); + if (!surah) continue; + const ref = validRef(surah, Number(m[2]), m[3] === undefined ? undefined : Number(m[3])); + if (ref) found.push({ ...ref, start: m.index, end: m.index + m[0].length, form: 'named' }); + } + + for (const m of ascii.matchAll(LATIN_NAMED_REF)) { + const surah = surahByEnglishName(m[1]); + if (!surah) continue; + const ref = validRef(surah, Number(m[2]), m[3] === undefined ? undefined : Number(m[3])); + if (ref) found.push({ ...ref, start: m.index, end: m.index + m[0].length, form: 'named' }); + } + + found.sort((a, b) => a.start - b.start || b.end - a.end); + // A named reference that contains a numeric one ("Surah At-Tur 52:48") is one reference. + const merged: RefOccurrence[] = []; + for (const ref of found) { + const prev = merged[merged.length - 1]; + if (prev && ref.start < prev.end) continue; + merged.push(ref); + } + return merged; +} diff --git a/apps/eval/lib/report.ts b/apps/eval/lib/report.ts new file mode 100644 index 00000000..58df875a --- /dev/null +++ b/apps/eval/lib/report.ts @@ -0,0 +1,512 @@ +/** + * The comparison report: per-model totals, the pre-registered gates against the baseline, + * and every item a human should read (each failed quote with its diff, each fabricated + * id, each answer in the wrong language, each error). Counts, not just verdicts. + */ +import { HARD_FAIL, type QuoteScore } from './score-quran'; +import type { ModelPrice, RunFile, TurnRecord } from './types'; + +type Grounding = 'this_turn' | 'earlier_turn' | 'none'; + +export interface ModelStats { + model: string; + turns: number; + ok: number; + errors: number; + skipped: number; + budgetSynthesis: number; + emptyFinalRetries: number; + transientRetries: number; + quran: { + quotes: number; + exact: number; + standard: number; + skeleton: number; + wrongReference: number; + mismatch: number; + suspect: number; + /** Arabic set aside as the text of a hadith, tafsir or fiqh source: not a Quran quote. */ + otherSource: number; + unlabelled: number; + unverifiable: number; + hardFails: number; + notFromThisTurn: number; + fromMemory: number; + byGrounding: Record; + followUp: { quotes: number; notFromThisTurn: number }; + }; + expected: { refs: number; labelled: number; quoted: number }; + hadith: { + ids: number; + thisTurn: number; + earlierTurn: number; + fabricated: number; + entriesWithoutLkId: number; + gradeMatches: number; + gradeContradicts: number; + gradeNotStated: number; + }; + language: { scored: number; inLanguage: number; arabicQuestions: number; arabicInLanguage: number }; + scriptureWithoutSearch: { quran: number; hadith: number }; + latency: { firstTextMedian: number | null; firstTextP90: number | null; totalMedian: number | null; totalP90: number | null }; + tokens: { promptMean: number | null; outputMean: number | null; thoughtsMean: number | null }; + cost: { perAnswerMean: number | null; total: number | null; priced: number }; + tools: { callsMean: number | null; notOk: number }; +} + +/** Nearest-rank percentile; null for no values. */ +export function percentile(values: number[], p: number): number | null { + if (values.length === 0) return null; + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))]; +} + +const mean = (values: number[]): number | null => + values.length === 0 ? null : values.reduce((a, b) => a + b, 0) / values.length; + +export function modelStats(model: string, records: TurnRecord[]): ModelStats { + const mine = records.filter((r) => r.model === model); + const scored = mine.filter((r) => r.outcome === 'ok' && r.scores); + const sum = (pick: (r: TurnRecord) => number) => scored.reduce((total, r) => total + pick(r), 0); + const quotes = scored.flatMap((r) => r.scores!.quran.quotes.map((q) => ({ q, r }))); + const quran = quotes.filter(({ q }) => q.grounding !== null && isQuranQuote(q)); + const byGrounding: ModelStats['quran']['byGrounding'] = { + this_turn: { quotes: 0, hardFails: 0 }, + earlier_turn: { quotes: 0, hardFails: 0 }, + none: { quotes: 0, hardFails: 0 }, + }; + for (const { q } of quran) { + const bucket = byGrounding[q.grounding as Grounding]; + bucket.quotes++; + if (HARD_FAIL.has(q.outcome)) bucket.hardFails++; + } + const followUps = scored.filter((r) => r.turn > 0); + const costs = scored.map((r) => r.scores!.costUsd).filter((c): c is number => c !== null); + const withUsage = scored.filter((r) => r.usage); + const arabic = scored.filter((r) => r.language === 'ar'); + + return { + model, + turns: mine.length, + ok: mine.filter((r) => r.outcome === 'ok').length, + errors: mine.filter((r) => r.outcome === 'error').length, + skipped: mine.filter((r) => r.outcome === 'skipped').length, + budgetSynthesis: scored.filter((r) => r.scores!.events.budgetSynthesis).length, + emptyFinalRetries: mine.reduce((t, r) => t + r.log.filter((l) => l.message.includes('empty final completion — retrying')).length, 0), + transientRetries: mine.reduce((t, r) => t + r.log.filter((l) => l.message.includes('transient error')).length, 0), + quran: { + quotes: sum((r) => r.scores!.quran.quranQuotes), + exact: sum((r) => r.scores!.quran.counts.exact), + standard: sum((r) => r.scores!.quran.counts.standard), + skeleton: sum((r) => r.scores!.quran.counts.skeleton), + wrongReference: sum((r) => r.scores!.quran.counts.wrong_reference), + mismatch: sum((r) => r.scores!.quran.counts.mismatch), + suspect: sum((r) => r.scores!.quran.counts.suspect), + otherSource: sum((r) => r.scores!.quran.counts.hadith_text + (r.scores!.quran.counts.other_source ?? 0)), + unlabelled: sum((r) => r.scores!.quran.counts.unlabelled), + unverifiable: sum((r) => r.scores!.quran.counts.unverifiable), + hardFails: sum((r) => r.scores!.quran.counts.wrong_reference + r.scores!.quran.counts.mismatch), + notFromThisTurn: sum((r) => r.scores!.quran.notFromThisTurn), + fromMemory: sum((r) => r.scores!.quran.fromMemory), + byGrounding, + followUp: { + quotes: followUps.reduce((t, r) => t + r.scores!.quran.quranQuotes, 0), + notFromThisTurn: followUps.reduce((t, r) => t + r.scores!.quran.notFromThisTurn, 0), + }, + }, + expected: { + refs: sum((r) => r.scores!.quran.expected.length), + labelled: sum((r) => r.scores!.quran.expected.filter((e) => e.labelled).length), + quoted: sum((r) => r.scores!.quran.expected.filter((e) => e.quoted).length), + }, + hadith: { + ids: sum((r) => r.scores!.hadith.total), + thisTurn: sum((r) => r.scores!.hadith.thisTurn), + earlierTurn: sum((r) => r.scores!.hadith.earlierTurn), + fabricated: sum((r) => r.scores!.hadith.fabricated), + entriesWithoutLkId: sum((r) => r.scores!.hadith.entriesWithoutLkId.length), + gradeMatches: sum((r) => r.scores!.hadith.grades.matches), + gradeContradicts: sum((r) => r.scores!.hadith.grades.contradicts), + gradeNotStated: sum((r) => r.scores!.hadith.grades.not_stated), + }, + language: { + scored: scored.length, + inLanguage: scored.filter((r) => r.scores!.language.inLanguage).length, + arabicQuestions: arabic.length, + arabicInLanguage: arabic.filter((r) => r.scores!.language.inLanguage).length, + }, + scriptureWithoutSearch: { + quran: scored.filter((r) => r.scores!.scriptureWithoutSearch.quran).length, + hadith: scored.filter((r) => r.scores!.scriptureWithoutSearch.hadith).length, + }, + latency: { + firstTextMedian: percentile(scored.flatMap((r) => (r.timing.firstTextMs === null ? [] : [r.timing.firstTextMs])), 50), + firstTextP90: percentile(scored.flatMap((r) => (r.timing.firstTextMs === null ? [] : [r.timing.firstTextMs])), 90), + totalMedian: percentile(scored.map((r) => r.timing.totalMs), 50), + totalP90: percentile(scored.map((r) => r.timing.totalMs), 90), + }, + tokens: { + promptMean: mean(withUsage.map((r) => r.usage!.promptTokenCount)), + outputMean: mean(withUsage.map((r) => r.usage!.candidatesTokenCount)), + thoughtsMean: mean(withUsage.map((r) => r.usage!.thoughtsTokenCount)), + }, + cost: { perAnswerMean: mean(costs), total: costs.length === 0 ? null : costs.reduce((a, b) => a + b, 0), priced: costs.length }, + tools: { callsMean: mean(scored.map((r) => r.scores!.tools.calls)), notOk: sum((r) => r.scores!.tools.notOk) }, + }; +} + +function isQuranQuote(q: QuoteScore): boolean { + return ['exact', 'standard', 'skeleton', 'wrong_reference', 'mismatch', 'unlabelled'].includes(q.outcome); +} + +export interface GateResult { + gate: string; + pass: boolean | null; + detail: string; +} + +const share = (n: number, of: number): number => (of === 0 ? 1 : n / of); +const pct = (n: number, of: number): string => (of === 0 ? 'n/a' : `${Math.round((100 * n) / of)}%`); + +/** + * The gates written into the experiment notes before the run (codev/experiments/393-*). + * Changing a threshold here after seeing results would defeat them. + */ +export function evaluateGates(base: ModelStats, cand: ModelStats): GateResult[] { + const reliability = (s: ModelStats) => s.errors + s.budgetSynthesis; + const within = (c: number | null, b: number | null) => (c === null || b === null ? null : c <= 1.5 * b); + const first = within(cand.latency.firstTextMedian, base.latency.firstTextMedian); + const total = within(cand.latency.totalMedian, base.latency.totalMedian); + const cost = + cand.cost.perAnswerMean === null || base.cost.perAnswerMean === null + ? null + : cand.cost.perAnswerMean <= 2 * base.cost.perAnswerMean; + return [ + { + gate: 'G1 Quran fidelity', + pass: cand.quran.hardFails <= base.quran.hardFails, + detail: `${cand.quran.hardFails} mismatch or wrong-reference quotes (baseline ${base.quran.hardFails})`, + }, + { gate: 'G2 Hadith ids', pass: cand.hadith.fabricated === 0, detail: `${cand.hadith.fabricated} fabricated LK ids` }, + { + gate: 'G3 Language', + pass: + share(cand.language.inLanguage, cand.language.scored) >= share(base.language.inLanguage, base.language.scored) && + cand.language.arabicInLanguage === cand.language.arabicQuestions, + detail: `${cand.language.inLanguage}/${cand.language.scored} in the question's language (baseline ${base.language.inLanguage}/${base.language.scored}); Arabic ${cand.language.arabicInLanguage}/${cand.language.arabicQuestions}`, + }, + { + gate: 'G4 Reliability', + pass: reliability(cand) <= reliability(base) + 1, + detail: `${cand.errors} errors + ${cand.budgetSynthesis} budget syntheses (baseline ${base.errors} + ${base.budgetSynthesis})`, + }, + { + gate: 'G5 Latency', + pass: first === null || total === null ? null : first && total, + detail: `median first text ${ms(cand.latency.firstTextMedian)} (baseline ${ms(base.latency.firstTextMedian)}), median total ${ms(cand.latency.totalMedian)} (baseline ${ms(base.latency.totalMedian)})`, + }, + { + gate: 'G6 Cost (not gated)', + pass: cost, + detail: `mean ${usd(cand.cost.perAnswerMean)} per answer, ${times(cand.cost.perAnswerMean, base.cost.perAnswerMean)} the baseline's ${usd(base.cost.perAnswerMean)}; see Cost`, + }, + ]; +} + +const ms = (value: number | null): string => (value === null ? 'n/a' : `${(value / 1000).toFixed(1)}s`); +const usd = (value: number | null): string => (value === null ? 'n/a' : `$${value.toFixed(4)}`); +const num = (value: number | null, digits = 0): string => (value === null ? 'n/a' : value.toFixed(digits)); +const verdict = (pass: boolean | null): string => (pass === null ? 'n/a' : pass ? 'pass' : 'FAIL'); + +function table(header: string[], rows: string[][]): string { + return [`| ${header.join(' | ')} |`, `|${header.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.join(' | ')} |`)].join('\n'); +} + +const cell = (text: string): string => text.replace(/\|/g, '\\|').replace(/\s*\n\s*/g, ' '); +const clip = (text: string, max = 160): string => (text.length <= max ? text : `${text.slice(0, max)}…`); +const where = (r: TurnRecord): string => `${r.questionId}${r.turn > 0 ? ` turn ${r.turn + 1}` : ''}${r.repeat > 0 ? ` (repeat ${r.repeat + 1})` : ''}`; + +const usd2 = (value: number | null): string => (value === null ? 'n/a' : `$${value.toFixed(2)}`); +const times = (value: number | null, base: number | null): string => + value === null || base === null || base === 0 ? 'n/a' : `${(value / base).toFixed(2)}x`; + +export interface CostSummary { + /** Mean cost of one answer (one facilitator request, all its model calls) at the price the run recorded. */ + perAnswer: number | null; + per1000: number | null; + /** + * The same answers costed once the model's announced price change (`next`) is in effect; + * equal to the current figures for a model with no announced change. + */ + laterPerAnswer: number | null; + laterPer1000: number | null; +} + +/** Cost per answer and per 1,000 answers, now and after any announced price change. */ +export function costSummary(stats: ModelStats, price: ModelPrice | undefined): CostSummary { + const perAnswer = stats.cost.perAnswerMean; + const { promptMean, outputMean, thoughtsMean } = stats.tokens; + const next = price?.next; + const laterPerAnswer = + perAnswer === null + ? null + : next === undefined + ? perAnswer + : promptMean === null || outputMean === null || thoughtsMean === null + ? null + : (promptMean * next.inputPerMTok + (outputMean + thoughtsMean) * next.outputPerMTok) / 1_000_000; + const k = (v: number | null) => (v === null ? null : v * 1000); + return { perAnswer, per1000: k(perAnswer), laterPerAnswer, laterPer1000: k(laterPerAnswer) }; +} + +/** `$0.75 / $3.75`, or n/a when either side is unknown. */ +const pricePair = (input: number | null | undefined, output: number | null | undefined): string => + input === null || input === undefined || output === null || output === undefined ? 'n/a' : `${usd2(input)} / ${usd2(output)}`; + +function costSection(run: RunFile, stats: ModelStats[], base: ModelStats): string[] { + const price = (s: ModelStats): ModelPrice | undefined => run.prices[s.model]; + const cost = (s: ModelStats) => costSummary(s, price(s)); + const baseCost = cost(base); + const row = (label: string, pick: (s: ModelStats) => string): string[] => [label, ...stats.map(pick)]; + const anyNext = stats.some((s) => price(s)?.next !== undefined); + const unconfirmed = stats.filter((s) => price(s)?.confirmed !== true); + const out: string[] = ['## Cost', '']; + out.push( + table( + ['Measure', ...stats.map((s) => s.model)], + [ + row('Price, US$ per million tokens: input / output', (s) => pricePair(price(s)?.inputPerMTok, price(s)?.outputPerMTok)), + row('Price confirmed on the Vertex AI pricing page', (s) => + price(s)?.confirmed === true ? 'yes' : price(s)?.checked ? `**NO** (${price(s)?.checked})` : '**NO**', + ), + row('Tokens per answer: input / output / thinking', (s) => `${num(s.tokens.promptMean)} / ${num(s.tokens.outputMean)} / ${num(s.tokens.thoughtsMean)}`), + row('Answers costed', (s) => `${s.cost.priced} of ${s.ok}`), + row('**Cost per answer**', (s) => usd(cost(s).perAnswer)), + row('**Cost per 1,000 answers**', (s) => usd2(cost(s).per1000)), + row('… relative to the baseline', (s) => times(cost(s).perAnswer, baseCost.perAnswer)), + ...(anyNext + ? [ + row('Announced price change: input / output', (s) => { + const next = price(s)?.next; + return next === undefined ? 'none known' : `${pricePair(next.inputPerMTok, next.outputPerMTok)} from ${next.from}`; + }), + row('Cost per 1,000 answers after the announced changes', (s) => usd2(cost(s).laterPer1000)), + row('… relative to the baseline, both after their changes', (s) => times(cost(s).laterPerAnswer, baseCost.laterPerAnswer)), + ] + : []), + ], + ), + '', + ); + out.push( + '- An answer is one facilitator request: every model call of the turn (tool rounds, retries, the final answer). Thinking tokens are billed at the output price.', + '- The mean is over this question set. Production traffic has a different mix of questions and longer histories, so read the ratio between models before the dollar figure.', + '- Input is costed at the full input price. The facilitator does not report cached-input tokens, so any caching discount Vertex applies makes the real bill lower than this.', + '- Model cost only: the search services are not in it. An errored turn reports no usage and is not costed.', + ...(unconfirmed.length > 0 + ? [ + `- **Prices not confirmed** for ${unconfirmed.map((s) => `\`${s.model}\``).join(', ')}. Every dollar figure for those models is an estimate until someone checks \`apps/eval/models.json\` against the pricing page, sets \`confirmed\`, and runs \`apps/eval/rescore.ts\`.`, + ] + : []), + '', + 'Where each price came from:', + '', + ...stats.map((s) => `- \`${s.model}\`: ${price(s)?.source ?? 'no source recorded'}`), + '', + ); + return out; +} + +export function renderReport(run: RunFile): string { + const stats = run.models.map((m) => modelStats(m, run.records)); + const base = stats.find((s) => s.model === run.baseline) ?? stats[0]; + const out: string[] = []; + + out.push(`# Model comparison ${run.runId}`, ''); + out.push( + `- Run: ${run.startedAt} to ${run.finishedAt}, git \`${run.git.revision.slice(0, 12)}\`${run.git.dirty ? ' (uncommitted changes)' : ''}`, + `- Question set: \`${run.questionSet.id}\` v${run.questionSet.version}, ${run.questionSet.questions} questions, ${run.questionSet.turns} turns, sha256 \`${run.questionSet.sha256.slice(0, 12)}\``, + `- Models: ${run.models.map((m) => `\`${m}\``).join(', ')}; baseline \`${base.model}\`; ${run.options.repeats} sample(s) per question`, + `- Facilitator prompt sha256 \`${run.promptSha256.slice(0, 12)}\``, + '', + ); + + const candidates = stats.filter((s) => s.model !== base.model); + if (candidates.length > 0) { + const gates = candidates.map((c) => evaluateGates(base, c)); + out.push('## Gates against the baseline', ''); + out.push( + table( + ['Gate', ...candidates.map((c) => c.model)], + gates[0].map((g, i) => [g.gate, ...gates.map((list) => `${verdict(list[i].pass)}: ${list[i].detail}`)]), + ), + '', + ); + } + + const row = (label: string, pick: (s: ModelStats) => string): string[] => [label, ...stats.map(pick)]; + out.push('## Comparison', ''); + out.push( + table( + ['Measure', ...stats.map((s) => s.model)], + [ + row('Turns answered / asked', (s) => `${s.ok} / ${s.turns}`), + row('Errors (and turns skipped after one)', (s) => `${s.errors} (${s.skipped})`), + row('Budget syntheses', (s) => `${s.budgetSynthesis}`), + row('Empty-final retries / transient retries', (s) => `${s.emptyFinalRetries} / ${s.transientRetries}`), + row('Quran quotes', (s) => `${s.quran.quotes}`), + row('… exact', (s) => `${s.quran.exact}`), + row('… correct in standard spelling', (s) => `${s.quran.standard}`), + row('… alef-only difference (read these)', (s) => `${s.quran.skeleton}`), + row('… **mismatch**', (s) => `${s.quran.mismatch}`), + row('… **wrong reference**', (s) => `${s.quran.wrongReference}`), + row('… no reference near the quote', (s) => `${s.quran.unlabelled}`), + row('Suspect Arabic near a reference (read these)', (s) => `${s.quran.suspect}`), + row('Arabic set aside as hadith, tafsir or fiqh text', (s) => `${s.quran.otherSource}`), + row('Quotes with no source text to check', (s) => `${s.quran.unverifiable}`), + row('Quran quotes not from a search in the same turn', (s) => `${s.quran.notFromThisTurn} (${pct(s.quran.notFromThisTurn, s.quran.quotes)})`), + row('… of which no search returned the verse or its words', (s) => `${s.quran.fromMemory}`), + row('Turns quoting Quran with no search_quran result', (s) => `${s.scriptureWithoutSearch.quran}`), + row('Expected references named / quoted correctly', (s) => `${s.expected.labelled} / ${s.expected.quoted} of ${s.expected.refs}`), + row('LK ids cited', (s) => `${s.hadith.ids}`), + row('… from this turn / an earlier turn', (s) => `${s.hadith.thisTurn} / ${s.hadith.earlierTurn}`), + row('… **fabricated**', (s) => `${s.hadith.fabricated}`), + row('Hadith citations with no LK id', (s) => `${s.hadith.entriesWithoutLkId}`), + row('Grade stated: agrees / contradicts / not stated', (s) => `${s.hadith.gradeMatches} / ${s.hadith.gradeContradicts} / ${s.hadith.gradeNotStated}`), + row('Turns citing hadith with no search_hadith result', (s) => `${s.scriptureWithoutSearch.hadith}`), + row("Answers in the question's language", (s) => `${s.language.inLanguage} / ${s.language.scored}`), + row('… Arabic questions', (s) => `${s.language.arabicInLanguage} / ${s.language.arabicQuestions}`), + row('Time to first text: median / p90', (s) => `${ms(s.latency.firstTextMedian)} / ${ms(s.latency.firstTextP90)}`), + row('Total time: median / p90', (s) => `${ms(s.latency.totalMedian)} / ${ms(s.latency.totalP90)}`), + row('Tool calls per answer (calls that returned no source)', (s) => `${num(s.tools.callsMean, 1)} (${s.tools.notOk})`), + row('Tokens per answer: input / output / thinking', (s) => `${num(s.tokens.promptMean)} / ${num(s.tokens.outputMean)} / ${num(s.tokens.thoughtsMean)}`), + row('Cost per answer / per 1,000 answers / this run', (s) => { + const c = costSummary(s, run.prices[s.model]); + const mark = c.perAnswer !== null && run.prices[s.model]?.confirmed !== true ? ' (price not confirmed)' : ''; + return `${usd(c.perAnswer)} / ${usd2(c.per1000)} / ${usd2(s.cost.total)}${mark}`; + }), + ], + ), + '', + ); + + out.push(...costSection(run, stats, base)); + + out.push('## Quran quotes by where the verse came from', ''); + out.push( + table( + ['Source of the verse', ...stats.map((s) => `${s.model}: quotes (failed)`)], + (['this_turn', 'earlier_turn', 'none'] as const).map((g) => [ + { this_turn: 'A search in the same turn', earlier_turn: 'A search in an earlier turn', none: 'No search (written from memory)' }[g], + ...stats.map((s) => `${s.quran.byGrounding[g].quotes} (${s.quran.byGrounding[g].hardFails})`), + ]), + ), + '', + `On follow-up turns: ${stats.map((s) => `${s.model} ${s.quran.followUp.notFromThisTurn} of ${s.quran.followUp.quotes} quotes not from a same-turn search`).join('; ')}.`, + '', + ); + + const categories = [...new Set(run.records.map((r) => r.category))]; + out.push('## By category', '', 'Each cell: failed Quran quotes / Quran quotes · fabricated LK ids / LK ids · answers in language / answered · errors.', ''); + out.push( + table( + ['Category', ...stats.map((s) => s.model)], + categories.map((category) => [ + category, + ...run.models.map((model) => { + const s = modelStats(model, run.records.filter((r) => r.category === category)); + return `${s.quran.hardFails}/${s.quran.quotes} · ${s.hadith.fabricated}/${s.hadith.ids} · ${s.language.inLanguage}/${s.language.scored} · ${s.errors}`; + }), + ]), + ), + '', + ); + + const languages = [...new Set(run.records.map((r) => r.language))]; + out.push('## By question language', '', 'Each cell: answers in the question\'s language / answered · failed Quran quotes / Quran quotes.', ''); + out.push( + table( + ['Language', ...stats.map((s) => s.model)], + languages.map((language) => [ + language, + ...run.models.map((model) => { + const s = modelStats(model, run.records.filter((r) => r.language === language)); + return `${s.language.inLanguage}/${s.language.scored} · ${s.quran.hardFails}/${s.quran.quotes}`; + }), + ]), + ), + '', + ); + + // Every item a human should read. + const answered = run.records.filter((r) => r.outcome === 'ok' && r.scores); + const quoteRows = (outcomes: string[]): string[][] => + answered.flatMap((r) => + r.scores!.quran.quotes + .filter((q) => outcomes.includes(q.outcome)) + .map((q) => [ + r.model, + where(r), + q.outcome, + q.labels.join(', ') || 'none', + cell(clip(q.text)), + q.diff + ? cell(`vs ${q.diff.against}: wrote [${q.diff.extra.join(' ')}] for [${q.diff.missing.join(' ')}]`) + : q.matched.length > 0 + ? `text is ${q.matched.join(', ')}` + : '', + q.grounding ?? '', + ]), + ); + const listing = (title: string, header: string[], rows: string[][]) => { + out.push(`## ${title}`, '', rows.length === 0 ? 'None.' : table(header, rows), ''); + }; + const quoteHeader = ['Model', 'Question', 'Outcome', 'Labelled', 'Quoted text', 'Difference (standard spelling)', 'Verse source']; + listing('Failed Quran quotes', quoteHeader, quoteRows(['mismatch', 'wrong_reference'])); + listing('Quotes to read: alef-only differences and suspect Arabic', quoteHeader, quoteRows(['skeleton', 'suspect'])); + listing( + 'Fabricated LK ids', + ['Model', 'Question', 'LK id'], + answered.flatMap((r) => r.scores!.hadith.lkIds.filter((l) => l.status === 'fabricated').map((l) => [r.model, where(r), l.id])), + ); + listing( + 'Grades that contradict the search result', + ['Model', 'Question', 'LK id', 'Search result', 'Answer states'], + answered.flatMap((r) => + r.scores!.hadith.lkIds + .filter((l) => l.grade === 'contradicts') + .map((l) => [r.model, where(r), l.id, cell(l.sourceGrade ?? ''), (l.stated ?? []).join(', ')]), + ), + ); + listing( + 'Hadith citations with no LK id', + ['Model', 'Question', 'Citation'], + answered.flatMap((r) => r.scores!.hadith.entriesWithoutLkId.map((e) => [r.model, where(r), cell(clip(e))])), + ); + listing( + "Answers not in the question's language", + ['Model', 'Question', 'Expected', 'Read as', 'Arabic-script share', 'Opening'], + answered + .filter((r) => !r.scores!.language.inLanguage) + .map((r) => [r.model, where(r), r.language, r.scores!.language.detected, r.scores!.language.arabicShare.toFixed(2), cell(clip(r.answer, 100))]), + ); + listing( + 'Errors', + ['Model', 'Question', 'Error', 'Seconds'], + run.records.filter((r) => r.outcome === 'error').map((r) => [r.model, where(r), cell(clip(r.error ?? '', 200)), (r.timing.totalMs / 1000).toFixed(1)]), + ); + + const unpriced = run.models.filter((m) => { + const p = run.prices[m]; + return !p || p.inputPerMTok === null || p.outputPerMTok === null; + }); + out.push('## What this report does not show', ''); + out.push( + `- One run of ${run.options.repeats} sample(s) per question. Zero failures in n answers bounds the true rate below about 3/n, no lower.`, + '- A Quran quote with no reference near it and no matching verse in hand is not scored. In an answer written in Arabic script, only quoted or vowelled Arabic is read as a quote.', + '- An errored turn reports no token usage, so its cost is not in the totals.', + ...(unpriced.length > 0 ? [`- No price in models.json for ${unpriced.map((m) => `\`${m}\``).join(', ')}: cost is n/a for those.`] : []), + '', + ); + return out.join('\n'); +} diff --git a/apps/eval/lib/runner.ts b/apps/eval/lib/runner.ts new file mode 100644 index 00000000..eadd7b8b --- /dev/null +++ b/apps/eval/lib/runner.ts @@ -0,0 +1,191 @@ +/** + * Running a question set through the facilitator, one conversation at a time. + * + * The facilitator is injected, so the tests drive this with a scripted one and the CLI + * (`run.ts`) passes the real `runFacilitator`, pinned to the model under test. History + * between the turns of a conversation is built the way the chat route builds it: the + * streamed text of each answer, with the final model turn's raw payload riding along. + */ +import type { ToolCallRecord, ModelProvenance, ContentBlock } from '@/db/schema/messages'; +import type { GeminiUsageMetadata, Content } from '@/lib/ai/gemini-client'; +import { withLogCapture } from './capture'; +import { refsToLookUp } from './score-quran'; +import { turnSources } from './sources'; +import type { Question, TurnRecord } from './types'; + +/** The part of `Message` (lib/facilitator/agent.ts) the harness builds. */ +export interface HistoryMessage { + role: 'user' | 'assistant'; + content: ContentBlock[]; + rawPayload?: Content | null; +} + +/** The part of `FacilitatorStreamEvent` the harness reads. */ +export interface FacilitatorEvent { + type: 'text' | 'tool_use' | 'tool_result' | 'done' | 'error'; + data: string; + usage?: GeminiUsageMetadata; + rawPayload?: Content | null; + toolCalls?: ToolCallRecord[]; + provenance?: ModelProvenance; +} + +export interface RunnerDeps { + /** One facilitator request for `model` over `history`. */ + facilitator: (history: HistoryMessage[], model: string) => AsyncIterable; + /** The source text of one verse (`surah:ayah`), or null when it cannot be had. */ + lookupVerse: (key: string) => Promise<{ ar: string; en: string } | null>; + now?: () => number; +} + +/** No answer names more verses than this that a search did not return; the rest are left unverifiable. */ +const MAX_LOOKUPS_PER_TURN = 12; + +const userMessage = (text: string): HistoryMessage => ({ role: 'user', content: [{ type: 'text', text }] }); + +/** + * Ask every turn of one question, in order, and return a record per turn. A turn that + * errors ends the conversation: the turns after it are recorded as `skipped`, since + * their history would be missing an answer. + */ +export async function runConversation( + deps: RunnerDeps, + model: string, + question: Question, + repeat: number, +): Promise { + const now = deps.now ?? Date.now; + const records: TurnRecord[] = []; + const history: HistoryMessage[] = []; + const haveVerses = new Set(); + let failed = false; + + for (const [turn, { text, expectRefs }] of question.turns.entries()) { + const base = { + model, + questionId: question.id, + category: question.category, + language: question.language, + repeat, + turn, + question: text, + ...(expectRefs ? { expectRefs } : {}), + }; + if (failed) { + records.push({ + ...base, + outcome: 'skipped', + answer: '', + startedAt: new Date(now()).toISOString(), + timing: { firstEventMs: null, firstTextMs: null, totalMs: 0 }, + usage: null, + provenance: null, + toolCalls: [], + log: [], + lookups: {}, + }); + continue; + } + + history.push(userMessage(text)); + const startedAt = now(); + let answer = ''; + let firstEventMs: number | null = null; + let firstTextMs: number | null = null; + let terminal: FacilitatorEvent | null = null; + let thrown: string | undefined; + + const { log } = await withLogCapture(async () => { + try { + for await (const event of deps.facilitator([...history], model)) { + const at = now() - startedAt; + firstEventMs ??= at; + if (event.type === 'text') { + firstTextMs ??= at; + answer += event.data; + } else if (event.type === 'done' || event.type === 'error') { + terminal = event; + } + } + } catch (error) { + // The facilitator reports failures as an `error` event; a throw is a harness or + // configuration fault. Recorded, not swallowed: the turn is an error either way. + thrown = error instanceof Error ? error.message : String(error); + } + }); + const totalMs = now() - startedAt; + // TypeScript cannot see the assignment inside the closure above. + const end = terminal as FacilitatorEvent | null; + + const ok = end?.type === 'done' && thrown === undefined; + const toolCalls = end?.toolCalls ?? []; + const record: TurnRecord = { + ...base, + outcome: ok ? 'ok' : 'error', + answer, + startedAt: new Date(startedAt).toISOString(), + timing: { firstEventMs, firstTextMs, totalMs }, + usage: end?.usage ?? null, + provenance: end?.provenance ?? null, + toolCalls, + log, + lookups: {}, + }; + if (!ok) { + record.error = thrown ?? (end?.type === 'error' ? end.data : 'the facilitator ended without a done or error event'); + failed = true; + records.push(record); + continue; + } + + // Fetch the source text of every verse the answer names that no search returned, + // so a quote written from memory is still checked against a source. + for (const verse of turnSources(toolCalls).verses) haveVerses.add(verse.key); + for (const key of refsToLookUp(answer, haveVerses).slice(0, MAX_LOOKUPS_PER_TURN)) { + record.lookups[key] = await deps.lookupVerse(key); + } + + history.push({ role: 'assistant', content: [{ type: 'text', text: answer }], rawPayload: end?.rawPayload ?? null }); + records.push(record); + } + return records; +} + +export interface Job { + model: string; + question: Question; + repeat: number; +} + +/** Every (question, model, repeat), question first: the models meet each question side by side. */ +export function planJobs(models: string[], questions: Question[], repeats: number): Job[] { + const jobs: Job[] = []; + for (const question of questions) { + for (let repeat = 0; repeat < repeats; repeat++) { + for (const model of models) jobs.push({ model, question, repeat }); + } + } + return jobs; +} + +/** Run the jobs with at most `concurrency` conversations in flight. */ +export async function runJobs( + deps: RunnerDeps, + jobs: Job[], + concurrency: number, + onDone?: (job: Job, records: TurnRecord[], done: number) => void, +): Promise { + const results: TurnRecord[][] = new Array(jobs.length); + let next = 0; + let done = 0; + const worker = async () => { + while (next < jobs.length) { + const index = next++; + const job = jobs[index]; + results[index] = await runConversation(deps, job.model, job.question, job.repeat); + onDone?.(job, results[index], ++done); + } + }; + await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, jobs.length)) }, worker)); + return results.flat(); +} diff --git a/apps/eval/lib/score-hadith.ts b/apps/eval/lib/score-hadith.ts new file mode 100644 index 00000000..ee402faf --- /dev/null +++ b/apps/eval/lib/score-hadith.ts @@ -0,0 +1,130 @@ +/** + * Does every hadith citation carry an `LK id` that a search actually returned? + * + * The facilitator prompt requires the id to be copied from the search result. So every + * `LK id ` token in an answer is looked up among the ids search_hadith returned: + * in this turn, in an earlier turn of the conversation, or nowhere (`fabricated`). + * Alongside: citation entries that read as hadith but carry no id, and whether the grade + * an answer states for a cited hadith agrees with the grade the search returned. + */ +import { parseAnswer } from './answer'; +import { findRefs } from './quran-refs'; +import type { RetrievedHadith } from './sources'; + +/** As apps/frontend reads it (`lib/citations.ts`): the literal "LK id", then the id. */ +const LK_ID = /\bLK id[ \t]*:?[ \t]*([A-Za-z0-9_-]+)/gi; + +export type GradeClass = 'sahih' | 'hasan' | 'daif' | 'mawdu'; + +const GRADE_PATTERNS: ReadonlyArray = [ + ['sahih', /\b(?:sahih|saheeh|sahīh|authentic|sound)\b|صحيح/iu], + ['hasan', /\b(?:hasan|hassan|good|fair)\b|حسن/iu], + ['daif', /\b(?:da['’ʿ]?if|da['’ʿ]?eef|daeef|weak)\b|ضعيف/iu], + ['mawdu', /\b(?:mawdu['’ʿ]?|mawdoo['’ʿ]?|fabricated|forged)\b|موضوع/iu], +]; + +/** The grade classes a piece of text names. Diacritics folded first (Ṣaḥīḥ, Ḍaʿīf). */ +export function gradeClasses(text: string): GradeClass[] { + const plain = text.normalize('NFD').replace(/[̀-ͯ]/g, ''); + return GRADE_PATTERNS.filter(([, pattern]) => pattern.test(plain)).map(([name]) => name); +} + +/** + * A grade as an answer states it: the word for "grade", then what follows on the line. + * Only a statement introduced this way is read, so `Sahih Bukhari` (a book) and + * `al-Hasan` (a narrator) are never taken for a grade. + */ +const GRADE_STATEMENT = + /(?:\bgraded?\b|\bgrading\b|\bauthenticity\b|\bderajat\b|\bdegré\b|\bgrado\b|\bderece\b|\bstatus\b|الدرجة|درجة|درجته|الحكم|حكمه|درجہ)[ \t]*(?:as|is|of)?[ \t]*[::\-–—]?[ \t]*([^\n\])]{0,60})/giu; + +const HADITH_ENTRY = + /bukhari|tirmidhi|tirmizi|abu\s*daw|abi\s*daw|nasa['’]?i|ibn\s*maja|muwatta|musnad|darimi|riyad|hadith|hadis|hadits|sunan|sahih\s+muslim|البخاري|صحيح مسلم|الترمذي|[أا]بو داود|[أا]بي داود|النسائي|ابن ماجه|موط[أا]|مسند|حديث/iu; +const NOT_HADITH_ENTRY = /qur['’]?an|koran|coran|القر[آا]ن|tafsir|tafseer|تفسير|mawsu|موسوعة/iu; + +export type LkStatus = 'this_turn' | 'earlier_turn' | 'fabricated'; +export type GradeAgreement = 'matches' | 'contradicts' | 'not_stated' | 'no_grade_in_source'; + +export interface LkIdScore { + id: string; + status: LkStatus; + /** Null for a fabricated id: there is no source grade to agree with. */ + grade: GradeAgreement | null; + sourceGrade?: string; + stated?: GradeClass[]; +} + +export interface HadithScore { + lkIds: LkIdScore[]; + total: number; + thisTurn: number; + earlierTurn: number; + fabricated: number; + /** Citation entries that read as hadith and carry no LK id: their first lines. */ + entriesWithoutLkId: string[]; + grades: Record; +} + +export interface HadithInput { + answer: string; + thisTurn: RetrievedHadith[]; + earlierTurns: RetrievedHadith[]; +} + +function lineAt(text: string, index: number): string { + const from = text.lastIndexOf('\n', index - 1) + 1; + const to = text.indexOf('\n', index); + return text.slice(from, to === -1 ? text.length : to); +} + +export function scoreHadith(input: HadithInput): HadithScore { + const parsed = parseAnswer(input.answer); + const now = new Map(input.thisTurn.map((h) => [h.lkId, h])); + const before = new Map(input.earlierTurns.map((h) => [h.lkId, h])); + + // Each id once, with every place it is written (its citation entry, or its line). + const contexts = new Map(); + for (const m of input.answer.matchAll(LK_ID)) { + const id = m[1].replace(/[-_]+$/, ''); + if (!id) continue; + const entry = parsed.entries.find((e) => m.index >= e.start && m.index < e.end); + const context = entry ? entry.text : lineAt(input.answer, m.index); + contexts.set(id, [...(contexts.get(id) ?? []), context]); + } + + const grades: Record = { matches: 0, contradicts: 0, not_stated: 0, no_grade_in_source: 0 }; + const lkIds: LkIdScore[] = [...contexts].map(([id, places]) => { + const source = now.get(id) ?? before.get(id); + if (!source) return { id, status: 'fabricated' as const, grade: null }; + const status: LkStatus = now.has(id) ? 'this_turn' : 'earlier_turn'; + const sourceClasses = gradeClasses(source.grade); + const stated = new Set(); + for (const place of places) { + for (const m of place.matchAll(GRADE_STATEMENT)) for (const c of gradeClasses(m[1])) stated.add(c); + } + let grade: GradeAgreement; + if (sourceClasses.length === 0) grade = 'no_grade_in_source'; + else if (stated.size === 0) grade = 'not_stated'; + else grade = sourceClasses.some((c) => stated.has(c)) ? 'matches' : 'contradicts'; + grades[grade]++; + return { id, status, grade, sourceGrade: source.grade, stated: [...stated] }; + }); + + const entriesWithoutLkId = parsed.entries + .filter((entry) => { + const title = entry.text.split('\n')[0]; + if (!HADITH_ENTRY.test(title) || NOT_HADITH_ENTRY.test(title)) return false; + if (findRefs(title).length > 0) return false; + return !/\bLK id\b/i.test(entry.text); + }) + .map((entry) => entry.text.split('\n')[0].trim()); + + return { + lkIds, + total: lkIds.length, + thisTurn: lkIds.filter((l) => l.status === 'this_turn').length, + earlierTurn: lkIds.filter((l) => l.status === 'earlier_turn').length, + fabricated: lkIds.filter((l) => l.status === 'fabricated').length, + entriesWithoutLkId, + grades, + }; +} diff --git a/apps/eval/lib/score-language.ts b/apps/eval/lib/score-language.ts new file mode 100644 index 00000000..eb2abf69 --- /dev/null +++ b/apps/eval/lib/score-language.ts @@ -0,0 +1,114 @@ +/** + * Is the answer in the question's language? + * + * Decided on the prose only: the Citations section is bilingual by instruction, and + * quoted Arabic is scripture, not the answer's language. Two measurements, both code: + * + * - Script. For a question in an Arabic-script language (ar, ur, fa) the prose must be + * mostly Arabic script. For any other language it must be mostly not: an English + * answer that quotes a great deal of Arabic still has more Latin letters than Arabic. + * - Language within the script. Latin-script languages are told apart by counting each + * language's most common function words; Urdu and Persian are told from Arabic by the + * letters Arabic does not use (ے ں ٹ ڈ ڑ گ پ چ). + * + * The numbers behind the verdict are returned with it, so a threshold can be argued with. + */ +import { parseAnswer } from './answer'; + +export const LANGUAGES = ['en', 'ar', 'fr', 'id', 'tr', 'ur', 'es', 'de', 'bs', 'ms', 'fa'] as const; +export type Language = (typeof LANGUAGES)[number]; + +const ARABIC_SCRIPT: ReadonlySet = new Set(['ar', 'ur', 'fa']); + +/** Function words that are common in one language and absent from the others listed. */ +const STOPWORDS: Readonly> = { + en: ['the', 'and', 'of', 'to', 'is', 'that', 'it', 'for', 'with', 'as', 'this', 'are', 'was', 'by', 'not', 'be', 'which', 'from', 'or', 'his', 'who', 'have', 'has', 'there', 'their', 'they', 'were', 'these', 'those', 'should'], + fr: ['le', 'les', 'des', 'est', 'et', 'que', 'qui', 'dans', 'pour', 'une', 'du', 'au', 'sur', 'par', 'pas', 'ce', 'il', 'sont', 'avec', 'plus', 'comme', 'être', 'cette', 'ses', 'aux', 'nous', 'mais', 'ou', 'leur', 'selon'], + id: ['yang', 'dan', 'dari', 'untuk', 'dengan', 'ini', 'itu', 'adalah', 'pada', 'dalam', 'tidak', 'kepada', 'atau', 'juga', 'akan', 'oleh', 'sebagai', 'mereka', 'kita', 'karena', 'bahwa', 'seperti', 'telah', 'lebih', 'ada', 'bagi', 'hal', 'para', 'serta', 'maka'], + tr: ['ve', 'bir', 'bu', 'için', 'ile', 'olarak', 'olan', 'daha', 'gibi', 'değil', 'çok', 'her', 'ise', 'veya', 'şöyle', 'ancak', 'kadar', 'sonra', 'göre', 'ya', 'hem', 'ne', 'onun', 'bunu', 'şu', 'eder', 'etmek', 'olur', 'vardır', 'üzerine'], + es: ['el', 'los', 'las', 'es', 'y', 'que', 'en', 'por', 'para', 'una', 'del', 'con', 'no', 'se', 'su', 'como', 'más', 'este', 'esta', 'son', 'pero', 'sobre', 'entre', 'cuando', 'también', 'fue', 'ha', 'sus', 'al', 'lo'], + de: ['der', 'die', 'das', 'und', 'ist', 'nicht', 'mit', 'für', 'auf', 'ein', 'eine', 'den', 'dem', 'des', 'sich', 'auch', 'von', 'zu', 'als', 'wie', 'oder', 'aber', 'wird', 'sind', 'dass', 'bei', 'nach', 'durch', 'über', 'wenn'], + bs: ['je', 'i', 'da', 'se', 'na', 'su', 'za', 'od', 'što', 'koji', 'kao', 'ili', 'ali', 'koje', 'biti', 'bio', 'nije', 'sa', 'to', 'kada', 'ovo', 'tako', 'jer', 'koja', 'njegov', 'prema', 'među', 'treba', 'može', 'također'], + ms: ['yang', 'dan', 'daripada', 'untuk', 'dengan', 'ini', 'itu', 'adalah', 'pada', 'dalam', 'tidak', 'kepada', 'atau', 'juga', 'akan', 'oleh', 'sebagai', 'mereka', 'kita', 'kerana', 'bahawa', 'seperti', 'telah', 'lebih', 'ada', 'bagi', 'hal', 'para', 'serta', 'maka'], +}; + +/** Letters Urdu and Persian use and Arabic does not. */ +const NON_ARABIC_LETTERS = /[ےںٹڈڑگپچژ]/gu; +const URDU_ONLY = /[ےںٹڈڑ]/gu; + +const LETTER = /\p{L}/gu; +const ARABIC_LETTER = /(?=\p{L})\p{Script=Arabic}/gu; +const LATIN_WORD = /[\p{Script=Latin}]+(?:['’][\p{Script=Latin}]+)?/gu; + +/** Share of the prose's letters that must be in the expected script. */ +const SCRIPT_SHARE = 0.6; +/** Share of Arabic-script letters that are non-Arabic letters, above which the text is Urdu or Persian. */ +const NON_ARABIC_SHARE = 0.02; +/** Function-word hits that name a Latin-script language outright. */ +const MIN_HITS = 5; +/** + * A short answer (a verse and its translation) has few function words. Fewer hits still + * name the language when no other language comes close: at least this many, and at least + * twice the runner-up's. + */ +const MIN_HITS_CLEAR = 2; + +export interface LanguageScore { + expected: string; + /** What the prose reads as: a language code, `arabic-script`, `latin-script` or `none`. */ + detected: string; + inLanguage: boolean; + /** Share of the prose's letters that are Arabic script. */ + arabicShare: number; + /** Function-word hits per Latin-script language, when the prose is Latin script. */ + hits?: Record; + /** Share of Arabic-script letters that Arabic does not use. */ + nonArabicLetterShare?: number; +} + +export function scoreLanguage(answer: string, expected: string): LanguageScore { + const body = parseAnswer(answer).body; + const letters = body.match(LETTER)?.length ?? 0; + const arabicLetters = body.match(ARABIC_LETTER)?.length ?? 0; + const arabicShare = letters === 0 ? 0 : arabicLetters / letters; + if (letters === 0) return { expected, detected: 'none', inLanguage: false, arabicShare }; + + const expectArabicScript = ARABIC_SCRIPT.has(expected); + + if (arabicShare >= SCRIPT_SHARE) { + const nonArabic = (body.match(NON_ARABIC_LETTERS)?.length ?? 0) / arabicLetters; + const urdu = (body.match(URDU_ONLY)?.length ?? 0) / arabicLetters; + let detected = 'ar'; + if (nonArabic >= NON_ARABIC_SHARE) detected = urdu >= NON_ARABIC_SHARE / 2 ? 'ur' : 'fa'; + return { + expected, + detected, + inLanguage: expectArabicScript && detected === expected, + arabicShare, + nonArabicLetterShare: nonArabic, + }; + } + + // Mostly not Arabic script: name the Latin-script language by its function words. + const words = (body.toLowerCase().match(LATIN_WORD) ?? []).map((w) => w.normalize('NFC')); + const hits: Record = {}; + for (const [language, list] of Object.entries(STOPWORDS)) { + const set = new Set(list); + hits[language] = words.filter((w) => set.has(w)).length; + } + const ranked = Object.entries(hits).sort((a, b) => b[1] - a[1]); + const [best, bestHits] = ranked[0]; + const runnerUp = ranked[1]?.[1] ?? 0; + let detected = bestHits >= MIN_HITS || (bestHits >= MIN_HITS_CLEAR && bestHits >= 2 * runnerUp) ? best : 'latin-script'; + // Indonesian and Malay share most function words; an answer is not failed for the tie. + if ((detected === 'id' || detected === 'ms') && (expected === 'id' || expected === 'ms')) detected = expected; + // Between the two scripts: neither dominates. Named, and never a pass. + if (arabicShare > 1 - SCRIPT_SHARE) detected = 'mixed'; + return { + expected, + detected, + inLanguage: !expectArabicScript && detected === expected, + arabicShare, + hits, + }; +} diff --git a/apps/eval/lib/score-quran.ts b/apps/eval/lib/score-quran.ts new file mode 100644 index 00000000..1048543c --- /dev/null +++ b/apps/eval/lib/score-quran.ts @@ -0,0 +1,529 @@ +/** + * Does every Quran passage an answer quotes match the retrieved text of the verse it is + * labelled with? + * + * The check is code, not judgement. For each run of Arabic in the answer: + * 1. Find the references it is labelled with (`labelsFor`: same line, then paragraph, + * then the closest one nearby; a `[n]` marker counts as its citation entry's refs). + * 2. Compare its letters with every verse text in hand (`matchLevel`, three levels; see + * arabic.ts). The texts in hand are the verses search_quran returned in this turn or + * an earlier one, plus a lookup of every reference the answer names that no search + * returned, so a quote written from memory is still checked against a source. + * 3. Decide the outcome (QuoteOutcome). + * + * A quote fails (gate G1) only when it carries a label. `wrong_reference` needs the + * reference on the quote's own line or heading its citation entry. `mismatch` needs that, + * or a text that is plainly an attempt at a verse named near it. Arabic that a tafsir, + * fiqh or hadith search returned word for word is that source's text and is set aside. + * What is left over and looks wrong without a label is `suspect`: listed for a person. + * + * What it cannot see is stated rather than guessed: a quote with no reference near it and + * no matching verse in hand is `unattributed`, and is counted, not scored. + */ +import { normalizeAll, matchLevel, overlap, wordDiff, type MatchLevel, type NormalizedText } from './arabic'; +import { answerLabels, arabicSegments, arabicShare, labelsFor, parseAnswer, type LabelScope } from './answer'; +import { formatRef, refVerses, parseRef, type QuranRef } from './quran-refs'; +import type { RetrievedHadith } from './sources'; + +export type VerseOrigin = 'this_turn' | 'earlier_turn' | 'lookup'; + +export interface PoolVerse { + key: string; + ar: string; + origin: VerseOrigin; +} + +/** + * - `exact`: the quote's letters are in a verse it is labelled with, as written there. + * - `standard`: the same after the standard-spelling rules. Correct, retyped. + * - `skeleton`: the same only once alefs are ignored. Probably correct; read it. + * - `wrong_reference`: the text is a verse in hand, but not the one named on its own line + * (or heading its citation entry). + * - `mismatch`: the text is not in any verse in hand, and either it is clearly an attempt + * at a verse it is labelled with (half its letter windows are that verse's; the label + * may be on its line, in its paragraph, nearby, or head its citation entry), or a + * reference sits on its own line. The quoted text differs from its source. + * - `suspect`: read it. Either four or more words of Arabic that match nothing, with a + * reference only in the paragraph or nearby (or resembling a verse in hand with no + * reference at all); or the text of one verse in a paragraph that names only another. + * - `unlabelled`: the text is a verse in hand, with no reference near it. + * - `unverifiable`: a reference is named but no source text for it could be fetched. + * - `hadith_text`: the Arabic is from a hadith a search returned. Not Quran. + * - `other_source`: the Arabic is from another search result (tafsir, fiqh encyclopedia), + * or sits in a citation entry that is not headed with a Quran reference. Not Quran. + * - `term`: under four words next to a reference and matching nothing: a phrase. + * - `unattributed`: Arabic with no reference near it that matches nothing in hand. + */ +export type QuoteOutcome = + | 'exact' + | 'standard' + | 'skeleton' + | 'wrong_reference' + | 'mismatch' + | 'suspect' + | 'unlabelled' + | 'unverifiable' + | 'hadith_text' + | 'other_source' + | 'term' + | 'unattributed'; + +export const QUOTE_OUTCOMES: readonly QuoteOutcome[] = [ + 'exact', 'standard', 'skeleton', 'wrong_reference', 'mismatch', 'suspect', 'unlabelled', + 'unverifiable', 'hadith_text', 'other_source', 'term', 'unattributed', +]; + +/** The outcomes that mean the answer quoted Quran text (rightly or wrongly). */ +const QURAN_QUOTE: ReadonlySet = new Set([ + 'exact', 'standard', 'skeleton', 'wrong_reference', 'mismatch', 'unlabelled', +]); +/** The outcomes gate G1 counts. */ +export const HARD_FAIL: ReadonlySet = new Set(['wrong_reference', 'mismatch']); + +export interface QuoteScore { + text: string; + where: 'body' | 'citation'; + words: number; + outcome: QuoteOutcome; + /** References it was read against, e.g. ['68:48']. */ + labels: string[]; + labelScope: LabelScope | null; + /** Verses in hand whose text contains the quote. */ + matched: string[]; + /** For a quote that matched nothing: the verse in hand it most resembles. */ + nearest?: { key: string; overlap: number }; + /** Where it departs from that verse: its own words not there, and the words it skipped. */ + diff?: { against: string; extra: string[]; missing: string[] }; + /** + * Where the verse it quotes came from: a search in this turn, a search in an earlier + * turn, or nowhere (`none`: no search ever returned it; the text was written from + * memory). Null when the quote is not tied to a verse. + */ + grounding: 'this_turn' | 'earlier_turn' | 'none' | null; +} + +export interface ExpectedRefScore { + ref: string; + /** The answer names this reference. */ + labelled: boolean; + /** A quote that passed is tied to it. */ + quoted: boolean; +} + +export interface QuranScore { + quotes: QuoteScore[]; + counts: Record; + /** Quran quotes (any outcome that is Quran text). */ + quranQuotes: number; + /** Of those, how many are tied to a verse no search in this turn returned. */ + notFromThisTurn: number; + /** Of those, how many are tied to a verse no search ever returned. */ + fromMemory: number; + /** Every verse the answer names. */ + labelled: string[]; + /** Named verses with no source text in hand. */ + unverifiable: string[]; + /** + * Runs of Arabic script left out as the answer's own prose: in an answer written in + * Arabic script, a run that is neither quoted nor vowelled; in any answer, a run in + * Urdu or Persian (it holds letters Arabic does not use). + */ + proseRunsSkipped: number; + expected: ExpectedRefScore[]; +} + +const BASMALA = normalizeAll('بسم الله الرحمن الرحيم'); +/** + * Arabic an English answer writes that is not a quotation of anything: honorifics and + * set phrases. A run made only of these is a `term`, whatever its length. + */ +const FORMULAE = [ + 'صلى الله عليه وسلم', 'صلى الله عليه وآله وسلم', 'عليه الصلاة والسلام', 'عليه السلام', 'عليهم السلام', + 'عليها السلام', 'رضي الله عنه', 'رضي الله عنها', 'رضي الله عنهما', 'رضي الله عنهم', 'رحمه الله', + 'رحمهم الله', 'سبحانه وتعالى', 'عز وجل', 'جل جلاله', 'تبارك وتعالى', 'إن شاء الله', 'والله أعلم', + 'الله أعلم', 'قال الله تعالى', 'قال الله عز وجل', 'قال الله', 'قال تعالى', 'قال رسول الله', 'قال النبي', +] + .map((f) => normalizeAll(f).standard) + .sort((a, b) => b.length - a.length); + +/** The run's letters once every set phrase is taken out. */ +function withoutFormulae(standard: string): string { + let rest = standard; + for (const formula of FORMULAE) rest = rest.split(formula).join(''); + return rest; +} +const LEVELS: readonly MatchLevel[] = ['verbatim', 'standard', 'skeleton']; +const OUTCOME_OF: Record = { verbatim: 'exact', standard: 'standard', skeleton: 'skeleton' }; + +/** Fewest letters (at `standard`) a run needs to be compared at all. */ +const MIN_LETTERS = 6; +/** Vowel marks per letter above which a run in an Arabic answer is taken as quoted text. */ +const VOWELLED = 0.25; +/** Share of a failed quote's letter windows that must be a verse's to call it an attempt at that verse. */ +const ATTEMPT_OVERLAP = 0.5; +/** The same, against a retrieved hadith's or other source's Arabic, to set a run aside as that source's text. */ +const HADITH_OVERLAP = 0.6; +/** A run this short that matches nothing is a phrase, not a quote. */ +const TERM_WORDS = 4; +/** + * Letters Urdu and Persian write and Arabic does not. A run holding one is Urdu or + * Persian (a translation of the verse, the answer's own prose), never Quran text: none of + * the verse texts the search returns contains any of them. + */ +const NOT_ARABIC = /[پچژگٹڈڑںےھہۂۃ]/u; + +interface Chain { + keys: string[]; + /** Per level: the verses' letters joined, and where each verse starts and ends in it. */ + text: Record; + spans: Record>; +} + +function splitKey(key: string): [number, number] { + const [s, a] = key.split(':').map(Number); + return [s, a]; +} + +/** + * Consecutive verses joined, so a quote that runs from one verse into the next is still + * found. A verse alone is a chain of one. + */ +function buildChains(pool: Map): Chain[] { + const keys = [...pool.keys()].sort((x, y) => { + const [xs, xa] = splitKey(x); + const [ys, ya] = splitKey(y); + return xs - ys || xa - ya; + }); + const groups: string[][] = []; + for (const key of keys) { + const last = groups[groups.length - 1]; + const prev = last?.[last.length - 1]; + if (prev) { + const [ps, pa] = splitKey(prev); + const [s, a] = splitKey(key); + if (ps === s && a === pa + 1) { + last.push(key); + continue; + } + } + groups.push([key]); + } + return groups.map((group) => { + const chain: Chain = { + keys: group, + text: { verbatim: '', standard: '', skeleton: '' }, + spans: { verbatim: [], standard: [], skeleton: [] }, + }; + for (const key of group) { + const norm = pool.get(key)!.norm; + for (const level of LEVELS) { + const start = chain.text[level].length; + chain.text[level] += norm[level]; + chain.spans[level].push([start, chain.text[level].length]); + } + } + return chain; + }); +} + +/** Every verse whose text holds (part of) the quote, at one level. */ +function versesContaining(quote: string, chains: Chain[], level: MatchLevel): Set { + const found = new Set(); + if (!quote) return found; + for (const chain of chains) { + const text = chain.text[level]; + for (let at = text.indexOf(quote); at !== -1; at = text.indexOf(quote, at + 1)) { + const end = at + quote.length; + chain.spans[level].forEach(([s, e], i) => { + if (s < end && e > at) found.add(chain.keys[i]); + }); + } + } + return found; +} + +function withoutBasmala(norm: NormalizedText): NormalizedText | null { + const out = { ...norm }; + let stripped = false; + for (const level of LEVELS) { + if (norm[level].startsWith(BASMALA[level]) && norm[level].length >= BASMALA[level].length + MIN_LETTERS) { + out[level] = norm[level].slice(BASMALA[level].length); + stripped = true; + } + } + return stripped ? out : null; +} + +export interface QuranInput { + answer: string; + /** Verses search_quran returned in this turn. */ + thisTurn: Array<{ key: string; ar: string }>; + /** Verses search_quran returned in earlier turns of the conversation. */ + earlierTurns: Array<{ key: string; ar: string }>; + /** Source text looked up for references the answer names; null when the lookup found nothing. */ + lookups: Record; + /** Hadith in hand (any turn), to tell hadith Arabic from Quran Arabic. */ + hadith: RetrievedHadith[]; + /** Text of every non-Quran search result of this turn: tafsir, fiqh, hadith. */ + otherTexts?: string[]; + /** The same, from earlier turns of the conversation. */ + earlierOtherTexts?: string[]; + /** References the question expects the answer to quote, e.g. ['52:48']. */ + expectRefs?: string[]; +} + +/** The verses in hand, nearest origin winning when a verse came from more than one place. */ +export function buildPool(input: Pick): Map { + const pool = new Map(); + const add = (key: string, ar: string, origin: VerseOrigin) => { + if (!ar || pool.has(key)) return; + pool.set(key, { key, ar, origin }); + }; + for (const v of input.thisTurn) add(v.key, v.ar, 'this_turn'); + for (const v of input.earlierTurns) add(v.key, v.ar, 'earlier_turn'); + for (const [key, v] of Object.entries(input.lookups)) if (v) add(key, v.ar, 'lookup'); + return pool; +} + +/** A range longer than this is read as its first verses only; no answer quotes forty. */ +const MAX_RANGE = 40; + +function versesOf(ref: QuranRef): string[] { + return refVerses(ref).slice(0, MAX_RANGE); +} + +/** + * The verses an answer names that are not among `have`: what the runner must look up + * before the answer can be scored. + */ +export function refsToLookUp(answer: string, have: Iterable): string[] { + const known = new Set(have); + const labels = answerLabels(parseAnswer(answer)); + const need = new Set(); + for (const ref of labels.all) { + for (const key of versesOf(ref)) if (!known.has(key)) need.add(key); + } + return [...need]; +} + +export function scoreQuran(input: QuranInput): QuranScore { + const parsed = parseAnswer(input.answer); + const labels = answerLabels(parsed); + const poolVerses = buildPool(input); + const pool = new Map([...poolVerses].map(([key, verse]) => [key, { verse, norm: normalizeAll(verse.ar) }])); + const chains = buildChains(pool); + const hadithNorm = input.hadith.filter((h) => h.ar).map((h) => normalizeAll(h.ar)); + const normTexts = (texts: string[] | undefined) => + (texts ?? []).map((t) => normalizeAll(t)).filter((t) => t.standard.length >= MIN_LETTERS); + const otherThisTurn = normTexts(input.otherTexts); + const otherEarlier = normTexts(input.earlierOtherTexts); + const otherNorm = [...otherThisTurn, ...otherEarlier]; + const arabicAnswer = arabicShare(parsed.body) > 0.6; + + const labelled = new Set(); + for (const ref of labels.all) for (const key of versesOf(ref)) labelled.add(key); + const unverifiable = [...labelled].filter((key) => !pool.has(key)); + + /** + * Where the quoted verse came from. A verse search_quran returned counts; so does a + * quote whose words stand in another search result (a tafsir or hadith that cites the + * verse): the model had the text in front of it either way. + */ + const grounding = (keys: string[], quote?: NormalizedText): QuoteScore['grounding'] => { + const origins = keys.map((k) => pool.get(k)?.verse.origin); + const within = (sources: NormalizedText[]) => quote !== undefined && sources.some((s) => matchLevel(quote, s) !== null); + if (origins.includes('this_turn') || within(otherThisTurn)) return 'this_turn'; + if (origins.includes('earlier_turn') || within(otherEarlier)) return 'earlier_turn'; + return keys.length > 0 ? 'none' : null; + }; + + const quotes: QuoteScore[] = []; + let proseRunsSkipped = 0; + + for (const segment of arabicSegments(parsed)) { + // In an answer written in Arabic script the prose is Arabic too. Only a run that is + // quoted (between marks) or vowelled like scripture is read as a quote. + if (arabicAnswer && !segment.delimited && !(segment.vowelDensity >= VOWELLED && segment.words >= 3)) { + proseRunsSkipped++; + continue; + } + // Urdu or Persian, quoted or not: a translation of a verse is not the verse. + if (NOT_ARABIC.test(segment.text)) { + proseRunsSkipped++; + continue; + } + const whole = normalizeAll(segment.text); + if (whole.standard.length < MIN_LETTERS) continue; + const onlyFormulae = withoutFormulae(whole.standard).length < MIN_LETTERS; + + const scoped = labelsFor(segment, parsed, labels); + const labelRefs = scoped.labels.map(formatRef).filter((r, i, all) => all.indexOf(r) === i); + const labelVerses = new Set(scoped.labels.flatMap(versesOf)); + const base = { + text: segment.text, + where: segment.where, + words: segment.words, + labels: labelRefs, + labelScope: scoped.scope, + }; + + // A quote may open with the basmala; read it with and without. + const forms = [whole, withoutBasmala(whole)].filter((f): f is NormalizedText => f !== null); + const containing = (level: MatchLevel): Set => { + const found = new Set(); + for (const form of forms) for (const key of versesContaining(form[level], chains, level)) found.add(key); + return found; + }; + const byLevel = Object.fromEntries(LEVELS.map((l) => [l, containing(l)])) as Record>; + + // A citation entry not headed with a Quran reference (a hadith, a tafsir) whose words + // are in a retrieved source: the entry's own text, verse fragments inside it included. + const copied = (source: NormalizedText) => matchLevel(whole, source) !== null; + if (segment.where === 'citation' && labelVerses.size === 0 && (hadithNorm.some(copied) || otherNorm.some(copied))) { + quotes.push({ ...base, outcome: hadithNorm.some(copied) ? 'hadith_text' : 'other_source', matched: [], grounding: null }); + continue; + } + + // 1. The text is in a verse it is labelled with. + const labelledLevel = LEVELS.find((l) => [...byLevel[l]].some((k) => labelVerses.has(k))); + if (labelledLevel) { + const matched = [...byLevel[labelledLevel]].filter((k) => labelVerses.has(k)); + quotes.push({ ...base, outcome: OUTCOME_OF[labelledLevel], matched, grounding: grounding(matched, whole) }); + continue; + } + + const labelsMissingText = [...labelVerses].some((k) => !pool.has(k)); + + // 2. The text is a verse in hand, but not a labelled one. + const anyLevel = LEVELS.find((l) => byLevel[l].size > 0); + if (anyLevel) { + const matched = [...byLevel[anyLevel]]; + // Only a reference on the quote's own line (or heading its entry) labels it. A + // paragraph that names one verse and quotes another may be discussing both: read it. + const outcome: QuoteOutcome = + scoped.scope === 'line' + ? labelsMissingText + ? 'unverifiable' + : 'wrong_reference' + : scoped.scope === 'paragraph' + ? 'suspect' + : 'unlabelled'; + quotes.push({ ...base, outcome, matched, grounding: grounding(matched, whole) }); + continue; + } + + // 3. The text is in no verse in hand. + // 3a. Word for word in a hadith, tafsir or fiqh result, or inside a citation entry + // that is not a Quran entry: that source's text, not a quotation of the Quran. + if (hadithNorm.some(copied)) { + quotes.push({ ...base, outcome: 'hadith_text', matched: [], grounding: null }); + continue; + } + if (otherNorm.some(copied) || (segment.where === 'citation' && labelVerses.size === 0)) { + quotes.push({ ...base, outcome: 'other_source', matched: [], grounding: null }); + continue; + } + + const share = (norm: NormalizedText) => Math.max(...forms.map((f) => overlap(f, norm))); + let nearest: { key: string; overlap: number } | undefined; + let nearestLabelled: { key: string; overlap: number } | undefined; + for (const [key, { norm }] of pool) { + const candidate = { key, overlap: share(norm) }; + if (!nearest || candidate.overlap > nearest.overlap) nearest = candidate; + if (labelVerses.has(key) && (!nearestLabelled || candidate.overlap > nearestLabelled.overlap)) nearestLabelled = candidate; + } + const diffAgainst = (key: string) => ({ against: key, ...wordDiff(segment.text, pool.get(key)!.verse.ar) }); + // A short run is scripture only when it is written like scripture: vowelled, or in ﴿ ﴾. + const phrase = (segment.words < TERM_WORDS && segment.vowelDensity < VOWELLED && !segment.delimited) || onlyFormulae; + + // 3b. An attempt at a verse it is labelled with: most of its letters are that verse's, + // and they are not that verse. This comes before the looser test below, or a misquote + // of a verse that a retrieved hadith or tafsir also cites would pass as that source's text. + if (nearestLabelled && nearestLabelled.overlap >= ATTEMPT_OVERLAP && !phrase) { + quotes.push({ + ...base, + outcome: 'mismatch', + matched: [], + nearest: nearestLabelled, + diff: diffAgainst(nearestLabelled.key), + grounding: grounding([nearestLabelled.key]), + }); + continue; + } + + // 3c. Mostly the words of a hadith, tafsir or fiqh result (the model cut or joined it). + const mostly = (source: NormalizedText) => overlap(whole, source) >= HADITH_OVERLAP; + if (hadithNorm.some(mostly)) { + quotes.push({ ...base, outcome: 'hadith_text', matched: [], grounding: null }); + continue; + } + if (otherNorm.some(mostly)) { + quotes.push({ ...base, outcome: 'other_source', matched: [], grounding: null }); + continue; + } + + // 3d. An attempt at a verse in hand that it is not labelled with. With a reference on + // its own line it is a failed quote; otherwise gate G1, which is about labelled + // quotes, does not count it and a person reads it. + if (nearest && nearest.overlap >= ATTEMPT_OVERLAP) { + quotes.push({ + ...base, + outcome: phrase ? 'term' : scoped.scope === 'line' ? 'mismatch' : 'suspect', + matched: [], + nearest, + diff: diffAgainst(nearest.key), + grounding: grounding([nearest.key]), + }); + continue; + } + if (labelVerses.size === 0) { + quotes.push({ ...base, outcome: 'unattributed', matched: [], nearest, grounding: null }); + continue; + } + if (labelsMissingText) { + quotes.push({ ...base, outcome: 'unverifiable', matched: [], nearest, grounding: null }); + continue; + } + if (segment.words < TERM_WORDS || onlyFormulae) { + quotes.push({ ...base, outcome: 'term', matched: [], nearest, grounding: null }); + continue; + } + const first = [...labelVerses][0]; + quotes.push({ + ...base, + outcome: scoped.scope === 'line' ? 'mismatch' : 'suspect', + matched: [], + nearest, + diff: diffAgainst(first), + grounding: grounding([...labelVerses]), + }); + } + + const counts = Object.fromEntries(QUOTE_OUTCOMES.map((o) => [o, 0])) as Record; + for (const q of quotes) counts[q.outcome]++; + const quran = quotes.filter((q) => QURAN_QUOTE.has(q.outcome)); + + const passed = quotes.filter((q) => q.outcome === 'exact' || q.outcome === 'standard' || q.outcome === 'skeleton'); + const expected: ExpectedRefScore[] = (input.expectRefs ?? []).map((text) => { + const ref = parseRef(text); + if (!ref) throw new Error(`expectRefs: "${text}" is not a Quran reference`); + const keys = versesOf(ref); + return { + ref: text, + labelled: keys.every((k) => labelled.has(k)), + quoted: keys.every((k) => passed.some((q) => q.matched.includes(k))), + }; + }); + + return { + quotes, + counts, + quranQuotes: quran.length, + notFromThisTurn: quran.filter((q) => q.grounding !== 'this_turn').length, + fromMemory: quran.filter((q) => q.grounding === 'none').length, + labelled: [...labelled], + unverifiable, + proseRunsSkipped, + expected, + }; +} diff --git a/apps/eval/lib/score.ts b/apps/eval/lib/score.ts new file mode 100644 index 00000000..68e71b8e --- /dev/null +++ b/apps/eval/lib/score.ts @@ -0,0 +1,104 @@ +/** + * Scoring one turn: everything the comparison measures, computed from what the run + * recorded (the answer, the tool-call records, the log lines, the looked-up verses). + * + * Pure: no network, no clock. `rescore` runs it again over a results file, so a scorer + * can be corrected without paying for the model calls twice. + */ +import { scoreHadith } from './score-hadith'; +import { scoreLanguage } from './score-language'; +import { scoreQuran } from './score-quran'; +import { turnSources, type RetrievedHadith, type RetrievedVerse } from './sources'; +import type { LogEvent, ModelPrice, RequestEvents, RunFile, TurnRecord, TurnScores } from './types'; + +export function requestEvents(log: LogEvent[]): RequestEvents { + const count = (needle: string) => log.filter((l) => l.message.includes(needle)).length; + return { + emptyFinalRetries: count('empty final completion — retrying'), + transientRetries: count('transient error'), + repetitionCuts: count('repetition loop detected'), + budgetSynthesis: count('request-budget short-circuit') > 0, + }; +} + +/** Input at the input price; visible output and thinking at the output price. */ +export function costUsd(record: Pick, price: ModelPrice | undefined): number | null { + if (!record.usage || !price || price.inputPerMTok === null || price.outputPerMTok === null) return null; + const { promptTokenCount, candidatesTokenCount, thoughtsTokenCount } = record.usage; + return ( + (promptTokenCount * price.inputPerMTok + (candidatesTokenCount + thoughtsTokenCount) * price.outputPerMTok) / + 1_000_000 + ); +} + +export interface EarlierTurns { + verses: RetrievedVerse[]; + hadith: RetrievedHadith[]; + otherTexts: string[]; +} + +export function scoreTurn(record: TurnRecord, earlier: EarlierTurns, price: ModelPrice | undefined): TurnScores { + const sources = turnSources(record.toolCalls); + const quran = scoreQuran({ + answer: record.answer, + thisTurn: sources.verses, + earlierTurns: earlier.verses, + lookups: record.lookups, + hadith: [...sources.hadith, ...earlier.hadith], + otherTexts: sources.otherTexts, + earlierOtherTexts: earlier.otherTexts, + expectRefs: record.expectRefs, + }); + const hadith = scoreHadith({ answer: record.answer, thisTurn: sources.hadith, earlierTurns: earlier.hadith }); + const byName: Record = {}; + for (const call of sources.calls) byName[call.name] = (byName[call.name] ?? 0) + 1; + const returned = (name: string) => sources.calls.some((c) => c.name === name && c.status === 'ok'); + const searchedQuran = returned('search_quran'); + const searchedHadith = returned('search_hadith'); + return { + quran, + hadith, + language: scoreLanguage(record.answer, record.language), + tools: { + calls: sources.calls.length, + byName, + notOk: sources.calls.filter((c) => c.status !== 'ok').length, + searchedQuran, + searchedHadith, + }, + scriptureWithoutSearch: { + quran: quran.quranQuotes > 0 && !searchedQuran, + hadith: hadith.total > 0 && !searchedHadith, + }, + events: requestEvents(record.log), + costUsd: costUsd(record, price), + }; +} + +function conversationKey(r: TurnRecord): string { + return `${r.model}\u0000${r.questionId}\u0000${r.repeat}`; +} + +/** + * Score every answered turn of a run, in place. A turn is scored against its own search + * results and those of the earlier turns of the same conversation. + */ +export function scoreRun(run: RunFile): void { + const conversations = new Map(); + for (const record of run.records) { + const key = conversationKey(record); + conversations.set(key, [...(conversations.get(key) ?? []), record]); + } + for (const turns of conversations.values()) { + turns.sort((a, b) => a.turn - b.turn); + const earlier: EarlierTurns = { verses: [], hadith: [], otherTexts: [] }; + for (const record of turns) { + if (record.outcome === 'ok') record.scores = scoreTurn(record, earlier, run.prices[record.model]); + else delete record.scores; + const sources = turnSources(record.toolCalls); + earlier.verses.push(...sources.verses); + earlier.hadith.push(...sources.hadith); + earlier.otherTexts.push(...sources.otherTexts); + } + } +} diff --git a/apps/eval/lib/sources.ts b/apps/eval/lib/sources.ts new file mode 100644 index 00000000..acaa9841 --- /dev/null +++ b/apps/eval/lib/sources.ts @@ -0,0 +1,118 @@ +/** + * What the search tools returned, read back out of the facilitator's tool-call records: + * the Quran verses and the hadith a turn retrieved, and the text of every other result. + * These are the texts an answer's quotes and `LK id` tokens are checked against. + * + * The record's `content` is exactly what the model received (`formatToolResultForGemini`): + * `{ results: [{ title, context, content }], summary }`. search_quran titles a verse + * `Quran 2:255` with content `{"ar": …, "en": …}`; search_hadith ends its title with + * `(LK id …)` and carries `{"ar", "en", "grade", "collection", "chapter", "lk_id"}`. + */ +import type { ToolCallRecord } from '@/db/schema/messages'; + +export type ToolResultRecord = Extract; +export type ToolUseRecord = Extract; + +export interface RetrievedVerse { + /** `surah:ayah`. */ + key: string; + ar: string; + en: string; +} + +export interface RetrievedHadith { + lkId: string; + ar: string; + en: string; + grade: string; + collection: string; +} + +export interface ToolCallSummary { + name: string; + query: string; + status: string; + durationMs: number | null; + resultCount: number; +} + +export interface TurnSources { + verses: RetrievedVerse[]; + hadith: RetrievedHadith[]; + /** + * The raw text of every result a tool other than search_quran returned (tafsir, fiqh + * encyclopedia, hadith): Arabic an answer copies from these is that source's text, not + * a Quran quote. + */ + otherTexts: string[]; + calls: ToolCallSummary[]; +} + +const QURAN_TITLE = /^Quran (\d{1,3}):(\d{1,3})$/; + +interface GeminiResult { + title?: unknown; + content?: unknown; +} + +function resultsOf(record: ToolResultRecord): GeminiResult[] { + const results = (record.content as { results?: unknown }).results; + return Array.isArray(results) ? (results as GeminiResult[]) : []; +} + +function parseJsonObject(text: unknown): Record | null { + if (typeof text !== 'string') return null; + try { + const value: unknown = JSON.parse(text); + return typeof value === 'object' && value !== null ? (value as Record) : null; + } catch { + return null; + } +} + +const str = (value: unknown): string => (typeof value === 'string' ? value : ''); + +/** The verses, hadith and call summaries in one turn's tool-call records. */ +export function turnSources(records: ToolCallRecord[] | null | undefined): TurnSources { + const out: TurnSources = { verses: [], hadith: [], otherTexts: [], calls: [] }; + if (!records) return out; + const uses = new Map(); + for (const record of records) { + if (record.type === 'tool_use') { + uses.set(record.id, record); + continue; + } + const use = uses.get(record.tool_use_id); + const name = use?.name ?? 'unknown'; + // Only a result the tool actually returned counts as retrieved: a degraded, + // skipped or refused call carries a notice, not a source. + if (record.status === 'ok') { + for (const result of resultsOf(record)) { + if (name !== 'search_quran' && str(result.content)) out.otherTexts.push(str(result.content)); + const body = parseJsonObject(result.content); + if (!body) continue; + const verse = QURAN_TITLE.exec(str(result.title)); + if (name === 'search_quran' && verse) { + out.verses.push({ key: `${Number(verse[1])}:${Number(verse[2])}`, ar: str(body.ar), en: str(body.en) }); + } else if (name === 'search_hadith' && str(body.lk_id)) { + out.hadith.push({ + lkId: str(body.lk_id), + ar: str(body.ar), + en: str(body.en), + grade: str(body.grade), + collection: str(body.collection), + }); + } + } + } + out.calls.push({ + name, + query: str(use?.input.query), + status: record.status, + durationMs: record.duration_ms, + // Citable results: a "no results" or "unavailable" notice is not one (spec 168). + resultCount: (record.citations ?? []).filter((c) => c.enabled).length, + }); + } + return out; +} diff --git a/apps/eval/lib/types.ts b/apps/eval/lib/types.ts new file mode 100644 index 00000000..5825ba87 --- /dev/null +++ b/apps/eval/lib/types.ts @@ -0,0 +1,138 @@ +/** + * The shapes the harness reads and writes: the question set, and the results file a run + * leaves behind (inputs, model ids, git revision, date, raw answers, scores). + */ +import type { ModelProvenance, ToolCallRecord } from '@/db/schema/messages'; +import type { GeminiUsageMetadata } from '@/lib/ai/gemini-client'; +import type { HadithScore } from './score-hadith'; +import type { LanguageScore } from './score-language'; +import type { QuranScore } from './score-quran'; + +export interface QuestionTurn { + text: string; + /** Quran references the answer to this turn should quote, e.g. ["52:48"]. */ + expectRefs?: string[]; +} + +export interface Question { + id: string; + category: string; + /** Language the question is asked in, and so the answer must be in. */ + language: string; + turns: QuestionTurn[]; + /** Why the question is in the set. */ + note?: string; +} + +export interface QuestionSet { + id: string; + version: number; + description: string; + questions: Question[]; +} + +/** A console.warn / console.error line the facilitator or the Gemini client wrote during a request. */ +export interface LogEvent { + level: 'warn' | 'error'; + message: string; +} + +export interface TurnTiming { + /** Milliseconds to the first event of any kind (a tool call shows the request is alive). */ + firstEventMs: number | null; + /** Milliseconds to the first visible text: time to first token, as a user sees it. */ + firstTextMs: number | null; + totalMs: number; +} + +export interface ToolUseScore { + calls: number; + byName: Record; + /** Calls that did not return a source: degraded, skipped, refused, unknown. */ + notOk: number; + searchedQuran: boolean; + searchedHadith: boolean; +} + +/** Things the facilitator did on the way to the answer, read from its own log lines. */ +export interface RequestEvents { + emptyFinalRetries: number; + transientRetries: number; + repetitionCuts: number; + /** The answer is a best-effort synthesis written after the request budget ran out. */ + budgetSynthesis: boolean; +} + +export interface TurnScores { + quran: QuranScore; + hadith: HadithScore; + language: LanguageScore; + tools: ToolUseScore; + /** Scripture was quoted or cited in a turn where the matching search tool never returned a result. */ + scriptureWithoutSearch: { quran: boolean; hadith: boolean }; + events: RequestEvents; + /** Null when the model has no price in models.json or the turn reported no usage. */ + costUsd: number | null; +} + +export interface TurnRecord { + model: string; + questionId: string; + category: string; + language: string; + repeat: number; + /** 0 for the first turn of a conversation. */ + turn: number; + question: string; + expectRefs?: string[]; + /** + * `ok`: the facilitator finished with an answer. `error`: it ended with an error event + * (the message is in `error`). `skipped`: an earlier turn of this conversation errored, + * so this one was never asked. + */ + outcome: 'ok' | 'error' | 'skipped'; + error?: string; + /** The visible text, exactly as streamed. On an error, whatever arrived before it. */ + answer: string; + startedAt: string; + timing: TurnTiming; + /** Tokens summed over every model call of the turn. Null on an error (the facilitator reports none). */ + usage: GeminiUsageMetadata | null; + provenance: ModelProvenance | null; + toolCalls: ToolCallRecord[]; + log: LogEvent[]; + /** Source text looked up for references the answer names that no search returned. */ + lookups: Record; + scores?: TurnScores; +} + +export interface ModelPrice { + /** US dollars per million input tokens; null when not known. */ + inputPerMTok: number | null; + /** US dollars per million output tokens (visible and thinking); null when not known. */ + outputPerMTok: number | null; + source?: string; + /** True only when a person has checked the numbers against the Vertex AI pricing page. */ + confirmed?: boolean; + /** A weaker check than `confirmed`, in a few words: shown beside the NO in the report. */ + checked?: string; + /** A price change already announced: the report also costs the run at this price. */ + next?: { from: string; inputPerMTok: number; outputPerMTok: number }; +} + +export interface RunFile { + schemaVersion: 1; + runId: string; + startedAt: string; + finishedAt: string; + git: { revision: string; dirty: boolean }; + models: string[]; + /** The first model: what the others are compared against. */ + baseline: string; + questionSet: { id: string; version: number; sha256: string; questions: number; turns: number }; + /** sha256 of the facilitator system prompt the run used. */ + promptSha256: string; + options: { repeats: number; concurrency: number; only?: string[] }; + prices: Record; + records: TurnRecord[]; +} diff --git a/apps/eval/models.json b/apps/eval/models.json new file mode 100644 index 00000000..8ee541e6 --- /dev/null +++ b/apps/eval/models.json @@ -0,0 +1,53 @@ +{ + "note": "US dollars per million tokens, on-demand. Thinking tokens are billed at the output price. A null price makes the report say n/a for cost rather than guess. `confirmed` is true only after a person has checked the numbers against the Vertex AI pricing page (https://cloud.google.com/vertex-ai/generative-ai/pricing), which is what the app is billed through. `checked` names a weaker check (another pricing page) and is shown beside the NO. `next` is an announced price change; the report costs the run at both prices. After editing, run rescore.ts.", + "models": { + "gemini-3.7-flash": { + "inputPerMTok": 0.75, + "outputPerMTok": 3.75, + "confirmed": false, + "next": { + "from": "2027-01-01", + "inputPerMTok": 1.5, + "outputPerMTok": 7.5 + }, + "source": "Web search, 2026-11-15. NOT listed on the Gemini Developer API pricing page read the same day. The figures are identical to that page's price for gemini-3.8-flash (0.75 / 3.75 through 2026-12-31, then 1.50 / 7.50), so the search result may have been 3.8-flash's price. Treat the baseline's cost as the least certain number here." + }, + "gemini-3.8-flash": { + "inputPerMTok": 0.75, + "outputPerMTok": 3.75, + "confirmed": false, + "checked": "Developer API page, Vertex unconfirmed", + "next": { + "from": "2027-01-01", + "inputPerMTok": 1.5, + "outputPerMTok": 7.5 + }, + "source": "Gemini Developer API pricing page (aistudio.google.com/docs/pricing), read 2026-11-15 by the architect; the Vertex AI page would not load. Introductory rate through 2026-12-31." + }, + "gemini-4-hydrogen": { + "inputPerMTok": 1.5, + "outputPerMTok": 7.5, + "confirmed": false, + "checked": "Developer API page, Vertex unconfirmed", + "source": "Gemini Developer API pricing page (aistudio.google.com/docs/pricing), read 2026-11-15 by the architect; the Vertex AI page would not load. Output price includes thinking tokens. No introductory rate shown." + }, + "gemini-4-argon": { + "inputPerMTok": 2.0, + "outputPerMTok": 10.0, + "confirmed": false, + "checked": "Developer API page, Vertex unconfirmed", + "next": { + "from": "2026-12-01", + "inputPerMTok": 4.0, + "outputPerMTok": 20.0 + }, + "source": "Gemini Developer API pricing page (aistudio.google.com/docs/pricing), read 2026-11-15 by the architect; the Vertex AI page would not load. Output price includes thinking tokens. Introductory rate through 2026-11-30." + }, + "gemini-4-carbon": { + "inputPerMTok": null, + "outputPerMTok": null, + "confirmed": false, + "source": "input 4.00 reported from 2026-12-01, output not found, 2026-11-15" + } + } +} diff --git a/apps/eval/package.json b/apps/eval/package.json new file mode 100644 index 00000000..e74f2b0d --- /dev/null +++ b/apps/eval/package.json @@ -0,0 +1,27 @@ +{ + "name": "ansari-eval", + "version": "0.0.0", + "private": true, + "description": "Model evaluation harness: runs a question set through apps/api's facilitator per model and scores the answers. Never deployed.", + "engines": { + "node": ">=22.18.0" + }, + "scripts": { + "lint": "eslint .", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "zod": "4.6.7" + }, + "devDependencies": { + "@ansari/eslint-config": "workspace:*", + "@ansari/tsconfig": "workspace:*", + "@types/node": "25.9.5", + "eslint": "catalog:", + "tsx": "4.23.11", + "typescript": "catalog:", + "typescript-eslint": "catalog:", + "vitest": "5.1.1" + } +} diff --git a/apps/eval/questions/v1.json b/apps/eval/questions/v1.json new file mode 100644 index 00000000..18a52700 --- /dev/null +++ b/apps/eval/questions/v1.json @@ -0,0 +1,284 @@ +{ + "id": "facilitator-core", + "version": 1, + "description": "Scripture fidelity, citation validity and language adherence for the facilitator. Every question was written for this set; none is taken from a user's conversation. Do not edit a released version: copy it to a new file with the next version number, so results stay comparable.", + "questions": [ + { + "id": "ref-ayat-al-kursi", + "category": "quran-by-reference", + "language": "en", + "note": "A long, well-known verse: the easiest to write from memory, with many Uthmani-only spellings.", + "turns": [{ "text": "Please quote Ayat al-Kursi (Quran 2:255) in Arabic with an English translation.", "expectRefs": ["2:255"] }] + }, + { + "id": "ref-sharh-5-6", + "category": "quran-by-reference", + "language": "en", + "note": "Two consecutive verses that differ by one letter.", + "turns": [{ "text": "What does Quran 94:5-6 say? Give the Arabic text and a translation.", "expectRefs": ["94:5-6"] }] + }, + { + "id": "ref-baqarah-286", + "category": "quran-by-reference", + "language": "en", + "turns": [{ "text": "Quote the last verse of Surah Al-Baqarah (2:286) in Arabic and explain it briefly.", "expectRefs": ["2:286"] }] + }, + { + "id": "ref-al-imran-185", + "category": "quran-by-reference", + "language": "en", + "turns": [{ "text": "What is verse 3:185 of the Quran? Please include the Arabic.", "expectRefs": ["3:185"] }] + }, + { + "id": "ref-hujurat-13", + "category": "quran-by-reference", + "language": "en", + "turns": [{ "text": "Quote Quran 49:13 in Arabic and English. What does it teach about human equality?", "expectRefs": ["49:13"] }] + }, + + { + "id": "topic-patience", + "category": "quran-by-topic", + "language": "en", + "turns": [{ "text": "What does the Quran say about patience in hardship? Please quote two or three verses in Arabic with their references." }] + }, + { + "id": "topic-parents", + "category": "quran-by-topic", + "language": "en", + "turns": [{ "text": "Which verses of the Quran talk about being good to one's parents? Quote them with the Arabic text." }] + }, + { + "id": "topic-riba", + "category": "quran-by-topic", + "language": "en", + "turns": [{ "text": "What does the Quran say about riba (interest)? Quote the key verses in Arabic." }] + }, + { + "id": "topic-tawakkul", + "category": "quran-by-topic", + "language": "en", + "turns": [{ "text": "Which verses mention trusting in Allah (tawakkul)? Quote the Arabic for each, with its reference." }] + }, + + { + "id": "near-in-our-eyes", + "category": "near-identical", + "language": "en", + "note": "The staging misquote: 52:48 written with بِعَيْنِنَا and labelled 68:48.", + "turns": [{ "text": "Which verse of the Quran tells the Prophet to be patient for the decision of his Lord, 'for you are in Our eyes'? Quote the Arabic and give the exact reference.", "expectRefs": ["52:48"] }] + }, + { + "id": "near-68-48-vs-52-48", + "category": "near-identical", + "language": "en", + "turns": [{ "text": "Quote Quran 68:48 in Arabic. How is it different from 52:48?", "expectRefs": ["68:48", "52:48"] }] + }, + { + "id": "near-decision-of-your-lord", + "category": "near-identical", + "language": "en", + "note": "The same opening words in three surahs.", + "turns": [{ "text": "The command 'be patient for the decision of your Lord' appears in more than one surah. List every verse where it occurs, with the Arabic of each.", "expectRefs": ["52:48", "68:48", "76:24"] }] + }, + { + "id": "near-fear-of-poverty", + "category": "near-identical", + "language": "en", + "note": "6:151 and 17:31 swap the order of 'you' and 'them'.", + "turns": [{ "text": "Two verses forbid killing children because of poverty: one in Surah Al-An'am and one in Surah Al-Isra. Quote both in Arabic and explain the difference in their wording.", "expectRefs": ["6:151", "17:31"] }] + }, + { + "id": "near-2-62-vs-5-69", + "category": "near-identical", + "language": "en", + "turns": [{ "text": "Quote Quran 2:62 and Quran 5:69 in Arabic. What is the difference between them?", "expectRefs": ["2:62", "5:69"] }] + }, + { + "id": "near-adam-garden", + "category": "near-identical", + "language": "en", + "turns": [{ "text": "Quote the verse where Adam is told to live in the Garden as it appears in Surah Al-Baqarah and as it appears in Surah Al-A'raf, in Arabic, and point out how the wording differs.", "expectRefs": ["2:35", "7:19"] }] + }, + + { + "id": "hadith-intentions", + "category": "hadith-grade", + "language": "en", + "turns": [{ "text": "What is the hadith about actions being judged by intentions? Give the Arabic, the source and its grade." }] + }, + { + "id": "hadith-seeking-knowledge", + "category": "hadith-grade", + "language": "en", + "note": "Widely quoted; its grading is disputed, so the stated grade matters.", + "turns": [{ "text": "Is the hadith 'Seeking knowledge is an obligation upon every Muslim' authentic? Quote it and give its grade." }] + }, + { + "id": "hadith-knowledge-china", + "category": "hadith-grade", + "language": "en", + "note": "A saying with no sound chain: a model should not produce a citation for it.", + "turns": [{ "text": "Is there an authentic hadith that says 'Seek knowledge even if you have to go to China'? What is its grade?" }] + }, + { + "id": "hadith-smiling", + "category": "hadith-grade", + "language": "en", + "turns": [{ "text": "Quote a hadith about smiling being an act of charity, with its source and grading." }] + }, + { + "id": "hadith-neighbours", + "category": "hadith-grade", + "language": "en", + "turns": [{ "text": "What did the Prophet say about the rights of neighbours? Quote two hadith with their grades." }] + }, + + { + "id": "fiqh-wiping-socks", + "category": "fiqh", + "language": "en", + "turns": [{ "text": "Is it permissible to wipe over ordinary cotton socks during wudu? What are the conditions according to the four schools?" }] + }, + { + "id": "fiqh-travel-prayer", + "category": "fiqh", + "language": "en", + "turns": [{ "text": "Can a traveller combine and shorten prayers? What distance counts as travel according to the scholars?" }] + }, + { + "id": "fiqh-zakat-jewellery", + "category": "fiqh", + "language": "en", + "turns": [{ "text": "Is zakat due on gold jewellery that a woman wears regularly?" }] + }, + { + "id": "fiqh-forgetful-eating", + "category": "fiqh", + "language": "en", + "turns": [{ "text": "If someone eats or drinks out of forgetfulness while fasting in Ramadan, is the fast broken?" }] + }, + + { + "id": "followup-relief-after-hardship", + "category": "follow-up", + "language": "en", + "note": "The second turn asks for a verse the first turn's search may not have returned.", + "turns": [ + { "text": "What does the Quran say about relief coming after hardship?" }, + { "text": "Please write out that verse again in full Arabic, and also the verse that comes right before it." } + ] + }, + { + "id": "followup-after-ayat-al-kursi", + "category": "follow-up", + "language": "en", + "turns": [ + { "text": "Tell me about the Verse of the Throne and why it is considered so great." }, + { "text": "What is the verse immediately after it? Quote it in Arabic with a translation.", "expectRefs": ["2:256"] } + ] + }, + { + "id": "followup-anger-hadith", + "category": "follow-up", + "language": "en", + "turns": [ + { "text": "What does Islam teach about controlling anger? Include a hadith." }, + { "text": "Repeat the Arabic text of the hadith you cited, with its reference and grade, and add a Quran verse on the same subject." } + ] + }, + { + "id": "followup-yunus-dua", + "category": "follow-up", + "language": "en", + "turns": [ + { "text": "Briefly, what is the Quranic story of Prophet Yunus (Jonah)?" }, + { "text": "Quote the supplication he made inside the whale in Arabic, and give the verse reference.", "expectRefs": ["21:87"] } + ] + }, + + { + "id": "ar-ayat-al-kursi", + "category": "quran-by-reference", + "language": "ar", + "turns": [{ "text": "اذكر نص آية الكرسي كاملة مع رقم الآية واسم السورة.", "expectRefs": ["2:255"] }] + }, + { + "id": "ar-in-our-eyes", + "category": "near-identical", + "language": "ar", + "note": "The staging misquote, asked in Arabic.", + "turns": [{ "text": "ما الآية التي فيها قوله تعالى «فإنك بأعيننا»؟ اذكر نص الآية كاملاً ورقمها واسم السورة.", "expectRefs": ["52:48"] }] + }, + { + "id": "ar-topic-patience", + "category": "quran-by-topic", + "language": "ar", + "turns": [{ "text": "ماذا يقول القرآن الكريم عن الصبر عند المصيبة؟ اذكر آيتين أو ثلاثاً بنصها ومواضعها." }] + }, + { + "id": "ar-hadith-seeking-knowledge", + "category": "hadith-grade", + "language": "ar", + "turns": [{ "text": "ما صحة حديث «طلب العلم فريضة على كل مسلم»؟ اذكر نصه ودرجته." }] + }, + { + "id": "ar-fiqh-wiping-socks", + "category": "fiqh", + "language": "ar", + "turns": [{ "text": "ما حكم المسح على الجوارب في الوضوء عند المذاهب الأربعة؟" }] + }, + { + "id": "ar-followup-tawakkul", + "category": "follow-up", + "language": "ar", + "turns": [ + { "text": "ما معنى التوكل على الله؟" }, + { "text": "اذكر آية من القرآن في التوكل بنصها الكامل ورقمها، وحديثاً في الموضوع نفسه مع درجته." } + ] + }, + + { + "id": "fr-topic-patience", + "category": "quran-by-topic", + "language": "fr", + "turns": [{ "text": "Que dit le Coran sur la patience face aux épreuves ? Citez deux versets en arabe avec leur traduction et leur référence." }] + }, + { + "id": "fr-fiqh-travel-prayer", + "category": "fiqh", + "language": "fr", + "turns": [{ "text": "Est-il permis de regrouper et de raccourcir les prières en voyage ? Quelles en sont les conditions ?" }] + }, + { + "id": "id-topic-parents", + "category": "quran-by-topic", + "language": "id", + "turns": [{ "text": "Apa yang dikatakan Al-Qur'an tentang berbakti kepada orang tua? Kutip ayatnya dalam bahasa Arab beserta terjemahan dan nomor ayatnya." }] + }, + { + "id": "id-fiqh-forgetful-eating", + "category": "fiqh", + "language": "id", + "turns": [{ "text": "Apakah puasa batal jika seseorang makan atau minum karena lupa di bulan Ramadan?" }] + }, + { + "id": "ur-topic-patience", + "category": "quran-by-topic", + "language": "ur", + "turns": [{ "text": "قرآن مجید صبر کے بارے میں کیا کہتا ہے؟ دو آیات عربی متن، ترجمے اور حوالے کے ساتھ بیان کریں۔" }] + }, + { + "id": "ur-fiqh-travel-prayer", + "category": "fiqh", + "language": "ur", + "turns": [{ "text": "کیا سفر میں نمازیں جمع اور قصر کرنا جائز ہے؟ اس کی شرائط کیا ہیں؟" }] + }, + { + "id": "tr-hadith-intentions", + "category": "hadith-grade", + "language": "tr", + "turns": [{ "text": "Amellerin niyetlere göre olduğunu bildiren hadis nedir? Arapça metnini, kaynağını ve sıhhat derecesini yazar mısınız?" }] + } + ] +} diff --git a/apps/eval/rescore.ts b/apps/eval/rescore.ts new file mode 100644 index 00000000..79118b9d --- /dev/null +++ b/apps/eval/rescore.ts @@ -0,0 +1,42 @@ +/** + * Score a results file again and rewrite its report, without calling any model. + * + * pnpm --filter ansari-eval exec -- tsx rescore.ts + * + * For a corrected scorer, or prices added to models.json after the run. The raw answers, + * tool-call records and looked-up verses in the file are untouched; only `scores`, + * `prices` and the report change. + */ +import { readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { renderReport } from './lib/report'; +import { scoreRun } from './lib/score'; +import type { ModelPrice, RunFile } from './lib/types'; + +const file = process.argv[2]; +if (!file) { + console.error('usage: tsx rescore.ts '); + process.exit(2); +} + +const resultsPath = path.resolve(file); +const run = JSON.parse(readFileSync(resultsPath, 'utf8')) as RunFile; +if (run.schemaVersion !== 1) { + console.error(`${resultsPath}: schemaVersion ${String(run.schemaVersion)} is not one this harness reads (1)`); + process.exit(1); +} + +// A price that was unknown at run time may be known now. +const prices = JSON.parse(readFileSync(path.join(__dirname, 'models.json'), 'utf8')) as { + models: Record; +}; +for (const model of run.models) { + const current = prices.models[model]; + if (current && current.inputPerMTok !== null && current.outputPerMTok !== null) run.prices[model] = current; +} + +scoreRun(run); +writeFileSync(resultsPath, `${JSON.stringify(run, null, 1)}\n`); +const reportPath = resultsPath.replace(/\.json$/, '.md'); +writeFileSync(reportPath, renderReport(run)); +console.log(`Rescored ${run.records.filter((r) => r.scores).length} of ${run.records.length} turns.\nReport: ${reportPath}`); diff --git a/apps/eval/results/.gitignore b/apps/eval/results/.gitignore new file mode 100644 index 00000000..5657c8e0 --- /dev/null +++ b/apps/eval/results/.gitignore @@ -0,0 +1,3 @@ +# Run output. A run kept as evidence is copied into its experiment under codev/experiments/. +* +!.gitignore diff --git a/apps/eval/run.ts b/apps/eval/run.ts new file mode 100644 index 00000000..e8ae868a --- /dev/null +++ b/apps/eval/run.ts @@ -0,0 +1,230 @@ +/** + * Model evaluation harness (issue #393): run a question set through the real facilitator + * for each model, score every answer, write a results file and a comparison report. + * + * pnpm --filter ansari-eval exec -- tsx --env-file= run.ts \ + * --models gemini-3.7-flash,gemini-4-hydrogen,gemini-4-argon + * + * See README.md. + */ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { installLogCapture } from './lib/capture'; +import { loadQuestionSet } from './lib/question-set'; +import { renderReport } from './lib/report'; +import { planJobs, runJobs, type RunnerDeps } from './lib/runner'; +import { scoreRun } from './lib/score'; +import type { ModelPrice, Question, RunFile, TurnRecord } from './lib/types'; + +const EVAL_DIR = __dirname; +/** Conversations that must all fail, with none answered, before the run gives up. */ +const ABORT_AFTER = 4; + +interface Args { + models: string[]; + questions: string; + out: string; + repeats: number; + concurrency: number; + only: string[]; + dryRun: boolean; + verbose: boolean; +} + +const USAGE = `usage: tsx run.ts --models [options] + + --models Comma-separated model ids. The first is the baseline. + --questions Question set (default: questions/v1.json). + --out Where the results file and report go (default: results). + --repeats Samples per question per model (default: 1). + --concurrency Conversations in flight at once (default: 4). + --only Only these question ids or category:, comma-separated. + --dry-run Print the plan and the call estimate; call nothing. + --verbose Also print the facilitator's own warnings as they happen.`; + +function fail(message: string): never { + console.error(`${message}\n\n${USAGE}`); + process.exit(2); +} + +function parseArgs(argv: string[]): Args { + const args: Args = { + models: [], + questions: path.join(EVAL_DIR, 'questions/v1.json'), + out: path.join(EVAL_DIR, 'results'), + repeats: 1, + concurrency: 4, + only: [], + dryRun: false, + verbose: false, + }; + const list = (value: string) => value.split(',').map((s) => s.trim()).filter(Boolean); + const positive = (name: string, value: string) => { + const n = Number(value); + if (!Number.isInteger(n) || n < 1) fail(`${name} must be a positive integer, got "${value}"`); + return n; + }; + for (let i = 0; i < argv.length; i++) { + const flag = argv[i]; + if (flag === '--dry-run') args.dryRun = true; + else if (flag === '--verbose') args.verbose = true; + else if (flag === '--help' || flag === '-h') { + console.log(USAGE); + process.exit(0); + } else { + const value = argv[++i]; + if (value === undefined) fail(`${flag} needs a value`); + if (flag === '--models') args.models = list(value); + else if (flag === '--questions') args.questions = path.resolve(value); + else if (flag === '--out') args.out = path.resolve(value); + else if (flag === '--repeats') args.repeats = positive(flag, value); + else if (flag === '--concurrency') args.concurrency = positive(flag, value); + else if (flag === '--only') args.only = list(value); + else fail(`unknown option ${flag}`); + } + } + if (args.models.length === 0) fail('--models is required'); + if (new Set(args.models).size !== args.models.length) fail('--models lists a model twice'); + return args; +} + +function selectQuestions(all: Question[], only: string[]): Question[] { + if (only.length === 0) return all; + const selected = all.filter((q) => only.includes(q.id) || only.includes(`category:${q.category}`)); + // A filter that matches nothing must not pass as an empty, green run. + for (const wanted of only) { + const hit = all.some((q) => q.id === wanted || `category:${q.category}` === wanted); + if (!hit) fail(`--only "${wanted}" matches no question`); + } + return selected; +} + +function git(...args: string[]): string { + return execFileSync('git', args, { cwd: EVAL_DIR, encoding: 'utf8' }).trim(); +} + +function loadPrices(models: string[]): Record { + const file = JSON.parse(readFileSync(path.join(EVAL_DIR, 'models.json'), 'utf8')) as { + models: Record; + }; + return Object.fromEntries( + models.map((m) => [m, file.models[m] ?? { inputPerMTok: null, outputPerMTok: null, source: 'not in models.json' }]), + ); +} + +/** The real facilitator and the real Quran lookup. Imported here so --dry-run needs no credentials. */ +async function realDeps(): Promise<{ deps: RunnerDeps; promptSha256: string }> { + const { config } = await import('@/lib/config'); + // Touch the settings the run depends on now, so a missing credential fails before the + // first question rather than as forty error rows. + void config.gemini; + void config.tools; + const { runFacilitator } = await import('@/lib/facilitator/agent'); + const { SearchQuran } = await import('@/lib/tools/search-quran'); + const { FACILITATOR_SYSTEM_PROMPT } = await import('@/lib/ai/prompts/facilitator'); + + const search = new SearchQuran(); + const cache = new Map>(); + const lookupVerse = (key: string) => { + let pending = cache.get(key); + if (!pending) { + pending = search.run(key).then((result) => { + const doc = result.documents.find((d) => d.title === `Quran ${key}`); + if (!doc) return null; + const body = JSON.parse(doc.source.data) as { ar?: string; en?: string }; + return body.ar ? { ar: body.ar, en: body.en ?? '' } : null; + }); + cache.set(key, pending); + } + return pending; + }; + + return { + deps: { + facilitator: (history, model) => runFacilitator(history, undefined, { model }), + lookupVerse, + }, + promptSha256: createHash('sha256').update(FACILITATOR_SYSTEM_PROMPT).digest('hex'), + }; +} + +function summarize(records: TurnRecord[]): string { + const last = records[records.length - 1]; + const errors = records.filter((r) => r.outcome === 'error').length; + const seconds = records.reduce((t, r) => t + r.timing.totalMs, 0) / 1000; + return `${last.model} ${last.questionId}: ${errors > 0 ? `ERROR ${records.find((r) => r.error)?.error?.slice(0, 80)}` : 'ok'} (${seconds.toFixed(0)}s)`; +} + +async function main(): Promise { + const args = parseArgs(process.argv.slice(2)); + const { set, sha256 } = loadQuestionSet(args.questions); + const questions = selectQuestions(set.questions, args.only); + const turns = questions.reduce((t, q) => t + q.turns.length, 0); + const jobs = planJobs(args.models, questions, args.repeats); + const requests = turns * args.models.length * args.repeats; + + console.log(`Question set ${set.id} v${set.version}: ${questions.length} questions, ${turns} turns.`); + console.log(`Models: ${args.models.join(', ')} (baseline ${args.models[0]}); ${args.repeats} sample(s) each.`); + // Each request is 1 model call with no search, typically 2 to 4 with searches, and at + // most 11 (10 tool rounds + the answer) before the facilitator's own caps stop it. + console.log( + `Plan: ${jobs.length} conversations, ${requests} facilitator requests, about ${requests * 2} to ${requests * 4} model calls (hard ceiling ${requests * 11}).`, + ); + if (args.dryRun) { + for (const q of questions) console.log(` ${q.id} [${q.category}, ${q.language}] ${q.turns.length} turn(s)`); + return; + } + + const { deps, promptSha256 } = await realDeps(); + installLogCapture({ echo: args.verbose }); + + const startedAt = new Date(); + const revision = git('rev-parse', 'HEAD'); + const runId = `${startedAt.toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-')}-${revision.slice(0, 8)}`; + const run: RunFile = { + schemaVersion: 1, + runId, + startedAt: startedAt.toISOString(), + finishedAt: '', + git: { revision, dirty: git('status', '--porcelain', '--untracked-files=no') !== '' }, + models: args.models, + baseline: args.models[0], + questionSet: { id: set.id, version: set.version, sha256, questions: questions.length, turns }, + promptSha256, + options: { repeats: args.repeats, concurrency: args.concurrency, ...(args.only.length > 0 ? { only: args.only } : {}) }, + prices: loadPrices(args.models), + records: [], + }; + + mkdirSync(args.out, { recursive: true }); + const resultsPath = path.join(args.out, `${runId}.json`); + const save = () => writeFileSync(resultsPath, `${JSON.stringify(run, null, 1)}\n`); + + // Saved after every conversation: a run that dies part-way keeps what it paid for. + await runJobs(deps, jobs, args.concurrency, (_job, records, done) => { + run.records.push(...records); + save(); + console.log(`[${done}/${jobs.length}] ${summarize(records)}`); + // Nothing has answered yet and several conversations have failed: a credential, a + // model id or the network is wrong. Stop rather than write a file of errors. + if (done >= ABORT_AFTER && run.records.every((r) => r.outcome !== 'ok')) { + throw new Error( + `The first ${done} conversations all failed; stopping. Last error: ${run.records.find((r) => r.error)?.error ?? 'none recorded'}\nPartial results: ${resultsPath}`, + ); + } + }); + + run.finishedAt = new Date().toISOString(); + scoreRun(run); + save(); + const reportPath = path.join(args.out, `${runId}.md`); + writeFileSync(reportPath, renderReport(run)); + console.log(`\nResults: ${resultsPath}\nReport: ${reportPath}`); +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); +}); diff --git a/apps/eval/selfcheck.ts b/apps/eval/selfcheck.ts new file mode 100644 index 00000000..5593d266 --- /dev/null +++ b/apps/eval/selfcheck.ts @@ -0,0 +1,91 @@ +/** + * Does the Quran scorer catch a misquote in the answers of a real run? + * + * pnpm --filter ansari-eval exec -- tsx selfcheck.ts + * + * A run in which no quote fails is only good news if a failing quote would have been + * seen. This takes every answer in a results file that has a correctly quoted verse of + * five words or more, corrupts that one quote two ways (swaps two neighbouring words; + * drops a word), scores the corrupted answer, and reports how many corruptions the scorer + * failed (`mismatch` or `wrong_reference`), how many it only listed for a person to read + * (`suspect`), and how many it missed. No model is called and the file is not changed. + * + * Exits 1 if any corruption is missed outright. + */ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { scoreRun } from './lib/score'; +import { HARD_FAIL, type QuoteOutcome } from './lib/score-quran'; +import type { RunFile, TurnRecord } from './lib/types'; + +type Verdict = 'failed' | 'listed' | 'missed'; +type Mutation = 'swap' | 'drop'; + +/** A word of the verse, not a pause mark standing alone. */ +const HAS_LETTER = /[ء-يٱ]/u; + +function corrupt(text: string, how: Mutation): string | null { + const words = text.split(/\s+/u); + const lettered = words.flatMap((w, i) => (HAS_LETTER.test(w) ? [i] : [])); + if (lettered.length < 5) return null; + const pick = Math.floor(lettered.length / 2); + const at = lettered[pick]; + const before = lettered[pick - 1]; + if (how === 'drop') return [...words.slice(0, at), ...words.slice(at + 1)].join(' '); + if (words[at] === words[before]) return null; + const out = [...words]; + [out[before], out[at]] = [out[at], out[before]]; + return out.join(' '); +} + +const file = process.argv[2]; +if (!file) { + console.error('usage: tsx selfcheck.ts '); + process.exit(2); +} +const run = JSON.parse(readFileSync(path.resolve(file), 'utf8')) as RunFile; +// Score with the scorers as they are now, whatever the file was last scored with. +scoreRun(run); + +const tally: Record> = { + swap: { failed: 0, listed: 0, missed: 0 }, + drop: { failed: 0, listed: 0, missed: 0 }, +}; +const notFailed: string[] = []; + +for (const record of run.records) { + if (record.outcome !== 'ok' || !record.scores) continue; + const quote = record.scores.quran.quotes.find((q) => q.outcome === 'exact' && q.words >= 5); + if (!quote) continue; + const conversation = (r: TurnRecord) => r.model === record.model && r.questionId === record.questionId && r.repeat === record.repeat; + for (const how of ['swap', 'drop'] as const) { + const bad = corrupt(quote.text, how); + if (bad === null) continue; + const copy: RunFile = { + ...run, + records: run.records.filter(conversation).map((r) => (r === record ? { ...r, answer: r.answer.replace(quote.text, bad) } : { ...r })), + }; + scoreRun(copy); + const before: Record = record.scores.quran.counts; + const after: Record = copy.records.find((r) => r.turn === record.turn)!.scores!.quran.counts; + const more = (outcome: QuoteOutcome): number => after[outcome] - before[outcome]; + const failed: number = [...HARD_FAIL].reduce((n: number, outcome) => n + more(outcome), 0); + const verdict: Verdict = failed > 0 ? 'failed' : more('suspect') > 0 ? 'listed' : 'missed'; + tally[how][verdict]++; + if (verdict !== 'failed') { + notFailed.push( + `${verdict}: ${how} in ${record.model} ${record.questionId} turn ${record.turn + 1}, labelled ${quote.labels.join(', ') || 'nothing'} (${quote.labelScope ?? 'no label'}): ${bad.slice(0, 80)}`, + ); + } + } +} + +let missed = 0; +for (const how of ['swap', 'drop'] as const) { + const t = tally[how]; + const total = t.failed + t.listed + t.missed; + missed += t.missed; + console.log(`${how} a word: ${total} quotes corrupted, ${t.failed} failed, ${t.listed} listed for reading, ${t.missed} missed`); +} +for (const line of notFailed) console.log(` ${line}`); +if (missed > 0) process.exit(1); diff --git a/apps/eval/tests/fixtures.ts b/apps/eval/tests/fixtures.ts new file mode 100644 index 00000000..1edc4e37 --- /dev/null +++ b/apps/eval/tests/fixtures.ts @@ -0,0 +1,157 @@ +/** + * Source texts and answers for the model-eval scorer tests. + * + * The verse texts are Uthmani script as Kalimat serves it (2:255 and 2:45 are copied from + * tests/fixtures/kalemat/). The answers are written for these tests in the formats the + * facilitator prompt asks for; none is a real user's conversation. + */ +import type { ToolCallRecord } from '@/db/schema/messages'; + +export const VERSES: Record = { + '52:48': 'وَٱصْبِرْ لِحُكْمِ رَبِّكَ فَإِنَّكَ بِأَعْيُنِنَا ۖ وَسَبِّحْ بِحَمْدِ رَبِّكَ حِينَ تَقُومُ', + '68:48': 'فَٱصْبِرْ لِحُكْمِ رَبِّكَ وَلَا تَكُن كَصَاحِبِ ٱلْحُوتِ إِذْ نَادَىٰ وَهُوَ مَكْظُومٌ', + '2:45': 'وَٱسْتَعِينُوا بِٱلصَّبْرِ وَٱلصَّلَوٰةِ ۚ وَإِنَّهَا لَكَبِيرَةٌ إِلَّا عَلَى ٱلْخَـٰشِعِينَ', + '2:153': 'يَـٰٓأَيُّهَا ٱلَّذِينَ ءَامَنُوا۟ ٱسْتَعِينُوا۟ بِٱلصَّبْرِ وَٱلصَّلَوٰةِ ۚ إِنَّ ٱللَّهَ مَعَ ٱلصَّـٰبِرِينَ', + '2:255': + 'ٱللَّهُ لَآ إِلَـٰهَ إِلَّا هُوَ ٱلْحَىُّ ٱلْقَيُّومُ ۚ لَا تَأْخُذُهُۥ سِنَةٌ وَلَا نَوْمٌ ۚ لَّهُۥ مَا فِى ٱلسَّمَـٰوَٰتِ وَمَا فِى ٱلْأَرْضِ ۗ مَن ذَا ٱلَّذِى يَشْفَعُ عِندَهُۥٓ إِلَّا بِإِذْنِهِۦ ۚ يَعْلَمُ مَا بَيْنَ أَيْدِيهِمْ وَمَا خَلْفَهُمْ ۖ وَلَا يُحِيطُونَ بِشَىْءٍۢ مِّنْ عِلْمِهِۦٓ إِلَّا بِمَا شَآءَ ۚ وَسِعَ كُرْسِيُّهُ ٱلسَّمَـٰوَٰتِ وَٱلْأَرْضَ ۖ وَلَا يَـُٔودُهُۥ حِفْظُهُمَا ۚ وَهُوَ ٱلْعَلِىُّ ٱلْعَظِيمُ', + '94:5': 'فَإِنَّ مَعَ ٱلْعُسْرِ يُسْرًا', + '94:6': 'إِنَّ مَعَ ٱلْعُسْرِ يُسْرًا', + '112:1': 'قُلْ هُوَ ٱللَّهُ أَحَدٌ', + '112:2': 'ٱللَّهُ ٱلصَّمَدُ', +}; + +/** 2:255 retyped in standard spelling with vowels, as a model writes it from memory. */ +export const AYAT_AL_KURSI_STANDARD = + 'اللَّهُ لَا إِلَٰهَ إِلَّا هُوَ الْحَيُّ الْقَيُّومُ لَا تَأْخُذُهُ سِنَةٌ وَلَا نَوْمٌ لَهُ مَا فِي السَّمَاوَاتِ وَمَا فِي الْأَرْضِ مَنْ ذَا الَّذِي يَشْفَعُ عِنْدَهُ إِلَّا بِإِذْنِهِ يَعْلَمُ مَا بَيْنَ أَيْدِيهِمْ وَمَا خَلْفَهُمْ وَلَا يُحِيطُونَ بِشَيْءٍ مِنْ عِلْمِهِ إِلَّا بِمَا شَاءَ وَسِعَ كُرْسِيُّهُ السَّمَاوَاتِ وَالْأَرْضَ وَلَا يَئُودُهُ حِفْظُهُمَا وَهُوَ الْعَلِيُّ الْعَظِيمُ'; + +export interface HadithFixture { + lkId: string; + ar: string; + en: string; + grade: string; + collection: string; +} + +export const HADITH: Record = { + patience: { + lkId: '1_23_42_1302', + ar: 'حَدَّثَنَا مُحَمَّدُ بْنُ بَشَّارٍ، عَنِ النَّبِيِّ صلى الله عليه وسلم قَالَ الصَّبْرُ عِنْدَ الصَّدْمَةِ الأُولَى', + en: 'Narrated Anas: The Prophet (ﷺ) said, "The real patience is at the first stroke of a calamity."', + grade: 'Sahih-Authentic', + collection: 'Sahih Bukhari', + }, + knowledge: { + lkId: '6_1_17_224', + ar: 'طَلَبُ الْعِلْمِ فَرِيضَةٌ عَلَى كُلِّ مُسْلِمٍ', + en: 'Seeking knowledge is a duty upon every Muslim.', + grade: "Da'if (Darussalam)", + collection: 'Sunan Ibn Majah', + }, +}; + +let seq = 0; + +/** The tool-call records a search_quran call leaves, as the facilitator records them. */ +export function quranSearch(keys: string[], query = 'patience'): ToolCallRecord[] { + const id = `tool_test_${++seq}`; + return [ + { type: 'tool_use', id, name: 'search_quran', input: { query } }, + { + type: 'tool_result', + tool_use_id: id, + content: { + results: keys.map((key) => ({ + title: `Quran ${key}`, + context: 'Retrieved from the Holy Quran', + content: JSON.stringify({ ar: VERSES[key], en: `translation of ${key}` }), + })), + summary: 'Please see the Quran verses below.', + }, + status: 'ok', + duration_ms: 120, + citations: keys.map(() => ({ enabled: true })), + }, + ]; +} + +/** The tool-call records a search_hadith call leaves. */ +export function hadithSearch(items: HadithFixture[], query = 'patience'): ToolCallRecord[] { + const id = `tool_test_${++seq}`; + return [ + { type: 'tool_use', id, name: 'search_hadith', input: { query } }, + { + type: 'tool_result', + tool_use_id: id, + content: { + results: items.map((h) => ({ + title: `${h.collection} - Chapter 1: Test, Hadith 1 (Grade: ${h.grade}) (LK id ${h.lkId})`, + context: 'Retrieved from hadith collections', + content: JSON.stringify({ + ar: h.ar, + en: h.en, + grade: h.grade, + collection: h.collection, + chapter: 'Test', + lk_id: h.lkId, + }), + })), + summary: 'Please see the hadith references below.', + }, + status: 'ok', + duration_ms: 150, + citations: items.map(() => ({ enabled: true })), + }, + ]; +} + +/** A search that degraded: the model received a notice, not a source. */ +export function degradedSearch(name: string): ToolCallRecord[] { + const id = `tool_test_${++seq}`; + return [ + { type: 'tool_use', id, name, input: { query: 'q' } }, + { + type: 'tool_result', + tool_use_id: id, + content: { results: [{ title: 'Unavailable', context: 'System', content: 'temporarily unavailable' }], summary: 'unavailable' }, + status: 'degraded', + duration_ms: 20000, + error_class: 'timeout', + citations: [{ enabled: false }], + }, + ]; +} + +// ── Answers ────────────────────────────────────────────────────────────────── + +/** + * THE misquote from staging (issue #393): بِعَيْنِنَا for بِأَعْيُنِنَا, and the 52:48 text + * labelled 68:48, on a turn with no search_quran call. + */ +export const ANSWER_MISQUOTE_68_48 = `Allah tells His Messenger to be patient with His decree: + +وَاصْبِرْ لِحُكْمِ رَبِّكَ فَإِنَّكَ بِعَيْنِنَا (Quran 68:48) + +"So be patient for the decision of your Lord, for indeed, you are in Our eyes."`; + +/** The near-miss that must PASS: the right words, the right reference, standard spelling. */ +export const ANSWER_CORRECT_52_48 = `Allah tells His Messenger to be patient with His decree: + +وَاصْبِرْ لِحُكْمِ رَبِّكَ فَإِنَّكَ بِأَعْيُنِنَا (Quran 52:48) + +"So be patient for the decision of your Lord, for indeed, you are in Our eyes."`; + +/** The right words of 52:48 under the wrong reference. */ +export const ANSWER_RIGHT_TEXT_WRONG_REF = `Allah says: + +وَاصْبِرْ لِحُكْمِ رَبِّكَ فَإِنَّكَ بِأَعْيُنِنَا (Quran 68:48)`; + +/** An answer in the prompt's citation format: markers in the prose, texts in the entries. */ +export const ANSWER_WITH_CITATIONS = `Patience is tied to prayer in the Quran [1], and the Prophet (PBUH) said that real patience is at the first stroke of a calamity [2]. + +**Citations**: +[1] Quran 2:153 + Arabic: يَا أَيُّهَا الَّذِينَ آمَنُوا اسْتَعِينُوا بِالصَّبْرِ وَالصَّلَاةِ إِنَّ اللَّهَ مَعَ الصَّابِرِينَ + English: O you who believe, seek help through patience and prayer. +[2] Sahih Bukhari - Chapter 23: Funerals, Hadith 1302 (Grade: Sahih-Authentic) (LK id 1_23_42_1302) + Arabic: الصَّبْرُ عِنْدَ الصَّدْمَةِ الأُولَى + English: The real patience is at the first stroke of a calamity.`; diff --git a/apps/eval/tests/hadith-language.test.ts b/apps/eval/tests/hadith-language.test.ts new file mode 100644 index 00000000..e68d1bce --- /dev/null +++ b/apps/eval/tests/hadith-language.test.ts @@ -0,0 +1,119 @@ +import { describe, it, expect } from 'vitest'; +import { scoreHadith, gradeClasses } from '../lib/score-hadith'; +import { scoreLanguage } from '../lib/score-language'; +import { HADITH, ANSWER_WITH_CITATIONS } from './fixtures'; + +describe('scoreHadith', () => { + it('PASSES an LK id the search returned in this turn, with its grade', () => { + const score = scoreHadith({ answer: ANSWER_WITH_CITATIONS, thisTurn: [HADITH.patience], earlierTurns: [] }); + expect(score.lkIds).toEqual([ + { id: '1_23_42_1302', status: 'this_turn', grade: 'matches', sourceGrade: 'Sahih-Authentic', stated: ['sahih'] }, + ]); + expect(score.fabricated).toBe(0); + expect(score.entriesWithoutLkId).toEqual([]); + }); + + it('FAILS an LK id no search returned, even one digit off a real one', () => { + const answer = ANSWER_WITH_CITATIONS.replace('1_23_42_1302', '1_23_42_1303'); + const score = scoreHadith({ answer, thisTurn: [HADITH.patience], earlierTurns: [] }); + expect(score.fabricated).toBe(1); + expect(score.lkIds[0]).toEqual({ id: '1_23_42_1303', status: 'fabricated', grade: null }); + }); + + it('tells an id from an earlier turn apart from one from this turn', () => { + const score = scoreHadith({ answer: ANSWER_WITH_CITATIONS, thisTurn: [], earlierTurns: [HADITH.patience] }); + expect(score.thisTurn).toBe(0); + expect(score.earlierTurn).toBe(1); + expect(score.fabricated).toBe(0); + }); + + it('counts an id once however often it is written, in prose or in a citation', () => { + const answer = `The Prophet said real patience is at the first blow (LK id 1_23_42_1302) [1].\n\n${ANSWER_WITH_CITATIONS}`; + const score = scoreHadith({ answer, thisTurn: [HADITH.patience], earlierTurns: [] }); + expect(score.total).toBe(1); + }); + + it('FAILS a grade that contradicts the search result, and passes the near-miss', () => { + const cite = (grade: string) => + `It is reported [1].\n\n**Citations**:\n[1] Sunan Ibn Majah - Chapter 1, Hadith 224 (Grade: ${grade}) (LK id 6_1_17_224)\n Arabic: طَلَبُ الْعِلْمِ فَرِيضَةٌ عَلَى كُلِّ مُسْلِمٍ`; + const grade = (stated: string) => + scoreHadith({ answer: cite(stated), thisTurn: [HADITH.knowledge], earlierTurns: [] }).lkIds[0].grade; + // The search result says Da'if. + expect(grade('Sahih')).toBe('contradicts'); + expect(grade("Da'if (Darussalam)")).toBe('matches'); + expect(grade('Weak')).toBe('matches'); + expect(grade('ضعيف')).toBe('matches'); + }); + + it('does not read a book or a narrator as a grade', () => { + // "Sahih Bukhari" and "al-Hasan" are not grade statements: nothing follows the word "grade". + const answer = `Narrated by al-Hasan in Sahih Bukhari (LK id 1_23_42_1302).`; + const score = scoreHadith({ answer, thisTurn: [HADITH.patience], earlierTurns: [] }); + expect(score.lkIds[0].grade).toBe('not_stated'); + expect(gradeClasses('Ṣaḥīḥ')).toEqual(['sahih']); + expect(gradeClasses('Hasan Sahih')).toEqual(['sahih', 'hasan']); + expect(gradeClasses('Ḍaʿīf')).toEqual(['daif']); + }); + + it('lists a hadith citation that carries no LK id, and not a Quran or tafsir one', () => { + const answer = `Text [1] [2] [3].\n\n**Citations**:\n[1] Sahih Bukhari, Book of Funerals, Hadith 1302\n Arabic: الصَّبْرُ عِنْدَ الصَّدْمَةِ الأُولَى\n[2] Quran 2:153\n Arabic: إِنَّ اللَّهَ مَعَ الصَّابِرِينَ\n[3] Tafsir Encyclopedia, Volume 3, Page 45 (on the hadith of patience)`; + const score = scoreHadith({ answer, thisTurn: [], earlierTurns: [] }); + expect(score.entriesWithoutLkId).toEqual(['[1] Sahih Bukhari, Book of Funerals, Hadith 1302']); + }); +}); + +const ENGLISH = `Patience is one of the most emphasised virtues in the Quran. Allah says that He is with those who are patient, and the believers are told to seek help through patience and prayer. This is a command that the scholars have explained at length, and it applies to every hardship that a person may face in this life. + +وَاسْتَعِينُوا بِالصَّبْرِ وَالصَّلَاةِ (2:45)`; + +const ARABIC = `الصبر من أعظم الأخلاق التي حثّ عليها القرآن الكريم، وقد أمر الله تعالى عباده بالاستعانة بالصبر والصلاة، وبيّن أنه مع الصابرين في كل حال. قال تعالى: ﴿وَاسْتَعِينُوا بِالصَّبْرِ وَالصَّلَاةِ﴾ [البقرة: 45].`; + +const FRENCH = `La patience est l'une des vertus les plus importantes dans le Coran. Allah dit qu'Il est avec ceux qui sont patients, et les croyants sont invités à chercher de l'aide dans la patience et la prière. Les savants ont expliqué que cette patience est une obligation pour le croyant dans les épreuves.`; + +const INDONESIAN = `Sabar adalah salah satu akhlak yang paling ditekankan dalam Al-Qur'an. Allah berfirman bahwa Dia bersama orang-orang yang sabar, dan orang beriman diperintahkan untuk memohon pertolongan dengan sabar dan shalat. Para ulama menjelaskan bahwa kesabaran ini adalah kewajiban bagi setiap muslim dalam menghadapi ujian.`; + +const URDU = `صبر ان اخلاق میں سے ہے جن پر قرآن مجید نے بہت زور دیا ہے۔ اللہ تعالیٰ فرماتا ہے کہ وہ صبر کرنے والوں کے ساتھ ہے، اور مومنوں کو حکم دیا گیا ہے کہ وہ صبر اور نماز سے مدد لیں۔ علماء نے اس کی تفصیل بیان کی ہے۔`; + +const TURKISH = `Sabır, Kur'an'da en çok vurgulanan erdemlerden biridir. Allah sabredenlerle beraber olduğunu bildirir ve müminlere sabır ve namaz ile yardım dilemeleri emredilir. Bu, her zorluk için geçerli olan bir emirdir ve âlimler bunu uzun uzun açıklamıştır.`; + +describe('scoreLanguage', () => { + it.each([ + ['en', ENGLISH], + ['ar', ARABIC], + ['fr', FRENCH], + ['id', INDONESIAN], + ['ur', URDU], + ['tr', TURKISH], + ])('PASSES an answer in %s to a question in %s', (language, answer) => { + const score = scoreLanguage(answer, language); + expect(score.detected).toBe(language); + expect(score.inLanguage).toBe(true); + }); + + it('FAILS an Arabic question answered in English, quoted Arabic and all (the staging report)', () => { + const score = scoreLanguage(ENGLISH, 'ar'); + expect(score.inLanguage).toBe(false); + expect(score.detected).toBe('en'); + }); + + it.each([ + ['fr', ENGLISH, 'en'], + ['en', ARABIC, 'ar'], + ['ur', ARABIC, 'ar'], + ['ar', URDU, 'ur'], + ['id', FRENCH, 'fr'], + ])('FAILS a %s question answered in another language', (expected, answer, detected) => { + const score = scoreLanguage(answer, expected); + expect(score.inLanguage).toBe(false); + expect(score.detected).toBe(detected); + }); + + it('judges the prose, not the bilingual Citations section', () => { + const answer = `${ARABIC}\n\n**Citations**:\n[1] Quran 2:45\n Arabic: وَاسْتَعِينُوا بِالصَّبْرِ وَالصَّلَاةِ\n English: ${ENGLISH}\n English: ${ENGLISH}`; + expect(scoreLanguage(answer, 'ar').inLanguage).toBe(true); + }); + + it('an empty answer is in no language', () => { + expect(scoreLanguage('', 'en')).toMatchObject({ detected: 'none', inLanguage: false }); + }); +}); diff --git a/apps/eval/tests/quran.test.ts b/apps/eval/tests/quran.test.ts new file mode 100644 index 00000000..01fe46d6 --- /dev/null +++ b/apps/eval/tests/quran.test.ts @@ -0,0 +1,300 @@ +import { describe, it, expect } from 'vitest'; +import { normalizeAll, normalizeStandard, normalizeVerbatim, matchLevel } from '../lib/arabic'; +import { AYAH_COUNTS, findRefs, formatRef, surahByArabicName, surahByEnglishName } from '../lib/quran-refs'; +import { scoreQuran, refsToLookUp, type QuranInput } from '../lib/score-quran'; +import { + VERSES, + HADITH, + AYAT_AL_KURSI_STANDARD, + ANSWER_MISQUOTE_68_48, + ANSWER_CORRECT_52_48, + ANSWER_RIGHT_TEXT_WRONG_REF, + ANSWER_WITH_CITATIONS, +} from './fixtures'; + +const verse = (key: string) => ({ key, ar: VERSES[key] }); +const lookups = (...keys: string[]) => Object.fromEntries(keys.map((k) => [k, { ar: VERSES[k] }])); + +function input(answer: string, over: Partial = {}): QuranInput { + return { answer, thisTurn: [], earlierTurns: [], lookups: {}, hadith: [], ...over }; +} + +describe('arabic normalization', () => { + it('a copy of the source with its marks dropped matches verbatim', () => { + const bare = 'واصبر لحكم ربك فإنك بأعيننا'; + expect(matchLevel(normalizeAll(bare), normalizeAll(VERSES['52:48']))).toBe('verbatim'); + }); + + it('standard spelling of a whole verse matches its Uthmani source at `standard`', () => { + // السماوات for ٱلسَّمَـٰوَٰتِ, الحي for ٱلْحَىُّ, يئوده for يَـُٔودُهُۥ, إله for إِلَـٰهَ. + expect(normalizeStandard(AYAT_AL_KURSI_STANDARD)).toBe(normalizeStandard(VERSES['2:255'])); + expect(matchLevel(normalizeAll(AYAT_AL_KURSI_STANDARD), normalizeAll(VERSES['2:255']))).toBe('standard'); + }); + + it.each([ + ['ٱلصَّلَوٰةَ', 'الصَّلَاةَ'], + ['ٱلزَّكَوٰةَ', 'الزَّكَاةَ'], + ['ٱلْحَيَوٰةِ', 'الْحَيَاةِ'], + ['ٱلسَّمَـٰوَٰتِ', 'السَّمَاوَاتِ'], + ['ٱلْكِتَـٰبُ', 'الْكِتَابُ'], + ['عَلَىٰ', 'عَلَى'], + ['مُوسَىٰ', 'مُوسَى'], + ['ٱلتَّوْرَىٰةَ', 'التَّوْرَاةَ'], + ['يَـٰٓأَيُّهَا', 'يَا أَيُّهَا'], + ['ءَامَنُوا۟', 'آمَنُوا'], + ['ٱلْقُرْءَانُ', 'الْقُرْآنُ'], + ['هَـٰذَا', 'هَذَا'], + ['ذَٰلِكَ', 'ذَلِكَ'], + ['أُو۟لَـٰٓئِكَ', 'أُولَئِكَ'], + ['هَـٰٓؤُلَآءِ', 'هَؤُلَاءِ'], + ['ٱلرَّحْمَـٰنِ', 'الرَّحْمَنِ'], + ['ٱلَّيْلِ', 'اللَّيْلِ'], + ['بِهِۦ', 'بِهِ'], + ['لَهُۥ', 'لَهُ'], + ['يُحْىِۦ', 'يُحْيِي'], + ['شَيْـًٔا', 'شَيْئًا'], + ['مَسْـُٔولًا', 'مَسْؤُولًا'], + ['إِبْرَٰهِـۧمَ', 'إِبْرَاهِيمَ'], + ])('%s and %s are one word at `standard`', (uthmani, standard) => { + expect(normalizeStandard(uthmani)).toBe(normalizeStandard(standard)); + }); + + // The near-misses: a real difference must survive every level. + it.each([ + ['بِأَعْيُنِنَا', 'بِعَيْنِنَا'], + ['وَٱصْبِرْ', 'فَٱصْبِرْ'], + ['يُسْرًا', 'عُسْرًا'], + ['نَرْزُقُكُمْ وَإِيَّاهُمْ', 'نَرْزُقُهُمْ وَإِيَّاكُمْ'], + ])('%s and %s stay different at every level', (a, b) => { + const x = normalizeAll(a); + const y = normalizeAll(b); + expect(x.verbatim).not.toBe(y.verbatim); + expect(x.standard).not.toBe(y.standard); + expect(x.skeleton).not.toBe(y.skeleton); + }); + + it('`skeleton` is the only level that forgives an alef, which is why it is reported, not passed', () => { + const x = normalizeAll('قَالَ'); + const y = normalizeAll('قُلْ'); + expect(x.standard).not.toBe(y.standard); + expect(x.skeleton).toBe(y.skeleton); + }); + + it('`verbatim` does not respell', () => { + expect(normalizeVerbatim('ٱلصَّلَوٰةَ')).toBe('الصلوة'); + expect(normalizeVerbatim('الصَّلَاةَ')).toBe('الصلاة'); + }); +}); + +describe('quran references', () => { + it('the ayah counts add up to the Quran', () => { + expect(AYAH_COUNTS).toHaveLength(114); + expect(AYAH_COUNTS.reduce((a, b) => a + b, 0)).toBe(6236); + }); + + it('every surah has an Arabic and an English name that resolve to it', () => { + expect(surahByArabicName('الطور')).toBe(52); + expect(surahByArabicName('القلم')).toBe(68); + expect(surahByArabicName('آل عمران')).toBe(3); + expect(surahByArabicName('الإسراء')).toBe(17); + expect(surahByEnglishName('At-Tur')).toBe(52); + expect(surahByEnglishName('Aṭ-Ṭūr')).toBe(52); + expect(surahByEnglishName('al-Baqara')).toBe(2); + expect(surahByEnglishName('Al-Baqarah')).toBe(2); + expect(surahByEnglishName('An-Nisa')).toBe(4); + expect(surahByEnglishName('Nowhere')).toBeNull(); + }); + + const refs = (text: string) => findRefs(text).map(formatRef); + + it.each([ + ['(Quran 52:48)', ['52:48']], + ['Surah Ash-Sharh (94:5-6)', ['94:5-6']], + ['[الطور: 48]', ['52:48']], + ['[الطور: ٤٨]', ['52:48']], + ['سورة البقرة، الآية 255', ['2:255']], + ['(سورة المؤمنون: 1-3)', ['23:1-3']], + ['Surah At-Tur, verse 48', ['52:48']], + ['Sourate Al-Baqara, verset 255', ['2:255']], + ['Surah Ash-Sharh (94), Verse 6', ['94:6']], + ['Surah Al-Baqarah: 255', ['2:255']], + ['QS. Al-Baqarah [2]: 153', ['2:153']], + ['سورۃ البقرہ: 153', ['2:153']], + ['Surah At-Tur (52:48)', ['52:48']], + ['see 2:153 and 2:45', ['2:153', '2:45']], + ['٢:٢٥٥', ['2:255']], + ])('reads %s', (text, expected) => { + expect(refs(text)).toEqual(expected); + }); + + // Near-misses: things shaped like a reference that are not one. + it.each([ + ['at 10:30 in the morning the ratio was 3:400'], // 10:30 is a valid verse, 3:400 is not + ['LK id 1_23_42_1302'], + ['Sahih Muslim 8:3371'], + ['115:1 and 2:287 do not exist'], + ['12:30:45'], + ['Surah Yusuf is a long surah revealed in 12 parts'], + ['the surah of mercy: 5 lessons'], + ])('does not over-read %s', (text) => { + const found = refs(text); + expect(found.filter((r) => r !== '10:30')).toEqual([]); + }); +}); + +describe('scoreQuran', () => { + it('FAILS the staging misquote: بِعَيْنِنَا labelled 68:48', () => { + // No search ran; the harness looked 68:48 up because the answer names it. + const score = scoreQuran(input(ANSWER_MISQUOTE_68_48, { lookups: lookups('68:48') })); + expect(score.quotes).toHaveLength(1); + expect(score.quotes[0].outcome).toBe('mismatch'); + expect(score.quotes[0].labels).toEqual(['68:48']); + expect(score.quotes[0].grounding).toBe('none'); + expect(score.counts.mismatch).toBe(1); + expect(score.fromMemory).toBe(1); + }); + + it('FAILS it as a misquote of 52:48 when that verse is in hand, and shows the word', () => { + const score = scoreQuran( + input(ANSWER_MISQUOTE_68_48, { earlierTurns: [verse('52:48')], lookups: lookups('68:48') }), + ); + const quote = score.quotes[0]; + expect(quote.outcome).toBe('mismatch'); + expect(quote.nearest?.key).toBe('52:48'); + expect(quote.diff).toEqual({ against: '52:48', extra: ['بعيننا'], missing: ['بءعيننا'] }); + }); + + it('PASSES the near-miss: the right words under the right reference', () => { + const score = scoreQuran(input(ANSWER_CORRECT_52_48, { thisTurn: [verse('52:48'), verse('68:48')] })); + expect(score.quotes).toHaveLength(1); + // These words carry no Uthmani-only spelling, so the retyped quote is letter-exact. + expect(score.quotes[0].outcome).toBe('exact'); + expect(score.quotes[0].matched).toEqual(['52:48']); + expect(score.quotes[0].grounding).toBe('this_turn'); + expect(score.counts.mismatch + score.counts.wrong_reference).toBe(0); + }); + + it('FAILS the right words under the wrong reference', () => { + // 52:48 was retrieved, so the text is recognised: wrong_reference. + const known = scoreQuran( + input(ANSWER_RIGHT_TEXT_WRONG_REF, { thisTurn: [verse('52:48')], lookups: lookups('68:48') }), + ); + expect(known.quotes[0].outcome).toBe('wrong_reference'); + expect(known.quotes[0].matched).toEqual(['52:48']); + // Nothing was retrieved: the text is simply not 68:48's. + const unknown = scoreQuran(input(ANSWER_RIGHT_TEXT_WRONG_REF, { lookups: lookups('68:48') })); + expect(unknown.quotes[0].outcome).toBe('mismatch'); + }); + + it('scores a quote inside a citation entry against that entry, and sets hadith text aside', () => { + const score = scoreQuran( + input(ANSWER_WITH_CITATIONS, { thisTurn: [verse('2:153'), verse('2:45')], hadith: [HADITH.patience] }), + ); + const byOutcome = score.quotes.map((q) => [q.outcome, q.where]); + expect(byOutcome).toEqual([ + ['standard', 'citation'], + ['hadith_text', 'citation'], + ]); + expect(score.quotes[0].matched).toEqual(['2:153']); + expect(score.quranQuotes).toBe(1); + expect(score.notFromThisTurn).toBe(0); + }); + + it('a quote of a verse retrieved in an earlier turn is correct but not grounded in this turn', () => { + const score = scoreQuran(input(ANSWER_CORRECT_52_48, { earlierTurns: [verse('52:48')] })); + expect(score.quotes[0].outcome).toBe('exact'); + expect(score.quotes[0].grounding).toBe('earlier_turn'); + expect(score.notFromThisTurn).toBe(1); + expect(score.fromMemory).toBe(0); + }); + + it('reads a quote that runs across two verses, and one that opens with the basmala', () => { + const answer = `Allah says in Surah Ash-Sharh (94:5-6): فَإِنَّ مَعَ الْعُسْرِ يُسْرًا إِنَّ مَعَ الْعُسْرِ يُسْرًا + +And in Surah Al-Ikhlas (112:1-2): بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ قُلْ هُوَ اللَّهُ أَحَدٌ اللَّهُ الصَّمَدُ`; + const score = scoreQuran( + input(answer, { thisTurn: [verse('94:5'), verse('94:6'), verse('112:1'), verse('112:2')] }), + ); + expect(score.quotes.map((q) => q.outcome)).toEqual(['exact', 'exact']); + expect(score.quotes[0].matched.sort()).toEqual(['94:5', '94:6']); + expect(score.quotes[1].matched.sort()).toEqual(['112:1', '112:2']); + }); + + it('a phrase shared by two verses passes under either reference', () => { + // إِنَّ مَعَ ٱلْعُسْرِ يُسْرًا is in both 94:5 and 94:6. + const answer = 'As 94:6 says: إِنَّ مَعَ الْعُسْرِ يُسْرًا'; + const score = scoreQuran(input(answer, { thisTurn: [verse('94:5'), verse('94:6')] })); + expect(score.quotes[0].outcome).toBe('exact'); + expect(score.quotes[0].matched).toEqual(['94:6']); + }); + + it('Ayat al-Kursi retyped in standard spelling passes at `standard`, not `exact`', () => { + const answer = `Ayat al-Kursi (2:255):\n\n${AYAT_AL_KURSI_STANDARD}`; + const score = scoreQuran(input(answer, { thisTurn: [verse('2:255')] })); + expect(score.quotes.map((q) => q.outcome)).toEqual(['standard']); + // The source's own string, copied, is exact. + const copied = scoreQuran(input(`Ayat al-Kursi (2:255):\n\n${VERSES['2:255']}`, { thisTurn: [verse('2:255')] })); + expect(copied.quotes.map((q) => q.outcome)).toEqual(['exact']); + }); + + it('a quote that differs only by an unwritten alef is `skeleton`: reported, not exact', () => { + // السموات is a common spelling of السماوات; the checker cannot tell it from a slip. + const answer = 'He owns everything (2:255): لَهُ مَا فِي السَّمَوَاتِ وَمَا فِي الْأَرْضِ'; + const score = scoreQuran(input(answer, { thisTurn: [verse('2:255')] })); + expect(score.quotes.map((q) => q.outcome)).toEqual(['skeleton']); + }); + + it('a reference with no source text is unverifiable, never a pass and never a fail', () => { + const score = scoreQuran(input(ANSWER_CORRECT_52_48, { lookups: { '52:48': null } })); + expect(score.quotes[0].outcome).toBe('unverifiable'); + expect(score.unverifiable).toEqual(['52:48']); + }); + + it('in an Arabic answer only quoted or vowelled runs are read as quotes', () => { + const answer = `أمر الله نبيه بالصبر على حكمه وبيّن أنه في حفظه ورعايته، قال تعالى: ﴿وَاصْبِرْ لِحُكْمِ رَبِّكَ فَإِنَّكَ بِأَعْيُنِنَا﴾ [الطور: 48]، وهذا من أعظم ما يثبت قلب المؤمن عند البلاء.`; + const score = scoreQuran(input(answer, { thisTurn: [verse('52:48')] })); + expect(score.quotes).toHaveLength(1); + expect(score.quotes[0].outcome).toBe('exact'); + expect(score.quotes[0].labels).toEqual(['52:48']); + expect(score.proseRunsSkipped).toBeGreaterThan(0); + expect(score.counts.mismatch + score.counts.suspect).toBe(0); + }); + + it('and the misquote is still caught inside an Arabic answer', () => { + const answer = `قال تعالى: ﴿وَاصْبِرْ لِحُكْمِ رَبِّكَ فَإِنَّكَ بِعَيْنِنَا﴾ [القلم: 48]، وهذا تثبيت للنبي.`; + const score = scoreQuran(input(answer, { lookups: lookups('68:48') })); + expect(score.quotes).toHaveLength(1); + expect(score.quotes[0].outcome).toBe('mismatch'); + }); + + it('an honorific next to a reference is not a quote, but a wrong verse there still fails', () => { + const honorific = 'The Prophet (صلى الله عليه وسلم) recited it often (Quran 52:48).'; + const score = scoreQuran(input(honorific, { thisTurn: [verse('52:48')] })); + expect(score.quotes.map((q) => q.outcome)).toEqual(['term']); + // The same shape with four words that ARE meant as the verse and are not. + const wrong = 'Allah says (Quran 52:48): إِنَّ اللَّهَ مَعَ الصَّابِرِينَ دَائِمًا'; + expect(scoreQuran(input(wrong, { thisTurn: [verse('52:48')] })).quotes.map((q) => q.outcome)).toEqual(['mismatch']); + }); + + it('Arabic far from its reference that matches nothing is suspect, not a failure', () => { + const answer = `The scholars discuss 52:48 at length in their commentaries.\nOne supplication reads:\nاللَّهُمَّ إِنِّي أَعُوذُ بِكَ مِنَ الْهَمِّ وَالْحَزَنِ`; + const score = scoreQuran(input(answer, { thisTurn: [verse('52:48')] })); + expect(score.quotes.map((q) => [q.outcome, q.labelScope])).toEqual([['suspect', 'paragraph']]); + expect(score.counts.mismatch).toBe(0); + }); + + it('reports whether the references a question expects were named and quoted', () => { + const right = scoreQuran(input(ANSWER_CORRECT_52_48, { thisTurn: [verse('52:48')], expectRefs: ['52:48'] })); + expect(right.expected).toEqual([{ ref: '52:48', labelled: true, quoted: true }]); + const wrong = scoreQuran( + input(ANSWER_MISQUOTE_68_48, { lookups: lookups('68:48'), expectRefs: ['52:48'] }), + ); + expect(wrong.expected).toEqual([{ ref: '52:48', labelled: false, quoted: false }]); + }); + + it('refsToLookUp names the references no search returned', () => { + expect(refsToLookUp(ANSWER_MISQUOTE_68_48, [])).toEqual(['68:48']); + expect(refsToLookUp(ANSWER_MISQUOTE_68_48, ['68:48'])).toEqual([]); + expect(refsToLookUp(ANSWER_WITH_CITATIONS, ['2:45'])).toEqual(['2:153']); + }); +}); diff --git a/apps/eval/tests/real-answers.test.ts b/apps/eval/tests/real-answers.test.ts new file mode 100644 index 00000000..1822cbf8 --- /dev/null +++ b/apps/eval/tests/real-answers.test.ts @@ -0,0 +1,249 @@ +/** + * Regression tests from the first credentialed run (2026-11-15). Until then the scorers + * had only seen fixtures I wrote; real answers quote tafsir in Arabic, put verse fragments + * inside tafsir and hadith citations, and write `﴿verse﴾ الآية`. Every case here was + * scored as a failed Quran quote and is not one. Each is paired with the near-miss that + * must still fail, so the correction cannot quietly pass a real misquote. + * + * The verse and tafsir texts are the ones the search tools returned in that run. + */ +import { describe, it, expect } from 'vitest'; +import { scoreLanguage } from '../lib/score-language'; +import { HARD_FAIL, scoreQuran, type QuranInput } from '../lib/score-quran'; +import { VERSES } from './fixtures'; + +const V_49_13 = "يَـٰٓأَيُّهَا ٱلنَّاسُ إِنَّا خَلَقْنَـٰكُم مِّن ذَكَرٍۢ وَأُنثَىٰ وَجَعَلْنَـٰكُمْ شُعُوبًا وَقَبَآئِلَ لِتَعَارَفُوٓا ۚ إِنَّ أَكْرَمَكُمْ عِندَ ٱللَّهِ أَتْقَىٰكُمْ ۚ إِنَّ ٱللَّهَ عَلِيمٌ خَبِيرٌ"; +const V_2_286 = "لَا يُكَلِّفُ ٱللَّهُ نَفْسًا إِلَّا وُسْعَهَا ۚ لَهَا مَا كَسَبَتْ وَعَلَيْهَا مَا ٱكْتَسَبَتْ ۗ رَبَّنَا لَا تُؤَاخِذْنَآ إِن نَّسِينَآ أَوْ أَخْطَأْنَا ۚ رَبَّنَا وَلَا تَحْمِلْ عَلَيْنَآ إِصْرًا كَمَا حَمَلْتَهُۥ عَلَى ٱلَّذِينَ مِن قَبْلِنَا ۚ رَبَّنَا وَلَا تُحَمِّلْنَا مَا لَا طَاقَةَ لَنَا بِهِۦ ۖ وَٱعْفُ عَنَّا وَٱغْفِرْ لَنَا وَٱرْحَمْنَآ ۚ أَنتَ مَوْلَىٰنَا فَٱنصُرْنَا عَلَى ٱلْقَوْمِ ٱلْكَـٰفِرِينَ"; +const V_2_284 = "لِّلَّهِ مَا فِى ٱلسَّمَـٰوَٰتِ وَمَا فِى ٱلْأَرْضِ ۗ وَإِن تُبْدُوا مَا فِىٓ أَنفُسِكُمْ أَوْ تُخْفُوهُ يُحَاسِبْكُم بِهِ ٱللَّهُ ۖ فَيَغْفِرُ لِمَن يَشَآءُ وَيُعَذِّبُ مَن يَشَآءُ ۗ وَٱللَّهُ عَلَىٰ كُلِّ شَىْءٍۢ قَدِيرٌ"; +/** What search_tafsir_encyclopedia returned, cut short. */ +const TAFSIR_2_286 = "(ز)﴿لا يكلف الله نفسا إلا وسعها﴾\n\n١١٦٩٥ - عن عبد الله بن عباس -من طريق علي بن أبي طلحة- في قوله: ﴿لا يكلف الله نفسا إلا وسعها﴾، قال: هم المؤمنون، وسع الله عليهم أمر دينهم، فقال: ﴿وما جعل عليكم في الدين من حرج﴾[الحج: ٧٨]"; +const TAFSIR_49_13 = "قال ابن عطية: قوله تعالى: ﴿من ذكر وأنثى﴾ يحتمل أن يريد: آدم وحواء. فكأنه قال: إنا خلقنا جميعكم من آدم وحواء. ويحتمل أن يريد: الذكر والأنثى اسم الجنس."; + +function input(answer: string, over: Partial = {}): QuranInput { + return { answer, thisTurn: [], earlierTurns: [], lookups: {}, hadith: [], ...over }; +} +const outcomes = (i: QuranInput) => scoreQuran(i).quotes.map((q) => q.outcome); +const hardFails = (i: QuranInput) => scoreQuran(i).quotes.filter((q) => HARD_FAIL.has(q.outcome)); + +/** A tafsir citation, as gemini-4-argon wrote it: Arabic tafsir, a verse fragment in ﴿ ﴾, and an English line that names another verse. */ +const TAFSIR_ENTRY_ANSWER = `Allah relieved the believers of what is beyond their capacity [1], as Ibn Abbas explained [2]. + +**Citations**: +[1] Quran 2:286 + Arabic: ${V_2_286} + English: Allah does not require of any soul more than what it can afford. + +[2] Tafsir Encyclopedia, Volume 4, Page 731 + Arabic: عن عبد الله بن عباس -من طريق علي بن أبي طلحة- في قوله: ﴿لا يكلف الله نفسا إلا وسعها﴾، قال: هم المؤمنون، وسع الله عليهم أمر دينهم + English: When [2:284] was revealed, the believers were distressed. So Jibril came with this verse.`; + +describe('Arabic from a tafsir is not a Quran quote', () => { + const sources = { thisTurn: [{ key: '2:286', ar: V_2_286 }], lookups: { '2:284': { ar: V_2_284 } } }; + + it('a tafsir citation entry: its Arabic is the tafsir, and the verse named in its English line is not its label', () => { + const score = scoreQuran(input(TAFSIR_ENTRY_ANSWER, { ...sources, otherTexts: [TAFSIR_2_286] })); + expect(score.counts).toMatchObject({ exact: 1, mismatch: 0, wrong_reference: 0, suspect: 0, unlabelled: 0 }); + expect(score.counts.other_source).toBe(score.quotes.length - 1); + expect(score.counts.other_source).toBeGreaterThanOrEqual(3); + expect(score.quranQuotes).toBe(1); + expect(score.fromMemory).toBe(0); + }); + + it('the same entry when the tafsir text is not in hand: still no failed quote, and the verse inside it is read as a verse', () => { + const score = scoreQuran(input(TAFSIR_ENTRY_ANSWER, sources)); + expect(score.quotes.filter((q) => HARD_FAIL.has(q.outcome))).toEqual([]); + expect(score.counts).toMatchObject({ exact: 1, unlabelled: 1, suspect: 0 }); + expect(score.quotes.find((q) => q.outcome === 'unlabelled')).toMatchObject({ text: 'لا يكلف الله نفسا إلا وسعها', matched: ['2:286'] }); + expect(score.counts.other_source).toBe(score.quotes.length - 2); + }); + + it('known-bad: a Quran citation entry with one wrong word still fails', () => { + const answer = `Be patient [1]. + +**Citations**: +[1] Quran 68:48 + Arabic: فَاصْبِرْ لِحُكْمِ رَبِّكَ وَلَا تَكُن كَصَاحِبِ الْحُوتِ إِذْ نَادَىٰ وَهُوَ مَغْمُومٌ + English: So be patient.`; + const failed = hardFails(input(answer, { thisTurn: [{ key: '68:48', ar: VERSES['68:48'] }] })); + expect(failed.map((q) => q.outcome)).toEqual(['mismatch']); + expect(failed[0].labels).toEqual(['68:48']); + }); + + it('known-bad: a Quran citation entry headed 68:48 that holds the text of 52:48 is a wrong reference', () => { + const answer = `Be patient [1]. + +**Citations**: +[1] Quran 68:48 + Arabic: ${VERSES['52:48']} + English: So be patient.`; + const both = [{ key: '68:48', ar: VERSES['68:48'] }, { key: '52:48', ar: VERSES['52:48'] }]; + expect(hardFails(input(answer, { thisTurn: both })).map((q) => q.outcome)).toEqual(['wrong_reference']); + }); + + it('tafsir Arabic in the prose that resembles a verse: set aside when the tafsir is in hand, read by a person when it is not', () => { + const answer = 'Ibn Atiyyah said of this verse: ويحتمل أن يريد الذكر والأنثى اسم الجنس. That is, the two sexes.'; + const verses = { thisTurn: [{ key: '49:13', ar: V_49_13 }, { key: '53:45', ar: 'وَأَنَّهُۥ خَلَقَ ٱلزَّوْجَيْنِ ٱلذَّكَرَ وَٱلْأُنثَىٰ' }] }; + expect(outcomes(input(answer, { ...verses, otherTexts: [TAFSIR_49_13] }))).toEqual(['other_source']); + const alone = outcomes(input(answer, verses)); + expect(alone).toHaveLength(1); + expect(['suspect', 'unattributed']).toContain(alone[0]); + }); +}); + +describe('a verse between ﴿ ﴾ is read without the word after the bracket', () => { + const sources = { thisTurn: [{ key: '49:13', ar: V_49_13 }] }; + + it('`﴿verse﴾ الآية` on a line that names the verse is a correct quote', () => { + const answer = 'The Prophet recited (49:13): ﴿يا أيها الناس إنا خلقناكم من ذكر وأنثى﴾ الآية'; + const score = scoreQuran(input(answer, sources)); + expect(score.quotes.map((q) => [q.outcome, q.text])).toEqual([['standard', 'يا أيها الناس إنا خلقناكم من ذكر وأنثى']]); + }); + + it('known-bad: a wrong word inside the brackets still fails', () => { + const answer = 'The Prophet recited (49:13): ﴿يا أيها الناس إنا خلقناكم من ذكر وأنثى وجعلناكم أمما وقبائل﴾ الآية'; + const failed = hardFails(input(answer, sources)); + expect(failed.map((q) => q.outcome)).toEqual(['mismatch']); + expect(failed[0].diff?.extra).toContain('ءمما'); + }); +}); + +describe('a wrong reference needs the reference on the quote’s own line', () => { + const sources = { thisTurn: [{ key: '2:286', ar: V_2_286 }], lookups: { '2:284': { ar: V_2_284 } } }; + + it('a paragraph that names one verse and quotes another on a different line is for a person to read', () => { + const answer = `When verse 2:284 was revealed the Companions were distressed. +Then Allah revealed: +﴿لا يكلف الله نفسا إلا وسعها﴾`; + expect(outcomes(input(answer, sources))).toEqual(['suspect']); + }); + + it('known-bad: the reference on the same line as another verse’s text is a wrong reference', () => { + const answer = 'Quran 2:284: ﴿لا يكلف الله نفسا إلا وسعها﴾'; + expect(outcomes(input(answer, sources))).toEqual(['wrong_reference']); + }); +}); + +describe('grounding: a verse quoted from a tafsir or hadith result was not written from memory', () => { + const answer = 'Allah says (2:286): ﴿لا يكلف الله نفسا إلا وسعها﴾'; + const lookedUp = { lookups: { '2:286': { ar: V_2_286 } } }; + + it('no search returned the verse or its words: from memory', () => { + const score = scoreQuran(input(answer, lookedUp)); + expect(score.quotes[0]).toMatchObject({ outcome: 'exact', grounding: 'none' }); + expect(score.fromMemory).toBe(1); + }); + + it('a tafsir result of this turn holds the words: grounded in this turn', () => { + const score = scoreQuran(input(answer, { ...lookedUp, otherTexts: [TAFSIR_2_286] })); + expect(score.quotes[0]).toMatchObject({ outcome: 'exact', grounding: 'this_turn' }); + expect(score.fromMemory).toBe(0); + expect(score.notFromThisTurn).toBe(0); + }); + + it('a tafsir result of an earlier turn holds the words: grounded in an earlier turn', () => { + const score = scoreQuran(input(answer, { ...lookedUp, earlierOtherTexts: [TAFSIR_2_286] })); + expect(score.quotes[0].grounding).toBe('earlier_turn'); + expect(score.notFromThisTurn).toBe(1); + }); +}); + +describe('language of a short answer', () => { + /** gemini-4-hydrogen, question ref-sharh-5-6: read as undetermined, though it is English. */ + const SHORT_ENGLISH = `In Surah Ash-Sharh (Chapter 94), Allah says: + +**Quran 94:5** [1] +**Arabic:** فَإِنَّ مَعَ ٱلْعُسْرِ يُسْرًا +**Translation:** "So, surely with hardship comes ease." + +**Quran 94:6** [2] +**Arabic:** إِنَّ مَعَ ٱلْعُسْرِ يُسْرًا +**Translation:** "Surely with ˹that˺ hardship comes ˹more˺ ease."`; + + it('a verse and its translation is in English', () => { + expect(scoreLanguage(SHORT_ENGLISH, 'en')).toMatchObject({ detected: 'en', inLanguage: true }); + }); + + it('known-bad: the same short answer in French fails an English question', () => { + const french = `Dans la sourate Ash-Sharh, Allah dit : + +**Arabe :** فَإِنَّ مَعَ ٱلْعُسْرِ يُسْرًا +**Traduction :** « Certes, avec la difficulté est la facilité. »`; + expect(scoreLanguage(french, 'en')).toMatchObject({ detected: 'fr', inLanguage: false }); + expect(scoreLanguage(french, 'fr').inLanguage).toBe(true); + }); + + it('one stray function word does not name a language', () => { + expect(scoreLanguage('Sabr. Tawakkul. Shukr the', 'en')).toMatchObject({ detected: 'latin-script', inLanguage: false }); + }); +}); + +describe('an Urdu translation of a verse is not the verse', () => { + const V_4_101 = 'وَإِذَا ضَرَبْتُمْ فِى ٱلْأَرْضِ فَلَيْسَ عَلَيْكُمْ جُنَاحٌ أَن تَقْصُرُوا۟ مِنَ ٱلصَّلَوٰةِ إِنْ خِفْتُمْ أَن يَفْتِنَكُمُ ٱلَّذِينَ كَفَرُوٓا۟'; + const sources = { thisTurn: [{ key: '4:101', ar: V_4_101 }] }; + /** gemini-3.7-flash, question ur-fiqh-travel-prayer: the Urdu line was scored as a misquote of 4:101. */ + const urdu = (arabic: string) => `قرآن مجید میں اللہ تعالیٰ کا ارشاد ہے (4:101): +> **﴿${arabic}﴾** +> *"اور جب تم زمین میں سفر کرو تو تم پر اس بات میں کوئی گناہ نہیں کہ نماز مختصر کر کے پڑھو۔"* (4:101)`; + + it('the Arabic is scored, the Urdu under it is left out', () => { + const score = scoreQuran(input(urdu('وَإِذَا ضَرَبْتُمْ فِى ٱلْأَرْضِ فَلَيْسَ عَلَيْكُمْ جُنَاحٌ أَن تَقْصُرُوا مِنَ ٱلصَّلَوٰةِ'), sources)); + expect(score.quotes.map((q) => q.outcome)).toEqual(['exact']); + expect(score.proseRunsSkipped).toBeGreaterThanOrEqual(1); + }); + + it('known-bad: a wrong word in the Arabic of an Urdu answer still fails', () => { + const failed = hardFails(input(urdu('وَإِذَا ضَرَبْتُمْ فِى ٱلْأَرْضِ فَلَيْسَ عَلَيْكُمْ إِثْمٌ أَن تَقْصُرُوا مِنَ ٱلصَّلَوٰةِ'), sources)); + expect(failed.map((q) => q.outcome)).toEqual(['mismatch']); + expect(failed[0].diff?.extra).toEqual(['ءثم']); + }); +}); + +describe('a misquote of a verse that a retrieved hadith or tafsir also cites still fails', () => { + // Found by corrupting real answers (selfcheck.ts): the corrupted verse shared most + // of its letters with the tafsir or hadith that cites the verse, and was set aside as + // that source's text. + const verseInHand = { thisTurn: [{ key: '2:286', ar: V_2_286 }] }; + const HADITH_CITING_2_286 = { + lkId: '2_1_57_328', + ar: 'فَأَنْزَلَ اللَّهُ عَزَّ وَجَلَّ لاَ يُكَلِّفُ اللَّهُ نَفْسًا إِلاَّ وُسْعَهَا لَهَا مَا كَسَبَتْ وَعَلَيْهَا مَا اكْتَسَبَتْ رَبَّنَا لاَ تُؤَاخِذْنَا إِنْ نَسِينَا أَوْ أَخْطَأْنَا قَالَ نَعَمْ', + en: '', + grade: 'Sahih', + collection: 'Muslim', + }; + const swapped = 'Allah says (2:286): ﴿لا يكلف الله نفسا إلا وسعها لها ما كسبت وعليها اكتسبت ما﴾'; + + it('with a hadith in hand that cites the verse', () => { + expect(outcomes(input(swapped, { ...verseInHand, hadith: [HADITH_CITING_2_286] }))).toEqual(['mismatch']); + }); + + it('with a tafsir in hand that cites the verse', () => { + const tafsir = 'عن قتادة قوله: ﴿لا يكلف الله نفسا إلا وسعها لها ما كسبت﴾ أي: من خير، ﴿وعليها ما اكتسبت﴾ أي: من شر'; + expect(outcomes(input(swapped, { ...verseInHand, otherTexts: [tafsir] }))).toEqual(['mismatch']); + }); + + it('near-miss: the hadith quoted word for word beside the same reference is hadith text', () => { + const answer = 'On this verse (2:286) the hadith says: فَأَنْزَلَ اللَّهُ عَزَّ وَجَلَّ لاَ يُكَلِّفُ اللَّهُ نَفْسًا إِلاَّ وُسْعَهَا'; + expect(hardFails(input(answer, { ...verseInHand, hadith: [HADITH_CITING_2_286] }))).toEqual([]); + }); +}); + +describe('a reference in the next sentence is not the quote’s label', () => { + const V_2_62 = 'إِنَّ ٱلَّذِينَ ءَامَنُوا۟ وَٱلَّذِينَ هَادُوا۟ وَٱلنَّصَـٰرَىٰ وَٱلصَّـٰبِـِٔينَ مَنْ ءَامَنَ بِٱللَّهِ وَٱلْيَوْمِ ٱلْـَٔاخِرِ'; + const V_5_69 = 'إِنَّ ٱلَّذِينَ ءَامَنُوا۟ وَٱلَّذِينَ هَادُوا۟ وَٱلصَّـٰبِـُٔونَ وَٱلنَّصَـٰرَىٰ مَنْ ءَامَنَ بِٱللَّهِ وَٱلْيَوْمِ ٱلْـَٔاخِرِ'; + const sources = { thisTurn: [{ key: '2:62', ar: V_2_62 }, { key: '5:69', ar: V_5_69 }] }; + + it('gemini-4-argon, near-2-62-vs-5-69: the words of 2:62, then a new sentence about 5:69', () => { + const answer = + 'In `الَّذِينَ آمَنُوا وَالَّذِينَ هَادُوا وَالنَّصَارَىٰ`, none of those words show visible case endings (*harakat zahirah*). In **5:69**, by placing the Sabians first, the Quran highlights a nuance.'; + const score = scoreQuran(input(answer, sources)); + expect(score.quotes.map((q) => q.outcome)).toEqual(['suspect']); + expect(score.quotes[0].matched).toEqual(['2:62']); + }); + + it('known-bad: the same words with 5:69 in their own sentence are a wrong reference', () => { + const after = 'The verse reads `الَّذِينَ آمَنُوا وَالَّذِينَ هَادُوا وَالنَّصَارَىٰ` (5:69). It promises a reward.'; + const before = 'Quran 5:69. `الَّذِينَ آمَنُوا وَالَّذِينَ هَادُوا وَالنَّصَارَىٰ`'; + expect(outcomes(input(after, sources))).toEqual(['wrong_reference']); + expect(outcomes(input(before, sources))).toEqual(['wrong_reference']); + }); +}); diff --git a/apps/eval/tests/run-command.test.ts b/apps/eval/tests/run-command.test.ts new file mode 100644 index 00000000..cedcbf89 --- /dev/null +++ b/apps/eval/tests/run-command.test.ts @@ -0,0 +1,43 @@ +/** + * The documented run command, started for real: tsx, in this package (issue #397). + * + * The harness reaches apps/api through `@/`, and apps/api's own files use `@/` among + * themselves. tsx takes the alias from this package's tsconfig.json and vitest takes it + * from vitest.config.ts, so each is proven here. The other suites cannot tell: what they + * import through `@/` is types, erased before anything is resolved. + */ +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const PACKAGE = path.resolve(__dirname, '..'); +const tsx = (...args: string[]) => + execFileSync(path.join(PACKAGE, 'node_modules/.bin/tsx'), args, { cwd: PACKAGE, encoding: 'utf8' }); + +/** The api modules run.ts loads for a real run, read from run.ts so the list cannot drift. */ +const API_MODULES = [...readFileSync(path.join(PACKAGE, 'run.ts'), 'utf8').matchAll(/import\('(@\/[^']+)'\)/g)].map((m) => m[1]); + +describe('the run command (issue #397)', () => { + it('prints the plan for --dry-run, calling nothing', () => { + const out = tsx('run.ts', '--models', 'model-a,model-b', '--dry-run'); + expect(out).toContain('Question set facilitator-core v1: 41 questions, 46 turns.'); + expect(out).toContain('Models: model-a, model-b (baseline model-a); 1 sample(s) each.'); + expect(out).toContain('Plan: 82 conversations, 92 facilitator requests'); + }); + + it('finds the facilitator among the api modules run.ts loads', () => { + expect(API_MODULES).toContain('@/lib/facilitator/agent'); + expect(API_MODULES.length).toBeGreaterThanOrEqual(4); + }); + + it('loads every one of them under tsx', () => { + const script = `Promise.all(${JSON.stringify(API_MODULES)}.map((s) => import(s))).then((m) => console.log('loaded ' + m.length))`; + expect(tsx('-e', script).trim()).toBe(`loaded ${API_MODULES.length}`); + }); + + it('loads the facilitator under vitest', async () => { + const agent = await import('@/lib/facilitator/agent'); + expect(typeof agent.runFacilitator).toBe('function'); + }); +}); diff --git a/apps/eval/tests/run.test.ts b/apps/eval/tests/run.test.ts new file mode 100644 index 00000000..4649cd2c --- /dev/null +++ b/apps/eval/tests/run.test.ts @@ -0,0 +1,457 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +import path from 'node:path'; +import { installLogCapture } from '../lib/capture'; +import { loadQuestionSet, parseQuestionSet } from '../lib/question-set'; +import { costSummary, evaluateGates, modelStats, percentile, renderReport } from '../lib/report'; +import { planJobs, runConversation, runJobs, type FacilitatorEvent, type HistoryMessage, type RunnerDeps } from '../lib/runner'; +import { costUsd, scoreRun } from '../lib/score'; +import type { Question, RunFile, TurnRecord } from '../lib/types'; +import { + VERSES, + HADITH, + quranSearch, + hadithSearch, + degradedSearch, + ANSWER_MISQUOTE_68_48, + ANSWER_CORRECT_52_48, + ANSWER_WITH_CITATIONS, +} from './fixtures'; + +/** + * The harness end to end against a scripted facilitator: two "models", one that searches + * and quotes correctly and one that reproduces the staging failures. No network. + */ + +const USAGE = { promptTokenCount: 10_000, candidatesTokenCount: 800, thoughtsTokenCount: 200, totalTokenCount: 11_000 }; + +const QUESTIONS: Question[] = [ + { + id: 'near-in-our-eyes', + category: 'near-identical', + language: 'en', + turns: [ + { text: 'Which verse says "you are in Our eyes"?', expectRefs: ['52:48'] }, + { text: 'Quote it again.', expectRefs: ['52:48'] }, + ], + }, + { id: 'hadith-patience', category: 'hadith-grade', language: 'en', turns: [{ text: 'A hadith on patience?' }] }, + { id: 'ar-question', category: 'quran-by-topic', language: 'ar', turns: [{ text: 'ما معنى الصبر؟' }] }, +]; + +const ARABIC_ANSWER = + 'الصبر هو حبس النفس على ما تكره ابتغاء وجه الله تعالى، وهو من أعظم الأخلاق التي أمر بها الإسلام وحث عليها في مواضع كثيرة.'; +const ENGLISH_ANSWER = + 'Patience means restraining the self for the sake of Allah, and it is one of the greatest virtues that the religion commands in many places.'; + +interface Call { + model: string; + history: HistoryMessage[]; +} + +function scriptedDeps(): { deps: RunnerDeps; calls: Call[]; lookedUp: string[] } { + const calls: Call[] = []; + const lookedUp: string[] = []; + let clock = 1_000_000; + const facilitator = async function* (history: HistoryMessage[], model: string): AsyncGenerator { + calls.push({ model, history }); + const question = history[history.length - 1].content.map((c) => (c.type === 'text' ? c.text : '')).join(''); + const provenance = { provider: 'gemini' as const, modelId: model }; + const done = (toolCalls?: FacilitatorEvent['toolCalls']): FacilitatorEvent => ({ + type: 'done', + data: '', + usage: USAGE, + rawPayload: { role: 'model', parts: [{ text: 'final turn' }] }, + toolCalls, + provenance, + }); + await Promise.resolve(); + + if (model === 'good-model') { + if (question.includes('in Our eyes')) { + yield { type: 'tool_use', data: '{"name":"search_quran"}' }; + yield { type: 'text', data: ANSWER_CORRECT_52_48.slice(0, 40) }; + yield { type: 'text', data: ANSWER_CORRECT_52_48.slice(40) }; + yield done(quranSearch(['52:48', '68:48'])); + } else if (question.includes('again')) { + // No search this turn: the verse comes from the first turn's results. + yield { type: 'text', data: ANSWER_CORRECT_52_48 }; + yield done(); + } else if (question.includes('hadith')) { + yield { type: 'text', data: ANSWER_WITH_CITATIONS }; + yield done([...quranSearch(['2:153']), ...hadithSearch([HADITH.patience])]); + } else { + yield { type: 'text', data: ARABIC_ANSWER }; + yield done(); + } + return; + } + + // bad-model: the staging failures. + if (question.includes('in Our eyes')) { + console.warn('[facilitator] empty final completion — retrying', { model }); + yield { type: 'text', data: ANSWER_MISQUOTE_68_48 }; + yield done(); + } else if (question.includes('again')) { + yield { type: 'error', data: 'Maximum iterations reached', toolCalls: degradedSearch('search_quran'), provenance }; + } else if (question.includes('hadith')) { + yield { type: 'text', data: ANSWER_WITH_CITATIONS.replace('1_23_42_1302', '9_9_9_9999') }; + yield done([...quranSearch(['2:153']), ...hadithSearch([HADITH.patience])]); + } else { + yield { type: 'text', data: ENGLISH_ANSWER }; + yield done(); + } + }; + return { + calls, + lookedUp, + deps: { + facilitator, + lookupVerse: async (key) => { + lookedUp.push(key); + return VERSES[key] ? { ar: VERSES[key], en: '' } : null; + }, + // Every reading advances the clock by 100 ms: timings are exact, not load-dependent. + now: () => (clock += 100), + }, + }; +} + +function runFile(records: TurnRecord[]): RunFile { + return { + schemaVersion: 1, + runId: 'test-run', + startedAt: '2026-11-15T00:00:00.000Z', + finishedAt: '2026-11-15T00:10:00.000Z', + git: { revision: 'a'.repeat(40), dirty: false }, + models: ['good-model', 'bad-model'], + baseline: 'good-model', + questionSet: { id: 'test', version: 1, sha256: 'b'.repeat(64), questions: QUESTIONS.length, turns: 4 }, + promptSha256: 'c'.repeat(64), + options: { repeats: 1, concurrency: 3 }, + prices: { + 'good-model': { inputPerMTok: 1, outputPerMTok: 4 }, + 'bad-model': { inputPerMTok: null, outputPerMTok: null }, + }, + records, + }; +} + +let run: RunFile; +let script: ReturnType; + +beforeAll(async () => { + installLogCapture(); + script = scriptedDeps(); + const jobs = planJobs(['good-model', 'bad-model'], QUESTIONS, 1); + // Concurrency 3: requests of both models are in flight together. + run = runFile(await runJobs(script.deps, jobs, 3)); + scoreRun(run); +}); + +const record = (model: string, questionId: string, turn = 0) => + run.records.find((r) => r.model === model && r.questionId === questionId && r.turn === turn)!; + +describe('runner', () => { + it('records one row per turn per model, in plan order', () => { + expect(run.records).toHaveLength(8); + expect(run.records.map((r) => `${r.model}/${r.questionId}/${r.turn}`).slice(0, 4)).toEqual([ + 'good-model/near-in-our-eyes/0', + 'good-model/near-in-our-eyes/1', + 'bad-model/near-in-our-eyes/0', + 'bad-model/near-in-our-eyes/1', + ]); + }); + + it('records the streamed text, timings, usage, provenance and tool calls', () => { + const r = record('good-model', 'near-in-our-eyes'); + expect(r.outcome).toBe('ok'); + expect(r.answer).toBe(ANSWER_CORRECT_52_48); + expect(r.usage).toEqual(USAGE); + expect(r.provenance).toEqual({ provider: 'gemini', modelId: 'good-model' }); + expect(r.toolCalls).toHaveLength(2); + }); + + it('times a turn from its start: first event, first visible text, end', async () => { + // Its own clock, one conversation: 100 ms per reading, one reading per event and one + // at the end. Events: tool_use, text, text, done. + const { deps } = scriptedDeps(); + const [first] = await runConversation(deps, 'good-model', QUESTIONS[0], 0); + expect(first.timing).toEqual({ firstEventMs: 100, firstTextMs: 200, totalMs: 500 }); + // A turn with no tool call (text, done): the first event is the first text. + const [plain] = await runConversation(deps, 'good-model', QUESTIONS[2], 0); + expect(plain.timing).toEqual({ firstEventMs: 100, firstTextMs: 100, totalMs: 300 }); + }); + + it('builds turn-2 history the way the chat route does: the answer text with its raw payload', () => { + const second = script.calls.find((c) => c.model === 'good-model' && c.history.length === 3)!; + expect(second.history.map((m) => m.role)).toEqual(['user', 'assistant', 'user']); + expect(second.history[1]).toEqual({ + role: 'assistant', + content: [{ type: 'text', text: ANSWER_CORRECT_52_48 }], + rawPayload: { role: 'model', parts: [{ text: 'final turn' }] }, + }); + }); + + it('looks up only the references no search returned', () => { + // good-model retrieved 52:48; bad-model named 68:48 with no search. + expect(script.lookedUp).toEqual(['68:48']); + expect(record('bad-model', 'near-in-our-eyes').lookups).toEqual({ '68:48': { ar: VERSES['68:48'], en: '' } }); + expect(record('good-model', 'near-in-our-eyes').lookups).toEqual({}); + }); + + it('records an error turn with its message and tool calls, and skips nothing silently', () => { + const r = record('bad-model', 'near-in-our-eyes', 1); + expect(r.outcome).toBe('error'); + expect(r.error).toBe('Maximum iterations reached'); + expect(r.toolCalls).toHaveLength(2); + expect(r.usage).toBeNull(); + expect(r.scores).toBeUndefined(); + }); + + it('marks the turns after an error as skipped, without asking them', async () => { + const { deps, calls } = scriptedDeps(); + const failing: RunnerDeps = { + ...deps, + facilitator: async function* (history, model) { + calls.push({ model, history }); + yield { type: 'error', data: 'boom' }; + }, + }; + const question: Question = { id: 'q', category: 'c', language: 'en', turns: [{ text: 'one' }, { text: 'two' }, { text: 'three' }] }; + const records = await runConversation(failing, 'm', question, 0); + expect(records.map((r) => r.outcome)).toEqual(['error', 'skipped', 'skipped']); + expect(calls).toHaveLength(1); + }); + + it('records a facilitator that throws as an error turn', async () => { + const { deps } = scriptedDeps(); + const throwing: RunnerDeps = { + ...deps, + facilitator: async function* () { + throw new Error('Gemini is not configured'); + }, + }; + const [r] = await runConversation(throwing, 'm', QUESTIONS[1], 0); + expect(r.outcome).toBe('error'); + expect(r.error).toBe('Gemini is not configured'); + }); + + it("attributes the facilitator's log lines to the request that wrote them", () => { + expect(record('bad-model', 'near-in-our-eyes').log).toEqual([ + { level: 'warn', message: '[facilitator] empty final completion — retrying' }, + ]); + for (const r of run.records.filter((x) => x.model === 'good-model')) expect(r.log).toEqual([]); + }); +}); + +describe('scoring a run', () => { + it('scores the good model clean', () => { + const first = record('good-model', 'near-in-our-eyes').scores!; + expect(first.quran.counts.exact).toBe(1); + expect(first.quran.expected).toEqual([{ ref: '52:48', labelled: true, quoted: true }]); + expect(first.scriptureWithoutSearch.quran).toBe(false); + expect(first.tools).toMatchObject({ calls: 1, notOk: 0, searchedQuran: true, searchedHadith: false }); + expect(first.costUsd).toBeCloseTo((10_000 * 1 + 1_000 * 4) / 1_000_000, 10); + }); + + it('on the follow-up turn: correct, but quoted with no search in that turn', () => { + const second = record('good-model', 'near-in-our-eyes', 1).scores!; + expect(second.quran.quotes[0]).toMatchObject({ outcome: 'exact', grounding: 'earlier_turn' }); + expect(second.quran.notFromThisTurn).toBe(1); + expect(second.quran.fromMemory).toBe(0); + expect(second.scriptureWithoutSearch.quran).toBe(true); + }); + + it('scores the bad model: misquote, fabricated id, wrong language, retry', () => { + const misquote = record('bad-model', 'near-in-our-eyes').scores!; + expect(misquote.quran.counts.mismatch).toBe(1); + expect(misquote.quran.fromMemory).toBe(1); + expect(misquote.scriptureWithoutSearch.quran).toBe(true); + expect(misquote.events.emptyFinalRetries).toBe(1); + expect(misquote.costUsd).toBeNull(); + expect(record('bad-model', 'hadith-patience').scores!.hadith.fabricated).toBe(1); + expect(record('bad-model', 'ar-question').scores!.language).toMatchObject({ inLanguage: false, detected: 'en' }); + expect(record('good-model', 'ar-question').scores!.language.inLanguage).toBe(true); + }); + + it('costUsd is null without usage or without a price, never zero', () => { + expect(costUsd({ usage: null }, { inputPerMTok: 1, outputPerMTok: 1 })).toBeNull(); + expect(costUsd({ usage: USAGE }, undefined)).toBeNull(); + expect(costUsd({ usage: USAGE }, { inputPerMTok: 1, outputPerMTok: null })).toBeNull(); + }); + + it('rescoring is repeatable: the same file scores the same', () => { + const before = JSON.stringify(run.records.map((r) => r.scores)); + scoreRun(run); + expect(JSON.stringify(run.records.map((r) => r.scores))).toBe(before); + }); +}); + +describe('report', () => { + it('totals each model', () => { + const good = modelStats('good-model', run.records); + const bad = modelStats('bad-model', run.records); + expect(good).toMatchObject({ turns: 4, ok: 4, errors: 0, skipped: 0 }); + expect(bad).toMatchObject({ turns: 4, ok: 3, errors: 1, emptyFinalRetries: 1 }); + expect(good.quran).toMatchObject({ quotes: 3, hardFails: 0, notFromThisTurn: 1, fromMemory: 0 }); + expect(good.quran.byGrounding).toEqual({ + this_turn: { quotes: 2, hardFails: 0 }, + earlier_turn: { quotes: 1, hardFails: 0 }, + none: { quotes: 0, hardFails: 0 }, + }); + expect(bad.quran).toMatchObject({ mismatch: 1, hardFails: 1, fromMemory: 1 }); + expect(bad.quran.byGrounding.none).toEqual({ quotes: 1, hardFails: 1 }); + expect(good.hadith).toMatchObject({ ids: 1, fabricated: 0 }); + expect(bad.hadith).toMatchObject({ ids: 1, fabricated: 1 }); + expect(good.language).toEqual({ scored: 4, inLanguage: 4, arabicQuestions: 1, arabicInLanguage: 1 }); + expect(bad.language).toEqual({ scored: 3, inLanguage: 2, arabicQuestions: 1, arabicInLanguage: 0 }); + expect(good.expected).toEqual({ refs: 2, labelled: 2, quoted: 2 }); + expect(bad.expected).toEqual({ refs: 1, labelled: 0, quoted: 0 }); + expect(good.latency.totalMedian).toBeGreaterThan(0); + expect(good.latency.firstTextMedian).toBeLessThanOrEqual(good.latency.totalMedian!); + expect(bad.cost).toEqual({ perAnswerMean: null, total: null, priced: 0 }); + }); + + it('fails the bad model on the gates it should fail, and passes a model against itself', () => { + const good = modelStats('good-model', run.records); + const bad = modelStats('bad-model', run.records); + const verdicts = Object.fromEntries(evaluateGates(good, bad).map((g) => [g.gate.slice(0, 2), g.pass])); + expect(verdicts).toEqual({ G1: false, G2: false, G3: false, G4: true, G5: true, G6: null }); + const self = evaluateGates(good, good).map((g) => g.pass); + expect(self).toEqual([true, true, true, true, true, true]); + }); + + it('G4 fails at two more failures than the baseline, not at one', () => { + const good = modelStats('good-model', run.records); + expect(evaluateGates(good, { ...good, errors: 1 })[3].pass).toBe(true); + expect(evaluateGates(good, { ...good, errors: 1, budgetSynthesis: 1 })[3].pass).toBe(false); + }); + + it('G5 fails above 1.5 times the baseline, on either measure', () => { + const good = modelStats('good-model', run.records); + const latency = (firstTextMedian: number, totalMedian: number) => ({ ...good, latency: { ...good.latency, firstTextMedian, totalMedian } }); + const base = latency(1000, 10_000); + expect(evaluateGates(base, latency(1500, 15_000))[4].pass).toBe(true); + expect(evaluateGates(base, latency(1501, 10_000))[4].pass).toBe(false); + expect(evaluateGates(base, latency(1000, 15_001))[4].pass).toBe(false); + }); + + it('lists every item a human should read', () => { + const report = renderReport(run); + expect(report).toContain('## Gates against the baseline'); + expect(report).toContain('| G1 Quran fidelity | FAIL: 1 mismatch or wrong-reference quotes (baseline 0) |'); + // The failed quote, with the word that is wrong. + expect(report).toMatch(/\| bad-model \| near-in-our-eyes \| mismatch \| 68:48 \|.*بِعَيْنِنَا/); + expect(report).toContain('| bad-model | hadith-patience | 9_9_9_9999 |'); + expect(report).toContain('| bad-model | ar-question | ar | en |'); + expect(report).toContain('| bad-model | near-in-our-eyes turn 2 | Maximum iterations reached |'); + expect(report).toContain('No price in models.json for `bad-model`'); + // And says None where there is nothing, rather than leaving a section out. + expect(report).toContain('## Grades that contradict the search result\n\nNone.'); + }); + + // Each good-model answer is 10,000 input and 1,000 output tokens at $1 / $4: $0.014. + it('costs an answer and 1,000 answers, shows the price inputs, and marks an unchecked price', () => { + const report = renderReport(run); + expect(report).toContain('| Price, US$ per million tokens: input / output | $1.00 / $4.00 | n/a |'); + expect(report).toContain('| Price confirmed on the Vertex AI pricing page | **NO** | **NO** |'); + // A weaker check is named beside the NO, and is still a NO. + const partly = renderReport({ ...run, prices: { ...run.prices, 'good-model': { inputPerMTok: 1, outputPerMTok: 4, checked: 'Developer API page, Vertex unconfirmed' } } }); + expect(partly).toContain('| Price confirmed on the Vertex AI pricing page | **NO** (Developer API page, Vertex unconfirmed) | **NO** |'); + expect(partly).toContain('**Prices not confirmed** for `good-model`, `bad-model`.'); + expect(report).toContain('| Tokens per answer: input / output / thinking | 10000 / 800 / 200 | 10000 / 800 / 200 |'); + expect(report).toContain('| Answers costed | 4 of 4 | 0 of 3 |'); + expect(report).toContain('| **Cost per answer** | $0.0140 | n/a |'); + expect(report).toContain('| **Cost per 1,000 answers** | $14.00 | n/a |'); + expect(report).toContain('| … relative to the baseline | 1.00x | n/a |'); + expect(report).toContain('| Cost per answer / per 1,000 answers / this run | $0.0140 / $14.00 / $0.06 (price not confirmed) | n/a / n/a / n/a |'); + expect(report).toContain('**Prices not confirmed** for `good-model`, `bad-model`.'); + // No announced change in these prices: the rows for one are left out. + expect(report).not.toContain('Announced price change'); + }); + + it('a confirmed price reads as confirmed, and an announced change is costed beside the current price', () => { + const report = renderReport({ + ...run, + prices: { + 'good-model': { inputPerMTok: 1, outputPerMTok: 4, confirmed: true, source: 'pricing page, read 2026-11-15', next: { from: '2027-01-01', inputPerMTok: 2, outputPerMTok: 8 } }, + // Same tokens, three times the price, no announced change. + 'bad-model': { inputPerMTok: 3, outputPerMTok: 12, confirmed: true, source: 'pricing page, read 2026-11-15' }, + }, + }); + expect(report).toContain('| Price confirmed on the Vertex AI pricing page | yes | yes |'); + expect(report).not.toContain('Prices not confirmed'); + expect(report).not.toContain('(price not confirmed)'); + expect(report).toContain('| Announced price change: input / output | $2.00 / $8.00 from 2027-01-01 | none known |'); + // The run recorded bad-model's scores with no price, so its cost stays n/a until rescored. + expect(report).toContain('| Cost per 1,000 answers after the announced changes | $28.00 | n/a |'); + expect(report).toContain('- `good-model`: pricing page, read 2026-11-15'); + }); + + it('costSummary: the later figure equals the current one without an announced change, and never invents a cost', () => { + const good = modelStats('good-model', run.records); + const now = costSummary(good, { inputPerMTok: 1, outputPerMTok: 4 }); + expect(now.perAnswer).toBeCloseTo(0.014, 10); + expect(now.per1000).toBeCloseTo(14, 8); + expect(now.laterPer1000).toBeCloseTo(14, 8); + const later = costSummary(good, { inputPerMTok: 1, outputPerMTok: 4, next: { from: '2027-01-01', inputPerMTok: 2, outputPerMTok: 8 } }); + expect(later.per1000).toBeCloseTo(14, 8); + expect(later.laterPer1000).toBeCloseTo(28, 8); + // An unpriced model has no cost now, so it has none later either, even with a `next` price. + const bad = modelStats('bad-model', run.records); + expect(costSummary(bad, { inputPerMTok: null, outputPerMTok: null, next: { from: '2027-01-01', inputPerMTok: 2, outputPerMTok: 8 } })).toEqual({ + perAnswer: null, + per1000: null, + laterPerAnswer: null, + laterPer1000: null, + }); + }); + + it('rescoring with a three-times price gives three times the cost per 1,000 answers', () => { + const copy = structuredClone(run); + copy.prices['bad-model'] = { inputPerMTok: 3, outputPerMTok: 12 }; + scoreRun(copy); + const report = renderReport(copy); + expect(report).toContain('| **Cost per 1,000 answers** | $14.00 | $42.00 |'); + expect(report).toContain('| … relative to the baseline | 1.00x | 3.00x |'); + expect(report).toMatch(/\| G6 Cost \(not gated\) \| FAIL: mean \$0\.0420 per answer, 3\.00x the baseline's \$0\.0140; see Cost \|/); + }); + + it('percentile is nearest-rank', () => { + expect(percentile([], 50)).toBeNull(); + expect(percentile([5], 90)).toBe(5); + expect(percentile([1, 2, 3, 4], 50)).toBe(2); + expect(percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 90)).toBe(9); + }); +}); + +describe('question set v1', () => { + const { set, sha256 } = loadQuestionSet(path.resolve(__dirname, '../questions/v1.json')); + + it('covers what issue #393 asks for', () => { + const categories = new Set(set.questions.map((q) => q.category)); + for (const c of ['quran-by-reference', 'quran-by-topic', 'near-identical', 'hadith-grade', 'fiqh', 'follow-up']) { + expect(categories.has(c), c).toBe(true); + } + const languages = new Set(set.questions.map((q) => q.language)); + expect(languages.has('ar')).toBe(true); + expect([...languages].filter((l) => l !== 'ar' && l !== 'en').length).toBeGreaterThanOrEqual(2); + // The 52:48 / 68:48 pair, and follow-ups that are really multi-turn. + const refs = set.questions.flatMap((q) => q.turns.flatMap((t) => t.expectRefs ?? [])); + expect(refs).toContain('52:48'); + expect(refs).toContain('68:48'); + for (const q of set.questions.filter((x) => x.category === 'follow-up')) expect(q.turns.length).toBeGreaterThan(1); + expect(sha256).toMatch(/^[0-9a-f]{64}$/); + }); + + it('a malformed set fails loudly', () => { + const base = { id: 's', version: 1, description: '', questions: [{ id: 'a', category: 'c', language: 'en', turns: [{ text: 't' }] }] }; + const withQuestion = (q: object) => JSON.stringify({ ...base, questions: [{ ...base.questions[0], ...q }] }); + expect(() => parseQuestionSet(JSON.stringify(base))).not.toThrow(); + expect(() => parseQuestionSet(withQuestion({ language: 'xx' }))).toThrow(/not valid/); + expect(() => parseQuestionSet(withQuestion({ turns: [] }))).toThrow(/not valid/); + expect(() => parseQuestionSet(withQuestion({ turns: [{ text: 't', expectRefs: ['115:1'] }] }))).toThrow(/Quran reference/); + expect(() => parseQuestionSet(withQuestion({ typo: true }))).toThrow(/not valid/); + expect(() => parseQuestionSet(JSON.stringify({ ...base, questions: [base.questions[0], base.questions[0]] }))).toThrow(/duplicate/); + }); +}); diff --git a/apps/eval/tsconfig.json b/apps/eval/tsconfig.json new file mode 100644 index 00000000..6753c396 --- /dev/null +++ b/apps/eval/tsconfig.json @@ -0,0 +1,23 @@ +{ + "extends": "@ansari/tsconfig/base.json", + "compilerOptions": { + "lib": ["dom", "dom.iterable", "esnext"], + "noEmit": true, + "module": "esnext", + "moduleResolution": "bundler", + "isolatedModules": true, + "target": "ES2017", + // The harness runs apps/api's facilitator in process, and apps/api's own + // files import each other through `@/`. So `@/` here means what it means + // there: the same three mappings as apps/api/tsconfig.json, one directory + // over. tsx reads them from this file (it runs with apps/eval as cwd); + // vitest.config.ts repeats them. + "paths": { + "@/*": ["../api/src/*"], + "@/lib/*": ["../api/lib/*"], + "@/db/*": ["../api/db/*"] + } + }, + "include": ["**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/apps/eval/turbo.json b/apps/eval/turbo.json new file mode 100644 index 00000000..eba37fcc --- /dev/null +++ b/apps/eval/turbo.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://turborepo.com/schema.json", + "extends": ["//"], + "tasks": { + // The harness runs apps/api's facilitator in process: `@/` in tsconfig.json + // and vitest.config.ts points into apps/api, so tsc checks those files and + // the tests load them. None of that is in this package's task hash by + // default, and a workspace dependency on ansari-api would not put it there + // (a `workspace:*` dependency's file contents are not hashed). So the three + // api trees the alias reaches are inputs here. Without them an edit under + // apps/api/lib left ansari-eval#typecheck and #test at the same hash, and a + // warm cache replayed a stale pass (issue #397; verified in both directions). + // `lint` reads only this package's files and needs nothing extra. + "typecheck": { + "inputs": [ + "$TURBO_DEFAULT$", + "$TURBO_ROOT$/apps/api/src/**", + "$TURBO_ROOT$/apps/api/lib/**", + "$TURBO_ROOT$/apps/api/db/**" + ] + }, + "test": { + "inputs": [ + "$TURBO_DEFAULT$", + "$TURBO_ROOT$/apps/api/src/**", + "$TURBO_ROOT$/apps/api/lib/**", + "$TURBO_ROOT$/apps/api/db/**" + ] + } + } +} diff --git a/apps/eval/vitest.config.ts b/apps/eval/vitest.config.ts new file mode 100644 index 00000000..2d7d3f97 --- /dev/null +++ b/apps/eval/vitest.config.ts @@ -0,0 +1,23 @@ +import { defineConfig } from 'vitest/config'; +import path from 'path'; + +const api = (dir: string) => path.resolve(__dirname, '../api', dir); + +export default defineConfig({ + test: { + environment: 'node', + include: ['tests/**/*.test.ts'], + // tests/run-command.test.ts starts tsx, a cold start that can cross + // vitest's 5 s default on a loaded machine. A hang still fails, at 30 s. + testTimeout: 30_000, + }, + resolve: { + // `@/` is apps/api's alias (see tsconfig.json), in the same order as + // apps/api/vitest.config.ts: the specific prefixes before the bare one. + alias: [ + { find: '@/lib', replacement: api('lib') }, + { find: '@/db', replacement: api('db') }, + { find: '@', replacement: api('src') }, + ], + }, +}); diff --git a/apps/frontend/.eas/workflows/update.yml b/apps/frontend/.eas/workflows/update.yml index bc6acd87..f8ff9351 100644 --- a/apps/frontend/.eas/workflows/update.yml +++ b/apps/frontend/.eas/workflows/update.yml @@ -3,7 +3,8 @@ # `eas workflow:run .eas/workflows/update.yml -F platform=all -F channel=preview`. # # `runtimeVersion: fingerprint` (app.json) decides which binaries an update -# reaches: only builds whose native fingerprint matches this commit's. +# reaches: only builds whose native fingerprint matches this commit's. An Expo +# SDK upgrade changes the fingerprint, so ship a new build before its updates. name: Update on: diff --git a/apps/frontend/.gitignore b/apps/frontend/.gitignore index ae496e94..c74dd498 100644 --- a/apps/frontend/.gitignore +++ b/apps/frontend/.gitignore @@ -9,7 +9,7 @@ dist/ web-build/ expo-env.d.ts -# Uniwind (generated on first `expo start`) +# Uniwind types (generated by `pnpm run gen:types`; Uniwind is not wired into Metro, #428) uniwind-types.d.ts # Play Store submit credentials (never commit) diff --git a/apps/frontend/Dockerfile.web b/apps/frontend/Dockerfile.web index 36bb4f94..d0e734e6 100644 --- a/apps/frontend/Dockerfile.web +++ b/apps/frontend/Dockerfile.web @@ -10,6 +10,22 @@ RUN corepack enable WORKDIR /repo +# EXPO_PUBLIC_* values are baked into the JS bundle at export time. +# Railway service variables arrive here as build args. EXPO_PUBLIC_API_URL and +# EXPO_PUBLIC_AUTH_URL are the app's ENTIRE env surface (lib/api/config.ts). +# BOTH ARE REQUIRED, in every environment (#317): the staging defaults in +# lib/api/config.ts are for local `expo start`/`expo export` only, and an image +# must never fall back to them. The guard below fails the build, naming the +# variable, when either is unset or empty, and refuses a pair that puts +# production api with non-production auth (or the reverse). It runs first, on +# plain Node, so a misconfigured service fails in seconds, before the install. +ARG EXPO_PUBLIC_API_URL +ARG EXPO_PUBLIC_AUTH_URL +# A declared ARG is visible as an env var to RUN steps in this stage, so the +# args above reach the guard and the export below without re-exporting via ENV. +COPY apps/frontend/scripts/check-web-env.mjs /tmp/check-web-env.mjs +RUN node /tmp/check-web-env.mjs + # Workspace manifests first so the dependency layer caches independently # of source changes. COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ @@ -22,16 +38,6 @@ RUN pnpm install --frozen-lockfile --filter ansari-frontend COPY apps/frontend apps/frontend -# EXPO_PUBLIC_* values are baked into the JS bundle at export time. -# Railway service variables arrive here as build args. -# EXPO_PUBLIC_API_URL and EXPO_PUBLIC_AUTH_URL are the app's ENTIRE env surface -# (lib/api/config.ts); unset, the bundle uses its baked staging defaults, -# https://api-staging.askansari.ai and https://auth-staging.askansari.ai. Set -# both on the Railway service, for the same environment. -ARG EXPO_PUBLIC_API_URL -ARG EXPO_PUBLIC_AUTH_URL -# A declared ARG is visible as an env var to RUN steps in this stage, so the -# args above reach the export below without re-exporting via ENV. ENV EXPO_NO_TELEMETRY=1 RUN pnpm --filter ansari-frontend run build:web diff --git a/apps/frontend/README.md b/apps/frontend/README.md index fb32a1b2..dc323c30 100644 --- a/apps/frontend/README.md +++ b/apps/frontend/README.md @@ -1,6 +1,6 @@ # Ansari — frontend (`apps/frontend`) -The Ansari app: an Expo (SDK 57, React Native 0.86, React 19.2) client for +The Ansari app: an Expo (SDK 58, React Native 0.88, React 19.3) client for iOS, Android and web (react-native-web), on the **Replit-sourced design** (dark mode, collapsible sidebar, source panel, a motion/layout/radius token system) and **wired end-to-end to this repo's backend** (`apps/api`) — auth, @@ -84,7 +84,12 @@ run it through turbo, or run `pnpm gen:types` first from this directory. (`https://api-staging.askansari.ai`, `https://auth-staging.askansari.ai`); override them together with `EXPO_PUBLIC_API_URL` and `EXPO_PUBLIC_AUTH_URL` in `.env.local` (see `.env.local.example`). Those are the app's only -environment variables. +environment variables. Since SDK 58 (#428), a development bundle +(`expo start`) reads the `.env*` files at runtime and lets them win over +variables set in the shell, even with `EXPO_NO_DOTENV=1`: to point a dev +build somewhere else, edit `.env.local` rather than prefixing the command. +Exports (`expo export`, the web image, EAS builds) still inline the shell's +values over the files, as before. Then: home screen (dark-mode-capable, sidebar, ambient palm-shadow layer) → ask a question and watch the answer stream in → open a past thread from the @@ -92,12 +97,20 @@ sidebar → sidebar collapses/expands (desktop) or opens as a drawer (narrow width) → open the source panel from a citation → "Log in" (rail or account corner) → About page. -### Uniwind: installed, wired, unused - -`uniwind` and Tailwind are dependencies, `metro.config.js` wraps the config -in `withUniwindConfig` (CSS entry `src/global.css`), and the `gen:types` task -generates `uniwind-types.d.ts` (gitignored; `types.d.ts` and -`uniwind-env.d.ts` are committed). The UI itself is `StyleSheet`-only, and +### Uniwind: installed, not wired, unused + +`uniwind` and Tailwind are dependencies, and the `gen:types` task generates +`uniwind-types.d.ts` (gitignored; `types.d.ts` and `uniwind-env.d.ts` are +committed). `metro.config.js` does **not** wrap the config in +`withUniwindConfig`: that wrapper replaces every `react-native` import with +Uniwind's own re-export shim, which (through uniwind 1.14.0) lacks React +Native 0.88's new exports such as `AssetRegistry`. expo-asset 58 imports it, +so with the wrapper every icon font fails on native (#428). Re-wiring is +#264's call once upstream forwards the new exports. Because `tsconfig.json` +still includes `uniwind-env.d.ts`, `` typechecks but does +nothing while Uniwind is unwired; `lib/no-classname.test.ts` fails on any JSX +`className` under `app/` and `components/` until it is re-wired (remove the +test then). The UI itself is `StyleSheet`-only, and `app/_layout.tsx` deliberately does **not** import `src/global.css`: Tailwind's preflight reset would restyle it on the web. Adopting Uniwind for new UI is a separate product decision. @@ -171,8 +184,9 @@ for five changes the upgrade forced or exposed: | `Sidebar`'s `style` prop typed as `Animated.View`'s | reanimated 4.5 typing | | `composerBottomPad` (`constants/layout.ts`) marked `'worklet'` | both screens call it inside `useAnimatedStyle`, which runs on the UI thread on native; unmarked, it threw "Tried to synchronously call a Remote Function". Pre-existing since #121; `lib/worklets.test.ts` now scans every worklet body for unmarked calls | -The React Compiler lint rules from eslint-config-expo 57 are warnings for -now (see `eslint.config.mjs`); fixing them is part of #264. +The React Compiler lint rules from eslint-config-expo (57, and 58 since +#428; both ship eslint-plugin-react-hooks v7) are warnings for now (see +`eslint.config.mjs`); fixing them is part of #264. ## Builds @@ -212,9 +226,14 @@ custom shell in `public/index.html`. Deployment is a Caddy-served Docker image (`Dockerfile.web`, built from the repo root: `docker build -f apps/frontend/Dockerfile.web .`) on Railway; `railway.toml` is the reviewable record of the dashboard settings. `EXPO_PUBLIC_API_URL` and -`EXPO_PUBLIC_AUTH_URL` are baked in at build time — set both on the Railway -service, for the same environment (or leave both unset for the staging -defaults); changing either requires a redeploy. +`EXPO_PUBLIC_AUTH_URL` are baked in at build time — both are mandatory on +every Railway web service built from `Dockerfile.web` (today staging web only; a +production `apps/frontend` service when one is created, #305), for the same +environment. Production web stays on `legacy/frontend-web` for now (#416): its own +Dockerfile, `EXPO_PUBLIC_API_V2_URL`, no such guard. The image build fails +at its guard (`scripts/check-web-env.mjs`) when either is unset or when only one +names production (the staging defaults serve local builds only); changing +either requires a redeploy. ## Layout @@ -236,6 +255,6 @@ apps/frontend/ lib/suggested-topics.ts static suggested-questions list (consumed by lib/api/hooks.ts) assets/ redrawn icons, ambient-shadow video public/ web shell: index.html, fonts, icons, manifest (scripts/build-icons.mjs) - src/global.css Uniwind/Tailwind CSS entry (wired, not imported; see above) + src/global.css Uniwind/Tailwind CSS entry (not wired, not imported; see above) vendor/api-client-react/ custom-fetch.ts (fetch runtime) + generated/api.schemas.ts (types); see above ``` diff --git a/apps/frontend/app.json b/apps/frontend/app.json index 14a84081..1607cf1d 100644 --- a/apps/frontend/app.json +++ b/apps/frontend/app.json @@ -34,7 +34,12 @@ "backgroundColor": "#E7E5E4" }, "plugins": [ - "expo-router", + [ + "expo-router", + { + "asyncRoutes": { "web": false } + } + ], "expo-font", "expo-web-browser", "expo-video", diff --git a/apps/frontend/app/chat/[id].tsx b/apps/frontend/app/chat/[id].tsx index 2f39eb21..e1027fc1 100644 --- a/apps/frontend/app/chat/[id].tsx +++ b/apps/frontend/app/chat/[id].tsx @@ -853,7 +853,7 @@ export default function ChatScreen() { question={retryQuestion} onRetry={() => send(retryQuestion)} /> - ) : null + ) : undefined } renderItem={({ item }) => ( // The question carried in from the ask is already drawn, diff --git a/apps/frontend/app/index.tsx b/apps/frontend/app/index.tsx index c9294f28..9a014bee 100644 --- a/apps/frontend/app/index.tsx +++ b/apps/frontend/app/index.tsx @@ -6,9 +6,9 @@ import { ScrollView, StyleSheet, Text, - TextInput, useWindowDimensions, View, + type TextInputInstance, } from 'react-native'; import { Feather } from '@expo/vector-icons'; import { useQueryClient } from '@tanstack/react-query'; @@ -185,7 +185,7 @@ export default function HomeScreen() { // directly through its ref and also ask the keyboard library's native // module (provably alive on device — it animates the composer) to // resign the keyboard itself. - const inputRef = useRef(null); + const inputRef = useRef(null); const closeKeyboard = () => { inputRef.current?.blur(); if (Platform.OS !== 'web') { diff --git a/apps/frontend/babel.config.js b/apps/frontend/babel.config.js index 851783fd..ffe81d7d 100644 --- a/apps/frontend/babel.config.js +++ b/apps/frontend/babel.config.js @@ -1,7 +1,7 @@ module.exports = function (api) { api.cache(true); - // babel-preset-expo 57 transforms `import.meta` by default - // (`transformImportMeta`, default true); the SDK 54 opt-in flag + // babel-preset-expo (57, and 58 since #428) transforms `import.meta` by + // default (`transformImportMeta`, default true); the SDK 54 opt-in flag // `unstable_transformImportMeta` is no longer read. return { presets: ['babel-preset-expo'], diff --git a/apps/frontend/components/AmbientVideo.tsx b/apps/frontend/components/AmbientVideo.tsx index fb9e0aba..c075f460 100644 --- a/apps/frontend/components/AmbientVideo.tsx +++ b/apps/frontend/components/AmbientVideo.tsx @@ -3,7 +3,7 @@ import { AppState, Platform, StyleSheet, - type View, + type ViewInstance, type ViewStyle, } from 'react-native'; import { Image } from 'expo-image'; @@ -528,7 +528,7 @@ const SEEK_SETTLE_MS = 200; */ function useClipBuffered( player: VideoPlayer, - hostRef: React.RefObject, + hostRef: React.RefObject, ): boolean { const [buffered, setBuffered] = useState(Platform.OS !== 'web'); @@ -664,7 +664,7 @@ function AmbientVideoPlayer({ }, [status]); const live = (Platform.OS === 'web' || ready) && !failed; - const hostRef = useRef(null); + const hostRef = useRef(null); const clipBuffered = useClipBuffered(player, hostRef); // Warm-up. On the web a browser fetches nothing until something asks it diff --git a/apps/frontend/components/ChatInput.tsx b/apps/frontend/components/ChatInput.tsx index 8c05860c..5aabecee 100644 --- a/apps/frontend/components/ChatInput.tsx +++ b/apps/frontend/components/ChatInput.tsx @@ -5,8 +5,8 @@ import { StyleSheet, TextInput, View, - type NativeSyntheticEvent, - type TextInputKeyPressEventData, + type TextInputInstance, + type TextInputKeyPressEvent, } from 'react-native'; import { BlurView } from 'expo-blur'; import { GlassView, isLiquidGlassAvailable } from 'expo-glass-effect'; @@ -300,7 +300,7 @@ export function ChatInput({ /** Fires when the question field gains or loses focus. */ onFocusChange?: (focused: boolean) => void; /** Direct handle on the field, so screens can blur it reliably. */ - inputRef?: React.Ref; + inputRef?: React.Ref; /** Clearer glass for media-backed screens (the ambient-video home). */ clearGlass?: boolean; /** Keeps the draft visible when the thread is unavailable. */ @@ -335,9 +335,7 @@ export function ChatInput({ // (Arabic transliteration and the like) is left alone. Native // keyboards never come through here with Enter; they use // submitBehavior/onSubmitEditing as before. - const submitOnEnter = ( - e: NativeSyntheticEvent, - ) => { + const submitOnEnter = (e: TextInputKeyPressEvent) => { if (Platform.OS !== 'web') return; const web = e as unknown as { key?: string; diff --git a/apps/frontend/components/SourceStack.tsx b/apps/frontend/components/SourceStack.tsx index 8c994467..17ef3940 100644 --- a/apps/frontend/components/SourceStack.tsx +++ b/apps/frontend/components/SourceStack.tsx @@ -6,6 +6,7 @@ import { type LayoutChangeEvent, type StyleProp, type ViewStyle, + type ScrollViewInstance, } from 'react-native'; import Animated, { ReduceMotion, @@ -127,7 +128,7 @@ export function SourceStack({ }) { const colors = useColors(); const reduced = useReducedMotion(); - const scrollRef = useRef(null); + const scrollRef = useRef(null); /** Where each source begins in the column, as the cards report it. */ const offsets = useRef(new Map()); /** A source asked for before its card had been laid out. */ diff --git a/apps/frontend/eslint.config.mjs b/apps/frontend/eslint.config.mjs index 9fe590c2..9d58de86 100644 --- a/apps/frontend/eslint.config.mjs +++ b/apps/frontend/eslint.config.mjs @@ -24,8 +24,8 @@ export default [ }, }, { - // SCOPED OVERRIDE (#262 -> #264). eslint-config-expo 57 ships - // eslint-plugin-react-hooks v7, whose React Compiler rules flag 26 sites + // SCOPED OVERRIDE (#262 -> #264). eslint-config-expo (57, and 58 since + // #428) ships eslint-plugin-react-hooks v7, whose React Compiler rules flag 26 sites // in code ported verbatim from the SDK 54 prototype (which never ran // eslint). They mark components the compiler skips optimising, not // runtime errors, and each fix restructures a component, which is diff --git a/apps/frontend/lib/api/config.ts b/apps/frontend/lib/api/config.ts index 387cc5b9..bf3def5b 100644 --- a/apps/frontend/lib/api/config.ts +++ b/apps/frontend/lib/api/config.ts @@ -8,7 +8,9 @@ * local `apps/api` and `apps/auth` — but staging is the default so a fresh * checkout boots without any `.env.local`. The two defaults name the SAME * environment, so an env-less build never signs in at one environment and - * calls the API of another. + * calls the API of another. The defaults serve local `expo start` and + * `expo export` only: the web image (`Dockerfile.web`) refuses to build + * without both variables (`scripts/check-web-env.mjs`, #317). * * `EXPO_PUBLIC_*` vars are inlined at bundle time, so a change here requires an * `expo start` restart to take effect. Each `process.env.EXPO_PUBLIC_*` access diff --git a/apps/frontend/lib/auth/guest.test.ts b/apps/frontend/lib/auth/guest.test.ts index 1f36bf9a..56abda79 100644 --- a/apps/frontend/lib/auth/guest.test.ts +++ b/apps/frontend/lib/auth/guest.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { generateGuestCredentials, makeGuestPassword, @@ -68,6 +68,48 @@ describe('makeGuestPassword — weakened generator fails, production passes', () }); }); +// Issue #403: the 500-draw test above failed about once in 800 runs. A random +// password that starts with "123" matches a common pattern, loses 2 points and +// scores 4 (24 of 10,000,000 draws, measured; no other pattern ever matched). +// The generator now draws again, so the property holds by construction. These +// force the draw, since waiting for chance to produce one proves nothing. +describe('makeGuestPassword: a penalised draw is drawn again', () => { + // A real generator output from the measurement, and a draw that is clean. + const PENALISED = '123!vpA^HZ@_kM'; + const CLEAN = 'k7!vpA^HZ@_kM2'; + + it('the forced draw really is below the bar the production test asserts', () => { + expect(passwordScore(PENALISED)).toBe(4); + expect(passwordScore(CLEAN)).toBe(6); + }); + + it('skips a draw that starts with "123" and returns the next one', () => { + const draws = [PENALISED, PENALISED, CLEAN]; + const draw = vi.fn(() => draws.shift() as string); + + const password = makeGuestPassword({ draw }); + + expect(password).toBe(CLEAN); + expect(passwordScore(password)).toBeGreaterThanOrEqual(5); + expect(draw).toHaveBeenCalledTimes(3); + }); + + it.each(['xPassWord9!kQzR', 'aQWERTY7!bcdEf', 'zAbC123!kQmRtY'])( + 'skips every pattern the backend penalises: %s', + (penalised) => { + expect(passwordScore(penalised)).toBeLessThan(5); + const draws = [penalised, CLEAN]; + expect(makeGuestPassword({ draw: () => draws.shift() as string })).toBe(CLEAN); + }, + ); + + it('fails loudly instead of looping forever when every draw is penalised', () => { + const draw = vi.fn(() => PENALISED); + expect(() => makeGuestPassword({ draw })).toThrow(/100 draws in a row/); + expect(draw).toHaveBeenCalledTimes(100); + }); +}); + describe('generateGuestCredentials', () => { it('produces the fixed guest identity fields', () => { const creds = generateGuestCredentials(); diff --git a/apps/frontend/lib/auth/guest.ts b/apps/frontend/lib/auth/guest.ts index 0461588b..72fe66ce 100644 --- a/apps/frontend/lib/auth/guest.ts +++ b/apps/frontend/lib/auth/guest.ts @@ -9,7 +9,7 @@ import type { RegisterInput } from './api'; * `@ansari.chat` is a normal (non-reserved) domain on the backend, so these * register like any other account. The password is built to clear the backend's * strength check (score ≥ 3) with room to spare — length ≥ 12 plus one each of - * lower/upper/digit/symbol. + * lower/upper/digit/symbol, and never one of the patterns the check penalises. * * NOTE ON PERSISTENCE: each registration creates a REAL, PERSISTENT staging * account. To avoid minting a new one on every tap, the credentials are stored @@ -61,17 +61,23 @@ export interface GuestPasswordOptions { * check that cannot fail is not evidence (lessons-critical). */ guaranteeVariety?: boolean; + /** + * Replaces the random draw of one candidate password. Tests pass it to force + * a candidate the backend would penalise and prove it is drawn again. + */ + draw?: () => string; } -export function makeGuestPassword(options: GuestPasswordOptions = {}): string { - const length = options.length ?? 14; - const charset = options.charset ?? ALNUM + SYMBOLS; - const guaranteeVariety = options.guaranteeVariety ?? true; - - if (!guaranteeVariety) { - return randomFromCharset(length, charset); - } +/** + * The backend's strength check takes 2 points off a password that matches one + * of these (`checkPasswordStrength`, packages/auth/src/password.ts). A random + * password starts with "123" about twice in a million draws (24 of 10,000,000 + * measured, issue #403), so a candidate that matches is drawn again. + */ +const PENALISED_PATTERNS = [/^123/, /password/i, /qwerty/i, /abc123/i]; +const MAX_DRAWS = 100; +function drawVaried(length: number, charset: string): string { const required = [ LOWER[randomInt(LOWER.length)], UPPER[randomInt(UPPER.length)], @@ -85,6 +91,27 @@ export function makeGuestPassword(options: GuestPasswordOptions = {}): string { return shuffle([...required, ...fill]); } +export function makeGuestPassword(options: GuestPasswordOptions = {}): string { + const length = options.length ?? 14; + const charset = options.charset ?? ALNUM + SYMBOLS; + const guaranteeVariety = options.guaranteeVariety ?? true; + + if (!guaranteeVariety) { + return randomFromCharset(length, charset); + } + + const draw = options.draw ?? (() => drawVaried(length, charset)); + for (let attempt = 0; attempt < MAX_DRAWS; attempt++) { + const password = draw(); + if (!PENALISED_PATTERNS.some((pattern) => pattern.test(password))) { + return password; + } + } + throw new Error( + `makeGuestPassword: ${MAX_DRAWS} draws in a row matched a penalised pattern`, + ); +} + /** * The display name every guest account is registered with. `store.ts` also keys * on it to classify session blobs written before `isGuest` was persisted. diff --git a/apps/frontend/lib/history-notice.test.ts b/apps/frontend/lib/history-notice.test.ts new file mode 100644 index 00000000..18cfa691 --- /dev/null +++ b/apps/frontend/lib/history-notice.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it } from 'vitest'; +import type { WireDocument, WireMessage } from '@/lib/api/wire-schemas'; +import { mapMessage } from '@/lib/api/mappers'; +import { stripStreamingCitations, stripUnbackedCitations } from '@/lib/citations'; +import { resolveCitations } from '@/lib/document-citations'; +import { answerDirection } from '@/lib/script'; + +/** + * The thread-history warning on the screen (issue #400). + * + * apps/api adds a notice to the answers of a long thread, as ordinary answer + * text. This app cuts a "Citations" heading and everything after it from what + * it shows, so a notice placed after the answer was removed from every answer + * that cited a source, live and on re-read. apps/api therefore sends it as the + * answer's FIRST paragraph. These tests put that text through the functions the + * chat screen and the mappers really use, and pin the old placement as lost, so + * the method is shown to see the loss. + * + * The sentence is apps/api's HISTORY_WARNING_MESSAGE + * (apps/api/lib/facilitator/history-limit.ts); apps/api/tests/history-limit.test.ts + * pins the same words, so a rewording has to visit both. + */ +const WARNING = + 'Note: this conversation is getting long. Please start a new conversation soon. Ansari cannot continue a conversation beyond a certain length.'; + +const BODY = 'Five prayers wash sins away [1]. Establish prayer for remembrance [2].'; +const CITATIONS = + '**Citations**:\n' + + '[1] Sahih al-Bukhari - Chapter 9, Hadith 528 (LK id 2_9_6_528)\n' + + ' Arabic: …\n English: …\n' + + "[2] Qur'an 20:14\n"; + +/** What apps/api stores and streams for a warned, cited answer. */ +const WARNED = `${WARNING}\n\n${BODY}\n\n${CITATIONS}`; +/** The placement this replaced: the notice after the answer, so after its citations. */ +const WARNED_AFTER = `${BODY}\n\n${CITATIONS}\n\n${WARNING}`; + +// Fixtures shaped as apps/api/lib/tools/search-*.ts builds them. +const doc = (title: string, context: string, data: string): WireDocument => ({ + type: 'document', + source: { type: 'text', media_type: 'text/plain', data }, + title, + context, +}); +const Q_20_14 = doc( + 'Quran 20:14', + 'Retrieved from the Holy Quran', + JSON.stringify({ ar: 'وَأَقِمِ ٱلصَّلَوٰةَ لِذِكْرِىٓ', en: 'And establish prayer for My remembrance.' }), +); +const H_528 = doc( + 'Sahih al-Bukhari - Chapter 9: Times of the Prayers, Hadith 528 (Grade: Sahih) (LK id 2_9_6_528)', + 'Retrieved from hadith collections', + JSON.stringify({ + ar: 'أَرَأَيْتُمْ لَوْ أَنَّ نَهَرًا', + en: 'If there was a river at the door…', + grade: 'Sahih', + collection: 'Sahih al-Bukhari', + chapter: 'Times of the Prayers', + lk_id: '2_9_6_528', + }), +); + +const stored = (content: string): WireMessage => + ({ id: 'm1', role: 'assistant', content, created_at: '2026-11-17T00:00:00.000Z' }) as WireMessage; + +describe('a warned answer with a Citations section keeps its warning', () => { + it('re-read with its source documents: the warning opens the answer, the markers resolve', () => { + const { content, citations } = resolveCitations(WARNED, [Q_20_14, H_528], 'm1'); + expect(content).toBe(`${WARNING}\n\n${BODY}`); + expect(citations.map((c) => c.marker)).toEqual([1, 2]); + }); + + it('re-read through the message mapper, as the thread screen gets it', () => { + const message = mapMessage(stored(WARNED), 'c1', [Q_20_14, H_528]); + expect(message?.content).toBe(`${WARNING}\n\n${BODY}`); + expect(message?.citations).toHaveLength(2); + }); + + it('re-read with documents none of which the section names: still there', () => { + const { content } = resolveCitations(WARNED, [doc('Quran 2:255', 'Retrieved from the Holy Quran', '{}')], 'm1'); + expect(content.startsWith(`${WARNING}\n\n`)).toBe(true); + expect(content).not.toContain('Citations'); + }); + + it('re-read with no documents at all: still there', () => { + expect(stripUnbackedCitations(WARNED)).toBe( + `${WARNING}\n\nFive prayers wash sins away. Establish prayer for remembrance.`, + ); + }); + + it('while it streams: shown whole from the moment it has arrived, at every later length', () => { + const arrived = WARNING.length; + let shownAt = 0; + for (let length = arrived; length <= WARNED.length; length++) { + const shown = stripStreamingCitations(WARNED.slice(0, length)); + if (shown.startsWith(WARNING)) shownAt++; + else throw new Error(`warning missing at stream length ${length}: ${JSON.stringify(shown.slice(0, 60))}`); + } + expect(shownAt).toBe(WARNED.length - arrived + 1); + expect(stripStreamingCitations(WARNED)).toBe( + `${WARNING}\n\nFive prayers wash sins away. Establish prayer for remembrance.`, + ); + }); + + it('is not read as a Citations heading, on its own line or as the whole answer so far', () => { + expect(stripUnbackedCitations(WARNING)).toBe(WARNING); + expect(stripStreamingCitations(`${WARNING}\n\n`)).toBe(WARNING); + }); +}); + +describe('the placement it replaced: a warning after the Citations section is cut with it', () => { + it('on every display path', () => { + expect(resolveCitations(WARNED_AFTER, [Q_20_14, H_528], 'm1').content).not.toContain(WARNING); + expect(mapMessage(stored(WARNED_AFTER), 'c1', [Q_20_14, H_528])?.content).not.toContain(WARNING); + expect(stripUnbackedCitations(WARNED_AFTER)).not.toContain(WARNING); + expect(stripStreamingCitations(WARNED_AFTER)).not.toContain(WARNING); + }); +}); + +describe('an English warning ahead of an Arabic answer', () => { + const SENTENCE = 'الصبر هو حبس النفس على ما تكره ابتغاء مرضاة الله تعالى، وهو من أعظم أخلاق المؤمنين.'; + + it('an answer of ordinary length still reads right-to-left', () => { + const answer = Array.from({ length: 6 }, () => SENTENCE).join(' '); + expect(answerDirection(answer)).toBe('rtl'); + expect(answerDirection(`${WARNING}\n\n${answer}`)).toBe('rtl'); + }); + + it('a one-sentence answer is outweighed by it and reads left-to-right: a known cost', () => { + expect(answerDirection(SENTENCE)).toBe('rtl'); + expect(answerDirection(`${WARNING}\n\n${SENTENCE}`)).toBe('ltr'); + }); +}); diff --git a/apps/frontend/lib/no-classname.test.ts b/apps/frontend/lib/no-classname.test.ts new file mode 100644 index 00000000..2999bee6 --- /dev/null +++ b/apps/frontend/lib/no-classname.test.ts @@ -0,0 +1,65 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import ts from 'typescript'; +import { describe, expect, it } from 'vitest'; + +// Uniwind is installed but NOT wired into Metro (#428: its react-native shim +// lacks RN 0.88's AssetRegistry; see metro.config.js). tsconfig still includes +// uniwind-env.d.ts, so `` typechecks, and with the wrapper +// unwired it silently does nothing on every platform. This scan keeps +// `className` out of the UI until Uniwind is re-wired (#264): remove it then. + +const root = path.resolve(__dirname, '..'); +const SCANNED_DIRS = ['app', 'components']; + +function walk(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return walk(full); + return /\.tsx$/.test(entry.name) && !/\.test\.tsx$/.test(entry.name) ? [full] : []; + }); +} + +/** `file:line` of every JSX `className` attribute (comments and strings never match). */ +function classNameSites(file: string, text: string): string[] { + const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const sites: string[] = []; + const visit = (node: ts.Node) => { + if (ts.isJsxAttribute(node) && node.name.getText(sf) === 'className') { + const { line } = sf.getLineAndCharacterOfPosition(node.getStart(sf)); + sites.push(`${path.relative(root, file)}:${line + 1}`); + } + ts.forEachChild(node, visit); + }; + visit(sf); + return sites; +} + +describe('no className while Uniwind is unwired (#428)', () => { + const files = SCANNED_DIRS.flatMap((dir) => walk(path.join(root, dir))); + + it('scans the UI sources', () => { + expect(files.length).toBeGreaterThan(20); + }); + + it('app/ and components/ set no className', () => { + const sites = files.flatMap((file) => classNameSites(file, readFileSync(file, 'utf8'))); + expect(sites).toEqual([]); + }); + + it('the scan flags a planted className', () => { + const planted = 'export const A = () => ;'; + expect(classNameSites(path.join(root, 'components', 'Planted.tsx'), planted)).toEqual([ + 'components/Planted.tsx:1', + ]); + }); + + it('the scan ignores near-misses: comments, strings and other props', () => { + const nearMiss = [ + '// in a comment', + 'const doc = \'\';', + 'export const B = () => ;', + ].join('\n'); + expect(classNameSites(path.join(root, 'components', 'NearMiss.tsx'), nearMiss)).toEqual([]); + }); +}); diff --git a/apps/frontend/metro.config.js b/apps/frontend/metro.config.js index e03cfd4b..fe99549e 100644 --- a/apps/frontend/metro.config.js +++ b/apps/frontend/metro.config.js @@ -1,11 +1,12 @@ const { getDefaultConfig } = require("expo/metro-config"); -const { withUniwindConfig } = require("uniwind/metro"); -const config = getDefaultConfig(__dirname); - -// Uniwind stays wired but unused: the ported UI is StyleSheet-only, and -// src/global.css is deliberately not imported by app/_layout.tsx (Tailwind's -// preflight reset would restyle it on web). Adopting it is #264's call. -module.exports = withUniwindConfig(config, { - cssEntryFile: "./src/global.css", -}); +// Uniwind is installed but NOT wired into Metro. Its Metro wrapper +// (`withUniwindConfig` from "uniwind/metro") redirects every `react-native` +// import to its own re-export shim, and that shim (checked through uniwind +// 1.14.0, the latest on 2026-11-24) does not forward React Native 0.88's new +// exports such as `AssetRegistry`. expo-asset 58 imports `AssetRegistry` from +// "react-native", so with the wrapper every @expo/vector-icons font fails to +// load on native (#428). Nothing in the app uses Uniwind (the UI is +// StyleSheet-only); `gen:types` still generates its types. Re-wiring it is +// #264's call, once upstream forwards the new exports. +module.exports = getDefaultConfig(__dirname); diff --git a/apps/frontend/package.json b/apps/frontend/package.json index c7014359..2a7d97da 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -27,63 +27,62 @@ "@expo-google-fonts/amiri": "^0.4.1", "@expo-google-fonts/inter": "^0.4.2", "@expo-google-fonts/literata": "^0.4.3", - "@expo/metro-runtime": "~57.0.16", + "@expo/metro-runtime": "~58.0.17", "@expo/vector-icons": "^15.1.1", "@react-native-async-storage/async-storage": "2.2.0", "@stardazed/streams-text-encoding": "^1.0.2", "@tanstack/react-query": "^5.104.1", "@ungap/structured-clone": "^1.3.3", - "expo": "~57.0.27", - "expo-blur": "~57.0.3", - "expo-clipboard": "~57.0.2", - "expo-constants": "~57.0.21", - "expo-dev-client": "~57.0.19", - "expo-font": "~57.0.4", - "expo-glass-effect": "~57.0.4", - "expo-haptics": "~57.0.3", - "expo-image": "~57.0.5", - "expo-linear-gradient": "~57.0.2", - "expo-linking": "~57.0.12", - "expo-navigation-bar": "~57.0.3", - "expo-router": "~57.0.25", - "expo-secure-store": "~57.0.4", - "expo-splash-screen": "~57.0.9", - "expo-status-bar": "~57.0.0", - "expo-symbols": "~57.0.3", - "expo-system-ui": "~57.0.4", - "expo-updates": "~57.0.25", - "expo-video": "~57.0.5", - "expo-web-browser": "~57.0.3", - "react": "19.2.3", - "react-dom": "19.2.3", - "react-native": "0.86.3", - "react-native-gesture-handler": "~2.32.0", - "react-native-keyboard-controller": "1.21.9", - "react-native-reanimated": "4.5.1", - "react-native-safe-area-context": "~5.7.0", - "react-native-screens": "~4.26.0", - "react-native-svg": "15.15.4", - "react-native-web": "^0.21.2", - "react-native-worklets": "0.10.1", + "expo": "~58.0.26", + "expo-blur": "~58.0.6", + "expo-clipboard": "~58.0.4", + "expo-constants": "~58.0.16", + "expo-dev-client": "~58.0.21", + "expo-font": "~58.0.12", + "expo-glass-effect": "~58.0.5", + "expo-haptics": "~58.0.8", + "expo-image": "~58.0.18", + "expo-linear-gradient": "~58.0.4", + "expo-linking": "~58.0.17", + "expo-navigation-bar": "~58.0.4", + "expo-router": "~58.0.32", + "expo-secure-store": "~58.0.3", + "expo-splash-screen": "~58.0.14", + "expo-status-bar": "~58.0.5", + "expo-symbols": "~58.0.5", + "expo-system-ui": "~58.0.7", + "expo-updates": "~58.0.22", + "expo-video": "~58.0.14", + "expo-web-browser": "~58.1.0", + "react": "19.3.0", + "react-dom": "19.3.0", + "react-native": "0.88.1", + "react-native-gesture-handler": "~3.3.0", + "react-native-keyboard-controller": "1.22.7", + "react-native-reanimated": "4.7.1", + "react-native-safe-area-context": "~5.11.1", + "react-native-screens": "~4.30.1", + "react-native-svg": "15.16.0", + "react-native-web": "^0.21.4", + "react-native-worklets": "0.13.0", "tailwindcss": "^4.3.2", - "uniwind": "^1.12.2", - "zod": "^3.25.76", - "zod-validation-error": "^3.5.4" + "uniwind": "^1.14.0", + "zod": "^4.6.7" }, "devDependencies": { "@ansari/eslint-config": "workspace:*", "@ansari/tsconfig": "workspace:*", "@testing-library/dom": "^10.4.1", "@testing-library/react": "^16.3.2", - "@types/react": "~19.2.15", - "@types/react-dom": "^19.2.4", - "babel-preset-expo": "^57.0.14", + "@types/react": "~19.3.0", + "@types/react-dom": "^19.3.0", + "babel-preset-expo": "^58.0.26", "eslint": "catalog:", - "eslint-config-expo": "^57.0.2", + "eslint-config-expo": "^58.0.4", "jsdom": "^26.1.0", "prettier": "^3.8.3", "sharp": "^0.35.5", "typescript": "catalog:", - "vitest": "^3.2.7" + "vitest": "^5.1.1" } } diff --git a/apps/frontend/railway.toml b/apps/frontend/railway.toml index c04eee5c..587aa008 100644 --- a/apps/frontend/railway.toml +++ b/apps/frontend/railway.toml @@ -11,7 +11,13 @@ # same PR. See the "Railway service configuration" block in RELEASE.md. # # Service variables (dashboard; baked into the bundle at build time by -# Dockerfile.web, so a change needs a redeploy), one environment per pair: +# Dockerfile.web, so a change needs a redeploy), one environment per pair. +# BOTH ARE MANDATORY on EVERY web service built from Dockerfile.web (today staging +# web only; a production apps/frontend service when one is created, #305): +# Dockerfile.web's guard (scripts/check-web-env.mjs, #317) fails the build when +# either is unset or empty, and when one names production and the other does not. +# Production web stays on legacy/frontend-web for now (#416): its own Dockerfile, +# EXPO_PUBLIC_API_V2_URL, no such guard; neither variable below is needed on it. # EXPO_PUBLIC_API_URL https://api.askansari.ai (staging: https://api-staging.askansari.ai) # EXPO_PUBLIC_AUTH_URL https://auth.askansari.ai (staging: https://auth-staging.askansari.ai) diff --git a/apps/frontend/scripts/check-web-env.mjs b/apps/frontend/scripts/check-web-env.mjs new file mode 100644 index 00000000..30b05765 --- /dev/null +++ b/apps/frontend/scripts/check-web-env.mjs @@ -0,0 +1,94 @@ +/** + * Build guard for the web image (#317), run by `Dockerfile.web` before + * `build:web`: + * + * node scripts/check-web-env.mjs + * + * `EXPO_PUBLIC_API_URL` and `EXPO_PUBLIC_AUTH_URL` are baked into the bundle + * at export time. Unset, `lib/api/config.ts` falls back to the STAGING hosts, + * so a production image built without them would build, deploy green, and + * sign real users in against staging. This turns that into a build failure. + * + * - Both are required in EVERY environment (no production flag: a flag is a + * check that passes by never being set). Staging sets its staging values. + * - Each must be an http(s) URL with a host. (`new URL` alone is not + * enough: `api.askansari.ai:443` parses, as scheme `api.askansari.ai:` + * with an empty host, and would slip past the pair check.) + * - A production api host and the production auth host only come as a + * pair: one without the other fails, showing both values. + * + * Plain Node, no dependencies: the image installs with + * `--filter ansari-frontend`, so root devDependencies are absent. + */ +import { fileURLToPath } from 'node:url'; + +/** Both domains of the production `backend` service (docs/cutover/deploy-guide.md). */ +export const PRODUCTION_API_HOSTS = ['api.askansari.ai', 'api-35.ansari.chat']; +export const PRODUCTION_AUTH_HOST = 'auth.askansari.ai'; + +const REQUIRED = ['EXPO_PUBLIC_API_URL', 'EXPO_PUBLIC_AUTH_URL']; + +/** The URL's hostname, or null unless it is an http(s) URL with a host. */ +function hostOf(value) { + let url; + try { + url = new URL(value); + } catch { + return null; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; + return url.hostname || null; +} + +/** + * Check the web build environment. Returns the list of problems; empty means + * the build may proceed. + * + * @param {Record} env + * @returns {string[]} + */ +export function checkWebEnv(env) { + const errors = []; + const values = {}; + for (const name of REQUIRED) { + const value = env[name]?.trim(); + if (!value) { + errors.push( + `${name} is unset or empty. Set it as a build variable on the web service ` + + `(it is baked into the bundle; the staging default is never used in an image).`, + ); + } else if (hostOf(value) === null) { + errors.push(`${name} is not an http(s) URL with a host: ${JSON.stringify(value)}`); + } else { + values[name] = value; + } + } + if (errors.length > 0) return errors; + + const api = values.EXPO_PUBLIC_API_URL; + const auth = values.EXPO_PUBLIC_AUTH_URL; + const apiIsProd = PRODUCTION_API_HOSTS.includes(hostOf(api)); + const authIsProd = hostOf(auth) === PRODUCTION_AUTH_HOST; + if (apiIsProd !== authIsProd) { + errors.push( + `EXPO_PUBLIC_API_URL and EXPO_PUBLIC_AUTH_URL name different environments: ` + + `a production api host (${PRODUCTION_API_HOSTS.join(', ')}) and ${PRODUCTION_AUTH_HOST} ` + + `must be set together.\n` + + ` EXPO_PUBLIC_API_URL=${api}\n` + + ` EXPO_PUBLIC_AUTH_URL=${auth}`, + ); + } + return errors; +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + const errors = checkWebEnv(process.env); + if (errors.length > 0) { + for (const error of errors) console.error(`check-web-env: ${error}`); + process.exit(1); + } + console.log( + `check-web-env: ok — EXPO_PUBLIC_API_URL=${process.env.EXPO_PUBLIC_API_URL.trim()} ` + + `EXPO_PUBLIC_AUTH_URL=${process.env.EXPO_PUBLIC_AUTH_URL.trim()}`, + ); +} diff --git a/apps/frontend/scripts/check-web-env.test.mjs b/apps/frontend/scripts/check-web-env.test.mjs new file mode 100644 index 00000000..849d3931 --- /dev/null +++ b/apps/frontend/scripts/check-web-env.test.mjs @@ -0,0 +1,165 @@ +import { describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +import { checkWebEnv } from './check-web-env.mjs'; + +const STAGING = { + EXPO_PUBLIC_API_URL: 'https://api-staging.askansari.ai', + EXPO_PUBLIC_AUTH_URL: 'https://auth-staging.askansari.ai', +}; +const PRODUCTION = { + EXPO_PUBLIC_API_URL: 'https://api.askansari.ai', + EXPO_PUBLIC_AUTH_URL: 'https://auth.askansari.ai', +}; + +describe('checkWebEnv', () => { + it('passes both staging values', () => { + expect(checkWebEnv(STAGING)).toEqual([]); + }); + + it('passes both production values, with or without a trailing slash', () => { + expect(checkWebEnv(PRODUCTION)).toEqual([]); + expect( + checkWebEnv({ + EXPO_PUBLIC_API_URL: 'https://api.askansari.ai/', + EXPO_PUBLIC_AUTH_URL: 'https://auth.askansari.ai/', + }), + ).toEqual([]); + }); + + it('passes a local pair (neither is production)', () => { + expect( + checkWebEnv({ + EXPO_PUBLIC_API_URL: 'http://localhost:8000', + EXPO_PUBLIC_AUTH_URL: 'http://localhost:3001', + }), + ).toEqual([]); + }); + + it.each(['EXPO_PUBLIC_API_URL', 'EXPO_PUBLIC_AUTH_URL'])( + 'fails when %s is unset, naming it', + (name) => { + for (const base of [STAGING, PRODUCTION]) { + const env = { ...base }; + delete env[name]; + const errors = checkWebEnv(env); + expect(errors).toHaveLength(1); + expect(errors[0]).toMatch(new RegExp(`^${name} is unset or empty`)); + } + }, + ); + + it.each(['', ' '])('fails when a value is empty (%j)', (empty) => { + const errors = checkWebEnv({ ...STAGING, EXPO_PUBLIC_AUTH_URL: empty }); + expect(errors).toHaveLength(1); + expect(errors[0]).toMatch(/^EXPO_PUBLIC_AUTH_URL is unset or empty/); + }); + + it('names both variables when both are unset', () => { + const errors = checkWebEnv({}); + expect(errors).toHaveLength(2); + expect(errors[0]).toMatch(/^EXPO_PUBLIC_API_URL/); + expect(errors[1]).toMatch(/^EXPO_PUBLIC_AUTH_URL/); + }); + + it('fails a value that is not a URL', () => { + const errors = checkWebEnv({ ...PRODUCTION, EXPO_PUBLIC_API_URL: 'api.askansari.ai' }); + expect(errors).toEqual([ + 'EXPO_PUBLIC_API_URL is not an http(s) URL with a host: "api.askansari.ai"', + ]); + }); + + // `new URL('api.askansari.ai:443')` parses: scheme `api.askansari.ai:`, empty host. + it('fails a scheme-less host:port that would read as a non-production URL', () => { + const errors = checkWebEnv({ + EXPO_PUBLIC_API_URL: 'api.askansari.ai:443', + EXPO_PUBLIC_AUTH_URL: STAGING.EXPO_PUBLIC_AUTH_URL, + }); + expect(errors).toEqual([ + 'EXPO_PUBLIC_API_URL is not an http(s) URL with a host: "api.askansari.ai:443"', + ]); + }); + + it('fails a pair of scheme-less host:port values, naming both', () => { + const errors = checkWebEnv({ + EXPO_PUBLIC_API_URL: 'api.askansari.ai:443', + EXPO_PUBLIC_AUTH_URL: 'auth.askansari.ai:443', + }); + expect(errors).toHaveLength(2); + expect(errors[0]).toMatch(/^EXPO_PUBLIC_API_URL is not an http\(s\) URL/); + expect(errors[1]).toMatch(/^EXPO_PUBLIC_AUTH_URL is not an http\(s\) URL/); + }); + + it.each(['ftp://api.askansari.ai', 'file:///etc/hosts', 'mailto:a@b.c'])( + 'fails a non-http(s) URL (%s)', + (value) => { + const errors = checkWebEnv({ ...STAGING, EXPO_PUBLIC_API_URL: value }); + expect(errors).toHaveLength(1); + expect(errors[0]).toMatch(/^EXPO_PUBLIC_API_URL is not an http\(s\) URL/); + }, + ); + + it('treats api-35.ansari.chat as a production api host', () => { + expect( + checkWebEnv({ ...PRODUCTION, EXPO_PUBLIC_API_URL: 'https://api-35.ansari.chat' }), + ).toEqual([]); + const errors = checkWebEnv({ + EXPO_PUBLIC_API_URL: 'https://api-35.ansari.chat', + EXPO_PUBLIC_AUTH_URL: STAGING.EXPO_PUBLIC_AUTH_URL, + }); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain('name different environments'); + }); + + it('fails production api with staging auth, showing both values', () => { + const errors = checkWebEnv({ + EXPO_PUBLIC_API_URL: PRODUCTION.EXPO_PUBLIC_API_URL, + EXPO_PUBLIC_AUTH_URL: STAGING.EXPO_PUBLIC_AUTH_URL, + }); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain('name different environments'); + expect(errors[0]).toContain('EXPO_PUBLIC_API_URL=https://api.askansari.ai'); + expect(errors[0]).toContain('EXPO_PUBLIC_AUTH_URL=https://auth-staging.askansari.ai'); + }); + + it('fails staging api with production auth, showing both values', () => { + const errors = checkWebEnv({ + EXPO_PUBLIC_API_URL: STAGING.EXPO_PUBLIC_API_URL, + EXPO_PUBLIC_AUTH_URL: PRODUCTION.EXPO_PUBLIC_AUTH_URL, + }); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain('EXPO_PUBLIC_API_URL=https://api-staging.askansari.ai'); + expect(errors[0]).toContain('EXPO_PUBLIC_AUTH_URL=https://auth.askansari.ai'); + }); + + it('does not take a lookalike host for the production one', () => { + const errors = checkWebEnv({ + EXPO_PUBLIC_API_URL: 'https://api.askansari.ai.example.com', + EXPO_PUBLIC_AUTH_URL: PRODUCTION.EXPO_PUBLIC_AUTH_URL, + }); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain('name different environments'); + }); +}); + +describe('check-web-env CLI', () => { + const script = fileURLToPath(new URL('./check-web-env.mjs', import.meta.url)); + const run = (env) => + spawnSync(process.execPath, [script], { + env: { PATH: process.env.PATH, ...env }, + encoding: 'utf8', + }); + + it('exits 1 and names the variable when one is missing', () => { + const result = run({ EXPO_PUBLIC_API_URL: PRODUCTION.EXPO_PUBLIC_API_URL }); + expect(result.status).toBe(1); + expect(result.stderr).toContain('check-web-env: EXPO_PUBLIC_AUTH_URL is unset or empty'); + }); + + it('exits 0 for a matching pair', () => { + const result = run(PRODUCTION); + expect(result.status).toBe(0); + expect(result.stdout).toContain('check-web-env: ok'); + }); +}); diff --git a/apps/frontend/vitest.config.ts b/apps/frontend/vitest.config.ts index cd6b9fb8..8c96d664 100644 --- a/apps/frontend/vitest.config.ts +++ b/apps/frontend/vitest.config.ts @@ -26,6 +26,8 @@ export default defineConfig({ 'components/**/*.test.{ts,tsx}', 'hooks/**/*.test.{ts,tsx}', 'constants/**/*.test.{ts,tsx}', + // Build scripts (plain Node ESM, e.g. the Dockerfile.web env guard). + 'scripts/**/*.test.mjs', ], }, }); diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example new file mode 100644 index 00000000..245c2795 --- /dev/null +++ b/apps/mcp/.env.example @@ -0,0 +1,43 @@ +# apps/mcp environment. Full descriptions: apps/mcp/README.md (Environment). +# Staging values: RELEASE.md (mcp service). +# +# Leave a variable commented out to use its default. Do NOT uncomment one with an +# empty value: for MCP_ALLOWED_HOSTS and MCP_ALLOWED_ORIGINS, set-but-empty means +# "allow none", not "use the default". + +# HTTP port. Default 3000. On Railway, set it explicitly (3000) so Railway does +# not assign its own, and make the domain's target port match. +PORT=3000 + +# Ansari API origin. Default https://api.askansari.ai (PRODUCTION). +# ANSARI_API_BASE_URL=https://api-staging.askansari.ai + +# Upstream Authorization header, sent verbatim. Required for a deployment that +# calls a deployed Ansari API once /api/v2/mcp-complete enforces keys (#314); +# optional only against a local API. The value is the whole header: +# Bearer ansari_mcp__<64 letters> (this deployment's key, from the operator). +# Never commit a value. +# ANSARI_API_AUTHORIZATION= + +# Upstream client label. Default ansari-mcp. +# ANSARI_CLIENT=ansari-mcp-staging + +# Comma-separated allowed Host names, without scheme. Default localhost,127.0.0.1. +# MCP_ALLOWED_HOSTS=mcp-staging.askansari.ai + +# Comma-separated allowed browser Origin hostnames. Default: the allowed hosts. +# Requests without an Origin header always pass. +# MCP_ALLOWED_ORIGINS= + +# json = final-answer-only responses; unset = SSE (supports progress updates). +# MCP_RESPONSE_MODE=json + +# Optional release id shown in /health, logs and the served HTML. Unset, it is the +# application version. On Railway, set it in the dashboard to ${{RAILWAY_GIT_COMMIT_SHA}}. +# ANSARI_RELEASE= + +# Local development (scripts/dev.ts, `pnpm dev`): PORT defaults to 3001 and ANSARI_API_BASE_URL to +# http://localhost:3000 when unset. A local apps/api enforces the key: set ANSARI_API_AUTHORIZATION to +# "Bearer ansari_mcp_development_<64 letters>" from apps/auth's service-keys script (see README, "Local development"). +# For local dev, set PORT=3001 in your apps/mcp/.env or drop the PORT line: PORT=3000 above is for the +# Railway service and collides with apps/api under the root `pnpm dev` (the dev server warns). diff --git a/apps/mcp/README.md b/apps/mcp/README.md index 0e15ee73..2fd5cda5 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -8,23 +8,33 @@ A standalone MCP application. `answer_islamic_question` calls the Ansari API and ## Screenshots +### Web, on SAGA 1.0.1 + +New conversations in Claude web and ChatGPT web on November 5, 2026. The card was served by the Dev deployment of this application on SAGA `1.0.1` (release `68dba3e8ce291be7c3c4c35d995fe9a7c8a1e84b`), at its stable address `ui://views/answer-card.v1.html`. Each host shows the card and then its own text reply with Ansari's attribution. + +![Answer card in Claude web on SAGA 1.0.1, with the complete answer, floral branding, attribution and SAGA credit](docs/screenshots/claude-web-saga-1.0.jpg) + +![Answer card in ChatGPT web on SAGA 1.0.1, with the complete answer, floral branding, attribution and SAGA credit](docs/screenshots/chatgpt-web-saga-1.0.jpg) + +### Earlier baseline + English and Arabic answer cards rendered in ChatGPT desktop web through the Dev connection on October 23, 2026. Both rendered on first load with application revision `ee7ea4a78933544c4a96577d7ffd7276df8ae037` and public npm SAGA SDK `0.7.6-rc.1`. Arabic headings, paragraphs and lists use RTL layout and the embedded Kitab fonts. The application owner also supplied the ChatGPT and Claude mobile captures below. These captures retain their original revision identity. The application owner accepts the existing ChatGPT, Claude and earlier Alexa baseline; the [consolidated host and release evidence](https://github.com/MachineWisdomAI/saga-a2ui/pull/321) records each observation and its limits. Earlier Alexa evidence is not presented as a fresh stable-version run, and the 239 successful RC HTTP requests measure transport activity rather than rendered answers. -### English +#### English ![English answer card in ChatGPT Dev, showing the complete answer, floral branding, attribution and SAGA credit](docs/screenshots/chatgpt-dev-english.jpg) -### Arabic +#### Arabic ![Arabic answer card in ChatGPT Dev, showing RTL text, numbered floral markers and attribution](docs/screenshots/chatgpt-dev-arabic.jpg) -### ChatGPT mobile +#### ChatGPT mobile User-provided capture of the Dev answer card in ChatGPT, showing English text and floral branding. ![Ansari MCP Dev card in ChatGPT mobile](docs/screenshots/chatgpt-dev-mobile.jpg) -### Claude mobile +#### Claude mobile User-provided capture of the Dev answer card in Claude, showing Arabic text, RTL layout and numbered floral markers. @@ -36,7 +46,7 @@ SAGA is installed from the public npm registry: the stack `@saga-a2ui/react-mcp- `@saga-a2ui/core@1.0.0`, `@saga-a2ui/components@1.0.0`, `@saga-a2ui/mcp@1.0.2` and `@saga-a2ui/react@1.0.0`. SAGA versions its packages independently, so the siblings need not share the stack's version; each resolves to exactly the version the stack pins. No private registry, credential, SDK tarball, SDK workspace link or SDK-package override is involved, and the manifest pins an exact version rather than a tag or range. -The root `pnpm-workspace.yaml` keeps the SDK's documented `dompurify` and `@hono/node-server` overrides. +The root `pnpm-workspace.yaml` pins `dompurify` to 3.4.17 for `@a2ui/markdown-it` only, which otherwise pins 3.4.11 (GHSA-cg2g-xh64-v4q7, GHSA-mrv2-3pqr-j5jr). The card's address names its compatibility line, `ui://views/answer-card.v1.html` (`VIEW_MAJOR` in `src/server/view-artifact.ts`), not its bytes: every compatible release is served at the same address, and only a change an already-loaded card cannot handle increases it. `pnpm check:release --target beta` checks the pinned release against the registry and the lockfile, including that every SAGA package resolves to @@ -46,15 +56,16 @@ corresponding gate before any build or deployment. The application depends on one SAGA package, the stack `@saga-a2ui/react-mcp-stack`, plus React and React DOM, and imports only its subpaths: `/faithful-card` (`FaithfulCardApp`, `startFaithfulCardApp`, and the definition's one `.result(...)` reader that reads the whole delivered result, `useHostLink`, `readingProfile`) and its stylesheet in the view; `/content-policy` (`createContentPolicy`, `embedContentPolicy`) -in the build; `/server` (`registerPublicOperation`, `operationViewFromHtml`, `createServerBudgets`, `attachRequestLifetime`) in the -MCP server. The browser bundle holds no `/server` module. The stack's exact-version siblings come from the same release, -and its installed tree includes `@saga-a2ui/components` and `markdown-it`. SAGA owns its A2UI and Zod 3 dependency +in the build; `/server` (`registerPublicOperation`, `operationViewFromHtml`, the `RequestLifetime` type) and `/server/http` +(`createMcpFetchApp`) in the MCP server. The browser bundle holds no `/server` module. The stack pins each sibling to one exact +version, which need not be its own (SAGA versions its packages independently), and its installed tree includes +`@saga-a2ui/components` and `markdown-it`. SAGA owns its A2UI and Zod 3 dependency context; the application uses Zod 4 for MCP. Do not add direct `@a2ui/react` or `@a2ui/web_core` dependencies or cast between their schema types. The artwork owner has authorized contribution and redistribution with the application; see `assets/NOTICE.md`. ## Development -Requires Node 22.18 or later and pnpm 10.33. Install once from the repository root using its authoritative lockfile. Run the app explicitly; root build, test, typecheck and coverage retain their existing scope, while root lint includes this application. +Requires Node 22.18 or later and pnpm 10.33. Install once from the repository root using its authoritative lockfile. Root build, test, typecheck and coverage retain their existing scope; root lint and root `pnpm dev` include this application. ```sh pnpm install --frozen-lockfile --strict-peer-dependencies --filter ansari-mcp... @@ -67,7 +78,26 @@ pnpm mcp test:browser pnpm mcp start ``` -`build` writes `dist/view.html` and a bundled `dist/server/index.js`. No API/auth/frontend build or SDK source checkout is needed. `dev` runs the Node entry source (`src/node/index.ts`) after `build`. The synthetic browser harness is test-only and uses no credentials or live answers. +`build` writes `dist/view.html` and a bundled `dist/server/index.js`. No API/auth/frontend build or SDK source checkout is needed. `dev` runs the Node entry source through `scripts/dev.ts` (see below) and needs `dist/view.html`: under turbo (`pnpm dev`, `pnpm dev:mcp`) the cached `build` task runs first (it shows as its own task, `ansari-mcp#build`); run directly, `pnpm mcp build` first. The synthetic browser harness is test-only and uses no credentials or live answers. + +### Local development + +The root `pnpm dev` starts this server beside apps/api, apps/auth and the frontend (`pnpm dev:mcp` starts it alone). `scripts/dev.ts` loads `apps/mcp/.env` when it exists (git-ignored), then fills only what is still unset: `PORT` 3001 (apps/api has 3000) and `ANSARI_API_BASE_URL` `http://localhost:3000`. `.env.example` sets `PORT=3000` for the Railway service, so if you copied it to `.env`, set `PORT=3001` there or drop the line; the dev server warns when `PORT` is 3000. Hosts connect at `http://localhost:3001/mcp`. + +A local apps/api enforces the `ansari-mcp` key like a deployed one (#314). Either issue a local key and put the whole header in `apps/mcp/.env`: + +```sh +# from apps/auth/, against the local auth database (ENVIRONMENT=development): show, then confirm +pnpm exec tsx scripts/service-keys.ts create-service ansari-mcp # once, then again with --confirm ansari-mcp +pnpm exec tsx scripts/service-keys.ts create-key ansari-mcp --rate-max 120 --rate-window 60 --daily 5000 \ + --name "local dev" --client-id ansari-mcp-local # then again with --confirm +# apps/mcp/.env +ANSARI_API_AUTHORIZATION=Bearer ansari_mcp_development_<64 letters> +``` + +or run apps/api with `MCP_COMPLETE_KEY_MODE=log-only`, which serves requests without a key and logs the verdict `missing`. Without either, every tool call fails: apps/api answers 401, and the dev server warns at start. The dev entry is for local work only; deployments run `pnpm start` (`dist/`) or the Worker entry. + +To try the tools by hand, `pnpm mcp inspect` opens the MCP Inspector (latest, via npx) connected to `http://localhost:3001/mcp` over Streamable HTTP; call `answer_islamic_question` from its Tools tab. `test` runs `build` and `build:worker` itself before any test, because the tests run the built artifacts: without a fresh build they pass against a stale `dist/`. `test:browser` reads `dist/view.html` without building, so run it after `test` (as `verify` and the Turbo task order do). @@ -96,12 +126,12 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets, | --- | --- | | `PORT` | HTTP port (default 3000). | | `ANSARI_API_BASE_URL` | Ansari API origin (default `https://api.askansari.ai`). | -| `ANSARI_API_AUTHORIZATION` | Optional upstream Authorization header. Supply through the environment; never commit it. | +| `ANSARI_API_AUTHORIZATION` | Upstream Authorization header, sent verbatim: `Bearer ansari_mcp__<64 letters>`, the word `Bearer`, a space, then this deployment's `ansari-mcp` service key (its prefix names the environment it was issued in: `development`, `staging` or `production`, and only that environment's API accepts it). Required for any deployment that calls a deployed Ansari API: `/api/v2/mcp-complete` refuses a call without a valid key (401) once it enforces (#314). A local apps/api enforces too (its default); leave it unset only against a local API run with `MCP_COMPLETE_KEY_MODE=log-only`. Issued per deployment by the operator (`docs/cutover/service-keys-runbook.md`); set it with `wrangler secret put ANSARI_API_AUTHORIZATION --env ` on Workers or as a service variable on Railway, never commit it. | | `ANSARI_CLIENT` | Upstream client label (default `ansari-mcp`). | | `MCP_ALLOWED_HOSTS` | Comma-separated allowed HTTP Host names, without scheme. A configured list replaces local defaults; an explicitly empty list permits no Host. Only an absent variable defaults to localhost and 127.0.0.1. | | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. | | `MCP_RESPONSE_MODE` | `json` for modern MCP final-answer-only responses; otherwise SSE, which supports client-requested progress notifications. Older-host compatibility responses may use SSE. | -| `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. | +| `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. Absent or unsafe, the release is the application version. On Railway, set it in the dashboard to the reference `${{RAILWAY_GIT_COMMIT_SHA}}`; the code reads no `RAILWAY_*` variable. | | `MCP_VIEW_DIAGNOSTICS_ORIGIN` | Set only on a deployment being diagnosed: its own public origin, such as `https://ansari-mcp-development.up.railway.app`. The card may then connect to that one origin and reports its start-up milestones to `POST /diag/view`; this changes the card's bytes and permissions, not its address. Unset, the card, its address and its closed permissions are unchanged and the route does not exist. A value that is not a bare `https` origin (`http` only for localhost) stops startup. Implies `MCP_LOG_LEVEL=debug`. See [First-load diagnosis](#first-load-diagnosis). | | `MCP_LOG_LEVEL` | `info` (default) or `debug`. `debug` also writes the first-load measurement records; set it only on a deployment being measured. Any other value, or `info` together with `MCP_VIEW_DIAGNOSTICS_ORIGIN`, stops startup. | @@ -201,6 +231,8 @@ Artwork is embedded as actual SVG/PNG data in application-local TypeScript modul The `MCP application` workflow runs for app, lockfile, workspace, root manifest/ignore, workflow and shared lint configuration changes on PRs and develop/main pushes. It installs the root lockfile frozen, then runs app lint, typechecking, both builds, tests and browser checks. `bash apps/mcp/scripts/verify-container.sh` performs one uncached root-context Docker build and verifies health, synthetic tool calls, full attribution, safe failure/recovery and resource identity in a container with no external network or mounted files. It removes its container and image on exit. Node 22, pnpm 10.33, Docker and Chromium system dependencies are required. +The Docker image is deployed to Railway **staging** only (`mcp-staging.askansari.ai`; hosts connect at `https:///mcp`). Its settings are recorded in `apps/mcp/railway.toml` (not read by Railway: the dashboard is the live configuration) and its staging environment in `RELEASE.md`. The Workers path is not deployed. + This job needs no host credentials. Deployment and actual ChatGPT, Claude and Alexa rendering remain separate integration checks. @@ -213,3 +245,12 @@ Hono runs on Node through `@hono/node-server`; the official `@modelcontextprotoc ## MCP compatibility The tool retains the legacy server's `answer_islamic_question` name, detailed description and input help, and `readOnlyHint: true` / `openWorldHint: true` annotations. It accepts 1–4,000 characters, matching the Ansari API. The earlier experimental RC exposed `ask_ansari`; a deployment owner must refresh host discovery when adopting this tool name. The endpoint remains `/mcp`. Replacing the existing `mcp.ansari.chat` service and changing its DNS are separate rollout actions. + +### "Unable to reach" after a deploy + +The card is served at `ui://views/answer-card.v1.html` for every compatible release. Builds before SAGA 1.0 used a different address on every deploy, so a host connection created or last refreshed before this change still names an address the server no longer serves, and the card shows "Unable to reach" (the server answers that read with JSON-RPC `-32602`). + +- **ChatGPT:** in Settings → Apps (Plugins), open the app and choose **Refresh tools** once after the first deploy of this version. Later compatible deploys keep the address, so no further refresh is needed. +- **Claude:** start a new conversation. A conversation that loaded the card before the deploy may keep the old address. + +A change an already-loaded card cannot handle increases `VIEW_MAJOR` and moves the address to `v2`; refresh host connections the same way after that deploy. diff --git a/apps/mcp/docs/screenshots/chatgpt-web-saga-1.0.jpg b/apps/mcp/docs/screenshots/chatgpt-web-saga-1.0.jpg new file mode 100644 index 00000000..d962903b Binary files /dev/null and b/apps/mcp/docs/screenshots/chatgpt-web-saga-1.0.jpg differ diff --git a/apps/mcp/docs/screenshots/claude-web-saga-1.0.jpg b/apps/mcp/docs/screenshots/claude-web-saga-1.0.jpg new file mode 100644 index 00000000..d308de12 Binary files /dev/null and b/apps/mcp/docs/screenshots/claude-web-saga-1.0.jpg differ diff --git a/apps/mcp/docs/show-me-ansari-mcp.html b/apps/mcp/docs/show-me-ansari-mcp.html index a19c9bdf..f0a74f76 100644 --- a/apps/mcp/docs/show-me-ansari-mcp.html +++ b/apps/mcp/docs/show-me-ansari-mcp.html @@ -56,9 +56,8 @@ Siblings pinned by the stack: core 1.0.0 · components 1.0.0 mcp 1.0.2 · react 1.0.0 -SDK overrides: dompurify 3.4.17 - @hono/node-server 2.1.5 -@a2ui/markdown-it override: 0.2.1

The app imports only stack subpaths. SAGA is installed from the public npm registry: the stack @saga-a2ui/react-mcp-stack@1.0.1 plus the siblings it pins exactly. SAGA versions its packages independently, so the siblings need not share the stack’s version; each resolves to exactly the version the stack pins, and the repository root’s one committed lockfile records their registry integrity. No private registry, credential, SDK tarball, SDK workspace link or SDK-package override is involved. The root pnpm-workspace.yaml keeps the SDK’s documented dompurify and @hono/node-server overrides.

→
Build-time content policy

Produce self-contained HTML

Vite + single-file plugin
+Security override: @a2ui/markdown-it>dompurify 3.4.17
+@a2ui/markdown-it override: 0.2.1

The app imports only stack subpaths. SAGA is installed from the public npm registry: the stack @saga-a2ui/react-mcp-stack@1.0.1 plus the siblings it pins exactly. SAGA versions its packages independently, so the siblings need not share the stack’s version; each resolves to exactly the version the stack pins, and the repository root’s one committed lockfile records their registry integrity. No private registry, credential, SDK tarball, SDK workspace link or SDK-package override is involved. The root pnpm-workspace.yaml pins dompurify to 3.4.17 for @a2ui/markdown-it only, which otherwise pins 3.4.11 (GHSA-cg2g-xh64-v4q7, GHSA-mrv2-3pqr-j5jr).

→
Build-time content policy

Produce self-contained HTML

Vite + single-file plugin
   React + card code + CSS
   embedded Kitab + floral assets
   application + SDK identity
@@ -201,7 +200,7 @@
 FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
 OTHER DEALINGS IN THE FONT SOFTWARE.
 
-