From 57109f8f23caf9e798cd39ad410b441beeb21860 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 11:09:50 +0100 Subject: [PATCH 001/421] docs: map existing codebase --- .planning/codebase/ARCHITECTURE.md | 304 ++++++++------ .planning/codebase/CONCERNS.md | 483 ++++++++++++++-------- .planning/codebase/CONVENTIONS.md | 276 ++++++------- .planning/codebase/INTEGRATIONS.md | 350 ++++++++-------- .planning/codebase/STACK.md | 264 ++++++------ .planning/codebase/STRUCTURE.md | 635 ++++++++++++++++------------- .planning/codebase/TESTING.md | 622 +++++++++++++--------------- 7 files changed, 1618 insertions(+), 1316 deletions(-) diff --git a/.planning/codebase/ARCHITECTURE.md b/.planning/codebase/ARCHITECTURE.md index 1633ed0b1..8f03c8bc1 100644 --- a/.planning/codebase/ARCHITECTURE.md +++ b/.planning/codebase/ARCHITECTURE.md @@ -1,172 +1,236 @@ # Architecture -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## Pattern Overview -**Overall:** Full-stack Next.js App Router + Convex BaaS with domain-driven module organization +**Overall:** Next.js 16 App Router frontend + Convex backend-as-a-service (reactive serverless functions), with a thin Next.js API/Server Actions layer for direct OpenAlex calls. Identity is delegated to Clerk, payments to Stripe (via `@convex-dev/stripe`). Long-running AI pipelines run as durable Convex workflows + workpools. **Key Characteristics:** -- Next.js 16 App Router for frontend with React 19 and React Compiler enabled -- Convex as backend-as-a-service: database, real-time queries, mutations, actions, cron jobs, HTTP endpoints -- URL-driven search state (nuqs) with SWR data fetching, Zustand for client-side persistence -- Durable workflow orchestration via `@convex-dev/workflow` and `@convex-dev/workpool` for extraction pipelines -- Clerk for authentication, Stripe for billing, OpenAlex API for academic paper search -- Internationalization via `next-intl` with 6 locales +- **Dual-runtime** — Next.js handles routing, SSR shells, and public OpenAlex proxying; Convex owns all authenticated data, AI orchestration, billing, and webhooks. +- **Reactive data layer** — Clients consume Convex queries via `useQuery`/`useProtectedQuery`; mutations and actions flow through `api`/`internal` refs generated into `convex/_generated/api.ts`. +- **URL as source of truth for search** — `nuqs` parsers in `lib/search-params/parsers.ts` drive SWR fetches; Zustand only mirrors for history persistence. +- **Durable workflows** — Extraction and screening run as `@convex-dev/workflow` pipelines backed by `@convex-dev/workpool` (`convex/workpool.ts`) with retry + parallelism caps. +- **Fully internationalized** — `next-intl` with 6 locales, locale cookie set by the root proxy (`proxy.ts`). +- **OpenAI-compatible wallet gateway** — `convex/wallet/gateway/handler.ts` exposes `/api/wallet/v1/chat/completions` for third parties using an API key backed by user credits. ## Layers -**Presentation Layer (Next.js App Router):** -- Purpose: Page routing, layouts, server components, and React client components -- Location: `app/`, `components/` -- Contains: Page components, UI components, layout wrappers, client providers -- Depends on: Convex client SDK, Zustand stores, SWR, nuqs -- Used by: End users via browser - -**Search State Layer:** -- Purpose: Manages search parameters, data fetching, and results caching -- Location: `lib/search/`, `lib/store.ts`, `lib/search-params/` -- Contains: SearchProvider context, URL param parsers (nuqs), SWR fetcher, Zustand stores -- Depends on: OpenAlex API (via `app/api/openalex/search/route.ts`), nuqs, SWR -- Used by: All search-related components - -**Client-Side AI Layer:** -- Purpose: AI-powered paper screening and analysis in the browser -- Location: `lib/ai/client/`, `lib/ai/core/` -- Contains: AI executor, mode routing (BYOK vs platform credits), batch processing, prompt templates -- Depends on: Vercel AI SDK, multiple LLM providers (OpenAI, Anthropic, Google, DeepSeek, OpenRouter) -- Used by: Search results screening, paper analysis features - -**Backend Layer (Convex):** -- Purpose: All server-side logic, database, real-time subscriptions, durable workflows -- Location: `convex/` -- Contains: Schema, queries, mutations, actions, HTTP endpoints, cron jobs, webhooks -- Depends on: Convex platform, Stripe SDK, Clerk webhooks, OpenAlex HTTP API -- Used by: Frontend via Convex React client, external webhooks (Clerk, Stripe) +**Next.js App (UI + Public API):** +- Purpose: Render UI, read URL state, proxy public OpenAlex searches, expose server actions and edge middleware. +- Location: `app/`, `components/`, `hooks/`, `i18n/`, `proxy.ts`, `next.config.ts` +- Contains: RSC page files, client components, server actions, one Next.js route handler, i18n request config. +- Depends on: `lib/`, `convex/_generated/api`, Clerk, next-intl, nuqs, SWR, Convex React client. +- Used by: Browser. -**Shared Utilities:** -- Purpose: Cross-cutting utilities, types, constants, formatting +**Shared Client Lib:** +- Purpose: Reusable client/server utilities — types, Zustand stores, AI client router, SWR hooks, filter builders, toast system, download/export helpers, PostHog wrappers. - Location: `lib/` -- Contains: Type definitions, utility functions, constants, validation, formatting -- Depends on: Zod (validation), date-fns -- Used by: Both frontend components and server actions +- Contains: `lib/store.ts` (Zustand), `lib/search/` (SWR provider), `lib/ai/client/`, `lib/ai/core/`, `lib/ai/server/providers.ts`, `lib/types/`, `lib/filters/`, `lib/search-params/`, `lib/toast/`, `lib/auth/`, `lib/feature-flags/`, `lib/extraction/`, `lib/hooks/`, `lib/openalex.ts`. +- Depends on: `@sickrin/openalex-sdk`, `ai` SDK, Clerk client hooks, nuqs, zod, date-fns. +- Used by: `app/`, `components/`, some `convex/` modules that share `lib/ai/core/` schemas and `lib/pdf/download.ts`. + +**Convex Backend:** +- Purpose: Authoritative data store, auth-aware queries/mutations/actions, durable workflows, HTTP webhooks, rate limiting, scheduled crons, feature flag gating. +- Location: `convex/` +- Contains: `schema.ts` (all tables + indexes), `http.ts` (Stripe + wallet + OAuth routes), `crons.ts`, per-domain folders (`wallet/`, `credits/`, `subscriptions/`, `extraction/`, `screening/`, `library/`, `zotero/`, `models/`, `users/`, `featureFlags/`, `apiKeys/`, `maintenance/`), shared helpers in `convex/lib/`, generated API in `convex/_generated/`. +- Depends on: Convex components `@convex-dev/stripe`, `@convex-dev/rag`, `@convex-dev/workflow`, `@convex-dev/workpool` (wired in `convex/convex.config.ts`), `convex-helpers` (rate limiting), `ai` SDK providers, `openai`, `zod`. +- Used by: `app/` via generated `api` + Clerk-authenticated `ConvexProviderWithClerk`; external AI clients via wallet HTTP gateway. + +**Integration Edge:** +- Purpose: Receive webhooks and OAuth callbacks, register CORS routes. +- Location: `convex/http.ts`, `convex/webhooks/clerk.ts`, `convex/zotero/actions.ts` +- Endpoints: Clerk user sync (`POST /webhooks/clerk`), Stripe events (`POST /webhooks/stripe`, wired by `registerRoutes` from `@convex-dev/stripe`), Zotero OAuth callback (`GET /api/zotero/callback`), OpenAI-compatible wallet routes (`POST /api/wallet/v1/chat/completions`, `GET /api/wallet/v1/models`, `GET /api/wallet/balance`). +- Depends on: Stripe webhook signing, Svix for Clerk signature, encrypted API key store (`convex/apiKeys/`). +- Used by: Stripe, Clerk, Zotero, external consumers of the wallet API. ## Data Flow -**Search Flow:** +**Interactive search flow (most common):** -1. User enters query on home page (`app/page.tsx`) -> creates search ID -> navigates to `app/results/[searchId]/page.tsx` -2. `SearchProvider` (`lib/search/provider.tsx`) reads URL params via nuqs as source of truth -3. SWR fetcher calls `getSearchResultsWithFilters()` (`lib/search-utils.ts`) which hits OpenAlex API -4. Results rendered in `results-list.tsx`, filters managed via URL params synced to Zustand store -5. Search history persisted in Zustand store with `persist` middleware (localStorage) +1. User types into `components/home/SearchInput.tsx` (rendered inside `components/PageContent.tsx`). Query lives in `useCurrentQueryStore` from `lib/store.ts`. +2. On submit, `lib/search/actions.ts` → `submitNewSearch` builds filters via `useCreateSearchFilters` (`lib/hooks.ts`) and returns a URL. `app/page.tsx` routes to `/results/[searchId]` using Next.js `router.push`. +3. `app/results/layout.tsx` → `results-client-layout.tsx` wraps children with `` + `` (`lib/search/provider.tsx`). +4. `SearchProvider` reads URL params via `useQueryStates(searchParamsParsers, ...)` from `lib/search-params/parsers.ts`, builds a stable SWR key, and calls `getSearchResultsWithFilters` (`lib/search-utils.ts`) — which delegates to the `"use server"` action in `app/actions/openalex.ts` using the singleton client in `lib/openalex.ts` (`@sickrin/openalex-sdk`). +5. PostHog events are captured via `lib/posthog-search.ts` on success/failure. +6. `components/results-page-content.tsx` consumes `useSearch()` and renders results through `components/results-list.tsx`. -**Extraction Workflow (Convex Durable Workflow):** +**Extraction pipeline (durable workflow):** -1. User creates extraction job with questions -> `convex/extraction/mutations.ts` creates job record -2. `runExtractionWorkflow` (`convex/extraction/workflow.ts`) orchestrated by `@convex-dev/workflow` -3. Step 1: Fetch papers from OpenAlex/Zotero/manual sources -4. Step 2: Create paper records, deduplicate -5. Step 3: Enqueue each paper to `pdfProcessingPool` (`convex/workpool.ts`, max parallelism 3) -6. Per-paper: Download PDF -> Index in RAG (`@convex-dev/rag`) -> Extract answers via AI -> Store results -7. Job status updates in real-time via Convex reactive queries +1. `components/extraction/job-creator.tsx` → Convex mutation `api.extraction.mutations.createJob` writes to `extractionJobs`/`extractionQuestions`. +2. Mutation schedules the workflow with `workflow.start(internal.extraction.workflow.runExtractionWorkflow, ...)` where `workflow` is the `WorkflowManager` from `convex/workflow.ts`. +3. `convex/extraction/workflow.ts#runExtractionWorkflow` runs as a durable `step.*` pipeline: fetches papers from OpenAlex (`internal.extraction.actions.fetchPapersFromHistory`), dedupes via `convex/extraction/dedupe.ts#buildDedupeKey`, inserts paper records, then enqueues each paper onto the PDF `pdfProcessingPool` (`convex/workpool.ts`). +4. `convex/extraction/workpoolActions.ts` runs Node actions (`"use node"`): `downloadPdf` (`lib/pdf/download.ts`), `extractPdfJsTextPages`, RAG indexing via `@convex-dev/rag`, answer generation via `ai` SDK with provider clients from `lib/ai/server/providers.ts`. +5. Results write back to `extractionResults`, `extractionEvidenceUnits`, and `extractionResultReviews`; the frontend subscribes via `useProtectedQuery(api.extraction.queries.getJobInternal, …)` for live progress. -**Authentication Flow:** +**Billing + credits:** -1. Clerk handles sign-in/sign-up (`app/sign-in/`, `app/sign-up/`) -2. `ConvexProviderWithClerk` (`components/providers/convex-provider.tsx`) bridges Clerk auth to Convex -3. `AuthReadinessProvider` calls `ensureUser` mutation on auth to sync Clerk user to Convex `users` table -4. Clerk webhook (`convex/webhooks/clerk.ts`) at `/webhooks/clerk` syncs user updates/deletions +1. Stripe webhooks hit `convex/http.ts` via `registerRoutes` from `@convex-dev/stripe`. +2. Each event is wrapped by `runAuditedStripeHandler` (`convex/lib/stripeWebhookHandlers.ts`) which writes to `stripeEventLogs` for idempotency. +3. Successful events call into `convex/credits/` (e.g., `internal.credits.internal.grantPurchasedCreditsFromPaymentIntent`) or `convex/subscriptions/` to mutate `credits`, `creditTransactions`, and `subscriptions` tables. +4. Hourly crons in `convex/crons.ts` reconcile paid invoices and check subscription status. +5. Client reads balances via `api.credits.queries.getBalance` subscribed through the Convex reactive client. -**Billing Flow:** +**Wallet API gateway (outbound AI proxy):** -1. Stripe webhooks registered at `/webhooks/stripe` via `@convex-dev/stripe` (`convex/http.ts`) -2. Subscription events -> `convex/subscriptions/` handles plan changes with idempotent handlers -3. Invoice/payment events -> `convex/credits/` grants/reverses credits with dedup gates -4. Credit usage tracked per extraction via `creditTransactions` table -5. Hourly cron reconciliation ensures Stripe and Convex stay in sync (`convex/crons.ts`) +1. External client calls `POST /api/wallet/v1/chat/completions` with `Authorization: Bearer `. +2. `convex/wallet/gateway/handler.ts#handleChatCompletions` validates the key via `internal.wallet.nodeActions.validateKey` (hashed lookup on `walletKeys`). +3. Request parsed with `parseRequest.ts`, forwarded to the relevant AI SDK provider using `lib/ai/server/providers.ts#getProviderModel`, and streamed back as SSE. +4. `cost.ts` computes usage + credits; `withUserCreditsBatch` deducts from `credits`/`creditTransactions`. +5. CORS is managed by `corsHeaders`/`handleCors` and the per-method `http.route` entries. **State Management:** - -- **URL State (Source of Truth for Search):** nuqs manages search params in URL; `SearchProvider` reads them -- **Client Persistence:** Zustand stores with `persist` middleware for search history, bookmarks, ratings, AI settings (`lib/store.ts`) -- **Server State:** Convex database is the source of truth for users, subscriptions, credits, extraction jobs, library items -- **Real-time:** Convex reactive queries auto-update UI when server data changes +- URL (`nuqs`) is the source of truth for search filters, pagination, and sorts — see `lib/search-params/parsers.ts` and `lib/search/provider.tsx`. +- `lib/store.ts` (Zustand + `persist`) holds: ratings, search history, UI toggles, focus-mode settings, keyword expansion bookmarks, current query, AI config, sidebar dimensions. +- Convex provides live server state via `useProtectedQuery` (`lib/auth/use-auth-query.ts`) which gates queries until `useAuthReadiness().canRunProtectedQueries` is true. +- Feature flags preloaded via `preloadQuery(api.featureFlags.queries.getAll)` in `app/layout.tsx` and exposed through `lib/feature-flags/provider.tsx`. ## Key Abstractions -**Search System:** -- Purpose: Academic paper search with complex filtering -- Examples: `lib/search/provider.tsx`, `lib/search/types.ts`, `lib/search-params/parsers.ts` -- Pattern: URL-as-state via nuqs, SWR for fetching, context provider for distribution +**`SearchProvider` (React context + SWR):** +- Purpose: Single source for all results-page search state (URL ↔ SWR ↔ Zustand history mirror). +- Examples: `lib/search/provider.tsx`, `lib/search/types.ts`, `lib/search/initializer.tsx` +- Pattern: Context provider wrapping a single SWR instance; URL changes drive refetches; setters update URL and opportunistically sync to Zustand for history persistence. + +**Convex function layering per domain:** +- Purpose: Split public-facing queries/mutations from `"use node"` actions and internal helpers. +- Examples: `convex/extraction/queries.ts`, `convex/extraction/mutations.ts`, `convex/extraction/actions.ts`, `convex/extraction/workpoolActions.ts`, `convex/extraction/workflow.ts` +- Pattern: Every major domain has `queries.ts`, `mutations.ts`, `actions.ts`, and for long-running work a `workflow.ts` + `workpoolActions.ts`. Shared policy/helper logic lives in domain-local `lib/` subfolders (e.g., `convex/credits/lib/`, `convex/subscriptions/lib/`). -**Extraction Pipeline:** -- Purpose: AI-powered data extraction from academic papers -- Examples: `convex/extraction/workflow.ts`, `convex/extraction/actions.ts`, `convex/extraction/prompts.ts` -- Pattern: Durable workflow with workpool parallelism, RAG indexing, citation grounding +**Workflow + Workpool:** +- Purpose: Durable, retry-safe execution for PDF processing and bulk screening. +- Examples: `convex/workflow.ts` (`WorkflowManager`, 10-way parallelism), `convex/workpool.ts` (`pdfProcessingPool` 3-way, `screeningPool` 5-way) +- Pattern: Workflows orchestrate steps (`step.runQuery`, `step.runAction`); workpools process fan-out work units with independent retry budgets; cross-pool cancellation is avoided by keeping extraction and screening in separate pools. -**Credit System:** -- Purpose: Usage-based billing with free and paid credit pools -- Examples: `convex/credits/internal.ts`, `convex/credits/actions.ts`, `convex/credits/lib/` -- Pattern: Dual balance (free/paid), idempotent grant/deduct via Stripe dedup keys +**Wallet gateway:** +- Purpose: OpenAI-compatible relay so other apps (registered origins) consume credits through a single endpoint. +- Examples: `convex/wallet/gateway/handler.ts`, `convex/wallet/gateway/parseRequest.ts`, `convex/wallet/gateway/formatResponse.ts`, `convex/wallet/gateway/cost.ts`, `convex/wallet/gateway/reasoning.ts`, `convex/wallet/nodeActions.ts` +- Pattern: `httpAction` handlers in `convex/http.ts` route directly to pure functions; cost accounting and credit deduction happen in a single transactional helper. -**Library:** -- Purpose: User's saved/rated paper collection with collections -- Examples: `convex/library/mutations.ts`, `convex/library/queries.ts`, `components/library/` -- Pattern: Convex tables with full-text search index, many-to-many via junction table +**Error envelopes:** +- Purpose: Unified error codes across Convex + UI. +- Examples: `convex/lib/errors.ts` (`ErrorCode` union, `createError`), `lib/toast/error-resolver.ts`, `lib/toast/action-routing.ts` +- Pattern: Backend throws `ConvexError<{ code, message }>`; `lib/toast/` resolves codes into localized messages and optional actions (e.g. "Upgrade plan"). -**AI Integration:** -- Purpose: Multi-provider AI for screening and extraction -- Examples: `lib/ai/client/router.ts`, `lib/ai/core/execute.ts`, `convex/ai/` -- Pattern: BYOK (bring your own key) + platform credits mode routing, Vercel AI SDK +**Feature flags:** +- Purpose: DB-driven feature gates with tier gating. +- Examples: `convex/featureFlags/queries.ts`, `convex/featureFlags/guard.ts`, `lib/feature-flags/registry.ts`, `lib/feature-flags/provider.tsx`, `lib/feature-flags/hook.ts` +- Pattern: Flags preloaded in root layout, resolved in provider context, consumed via `useFeatureFlag("flag_key")`, enforced server-side in `convex/featureFlags/guard.ts`. ## Entry Points -**Next.js App Router:** +**Next.js Root Layout:** - Location: `app/layout.tsx` -- Triggers: All page loads -- Responsibilities: Provider tree setup (NextIntl -> Theme -> Convex/Clerk -> Config -> Nuqs -> Tooltips), sidebar + mobile navbar layout - -**API Route:** +- Triggers: Every page request. +- Responsibilities: Load locale + messages, preload feature flags via `preloadQuery`, wire providers — `ThemeProvider`, `ConvexClientProvider` (which nests `ClerkProvider` + `ConvexProviderWithClerk` + `FeatureFlagProvider`), `ConfigProvider`, `NuqsAdapter`, `QuerySyncProvider`, `TooltipProvider`, mount `AppSidebar` + `MobileNavbar`, `AuthRouteGate`, `Toaster`, `ConfirmationHost`, `CookieConsentBanner`, and `ConsentAwareGoogleAnalytics`. + +**Home page:** +- Location: `app/page.tsx` → `components/PageContent.tsx` +- Triggers: `/` visit. +- Responsibilities: Render hero + `SearchInput`, detect search mode, optionally call `useEnhanceSearchQuery()` for AI expansion, submit to `/results/[searchId]`. + +**Results pages:** +- Location: `app/results/layout.tsx` → `app/results/results-client-layout.tsx` (wraps with `SearchInitializer` + `SearchProvider`); `app/results/[searchId]/page.tsx` renders `components/results-page-content.tsx`. +- Triggers: `/results`, `/results/[searchId]`, `/results/[searchId]/history`. +- Responsibilities: Parse URL params, fetch OpenAlex results via the `"use server"` action in `app/actions/openalex.ts`, render list + sidebar filters. + +**Extraction pages:** +- Location: `app/extraction/page.tsx`, `app/extraction/new/page.tsx`, `app/extraction/[jobId]/page.tsx` +- Triggers: Authenticated navigation to `/extraction*`. +- Responsibilities: List jobs via `api.extraction.queries.getMyJobs`, create new jobs through `job-creator.tsx`, stream job detail/status + results/citations/review queue. + +**Wallet connect consent:** +- Location: `app/connect/page.tsx` +- Triggers: External client redirect for wallet key issuance. +- Responsibilities: OAuth-style consent screen, creates `walletKeys` row against the calling origin (matched against `walletAllowedOrigins`). + +**Settings surface:** +- Location: `app/settings/page.tsx`, `app/settings/ai/page.tsx`, `app/settings/billing/page.tsx`, `app/settings/connections/page.tsx` +- Triggers: `/settings*`. +- Responsibilities: Manage Zotero connection, AI provider + BYOK keys, subscription/credits, account preferences. + +**Server action (public OpenAlex proxy):** +- Location: `app/actions/openalex.ts` (`"use server"`) +- Triggers: Called from the client SWR fetcher. +- Responsibilities: Wrap the OpenAlex SDK, no auth required. + +**Next.js route handler:** - Location: `app/api/openalex/search/route.ts` -- Triggers: SWR fetcher from SearchProvider -- Responsibilities: Proxy search queries to OpenAlex API with consistent parameter building +- Triggers: `GET /api/openalex/search`. +- Responsibilities: Unauthenticated OpenAlex search passthrough (listed in `PUBLIC_UNAUTHENTICATED_PATHS`), used for lightweight lookups. -**Server Actions:** -- Location: `app/actions/openalex.ts`, `app/actions/openrouter.ts` -- Triggers: Client-side AI operations -- Responsibilities: Server-side API calls for AI providers and OpenAlex +**Proxy/middleware:** +- Location: `proxy.ts` (custom `proxy` export named via `next.config`) +- Triggers: All non-static requests per the `matcher` in `proxy.ts`. +- Responsibilities: Run `clerkMiddleware` protecting non-public paths via `lib/auth/proxy-policy.ts#shouldProtectPath`, detect locale from `Accept-Language` via `i18n/locale-detection.ts`, and set the `NEXT_LOCALE` cookie when missing. -**Convex HTTP Router:** +**Convex HTTP router:** - Location: `convex/http.ts` -- Triggers: External webhooks (Clerk at `/webhooks/clerk`, Stripe at `/webhooks/stripe`, Zotero OAuth at `/api/zotero/callback`) -- Responsibilities: Webhook processing, idempotent event handling, audit logging +- Triggers: External HTTP → Convex deployment. +- Responsibilities: Register Clerk webhook, Stripe webhooks via `registerRoutes`, Zotero OAuth callback, and OpenAI-compatible wallet routes. -**Convex Cron Jobs:** +**Convex crons:** - Location: `convex/crons.ts` -- Triggers: Scheduled intervals (hourly/daily) -- Responsibilities: Cleanup deleted users, check subscription status, reconcile Stripe invoices, monitor failed events, cleanup OAuth tokens, validate env vars +- Triggers: Scheduled. +- Responsibilities: Cleanup soft-deleted users, check subscription status, monitor failed Stripe events, reconcile paid invoices, cleanup expired Zotero tokens, sync OpenRouter models, validate env vars. ## Error Handling -**Strategy:** Multi-layered with structured errors on backend, toast notifications on frontend +**Strategy:** Typed error codes originate in Convex (`convex/lib/errors.ts#createError`), are propagated as `ConvexError<{code,message}>`, caught in client action/query hooks, then routed through `lib/toast/` which resolves the code to a localized message and optional actions (upgrade/redirect). **Patterns:** -- Convex backend uses `createError()` factory (`convex/lib/errors.ts`) for typed errors (NOT_FOUND, VALIDATION_ERROR, etc.) -- Stripe webhook handlers wrap in `runAuditedStripeHandler` for idempotent processing with retry tracking via `stripeEventLogs` -- Frontend uses toast system (`lib/toast/`) for user-facing errors -- Auth sync has exponential backoff retry (up to 6 attempts) in `AuthReadinessProvider` -- Rate limiting via `convex-helpers/server/rateLimit` +- Backend: `throw createError("CODE", "message")` — never throw raw errors from queries/mutations/actions. +- Client: Convex hooks surface errors to SWR/React state; `useAppToast()` (`lib/toast/use-app-toast.ts`) wraps `toast.search.failed`, `toast.ai.failed`, `toast.zotero.failed` with translated messages and action callbacks. +- Next.js boundaries: `app/error.tsx`, `app/global-error.tsx`, per-route `app/extraction/error.tsx`, plus `app/not-found.tsx` — all rendered with motion-aware skeletons. +- Idempotency contracts for Stripe: each webhook in `convex/http.ts` documents its own idempotency contract above the handler; dedup gates use `stripeInvoiceId` / `stripeEventId` / `stripePaymentIntentId`. +- SWR: `errorRetryCount: 2, errorRetryInterval: 1000`, with PostHog failure tracking (`captureSearchFailed`). +- Workflow: `@convex-dev/workflow` uses `retryActionsByDefault: true, maxAttempts: 3, initialBackoffMs: 1000, base: 2` (`convex/workflow.ts`). ## Cross-Cutting Concerns -**Logging:** `console.log`/`console.error` with `[Module]` prefixes (e.g., `[Workflow]`, `[StripeWebhook]`, `[Auth]`) -**Validation:** Convex validators for backend args, Zod for frontend schemas, `searchFiltersValidator` shared between client and server -**Authentication:** Clerk JWT verified by Convex via `auth.config.ts`; `AuthRouteGate` component gates protected pages; `convex/lib/auth.ts` provides server-side auth helpers -**Internationalization:** `next-intl` with 6 locales (en-US, en-GB, fr, hi, ja, zh) in `messages/` directory, locale detection in `i18n/` -**Analytics:** PostHog for product analytics with detailed search event tracking (`lib/posthog-search.ts`, `lib/posthog-ai.ts`) -**Feature Flags:** Feature flags managed in `convex/lib/featureFlags.ts`, `lib/credits/feature-flags.ts`, `lib/extraction/feature-flags.ts` +**Logging:** +- Server: `console.log`/`console.error` within Convex functions (e.g., `[Workflow] …`, `[StripeWebhook] …`, `[Auth] …`). +- Client: `console.error` + PostHog (`lib/posthog-search.ts`, `lib/posthog-ai.ts`, `lib/posthog-server.ts`, `lib/posthog-ai-shared.ts`) for analytics and error capture. +- Audit: `convex/lib/audit.ts` + `stripeEventLogs` table + `auditLogs` table. + +**Validation:** +- Convex validators (`v` from `convex/values`) on every mutation/query — see `convex/extraction/validators.ts`, `convex/screening/validators.ts`, `convex/schema.ts`. +- Zod schemas for AI tool outputs in `lib/ai/core/schemas.ts` and `lib/ai/core/validate.ts`. +- Client filter validation in `lib/keyword-validation.ts`, `lib/filters/filter-builder.ts`. +- i18n message coverage tests in `tests/extraction-i18n-coverage.test.ts`. + +**Authentication:** +- Clerk is the identity provider (`@clerk/nextjs`), wrapped by `ConvexProviderWithClerk` in `components/providers/convex-provider.tsx`. +- `convex/auth.config.ts` registers the Clerk issuer. +- `convex/lib/auth.ts` exposes `getCurrentUser`, `requireAuth`, `getOrCreateUserFromIdentity`, `requireActionAuth`. +- Users are mirrored into the `users` table; `AuthRouteGate` + `useAuthReadiness` block UI until `ensureUser` mutation completes. +- Route protection: `proxy.ts` calls `auth.protect()` for non-public paths defined in `lib/auth/public-routes.ts`. + +**Authorization / Feature Gating:** +- Plans modeled in `subscriptions` (free/go/pro/enterprise); entitlements computed in `lib/billing/entitlements.ts` + `lib/credits/feature-flags.ts`. +- Feature flag tier gating in `convex/featureFlags/guard.ts` via `minimumTier`. +- Wallet keys gated by `walletAllowedOrigins`; BYOK keys encrypted via `convex/lib/crypto.ts`. + +**Rate Limiting:** +- `convex-helpers` rate-limit tables merged into `convex/schema.ts` (`...rateLimitTables`), policy in `convex/lib/rateLimit.ts`. + +**Internationalization:** +- `next-intl` with locales `en-US`, `en-GB`, `zh`, `fr`, `hi`, `ja` (`i18n/config.ts`). +- Request config at `i18n/request.ts` reads cookie or `Accept-Language`. +- Translation bundles in `messages/*.json`. +- Clerk localization resolved in `lib/auth/clerk-ui-config.ts`. + +**Theming:** +- `next-themes` via `components/theme-provider.tsx`, OKLCH design tokens in `app/globals.css`, toggle in `components/theme-toggle.tsx`. + +**Analytics & Consent:** +- PostHog proxied via Next.js rewrites in `next.config.ts` (`/data/:path*` → `eu.i.posthog.com`). +- Consent managed by `components/cookie-consent-banner.tsx` + `lib/consent-storage.ts`; `ConsentAwareGoogleAnalytics` gates GA. +- Instrumentation at `instrumentation-client.ts`. + +**Security headers:** +- `next.config.ts` sets `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`, HSTS, `Permissions-Policy`, `X-DNS-Prefetch-Control` on all responses. --- -*Architecture analysis: 2026-03-06* +*Architecture analysis: 2026-04-14* diff --git a/.planning/codebase/CONCERNS.md b/.planning/codebase/CONCERNS.md index dbe5be18b..9137ae4b0 100644 --- a/.planning/codebase/CONCERNS.md +++ b/.planning/codebase/CONCERNS.md @@ -1,198 +1,361 @@ # Codebase Concerns -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## Tech Debt -**Monolithic Store File (1,275 lines, 22 Zustand stores):** -- Issue: `lib/store.ts` contains 22 separate Zustand stores in a single file, making it difficult to navigate and maintain -- Files: `lib/store.ts` -- Impact: Slow IDE performance, merge conflicts, hard to find specific store logic -- Fix approach: Split into per-domain store files (e.g., `lib/stores/search.ts`, `lib/stores/library.ts`, `lib/stores/extraction.ts`). Each store gets its own file with co-located types. - -**Oversized Convex Modules:** -- Issue: Several Convex modules exceed 1,000 lines with multiple responsibilities mixed together -- Files: `convex/extraction/mutations.ts` (2,283 lines), `convex/extraction/queries.ts` (1,646 lines), `convex/credits/internal.ts` (1,441 lines), `convex/extraction/workpoolActions.ts` (1,153 lines), `convex/subscriptions/actions.ts` (1,021 lines) -- Impact: Hard to navigate, difficult to understand scope of individual functions, increased risk of merge conflicts -- Fix approach: Split by sub-domain (e.g., `mutations.ts` into `mutations/startExtraction.ts`, `mutations/rerun.ts`, `mutations/delete.ts`). Convex supports re-exporting from barrel files. - -**Collection Counts Use N+1 Query Pattern:** -- Issue: `getCollectionsWithCounts` fetches all collections, then does a separate `.collect()` query per collection to count memberships. With 50 collections, this is 51 queries. -- Files: `convex/library/collections.ts` (lines 174-204) -- Impact: Slow response for users with many collections; each query reads all membership rows just to count them -- Fix approach: Add a denormalized `itemCount` field to the `collections` table (same pattern already used for `libraryItemCount` on users). Increment/decrement atomically in `addToCollection`/`removeFromCollection`. - -**Verbose Console Logging in Zotero Actions:** -- Issue: `convex/zotero/actions.ts` contains 20+ `console.log` calls with detailed request/response stats that are leftover development debugging -- Files: `convex/zotero/actions.ts` (lines 254, 417, 669, 801, 821, 835, 848, 857, 876, 892, 897, 898, 916, 966) -- Impact: Noisy Convex dashboard logs in production; may contain collection keys and fetch parameters -- Fix approach: Remove or gate behind a debug flag. Keep only `console.error` for actual failures. - -**NEXT_PUBLIC_ Env Vars Used in Convex Backend:** -- Issue: Feature flags in `convex/lib/featureFlags.ts` and `convex/extraction/guard.ts` reference `NEXT_PUBLIC_*` environment variables. These are Next.js conventions for client-side exposure, but they work in Convex only because they are manually duplicated as Convex env vars. -- Files: `convex/lib/featureFlags.ts`, `convex/extraction/guard.ts`, `convex/extraction/content.ts`, `convex/credits/queries.ts` -- Impact: Confusing naming -- implies these are client-side vars when they are server-side feature gates. If someone removes them from Convex env (thinking they are Next.js-only), features silently enable. -- Fix approach: Create Convex-specific env vars (e.g., `FEATURE_CREDITS_ENABLED`) or rename to drop the `NEXT_PUBLIC_` prefix in Convex config. +**Duplicate debug query files:** +- Issue: Two near-identical files expose the same "show recent extractionPapers" debug query under different names. `convex/debug.ts` exports `debugRecentPapers` (10 papers); `convex/debug_papers.ts` exports `recent` (5 papers) with a commented-out `// retryCount: p.retries,` field referencing a removed schema column. +- Files: `convex/debug.ts`, `convex/debug_papers.ts` +- Impact: DRY violation, dead/commented code shipped to production, two surfaces to maintain for the same purpose. +- Fix approach: Delete both files (debug-only internalQueries should not live in production source) or consolidate into a single `convex/internal/debugRecentPapers.ts` and remove the commented field. + +**Legacy migration ladder in Zustand persist store:** +- Issue: The search history store carries a 7-step migration chain (`version: 7`) from initial release. The project mandate is "I am NOT interested in legacy behavior." The migration helper `migrateSearchHistoryState` handles every historical shape from version 0 through 6, plus an inline `migrateSearchResult` rewriter. +- Files: `lib/store.ts:184-293`, `lib/store.ts:505-523`, `lib/store.ts:577-578`, `lib/store.ts:768-769`, `lib/store.ts:827-828` +- Impact: Three separate persist stores in one file each carry their own migrate function and version counter; cognitive overhead, dead code paths, and indirect bugs whenever a developer touches the store shape. +- Fix approach: Drop all migrations, bump version to 1, and let stale localStorage payloads be discarded. Pre-launch project — no users to preserve state for. + +**Custom UUID polyfill for "older mobile browsers":** +- Issue: `lib/store.ts:21-32` defines a UUID v4 fallback using `'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(...)` because `crypto.randomUUID` is "missing on older mobile browsers." +- Files: `lib/store.ts:21-32` +- Impact: Insecure RNG path (Math.random fallback inside the polyfill), maintenance burden, conflict with the no-legacy mandate. Modern Safari/Chrome on iOS/Android have shipped `crypto.randomUUID` for years. +- Fix approach: Delete the polyfill. Call `crypto.randomUUID()` directly. If a target browser truly lacks it, fail loudly. + +**Legacy error-resolver layer:** +- Issue: `lib/toast/error-resolver.ts` exports `LEGACY_CODE_MATCHERS`, `sanitizeLegacyConvexMessage`, and `inferLegacyCode` to translate legacy Convex error messages into modern codes. Project rule says we ship no legacy compatibility. +- Files: `lib/toast/error-resolver.ts:48-50`, `lib/toast/error-resolver.ts:173-205`, `lib/toast/error-resolver.ts:225-226`, `tests/toast-error-resolver.test.ts` +- Impact: Pre-testing project carrying compatibility shims for errors that the same codebase emits — should be unified at the throw site instead. +- Fix approach: Standardize on structured error codes from the throw site (Convex `ConvexError` with shape `{ code, message }`), delete the regex-based matcher, simplify the resolver. + +**Legacy pdfjs build import:** +- Issue: `convex/extraction/pdfjs_extract.ts:29` does `await import("pdfjs-dist/legacy/build/pdf.mjs")`. Already flagged in `.planning/milestones/v2.5-phases/52-cleanup-organization/52-01-PLAN.md:78` but not yet acted on. +- Files: `convex/extraction/pdfjs_extract.ts:29` +- Impact: Locks the project to the legacy pdfjs bundle, which has known performance and worker-thread differences from the modern build. Slower extractions, larger bundle. +- Fix approach: Switch to the modern pdfjs build (`pdfjs-dist/build/pdf.mjs`), validate worker compatibility under Convex node actions, run extraction smoke tests. + +**Lazy backfill for "legacy completed jobs":** +- Issue: `convex/extraction/mutations.ts:959-961` schedules `backfillJobStats` for "legacy completed jobs without stats." The backfill function itself lives at `convex/extraction/mutations.ts:1230-1234`. +- Files: `convex/extraction/mutations.ts:959-961`, `convex/extraction/mutations.ts:1230-1234` +- Impact: Production read paths still defend against rows missing `stats`, meaning every read carries an extra branch for jobs that should not exist in a pre-launch project. +- Fix approach: Run the backfill once, then delete the lazy-backfill scheduler call and assert non-null `stats` in the read path. + +**Cascade-delete uses `pdfProcessingPool.cancelAll(ctx)`:** +- Issue: `convex/extraction/mutations.ts:274-281` cancels every pending workpool item across every job, not only the items belonging to the cancelled job. The inline comment acknowledges this and relies on a downstream "credit-guard" check to refund/skip incorrectly-targeted items. +- Files: `convex/extraction/mutations.ts:274-281` +- Impact: Every call to cancel one extraction job kicks every other in-flight job in the head, increasing latency and risk of misbilling. Fragile — the credit-guard is a workaround, not a fix. +- Fix approach: Track per-job workpool item IDs in the schema; iterate `workpool.cancel(itemId)` on the targeted set only. + +**Legacy chunk formatter still exported:** +- Issue: `convex/extraction/chunking.ts:251` still exports a "Format chunk for legacy display" helper. +- Files: `convex/extraction/chunking.ts:251` +- Impact: Dead code path; downstream callers may use the legacy formatter when the modern path exists. +- Fix approach: Remove the legacy formatter and update any callers. + +**`renderItem` legacy code path in command center:** +- Issue: `components/command-center/command-center-list.tsx:17` comment: "Use ItemComponent for proper reconciliation; renderItem is legacy." Both code paths remain active. +- Files: `components/command-center/command-center-list.tsx:17` +- Impact: Two rendering APIs maintained side-by-side; reconciliation bugs surface only on the legacy path. +- Fix approach: Migrate every caller to `ItemComponent`, delete `renderItem`. + +**Deprecated `label` field in search types:** +- Issue: `lib/types/search.types.ts:78` keeps a `/** @deprecated Use key with translations instead */` field. +- Files: `lib/types/search.types.ts:78` +- Impact: TypeScript still admits the deprecated shape; new code can keep using it. +- Fix approach: Remove the field, fix any callers that still set it. + +**Deprecated `stats` prop in ``:** +- Issue: `components/ui/page-header.tsx:26` declares a `Statistics to display (number and label) - deprecated, will be ignored` prop. +- Files: `components/ui/page-header.tsx:26` +- Impact: Public component API leaks an inert prop that does nothing. Every consumer that still passes it is wrong but receives no warning. +- Fix approach: Remove the prop from the interface and from any caller still passing it. + +**`"use no memo"` opt-out from React Compiler in 19 components:** +- Issue: 19 component files (including `components/app-sidebar.tsx`, `app/settings/billing/page.tsx`, `components/Pricing.tsx`, every PDF/extraction-related component, search-command-center variants) opt out of React Compiler with `"use no memo"`. +- Files: `components/app-sidebar.tsx`, `app/settings/ai/page.tsx`, `app/settings/billing/page.tsx`, `components/Pricing.tsx`, `components/search-command-center/search-command-footer.tsx`, `components/ui/calendar.tsx`, `components/search-command-center/search-mode.tsx`, `components/search-command-center/screening-expansion.tsx`, `components/search-command-center/adjust-mode.tsx`, `components/providers/convex-provider.tsx`, `components/history-command-center/index.tsx`, `components/extraction/review-queue.tsx`, `components/extraction/report-builder.tsx`, `components/extraction/question-builder.tsx`, `components/extraction/pdf-viewer.tsx`, `components/extraction/manual-items.tsx`, `components/extraction/job-creator.tsx`, `components/bookmarks-command-center/bookmarks-guide.tsx`, `components/PageContent.tsx` +- Impact: Almost every heavy interactive surface skips compiler optimizations. Defeats the purpose of enabling `babel-plugin-react-compiler`. +- Fix approach: For each file, audit the offending pattern (typically `try/finally` in event handlers, refs touched during render, mutation in render), refactor to compiler-safe shape, remove the directive. + +**119 occurrences of `any` in source (excluding generated):** +- Issue: 119 `any` usages across 18 source files. Hot spots: `components/extraction/stacked-answer-bars.tsx` (4), `tests/extraction/workflow-cancel.test.ts` (4), `components/extraction/insights-question-panel.tsx` (2), and many extraction-component files cast `useTranslations` to `any`. +- Files: `components/extraction/insights-question-panel.tsx`, `components/extraction/stacked-answer-bars.tsx`, `components/extraction/disagreement-list.tsx`, `components/extraction/grouped-answer-row.tsx`, `components/extraction/confidence-badge.tsx`, `components/extraction/insights-overview.tsx`, `components/extraction/summary-cards.tsx`, `components/extraction/question-list-item.tsx`, `lib/filters/filter-builder.ts`, `lib/search/initializer.tsx`, `convex/extraction/chunking.ts`, `convex/extraction/workpoolActions.ts` +- Impact: Type safety holes concentrated in the extraction UI — the most data-dense and bug-sensitive feature in the app. +- Fix approach: Use `next-intl`'s typed `t` helper (`useTranslations`) instead of casting; introduce explicit row/answer types instead of `any[]`. + +**`eslint-disable` scattered through extraction UI and library:** +- Issue: 13 source files contain `eslint-disable` comments. The extraction UI accounts for 7 of them. +- Files: `components/library/collection-manager.tsx`, `components/extraction/summary-cards.tsx`, `components/extraction/stacked-answer-bars.tsx`, `components/extraction/insights-question-panel.tsx`, `components/extraction/insights-overview.tsx`, `components/extraction/grouped-answer-row.tsx`, `components/extraction/disagreement-list.tsx`, `components/extraction/confidence-badge.tsx` +- Impact: Hidden lint debt; rules silenced rather than fixed. +- Fix approach: For each disable, fix the underlying issue or scope the disable to a single line with a justification comment. + +**Stripe migration still ongoing:** +- Issue: `convex/subscriptions/actions.ts:907` notes "Uses Stripe's createPreview API (replacement for deprecated retrieveUpcoming)." Migration recently landed. +- Files: `convex/subscriptions/actions.ts:907` +- Impact: Stripe SDK upgrade churn. Verify there are no remaining callers of `retrieveUpcoming`. +- Fix approach: Grep for `retrieveUpcoming` across the codebase and confirm zero hits, lock Stripe SDK version. ## Known Bugs -No explicit bugs identified. No TODO/FIXME/HACK comments exist in source code. The codebase is clean of inline bug markers. +**BUG-03: orphaned extractionRunDiffs after baseline-job delete:** +- Symptoms: Diff rows pointed at a deleted baseline job and were never cleaned up. +- Files: `convex/extraction/mutations.ts:1184`, `convex/extraction/cascade-delete.test.ts:274` +- Trigger: Deleting a job that was the baseline for a comparison run. +- Workaround: A historical fix exists in `convex/extraction/mutations.ts` cascade-delete. Verify the test (`convex/extraction/cascade-delete.test.ts:274`) still passes after any cascade-delete refactor. -## Security Considerations +**Wallet gateway: stream succeeds, deduction can fail:** +- Symptoms: AI Gateway streams output to the client, then asynchronously deducts credits via `void (async () => { ... })()`. If the deduction throws (rate limit, network blip, race), it is logged with `console.error` and silently lost. +- Files: `convex/wallet/gateway/handler.ts:349-359` +- Trigger: Any failure inside the async IIFE — `streamResult.totalUsage` rejection, `deduct` exception, mutation conflict. +- Workaround: None today. The error is logged and discarded. -**Encryption Key Stored as Single Env Var Without Rotation Support:** -- Risk: `ENCRYPTION_KEY` is used for AES-256-GCM encryption of API keys and Zotero tokens. No key rotation mechanism exists -- rotating the key would break all existing encrypted values. -- Files: `convex/lib/crypto.ts`, `convex/apiKeys/actions.ts` (line 58), `convex/zotero/actions.ts` (lines 35, 605) -- Current mitigation: Key is stored as Convex env var (not in code). AES-256-GCM with random IV per encryption. -- Recommendations: Add a `keyVersion` field to `apiKeys` and `zoteroConnections` tables. Support decrypt-with-old + re-encrypt-with-new during rotation. Add a migration script. +**Auth sync exhaustion leaves user permanently stuck:** +- Symptoms: When `ensureUser` fails 6 times (`MAX_SYNC_RETRIES`), the provider transitions to `sync_error` state. The user stops syncing and there is no automatic recovery beyond the explicit `retryUserSync` callback. +- Files: `components/providers/convex-provider.tsx:28`, `components/providers/convex-provider.tsx:162-167`, `components/providers/convex-provider.tsx:197-198` +- Trigger: Six consecutive sync failures (Convex backend hiccup, Clerk JWT problem, network). +- Workaround: User must trigger `retryUserSync` manually (often by reloading the page). -**Decryption Audit Logging is Minimal:** -- Risk: `decryptApiKey` logs only the purpose string via `console.log`, not the userId or which key was decrypted. The `audit` parameter contains `userId` and `purpose` but only `purpose` is logged. -- Files: `convex/lib/crypto.ts` (line 81) -- Current mitigation: Caller passes both userId and purpose in the audit object -- Recommendations: Log the full audit object (userId + purpose) or write to the `auditLogs` table for a persistent, queryable trail. +## Security Considerations -**Test Runner Bypasses Authentication:** -- Risk: `convex/extraction/test_runner.ts` creates extraction jobs using the first user in the database, bypassing all auth checks -- Files: `convex/extraction/test_runner.ts` (lines 23-27) -- Current mitigation: Uses `internalMutation` so it is not exposed in the public API -- Recommendations: Acceptable as-is since it is internal-only. No action needed. +**CORS wildcard in wallet gateway:** +- Risk: `convex/wallet/gateway/handler.ts:23-44` defines `corsHeaders(origin: string = "*")` and `corsJson(..., origin = "*")`. `handler.ts:86` and `handler.ts:513` initialize `let allowedOrigin = "*"`, with downstream logic narrowing it. The OPTIONS handler at `handler.ts:559-560` also defaults to `"*"` if the request lacks an Origin header. +- Files: `convex/wallet/gateway/handler.ts:23`, `convex/wallet/gateway/handler.ts:31`, `convex/wallet/gateway/handler.ts:42`, `convex/wallet/gateway/handler.ts:86`, `convex/wallet/gateway/handler.ts:513`, `convex/wallet/gateway/handler.ts:559-560` +- Current mitigation: Authentication via API key on every wallet route; the gateway supplies `Authorization: Bearer` on each call. Wildcard is technically safe with bearer tokens (no cookies), but the broad default still hands attackers an easy CSRF/SSRF target if an endpoint ever migrates to cookies. +- Recommendations: Maintain an explicit allowlist of origins, drop the wildcard default, and add CSP/`Vary: Origin` headers. Document why bearer-only auth justifies any remaining `*`. + +**Crypto audit trail goes only to `console.log`:** +- Risk: `convex/lib/crypto.ts` (83 lines) implements AES-256-GCM properly, but the only audit signal on decryption is `console.log("[KEY_DECRYPT]", audit.purpose)` (or similar). No structured event, no PostHog capture, no tamper-resistant audit trail. +- Files: `convex/lib/crypto.ts` +- Current mitigation: Console output in Convex logs (ephemeral, retention-bounded). +- Recommendations: Replace `console.log` with `posthogServerCapture` or a dedicated `auditEvents` table; include actor, purpose, key fingerprint, timestamp. + +**`envValidation` covers only 6 env vars out of dozens:** +- Risk: `convex/lib/envValidation.ts` (42 lines) validates `STRIPE_SECRET_KEY`, `ENCRYPTION_KEY`, `STRIPE_GO_PRICE_ID`, `STRIPE_PRO_PRICE_ID`, `STRIPE_WEBHOOK_SECRET`, `CLERK_JWT_ISSUER_DOMAIN`. Missing: OpenRouter keys, Posthog tokens, Convex deploy URLs, Zotero OAuth secrets, embedding cost knobs. +- Files: `convex/lib/envValidation.ts` +- Current mitigation: `process.env.X` reads scattered through the codebase, each implementing its own fallback. Some throw, most do not. +- Recommendations: Centralize all env var contracts in a typed schema (Zod), validate at startup, fail fast with a list of missing/invalid vars. + +**Public unauthenticated `/api/openalex/search` route:** +- Risk: `app/api/openalex/search/route.ts` (70 lines) proxies OpenAlex without authentication or rate-limiting at the Next.js layer. Errors are logged with `console.error` only. +- Files: `app/api/openalex/search/route.ts` +- Current mitigation: OpenAlex itself has rate limits; bot abuse will hit OpenAlex first. +- Recommendations: Add Vercel Edge rate-limiting (or Convex `rateLimit.consume`) keyed by IP; add explicit error envelopes; add a `Cache-Control` header so identical queries hit the CDN. + +**Token-bucket rate limits cover a tiny surface area:** +- Risk: `convex/lib/rateLimit.ts` (77 lines) defines limits only for `start-extraction`, `api-key-save`, `checkout-session`, `wallet-generate`, `wallet-connect`. No protection for: search invocation, library mutations, screening kickoff, Zotero sync trigger, RAG ingest, gateway streaming endpoint per-user. +- Files: `convex/lib/rateLimit.ts` +- Current mitigation: Auth gates and credit deduction implicitly cap usage. +- Recommendations: Add buckets for every billable or expensive action; default-deny pattern. + +**322 console statements across 56 files:** +- Risk: 322 `console.log/warn/error/info/debug` calls across 56 files. `convex/zotero/actions.ts` alone has 18; `scripts/wallet-cli.ts` has 133 (CLI is fine); production hot paths (`convex/extraction/mutations.ts:19`, `convex/extraction/workpoolActions.ts:6`, `convex/subscriptions/actions.ts:9`) leak structured details to plaintext logs. +- Files: `convex/zotero/actions.ts`, `convex/extraction/mutations.ts`, `convex/extraction/workpoolActions.ts`, `convex/credits/internal.ts`, `convex/subscriptions/actions.ts`, `convex/wallet/gateway/handler.ts`, `convex/maintenance/internal.ts`, `convex/maintenance/mutations.ts`, `convex/lib/crypto.ts`, `convex/lib/envValidation.ts` +- Current mitigation: Convex log retention is bounded. +- Recommendations: Introduce a thin `log` helper (`info`, `warn`, `error`) that adds context (request id, user id) and routes through PostHog server capture; replace direct `console.*` calls. ## Performance Bottlenecks -**backfillJobStats Performs O(papers x questions) Individual Queries:** -- Problem: `backfillJobStats` iterates over every paper in a job and queries `extractionResults` for each paper separately. For a 500-paper job, this is 500 individual DB queries inside a single mutation. -- Files: `convex/extraction/mutations.ts` (lines 1240-1340) -- Cause: Sequential per-paper result queries inside a nested loop; no job-level index on `extractionResults` -- Improvement path: Add a `jobId` field and `by_job` index on `extractionResults` table, then load all results in one query and group in JS. Alternatively, batch papers into chunks. - -**loadJobPapersAndResults Issues Parallel Per-Paper Queries:** -- Problem: Loads papers then issues `Promise.all` over up to 500 papers, each querying `extractionResults` by paper ID. While parallel, this creates up to 500 concurrent Convex queries per call. -- Files: `convex/extraction/queries.ts` (lines 220-250) -- Cause: No job-level index on `extractionResults` -- Improvement path: Same as above -- add `by_job` index on `extractionResults` to enable single-query loading. - -**getJobInsights Loads Full Paper + Result Data Even When Pre-Aggregated Stats Exist:** -- Problem: `getJobInsights` always calls `loadJobPapersAndResults` (loading ALL papers and results) even when `extractionJobStats` records exist, because it needs raw data for disagreement clusters and other derived features. -- Files: `convex/extraction/queries.ts` (lines 692-720) -- Cause: Insight computation requires both aggregate stats and raw per-paper data for cluster analysis -- Improvement path: Split the query: use pre-aggregated stats for summary metrics, load full data only for cluster computation. Consider pre-computing clusters in the backfill mutation. - -**Client-Side Filtering of Extraction Results:** -- Problem: The extraction job detail page fetches all papers (up to 500) and filters/sorts client-side via `preprocessPapers()` and `filterPapers()`. -- Files: `lib/extraction/filtering.ts`, `app/extraction/[jobId]/page.tsx` -- Cause: Complex filter combinations (confidence ranges, question-specific filters, search text) are easier to implement client-side -- Improvement path: For jobs approaching 500 papers, consider server-side cursor-based pagination with filter pushdown. +**File size: `convex/extraction/mutations.ts` at 2288 lines:** +- Problem: Single file holds extraction kickoff, status transitions, retry orchestration, cascade-delete, baseline-diff machinery, and lazy backfills. Hard to reason about, fragile to refactor. +- Files: `convex/extraction/mutations.ts` +- Cause: Organic growth of the extraction feature without splitting per concern. +- Improvement path: Extract sub-modules: `convex/extraction/mutations/cascadeDelete.ts`, `convex/extraction/mutations/cancel.ts`, `convex/extraction/mutations/backfillStats.ts`, `convex/extraction/mutations/start.ts`. Keep a thin barrel file. + +**File size: `convex/extraction/queries.ts` at 1659 lines:** +- Problem: Includes both production read APIs and a `getPapersDebug` debug query. Inline comments warn about N+1 hazards (`loadReviewsByJob` "fixes N+1") and a hard `MAX_PAPERS_PER_JOB = 500` safety cap. +- Files: `convex/extraction/queries.ts:53`, `convex/extraction/queries.ts:230`, `convex/extraction/queries.ts:369` +- Cause: Dense feature surface; debug query mixed with production queries. +- Improvement path: Move debug query to `convex/internal/`, split read paths by concern (job summary, paper list, insights), document indexes assumed by each query. + +**File size: `convex/credits/internal.ts` at 1597 lines:** +- Problem: Stripe webhook reconciliation with retry policies, dedup contracts, race-condition mitigations, and credit deduction all live in one file. Comment block explicitly documents the concurrency model: "Convex mutations are serializable (OCC)." +- Files: `convex/credits/internal.ts:478` (DEDUP CONTRACT CRED-01), `convex/credits/internal.ts:1397` (race condition analysis) +- Cause: Billing logic concentration. +- Improvement path: Split into `convex/credits/grant.ts`, `convex/credits/deduct.ts`, `convex/credits/reconciliation.ts`, `convex/credits/dedup.ts`. Co-locate tests with each. + +**File size: `lib/store.ts` at 1260 lines:** +- Problem: Three persist stores (search history, sidebars, more) plus migration ladders, polyfills, and helpers in one file. +- Files: `lib/store.ts` +- Cause: Pile-on into one Zustand file. +- Improvement path: Split into `lib/stores/searchHistory.ts`, `lib/stores/sidebar.ts`, `lib/stores/uiPrefs.ts`. Drop legacy migrations as noted under Tech Debt. + +**File size: `convex/extraction/workpoolActions.ts` at 1191 lines:** +- Problem: Hardcoded magic numbers (`DENSE_LIMIT=120`, `RRF_CONSTANT=30`, `FUSED_TOP_N=48`) and a hardcoded `ARRAY_GENERIC_TERMS` Set with 17 LLM-related terms. Long extraction loop with many `console.info` statements. +- Files: `convex/extraction/workpoolActions.ts` +- Cause: Iterative tuning without a config surface. +- Improvement path: Move tuning constants to `convex/extraction/config.ts` (or env vars with safe defaults). Remove `console.info` chatter. + +**File size: `components/app-sidebar.tsx` at 988 lines:** +- Problem: Single largest component file. Opts out of React Compiler with `"use no memo"`. Holds the entire navigation tree, locale switching, and chromeless route handling. +- Files: `components/app-sidebar.tsx` +- Cause: Sidebar grew with each feature; never split. +- Improvement path: Split into `components/sidebar/SidebarNav.tsx`, `components/sidebar/SidebarFooter.tsx`, `components/sidebar/SidebarRouteFilter.tsx`. Audit the `try/finally` handler patterns that force the no-memo directive and refactor to compiler-safe shapes. + +**Wallet gateway handler at 561 lines:** +- Problem: Single file handles streaming + non-streaming, two billing paths, CORS, rate limiting, authentication, model lookups, and request parsing. The fire-and-forget deduction lives here too (see Known Bugs). +- Files: `convex/wallet/gateway/handler.ts` +- Cause: Convex HTTP actions encourage colocated logic. +- Improvement path: Extract `wallet/gateway/streaming.ts`, `wallet/gateway/nonStreaming.ts`, `wallet/gateway/cors.ts`, leave `handler.ts` as a thin router. + +**Hardcoded `MAX_PAPERS_PER_JOB = 500`:** +- Problem: Hard cap on jobs at 500 papers. Defined twice (`convex/extraction/mutations.ts:35` and `convex/extraction/queries.ts:53`) — DRY violation. +- Files: `convex/extraction/mutations.ts:35`, `convex/extraction/queries.ts:53` +- Cause: Quick safety bound. +- Improvement path: Move to a shared `convex/extraction/limits.ts`, expose as a plan-tier limit (Free=50, Pro=500, Enterprise=unlimited), let billing decide the ceiling. ## Fragile Areas -**Denormalized Library Counter Lazy Backfill:** -- Files: `convex/library/queries.ts` (lines 332-353), `convex/library/mutations.ts` (lines 65-66, 98-99) -- Why fragile: The `libraryItemCount` field on `users` is optional. Users who have never triggered a save/remove mutation after the feature was added fall through to the slow `.take(10_000)` scan path in `getLibraryCount`. The counter cannot be backfilled from a query context (no `ctx.scheduler`). A comment in the code acknowledges this limitation. -- Safe modification: Always update the counter in any mutation that adds/removes library items. The backfill path is read-only and idempotent. -- Test coverage: `convex/library/queries.test.ts` covers the query. No test for the lazy backfill edge case where `libraryItemCount` is undefined. - -**Stripe Webhook Event Processing Chain:** -- Files: `convex/http.ts`, `convex/lib/stripeWebhookHandlers.ts`, `convex/subscriptions/internal.ts`, `convex/credits/internal.ts` -- Why fragile: Webhook processing spans 4 files with multiple internal function calls. Event deduplication relies on `stripeInvoiceId`/`stripePaymentIntentId` uniqueness in `creditTransactions`. All handlers have documented idempotency contracts (INFRA-03) which must be maintained. -- Safe modification: Follow the existing pattern when adding new event handlers: always use `runAuditedStripeHandler` wrapper. Run `tests/stripe-webhook-handler.test.ts`, `tests/credit-grant-policy.test.ts`, `tests/credit-purchase-idempotency.test.ts` after changes. -- Test coverage: Good unit test coverage. E2E billing specs in `e2e/billing/specs/` cover live Stripe flows. - -**Extraction Workflow State Machine:** -- Files: `convex/extraction/mutations.ts`, `convex/extraction/workpoolActions.ts` -- Why fragile: Extraction jobs progress through 7 status states (pending -> downloading_pdfs -> indexing -> extracting -> completed/failed/cancelled). State transitions are spread across two large files (2,283 + 1,153 lines). The workpool/workflow system adds another layer of state. -- Safe modification: Always check current job status before transitioning. Use `assertJobOwnership`. Test with `convex/extraction/test_helpers.ts`. -- Test coverage: `convex/extraction/cascade-delete.test.ts` covers deletion. `tests/extraction/workflow-cancel.test.ts` covers cancellation. No test for the full happy-path state machine flow. - -**Subscription Plan Change with Schedule Management:** -- Files: `convex/subscriptions/actions.ts` (lines 600-780) -- Why fragile: Plan changes involve Stripe subscription schedule release/creation, metadata sync, pro-rata credit grants, and local state updates. The SUB-05 schedule leak detection (verify schedule detached after release) throws an error if verification fails, but there is no automated recovery. -- Safe modification: Run `tests/subscription-schedule-planning.test.ts` and `tests/subscription-entitlements.test.ts` after changes. -- Test coverage: Unit tests exist for schedule planning logic. No integration test for the schedule leak detection/recovery path. +**Wallet gateway fire-and-forget credit deduction:** +- Files: `convex/wallet/gateway/handler.ts:349-359` +- Why fragile: Stream may return successful 200 to the client while the deduction silently fails. Repeated failures = uncharged usage. +- Safe modification: Convert to a transactional pattern — credits debited at stream start (estimated), reconciled at stream end with a delta mutation. Or store a pending-charge row and reconcile via a workpool. +- Test coverage: `convex/wallet/gateway/gateway.test.ts` (2486 lines) tests many gateway paths but the failure-after-stream branch is hard to exercise without injecting faults. + +**Cascade-delete cancels every workpool item:** +- Files: `convex/extraction/mutations.ts:274-281` +- Why fragile: One job's cancellation cancels everyone's pending items. Concurrent cancellations interact unpredictably. +- Safe modification: Track per-job item IDs; cancel surgically. Add an integration test that exercises two concurrent jobs with overlapping items. +- Test coverage: `convex/extraction/cascade-delete.test.ts` exists; `tests/extraction/workflow-cancel.test.ts` exists. Verify they cover concurrent multi-job cancellation. + +**Auth sync state machine with hard 6-retry budget:** +- Files: `components/providers/convex-provider.tsx:28`, `components/providers/convex-provider.tsx:158-181`, `components/providers/convex-provider.tsx:197-198` +- Why fragile: Six exponential-backoff retries, then permanent `sync_error`. User has no automatic recovery; only manual `retryUserSync()`. +- Safe modification: Replace fixed budget with a periodic background retry on visibility/online events; show a non-blocking inline banner offering manual retry. +- Test coverage: Auth provider state transitions are not covered by unit tests in the test suite. + +**`migrateSearchHistoryState` switch ladder:** +- Files: `lib/store.ts:184-293` +- Why fragile: Each version branch must be kept in sync with the schema; one wrong cast inside a branch corrupts the entire persist store and breaks every user's search history on next load. +- Safe modification: Drop the entire ladder (no users), re-version to 1, validate persist payloads with a Zod schema and discard mismatches. +- Test coverage: No tests cover the migration ladder. + +**119 explicit `any` types in extraction UI:** +- Files: `components/extraction/insights-question-panel.tsx`, `components/extraction/stacked-answer-bars.tsx`, `components/extraction/disagreement-list.tsx`, `components/extraction/grouped-answer-row.tsx`, `components/extraction/confidence-badge.tsx`, `components/extraction/insights-overview.tsx`, `components/extraction/summary-cards.tsx`, `components/extraction/question-list-item.tsx` +- Why fragile: Every `any` cast is a runtime crash waiting for a refactor on the upstream Convex query shape. +- Safe modification: Strongly type `useTranslations` via next-intl's typed namespace export; introduce shared row/column types for extraction tables. +- Test coverage: Tests exist (`tests/extraction-insights-question-panel.test.tsx`, `tests/stacked-answer-bars.test.tsx`) but use `as any` to bypass types — same anti-pattern in tests. ## Scaling Limits -**Remaining `.collect()` Calls Without `.take()` Guards:** -- Current capacity: Many `.collect()` calls in `convex/subscriptions/internal.ts` (12 calls) and `convex/extraction/queries.ts` (13 calls) lack explicit `.take()` bounds -- Limit: Convex queries have response size and time limits. These calls rely on cardinality annotations (e.g., "~1-5 subscriptions per user", "~5-20 results per paper") which are assumptions, not enforced constraints. -- Scaling path: Monitor actual cardinalities. If assumptions change (e.g., questions-per-paper exceeds 20), add `.take()` guards. The `convex/lib/queryBounds.ts` module provides the pattern. +**`MAX_PAPERS_PER_JOB = 500` (hardcoded, duplicated):** +- Current capacity: 500 papers per extraction job. +- Limit: At 501+ papers, jobs silently truncate to the first 500 across at least 8 query/mutation call sites. +- Scaling path: Introduce per-plan ceilings and stream large jobs with cursor-based pagination instead of `take(500)`. -**Audit and Event Log Tables Grow Unbounded:** -- Current capacity: `auditLogs` and `stripeEventLogs` tables have no retention/cleanup policy -- Limit: Tables grow indefinitely, slowing index scans and increasing storage costs -- Scaling path: Add a cron job (similar to `cleanupDeletedUsers` in `convex/maintenance/mutations.ts`) that purges records older than 90 days from `stripeEventLogs` and 365 days from `auditLogs`. +**Rate-limit capacities:** +- Current capacity: `start-extraction` 5/hour (capacity 3), `api-key-save` 5/min, `checkout-session` 3/min, `wallet-generate` 60/min (capacity 10), `wallet-connect` 5/min. +- Limit: A scientist running 6 systematic reviews in an hour hits the start-extraction wall after the third. +- Scaling path: Tier rate limits by plan; expose remaining quota in the UI; convert to leaky-bucket at the proxy layer. -**Credit Transactions Table Grows Indefinitely:** -- Current capacity: `creditTransactions` records every purchase, usage, grant, refund, and expiry with no purge policy -- Limit: Heavy users accumulate thousands of records. `MAX_CREDIT_TRANSACTIONS = 1_000` in `convex/lib/queryBounds.ts` silently truncates older records from user-facing views. -- Scaling path: Consider archiving old transactions (> 1 year) to a separate table or external storage. The 1,000-record query bound is a bandaid, not a long-term fix. +**Auth sync 6-retry budget:** +- Current capacity: 6 retries with exponential backoff before permanent failure. +- Limit: Any 6-consecutive failure window strands the user. +- Scaling path: Background retry on tab focus / network online events; non-blocking inline banner. -**Extraction Job Paper Limit (500):** -- Current capacity: `MAX_PAPERS_PER_JOB = 500` constant in `convex/extraction/mutations.ts` (line 35) -- Limit: Hard cap in both queries and mutations. Users cannot extract data from more than 500 papers per job. -- Scaling path: Implement cursor-based pagination in extraction queries; switch insight aggregation to use pre-computed `extractionJobStats` exclusively rather than loading all papers. +**Stripe webhook dedup by `stripeInvoiceId`:** +- Current capacity: Idempotent on `stripeInvoiceId` per `convex/credits/internal.ts:478` "DEDUP CONTRACT (CRED-01)" and `convex/http.ts:111`. +- Limit: Edge cases where Stripe replays a webhook with a different `idempotency_key` but the same `stripeInvoiceId` are handled. Edge cases where two different invoices share an event window may not be. +- Scaling path: Add concurrency tests; verify that the OCC mutation pattern actually serializes overlapping grants. ## Dependencies at Risk -**Convex Dev Dependencies at 0.x Versions:** -- Risk: `@convex-dev/rag`, `@convex-dev/stripe`, `@convex-dev/workflow`, `@convex-dev/workpool` are community/experimental components at early versions (0.x) -- Impact: API changes in these packages require coordinated updates. Breaking changes are expected in 0.x semver. -- Migration plan: Pin exact versions via lockfile. Monitor changelogs. Consider vendoring critical functionality if stability is needed. +**`pdfjs-dist` legacy build:** +- Risk: Imports `pdfjs-dist/legacy/build/pdf.mjs` instead of the modern build. +- Files: `convex/extraction/pdfjs_extract.ts:29` +- Impact: Larger bundle, slower extraction, may break with future pdfjs releases that deprecate the legacy entry. +- Migration plan: Switch to `pdfjs-dist/build/pdf.mjs`; verify worker compatibility under Convex node actions. + +**Stripe SDK `retrieveUpcoming` -> `createPreview` migration:** +- Risk: Recent migration in `convex/subscriptions/actions.ts:907`. Transitive callers may still rely on old behavior. +- Files: `convex/subscriptions/actions.ts:907` +- Impact: Subscription preview rendering and upcoming-invoice math depend on the new API. +- Migration plan: Grep for any remaining `retrieveUpcoming` references; ensure billing UI tests cover both upgrade and downgrade preview paths. + +**`@convex-dev/stripe` 0.1.4:** +- Risk: Pre-1.0 component; minor releases may break wire format. +- Files: `package.json:34` +- Impact: Stripe integration depends on the component's webhook handling. +- Migration plan: Pin exact version; review changelog before bumping. + +**`@convex-dev/rag` 0.7.2:** +- Risk: Pre-1.0 component; embedding contract may evolve. +- Files: `package.json:33` +- Impact: PDF chunking + retrieval pipeline depends on this contract. +- Migration plan: Pin exact version; integration tests around chunk → retrieve → answer flow. + +**`@openrouter/ai-sdk-provider` ^6.0.0-alpha.1:** +- Risk: Alpha release in production. +- Files: `package.json:39` +- Impact: AI gateway model invocations. +- Migration plan: Track upstream stable release; pin until then. ## Missing Critical Features -**No Error Monitoring/Alerting Service:** -- Problem: Error tracking relies entirely on `console.error` calls in Convex dashboard logs and the `monitorFailedStripeEvents` cron (also uses `console.error`). No Sentry, Datadog, or equivalent. -- Blocks: No automated alerting for production errors, no error aggregation, no trend analysis -- Impact: Issues may go unnoticed until users report them +**Structured audit log:** +- Problem: API-key decryption logs to `console.log`; no tamper-resistant audit trail for sensitive operations (key reads, plan changes, credit grants, webhook outcomes). +- Blocks: Compliance posture (SOC 2, GDPR DPA), forensic investigation, abuse triage. -**No Structured Logging Framework:** -- Problem: Backend uses 100+ `console.log/warn/error` calls across Convex files with no structured format. No log levels, no correlation IDs, no machine-parseable output. -- Blocks: Difficult to debug production issues; cannot filter logs by severity or trace requests across function calls +**Centralized environment validation:** +- Problem: `convex/lib/envValidation.ts` only validates 6 of dozens of env vars. +- Blocks: Confidence at deploy time; missing env vars surface as runtime errors deep inside business logic. -**No Automated Backfill for libraryItemCount:** -- Problem: Users who existed before the denormalized counter was added must trigger a save/remove mutation to get their counter initialized. Until then, every `getLibraryCount` call does a `.take(10_000)` scan. -- Blocks: Consistent O(1) library count performance for all users -- Impact: Degraded query performance for pre-existing users who rarely modify their library. Fix: run a one-time internal mutation to backfill all users. +**Per-plan workspace limits enforced at the schema:** +- Problem: `MAX_PAPERS_PER_JOB` is a hardcoded 500; no plan-tier ceiling. +- Blocks: Differentiated pricing tiers; clear upgrade signals. -## Test Coverage Gaps +**Search-history backup beyond localStorage:** +- Problem: All search history persisted only via Zustand persist (localStorage). No server-side mirror. +- Blocks: Cross-device continuity, recovery after browser data clear, search-history-as-feature-marketing. -**Component/UI Layer:** -- What's not tested: All React components under `components/` -- including critical flows like extraction job creation, question builder, billing page, and search UI. Zero component test files exist. -- Files: All files under `components/`, `app/extraction/[jobId]/page.tsx` -- Risk: UI regressions go unnoticed; refactoring components is risky without test coverage -- Priority: High +**Background recovery for auth sync failures:** +- Problem: `convex-provider` requires a manual `retryUserSync` call after the 6-attempt budget exhausts. +- Blocks: Self-healing UX during transient backend issues. -**Extraction Workpool Actions:** -- What's not tested: Individual steps in `convex/extraction/workpoolActions.ts` -- PDF download, RAG search, evidence unit construction, AI extraction call, credit deduction within the workpool handler. This is the most complex backend module (1,153 lines) with external API calls. -- Files: `convex/extraction/workpoolActions.ts` -- Risk: Only tested indirectly through workflow integration. Individual step failures are not caught. -- Priority: High - -**Full Extraction Workflow Integration Test:** -- What's not tested: The complete extraction flow from `startExtraction` through PDF download, indexing, extraction, to completion. Individual pieces are tested but the end-to-end state machine is not. -- Files: `convex/extraction/mutations.ts`, `convex/extraction/workpoolActions.ts` -- Risk: State machine bugs could leave jobs permanently stuck in intermediate states -- Priority: Medium - -**Zotero Integration:** -- What's not tested: OAuth flow, collection fetching, item syncing in `convex/zotero/actions.ts` (1,110 lines) -- Files: `convex/zotero/actions.ts`, `convex/zotero/mutations.ts` -- Risk: Zotero API changes or OAuth issues would not be caught before production -- Priority: Medium - -**Search Provider:** -- What's not tested: `lib/search/provider.tsx` (722 lines) -- the central search state management context with URL sync and fetch integration -- Files: `lib/search/provider.tsx`, `lib/search/initializer.tsx` -- Risk: Search is the primary user flow; regressions in param serialization or fetch logic affect all users -- Priority: Medium - -**Subscription Schedule Leak Recovery:** -- What's not tested: The SUB-05 schedule leak detection in `convex/subscriptions/actions.ts` logs an error and throws when a Stripe schedule remains attached after release, but the recovery path is not tested. -- Files: `convex/subscriptions/actions.ts` (lines 660-730) -- Risk: Schedule leak could block future plan changes for affected users -- Priority: Medium +## Test Coverage Gaps + +**117 test files exist — strong overall coverage** but the following hot spots are under-tested: + +**Wallet gateway fire-and-forget deduction failure path:** +- What's not tested: The branch in `convex/wallet/gateway/handler.ts:349-359` where the deduction throws after the stream has already returned 200 to the client. +- Files: `convex/wallet/gateway/handler.ts:349-359` +- Risk: Silent revenue loss. +- Priority: High. + +**Auth provider state machine:** +- What's not tested: `components/providers/convex-provider.tsx` state transitions (`anonymous` → `initializing` → `authenticated` → `sync_error` → `synced`) and the 6-retry budget exhaustion. +- Files: `components/providers/convex-provider.tsx` +- Risk: Auth UX regressions slip through. +- Priority: High. + +**Cascade-delete concurrent multi-job interaction:** +- What's not tested: Two jobs cancelling at the same time when `cancelAll()` cancels every pending item. +- Files: `convex/extraction/mutations.ts:274-281`, `convex/extraction/cascade-delete.test.ts`, `tests/extraction/workflow-cancel.test.ts` +- Risk: Data corruption or misbilling under load. +- Priority: High. + +**Zustand store migration ladder:** +- What's not tested: Each of the 7 versions of `migrateSearchHistoryState`. +- Files: `lib/store.ts:184-293` +- Risk: Migration bug corrupts every user's search history. +- Priority: Medium (mitigated by the recommendation to delete the ladder entirely). + +**Crypto helpers under audit pressure:** +- What's not tested: `decryptApiKey` audit branches; what happens when the audit hook itself throws. +- Files: `convex/lib/crypto.ts` +- Risk: Silent failure to log a decryption. +- Priority: Medium. + +**`/api/openalex/search` rate-limiting and error envelope:** +- What's not tested: No tests on the public API route at all. +- Files: `app/api/openalex/search/route.ts` +- Risk: Public abuse vector with no observability. +- Priority: Medium. + +**Stripe webhook concurrency dedup:** +- What's not tested: Two simultaneous webhook deliveries for the same `stripeInvoiceId`. +- Files: `convex/credits/internal.ts:478`, `convex/credits/internal.ts:1397` +- Risk: Duplicate credit grants. +- Priority: High (billing). --- -*Concerns audit: 2026-03-06* +*Concerns audit: 2026-04-14* diff --git a/.planning/codebase/CONVENTIONS.md b/.planning/codebase/CONVENTIONS.md index d9d5fd1cd..f57355b70 100644 --- a/.planning/codebase/CONVENTIONS.md +++ b/.planning/codebase/CONVENTIONS.md @@ -1,197 +1,197 @@ # Coding Conventions -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## Naming Patterns **Files:** -- Use kebab-case for all files: `filter-builder.ts`, `search-actions.ts`, `credit-grant-policy.test.ts` -- React components use kebab-case files: `results-list.tsx`, `paper-card.tsx`, `cookie-consent-banner.tsx` -- Convex backend files use camelCase only for multi-word lib files: `stripeWebhookHandlers.ts`, `userCreation.ts` -- Convex domain modules follow `domain/queries.ts`, `domain/mutations.ts`, `domain/actions.ts` pattern -- Type definition files use `.types.ts` suffix: `ai.types.ts`, `search.types.ts`, `extraction.types.ts` -- Test files use `.test.ts` suffix: `ai-cost.test.ts` (never `.spec.ts` for unit/integration) -- E2E test files use `.spec.ts` suffix: `auth.spec.ts`, `subscribe.spec.ts` +- React components: `kebab-case.tsx` (e.g., `grouped-answer-row.tsx`, `cookie-consent-banner.tsx`, `insights-question-panel.tsx`) +- TypeScript modules: `kebab-case.ts` (e.g., `use-auth-query.ts`, `animation-config.ts`, `feature-flags/registry.ts`) +- Custom hook files: `use-*.ts` / `use-*.tsx` (e.g., `hooks/use-batch-screening.ts`, `hooks/use-mobile.tsx`, `lib/auth/use-sign-in-redirect.ts`) +- Type modules: `*.types.ts` (e.g., `lib/types/extraction.types.ts`, `lib/types/screening.types.ts`) +- Test files: `*.test.ts(x)` (e.g., `tests/auth-state-machine.test.ts`, `tests/components/grouped-answer-row.test.tsx`) +- E2E specs: `*.spec.ts` (e.g., `e2e/auth.spec.ts`) +- Config files: `*.config.ts` / `*.config.mjs` (e.g., `vitest.config.ts`, `next.config.ts`, `playwright.config.ts`) +- Convex modules: lowercase or camelCase (e.g., `convex/lib/auth.ts`, `convex/lib/rateLimit.ts`, `convex/lib/stripeWebhookHandlers.ts`) +- A few PascalCase exceptions for legacy components: `components/Pricing.tsx`, `components/PageContent.tsx`, `components/PageWrapper.tsx` **Functions:** -- Use camelCase for all functions: `buildFilterData()`, `requireAuth()`, `calculateCostInDollars()` -- Convex queries/mutations exported as named `const`: `export const browseLibrary = query({...})` -- Helper/private functions use plain camelCase: `matchesLibraryFilters()`, `assertActiveUser()` -- Factory functions use `create` prefix: `createError()`, `createMockStripeEvent()`, `createDefaultFilters()` -- Boolean-returning functions use `is`/`has` prefix: `isEligibleMonthlyCreditBillingReason()`, `hasActiveLibraryFilters()` +- Pure functions: `camelCase` (e.g., `createDefaultFilters`, `jsonToCSV`, `downloadAsFile`, `getEffectiveSearchId`) +- Hooks: `use*` (e.g., `useFeatureFlag`, `useProtectedQuery`, `useSignInRedirect`) +- React components: `PascalCase` (e.g., `GroupedAnswerRow`, `InsightsOverview`, `Button`) +- Server-side capture/event helpers: action-like camelCase (e.g., `captureAIGenerationServer`, `processClerkWebhookEvent`) +- Convex factories: `createMockQueryCtx`, `createMockMutationCtx`, `createMockUser` +- Boolean predicates: `is*` / `has*` (e.g., `isRatingFilterActive`, `isCountryFilterActive`, `hasConsentDecision`) **Variables:** -- Use camelCase for variables: `collectionItemIds`, `parsedUserId` -- Constants use UPPER_SNAKE_CASE: `SORT_INDEX_MAP`, `DEFAULT_FILTERS`, `ITEMS_PER_PAGE`, `MIN_YEAR` -- Map/lookup constants use UPPER_SNAKE_CASE: `FIELD_KEY_MAP`, `SORT_KEY_MAP`, `ELIGIBLE_MONTHLY_CREDIT_BILLING_REASONS` +- Local variables and props: `camelCase` +- Constants: `SCREAMING_SNAKE_CASE` (e.g., `MIN_YEAR`, `ITEMS_PER_PAGE`, `CONSENT_UPDATED_EVENT`, `EXTRACTION_INSIGHTS_NEW_KEYS`) +- Frozen object maps: `SCREAMING_SNAKE_CASE` with `as const` (e.g., `DEFAULT_FILTERS`, `FLAG_REGISTRY`, `TRACKED_GRANT_EVENT_TYPES`, `COLOR_PALETTE`) +- Discriminated unions and string literals: lowercase string members ("active", "free", "subscription_create") **Types:** -- Use PascalCase for types and interfaces: `AIProvider`, `FilterParams`, `LibraryItem`, `ErrorCode` -- Prefix interfaces with descriptive nouns (no `I` prefix): `AIModel`, `AIProviderConfig`, `SearchFilters` -- Union types for enums over TypeScript `enum`: `type AIProvider = 'openai' | 'google' | 'anthropic' | ...` -- Convex validators use camelCase: `librarySortValidator`, `searchFiltersValidator` - -**React Components:** -- Use PascalCase for component names: `ResultsList`, `PaperCard`, `AppSidebar` -- Props interfaces use `ComponentNameProps` pattern: `PapersListProps` -- Use `"use client"` directive at top of client components +- TypeScript types and interfaces: `PascalCase` (e.g., `SearchFilters`, `PaperResult`, `AuthContext`, `FlagName`, `ResolvedFlags`) +- Type-prefix for context-specific aliases: `AuthContext`, `ActionAuthContext`, `ErrorCode`, `PlanType` +- Validators (Convex): `*Validator` suffix (e.g., `planValidator`, `userStateValidator`, `creditTransactionTypeValidator`, `creditBalanceValidator`) +- Generic helpers: short, descriptive, PascalCase (e.g., `DeepPartial`) ## Code Style **Formatting:** -- No dedicated formatter config (no `.prettierrc` or `.editorconfig` in project root) -- 2-space indentation throughout -- Semicolons used consistently -- Single quotes for string literals in most source files -- Double quotes acceptable in JSX attributes -- Trailing commas in multi-line arrays/objects +- No Prettier config file detected at the project root (`.prettierrc*` not present) +- Indentation: 2 spaces (consistent across `.ts`, `.tsx`, and JSON) +- Quotes: double quotes for TS/TSX strings; single quotes seen in some legacy files (`lib/utils.ts`) +- Semicolons: used consistently in modern files; legacy `lib/utils.ts` mixes styles +- Trailing commas: present in multi-line objects, function args, and TS generics **Linting:** -- No project-level ESLint config detected -- Knip used for dead code detection: `knip.json` -- TypeScript strict mode enabled in `tsconfig.json` -- React Compiler enabled in `next.config.ts` (`reactCompiler: true`) +- No ESLint config file present at root (no `.eslintrc*`, no `eslint.config.*`) +- `knip.json` configured to detect unused exports/files (ignores `ecosystem.config.js`) +- Custom shell script enforces `no-any` discipline: `scripts/verify-no-any.sh` + - Forbids `: any`, `as any`, `any[]`, and `` in `app/`, `components/`, `lib/`, `convex/`, `tests/` + - Excludes `convex/_generated/` (auto-generated) + - Runs `tsc --noEmit` as final gate +- A few `eslint-disable-next-line @typescript-eslint/no-explicit-any` comments survive in components that proxy `useTranslations` (e.g., `components/extraction/grouped-answer-row.tsx:37`, `components/extraction/insights-overview.tsx:30`) **TypeScript:** -- Strict mode with `"strict": true` -- `"noEmit": true` (Next.js handles compilation) -- Module resolution: `"bundler"` -- Target: `"ES2017"` +- `strict: true` enforced via `tsconfig.json` +- `noEmit: true` (typecheck-only) +- `moduleResolution: "bundler"` +- Path alias `@/*` maps to project root +- Target ES2017, lib `dom`, `dom.iterable`, `esnext` ## Import Organization -**Order:** -1. Node built-ins: `import path from "node:path"`, `import { readFileSync } from "node:fs"` -2. External packages: `import { describe, expect, it } from "vitest"`, `import { v } from "convex/values"` -3. Internal aliases using `@/`: `import { cn } from "@/lib/utils"`, `import { useSearch } from "@/lib/search"` -4. Relative imports: `import { requireAuth } from "../lib/auth"`, `import { createMockStripeEvent } from "./factories"` +**Order (observed pattern across `lib/`, `components/`, `convex/`):** +1. Built-in / third-party packages (e.g., `import { useState } from "react"`, `import { create } from "zustand"`, `import { ConvexError } from "convex/values"`) +2. Type-only imports from third-party packages (e.g., `import type { FunctionReference } from "convex/server"`) +3. Internal aliased modules via `@/` (e.g., `import { api } from "@/convex/_generated/api"`, `import { Button } from "@/components/ui/button"`) +4. Relative imports for sibling modules (e.g., `import { SummaryCards } from "./summary-cards"`) +5. Type-only relative imports last (e.g., `import type { Doc } from "../convex/_generated/dataModel"`) **Path Aliases:** -- `@/*` maps to project root `"./*"` (configured in `tsconfig.json`) -- Use `@/components/...`, `@/lib/...`, `@/hooks/...` in Next.js app/component code -- Use relative imports (`../`, `./`) in Convex backend code and test files - -**Type imports:** -- Use `import type` for type-only imports: `import type { Doc, Id } from "../_generated/dataModel"` -- Mixed imports separate values from types: `import { v } from "convex/values"` + `import type { Cursor } from "convex/server"` +- `@/*` → project root (defined in `tsconfig.json` and mirrored in `vitest.config.ts`) +- Used liberally throughout the app: `@/components/...`, `@/lib/...`, `@/convex/_generated/...`, `@/hooks/...` ## Error Handling -**Convex Backend:** -- Use typed error codes via `createError()` from `convex/lib/errors.ts` -- Error codes are UPPER_SNAKE_CASE string literals: `"UNAUTHENTICATED"`, `"FORBIDDEN"`, `"NOT_FOUND"` -- Errors wrap `ConvexError` with `{ code, message }` payload -- Auth errors throw immediately at handler entry via `requireAuth(ctx)` -- Domain-specific error codes are namespaced: `AI_*`, `BILLING_*`, `ZOTERO_*`, `CREDITS_*` - -```typescript -// Pattern: use createError() for all backend errors -import { createError } from "../lib/errors"; -throw createError("UNAUTHENTICATED", "Authentication required"); -throw createError("NOT_FOUND", "Item not found"); -throw createError("AI_INSUFFICIENT_CREDITS", "Not enough credits"); -``` - -**Frontend:** -- Error resolver in `lib/toast/error-resolver.ts` maps Convex error codes to i18n toast message keys -- Toast notifications via sonner (configured in `components/ui/sonner.tsx`) -- Action routing in `lib/toast/action-routing.ts` attaches CTA buttons to specific error toasts - -**General:** -- Empty `catch {}` blocks acceptable for best-effort cleanup (e.g., sign-out in e2e teardown) -- Never silently swallow errors in business logic +**Convex (server) errors:** +- Centralized error factory in `convex/lib/errors.ts` exporting `createError(code, message)` +- All error codes are members of a discriminated union `ErrorCode` (over 60 codes covering auth, billing, AI, wallet, screening, integrations) +- Throws `ConvexError` so the client can switch on `err.data.code` +- Example pattern in `convex/lib/auth.ts`: + ```ts + if (!identity) { + throw createError("UNAUTHENTICATED", "Authentication required"); + } + ``` +- State-based assertions live in dedicated helpers (e.g., `assertActiveUser` in `convex/lib/auth.ts`) + +**Client (UI) errors:** +- Display fallbacks via discriminated `status` fields on query responses (e.g., `insights.status === "ok" | "no_access" | "unauthenticated"` in `components/extraction/insights-overview.tsx`) +- Toast-based user error surfacing via `lib/toast/` helpers (tested in `tests/toast-action-routing.test.ts`, `tests/toast-error-resolver.test.ts`) +- Form/file errors thrown as `new Error(...)` with descriptive messages (see `lib/utils.ts` `uploadFile`) + +**API routes:** +- `try`/`catch` wrapper returning `NextResponse.json({ error }, { status })` (see `app/api/openalex/search/route.ts`) +- Validation errors return `400`; missing required params return `400` with explicit messages + +**Webhook handlers:** +- Return `{ status, body }` shape so transport layer can dispatch (see `processClerkWebhookEvent` in `convex/webhooks/clerk.ts`) +- Malformed payloads return `400`; unknown events return `200` with no-op ## Logging -**Framework:** Console (no structured logging library) +**Framework:** Structured server-side analytics via PostHog HTTP API; no general logger abstraction **Patterns:** -- Backend: Convex provides built-in logging for function calls -- Debug gating via `convex/lib/debug_gate.ts` for conditional debug output -- PostHog analytics integration for user-facing events (`lib/posthog-ai.ts`, `lib/posthog-server.ts`) +- Server-side AI usage capture is fire-and-forget via `captureAIGenerationServer` and `captureServerEvent` in `lib/posthog-server.ts` + - Wraps `fetch` to PostHog `/i/v0/e/` endpoint + - Swallows errors to avoid breaking the main flow +- Client-side analytics via `posthog-js` initialized in `instrumentation-client.ts` +- Test artifacts use append-only file logging via `appendBillingArtifactLog` in `tests/live-billing/support.ts` +- Convex audit logging lives in `convex/lib/audit.ts` +- No `console.log` litter in production code; relies on structured analytics events ## Comments **When to Comment:** -- File-level JSDoc describing module purpose: `/** Filter Builder - Core logic for building structured filter data */` -- Section dividers in test files and factories use ASCII art: `// ---------------------------------------------------------------------------` -- Inline comments for non-obvious business logic or Stripe-specific behavior -- Step comments in E2E tests: `// 1. Subscribe via checkout-bypass`, `// 2. Wait for Convex webhook processing` +- File-level JSDoc blocks describe module purpose at the top (e.g., `lib/posthog-server.ts`, `lib/feature-flags/registry.ts`, `lib/animation-config.ts`) +- Function-level JSDoc on exported helpers and complex logic (e.g., `getEffectiveSearchId` in `lib/utils.ts`, `useFeatureFlag` in `lib/feature-flags/hook.ts`) +- Section dividers using `// ─── Section ────` are common in `convex/wallet/wallet.test.ts` and `tests/factories/convex-context.ts` +- Inline comments explain non-obvious type bridging (e.g., `Cast to never to satisfy Convex's exact generic constraint` in `lib/auth/use-auth-query.ts`) **JSDoc/TSDoc:** -- Used on exported types and interfaces in type definition files -- Used on Page Object Model methods in e2e page objects -- Not required on every function -- used when purpose is non-obvious +- Standard JSDoc, no required tags +- Used to document `@param` and `@returns` on exported pure functions (see `lib/utils.ts` `getEffectiveSearchId`) +- Avoid stale "old/new" or "before/after" comments — codebase follows current-state-only documentation ## Function Design -**Size:** Functions are generally focused and small (10-40 lines). Helper functions are extracted when logic is reusable. +**Size:** Small, single-purpose helpers preferred. Functions over ~80 lines tend to be Convex action handlers, top-level routes, or React components with substantial JSX. **Parameters:** -- Convex handlers receive `(ctx, args)` where args are validated via `v` validators -- Complex parameter objects use destructuring or typed interfaces -- Optional parameters via `v.optional()` in Convex, `?` in TypeScript +- Single object parameter for >2 args (e.g., `processClerkWebhookEvent({ eventId, eventType, data, runMutation, mutationRefs })`) +- Optional named parameters via `overrides?: { ... }` pattern in factories (`tests/factories/convex-context.ts`) +- Use of `DeepPartial` for selective overrides in test factories **Return Values:** -- Convex queries return typed documents or arrays -- Convex mutations return IDs or null -- Helper functions return explicit types, avoid `any` +- Discriminated unions for status-bearing responses: `{ status: "ok", ... } | { status: "no_access" }` +- Branded types for IDs: `Id<"users">` from Convex +- Tuples for fixed-length lists: `[number, number]` for ranges ## Module Design **Exports:** -- Named exports preferred over default exports -- Default exports used only for Next.js pages/layouts and Convex schema -- Barrel files (`index.ts`) used for grouped modules: `lib/types/index.ts`, `lib/filters/index.ts` -- Barrel files re-export with explicit `export type` for types and `export` for values - -**Convex Module Pattern:** -- Each domain has a directory: `convex/library/`, `convex/users/`, `convex/subscriptions/` -- Split into `queries.ts`, `mutations.ts`, `actions.ts`, and optionally `internal.ts` -- Shared logic in `convex/lib/` directory -- Sub-domain libs in `convex/domain/lib/`: `convex/subscriptions/lib/schedulePlanning.ts` +- Named exports preferred (no default-export bias) +- Default exports reserved for Next.js page components (`app/**/page.tsx`) and client singletons (`lib/openalex.ts`) +- Re-export barrels for type aggregation (`lib/types/index.ts`, `tests/factories/index.ts`) + +**Barrel Files:** +- `lib/types/index.ts` aggregates all type exports across `lib/types/*.types.ts` +- `tests/factories/index.ts` re-exports `convex-context`, `convex-ids`, `stripe-events` +- Convex modules avoid barrels — each file exports its own queries/mutations/actions + +## React Conventions + +**Client/server boundary:** +- All interactive components start with `"use client"` directive (e.g., `components/extraction/grouped-answer-row.tsx`, `components/cookie-consent-banner.tsx`) +- Server components and Convex query handlers omit the directive + +**Component structure:** +- Props interface declared above the component, typically named `*Props` (e.g., `GroupedAnswerRowProps`, `InsightsOverviewProps`) +- Internal small subcomponents declared in the same file when only used locally (e.g., `MiniBar` in `components/extraction/insights-question-panel.tsx`) +- Class composition via `cn(...)` from `lib/utils.ts` (clsx + tailwind-merge) +- Variant patterns use `class-variance-authority` (`cva`) — see `components/ui/button.tsx` +- Animation values pulled from `lib/animation-config.ts` (`subtleSpring`, `cardEntrance`, `commandCenterSpring`) rather than inlined + +**State management:** +- Global state via Zustand stores in `lib/store.ts` with `persist` middleware and JSON storage +- Server state via Convex `useQuery` wrapped by `useProtectedQuery` / `useOptionalAuthQuery` in `lib/auth/use-auth-query.ts` +- Search params via `nuqs` (URL-as-state) +- Local state via `useState`, memoization via `useMemo`/`useCallback` -## State Management - -**Client State:** -- Zustand stores in `lib/store.ts` with `persist` middleware for localStorage -- Each store is a separate `create()` call: `useRatingsStore`, `useSearchHistoryStore`, `useUIStore` - -**Server State:** -- Convex reactive queries for real-time data -- SWR for OpenAlex API calls (`swr` package) -- `nuqs` for URL search parameter state synchronization +**Styling:** +- TailwindCSS v4 with `@tailwindcss/postcss` +- Theme via `next-themes` and OKLCH colors +- Dark-mode classes via `dark:` prefix +- Custom UI primitives in `components/ui/` (shadcn-derived) ## Internationalization -**Framework:** `next-intl` (v4) +- Strings consumed via `useTranslations(namespace)` from `next-intl` +- All i18n keys must exist across all 6 supported locales (en-US, en-GB, fr, ja, zh, hi) — enforced by `tests/extraction-i18n-coverage.test.ts` +- Translation files under `messages/*.json` +- Locale matchers via `@formatjs/intl-localematcher` -**Patterns:** -- Translation files in `messages/`: `en-US.json`, `en-GB.json`, `fr.json`, etc. -- Server components use `getTranslations()` from `next-intl/server` -- Client components use `useTranslations()` hook -- Locale detection in `i18n/locale-detection.ts` -- All user-facing strings should use translation keys, not hardcoded strings - -## UI Component Patterns - -**Component Library:** shadcn/ui (new-york style) -- Configuration in `components.json` -- UI primitives in `components/ui/`: `button.tsx`, `card.tsx`, `dialog.tsx` -- Radix UI primitives via `radix-ui` package -- Icons via `lucide-react` - -**Styling:** -- Tailwind CSS v4 with `@tailwindcss/postcss` -- `cn()` utility from `lib/utils.ts` for conditional class merging (clsx + tailwind-merge) -- CSS variables for theming (configured via shadcn) -- Animation via `motion` (Framer Motion) package +## Convex Conventions -**Component Organization:** -- UI primitives in `components/ui/` -- Feature components directly in `components/` -- Sub-features in `components/feature-name/`: `components/command-center/` +- Always read `convex/_generated/ai/guidelines.md` before working on Convex code (per `CLAUDE.md`) +- All public functions specify `args` and `returns` validators using `v.*` from `convex/values` +- Validators centralized in `convex/lib/validators.ts` and reused across queries/mutations +- Internal vs. public separation: `convex/credits/internal.ts` vs `convex/credits/queries.ts` +- Generated artifacts under `convex/_generated/` are off-limits to manual edits --- -*Convention analysis: 2026-03-06* +*Convention analysis: 2026-04-14* diff --git a/.planning/codebase/INTEGRATIONS.md b/.planning/codebase/INTEGRATIONS.md index 2a622b48a..d7e4104ef 100644 --- a/.planning/codebase/INTEGRATIONS.md +++ b/.planning/codebase/INTEGRATIONS.md @@ -1,201 +1,215 @@ # External Integrations -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## APIs & External Services -**Academic Data:** -- OpenAlex API - Primary source for academic paper metadata (works, authors, institutions, etc.) - - SDK: `@sickrin/openalex-sdk` ^1.0.0 - - Client: `lib/openalex.ts` (singleton `OpenAlexClient`) - - Auth: No API key required (public API) - -**AI / LLM Providers:** -- Multi-provider AI via Vercel AI SDK (`ai` ^6.0.62) - - Provider selection: `lib/ai/server/providers.ts` (`getProviderModel()`) - - Server config: `convex/ai/config.ts` (`SERVER_AI_CONFIG`) - - Default: DeepSeek (`deepseek-chat`) - - Supported providers (env var: `AI_PROVIDER`): - - OpenAI (`@ai-sdk/openai`) - env: `OPENAI_API_KEY` - - Anthropic (`@ai-sdk/anthropic`) - env: `ANTHROPIC_API_KEY` - - Google (`@ai-sdk/google`) - env: `GOOGLE_GENERATIVE_AI_API_KEY` - - DeepSeek (`@ai-sdk/deepseek`) - env: `DEEPSEEK_API_KEY` - - Azure OpenAI (`@ai-sdk/azure`) - env: `AZURE_OPENAI_API_KEY` - - OpenRouter (`@openrouter/ai-sdk-provider`) - env: `OPENROUTER_API_KEY` - - BYOK support: Users can bring their own API keys (stored encrypted in `apiKeys` table) - - AI operations: `convex/ai/helpers.ts` (`withAuthAndCredits`, `withUserCreditsBatch`, `createAIAction`) - - Credit-based billing: AI operations deduct credits based on token usage with markup (`AI_COST_MARKUP`) - -**Reference Management:** -- Zotero API - User library sync and paper import - - OAuth 1.0a flow: `convex/zotero/actions.ts` - - Callback endpoint: `convex/http.ts` route `/api/zotero/callback` - - Connections stored in `zoteroConnections` table (encrypted API keys) - - OAuth tokens: `zoteroOAuthTokens` table (short-lived, cleaned hourly by cron) +**Authentication & Identity (Clerk):** +- **Clerk** — end-user authentication, sign-in/sign-up flows, JWT issuance for Convex + - Client SDK: `@clerk/nextjs` ^6.38.2 (wraps app via `ClerkProvider` in `components/providers/convex-provider.tsx`) + - Server SDK: `@clerk/backend` ^2.32.1 + - Theming/localization: `@clerk/themes` ^2.4.55, `@clerk/localizations` ^3.37.0 — resolved per-locale/theme in `lib/auth/clerk-ui-config.ts` (referenced from `convex-provider.tsx`) + - Auth middleware: `clerkMiddleware` in `proxy.ts` (Next.js edge middleware); protects paths via `shouldProtectPath` from `lib/auth/proxy-policy.ts` + - Convex JWT config: `convex/auth.config.ts` — `domain: process.env.CLERK_JWT_ISSUER_DOMAIN`, `applicationID: "convex"` + - Sign-in/sign-up routes: `app/sign-in/[[...sign-in]]/`, `app/sign-up/` + - Testing helpers: `@clerk/testing` ^1.14.1 (Playwright fixtures, `e2e/global.setup.ts`) + - Env vars: `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`, `CLERK_SECRET_KEY`, `CLERK_JWT_ISSUER_DOMAIN`, `CLERK_WEBHOOK_SIGNING_SECRET`, `NEXT_PUBLIC_CLERK_SIGN_IN_URL`, `NEXT_PUBLIC_CLERK_SIGN_UP_URL` + +**Payments & Billing (Stripe):** +- **Stripe** — subscriptions, one-time credit top-ups, invoicing, webhooks + - Node SDK: `stripe` ^20.3.0 — used in `convex/credits/actions.ts`, `convex/subscriptions/actions.ts`, `convex/maintenance/internal.ts`, `convex/lib/stripeCustomer.ts`, `convex/lib/stripeWebhookHandlers.ts`, `scripts/billing-preflight.mjs`, `e2e/billing/stripe-helpers.ts`, `tests/live-billing/support.ts` + - Convex component: `@convex-dev/stripe` ^0.1.4 — registered in `convex/convex.config.ts`; client in `convex/stripe.ts` (`StripeSubscriptions(components.stripe, {})`) + - Plans: `free`, `go`, `pro`, `enterprise` (see `convex/schema.ts` `subscriptions` table, `convex/lib/constants.ts`) + - Price IDs (env): `STRIPE_GO_PRICE_ID`, `STRIPE_PRO_PRICE_ID`, `STRIPE_ENTERPRISE_PRICE_ID` + - Credit top-up product: `STRIPE_CREDITS_PRODUCT_ID`, credit rate via `CREDITS_PER_USD` + - Env vars: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, plus price IDs above + +**AI / LLM Providers (via Vercel AI SDK):** +- **OpenAI** — `@ai-sdk/openai` ^3.0.23 (factory in `lib/ai/server/providers.ts`) +- **Anthropic** — `@ai-sdk/anthropic` ^3.0.31 +- **Google** — `@ai-sdk/google` ^3.0.18 (Generative AI / Gemini) +- **Azure OpenAI** — `@ai-sdk/azure` ^3.0.26 +- **DeepSeek** — `@ai-sdk/deepseek` ^2.0.15 +- **OpenRouter** — `@openrouter/ai-sdk-provider` ^6.0.0-alpha.1 — also used as the unified model catalog source (see below) +- Default provider/model (server): `AI_PROVIDER=deepseek`, `AI_MODEL=deepseek-chat` (`convex/ai/config.ts`) +- OpenRouter routing tuning: `OPENROUTER_PROVIDER_ORDER` (comma list), `OPENROUTER_ALLOW_FALLBACKS` (boolean, default `true`) +- AI runtime entrypoints: `lib/ai/core/execute.ts`, `lib/ai/client/*.ts`, `convex/ai/*.ts`, `convex/wallet/gateway/handler.ts` +- API key storage: user-supplied keys encrypted with `ENCRYPTION_KEY` and stored in Convex; decryption via `convex/lib/crypto.ts` (`encrypt`, `decryptApiKey`, `getKeyPrefix`) — referenced from `convex/apiKeys/actions.ts`, `convex/zotero/actions.ts`, `convex/extraction/workpoolActions.ts` + +**Model Catalog (OpenRouter):** +- Daily sync of OpenRouter model metadata into Convex `models` table +- Source: `https://openrouter.ai/api/v1/models` (see `convex/models/sync.ts` `OPENROUTER_MODELS_URL`) +- Cron: `sync openrouter models` every 24 hours (`convex/crons.ts` → `internal.models.sync.syncFromOpenRouter`) +- Stored fields include provider, modality, pricing per-million tokens (input, output, cache read/write, reasoning, web search, image, audio), context length, supported parameters (`convex/schema.ts` `models` table) + +**Research Data (OpenAlex):** +- **OpenAlex** — public research metadata API covering 250M+ works + - SDK: `@sickrin/openalex-sdk` ^1.0.0 — default client in `lib/openalex.ts` (`new OpenAlexClient()`) + - Used by: `app/api/openalex/search/route.ts` (Next.js Route Handler for search) + - Direct HTTP usage: `convex/extraction/actions.ts` hits `https://api.openalex.org/works` with `URLSearchParams` for extraction workflows + - Abstract reconstruction helper: `lib/openalex/reconstruct-abstract.ts` + - Polite-pool contact email: `OPENALEX_CONTACT_EMAIL` (used in `convex/extraction/actions.ts`) + +**Reference Manager (Zotero):** +- **Zotero** — OAuth 1.0a flow and library import + - Endpoints (constants in `convex/zotero/actions.ts`): + - Request token: `https://www.zotero.org/oauth/request` + - Access token: `https://www.zotero.org/oauth/access` + - Authorize: `https://www.zotero.org/oauth/authorize` + - API base: `https://api.zotero.org` + - OAuth signing: HMAC-SHA1 via Node `crypto` (`convex/zotero/actions.ts`) + - API credentials encrypted with `ENCRYPTION_KEY` and persisted in Convex + - Env vars: `ZOTERO_CLIENT_KEY`, `ZOTERO_CLIENT_SECRET`, `ENCRYPTION_KEY` + - Expired OAuth request tokens cleaned hourly via `cleanup expired zotero oauth tokens` cron (`convex/crons.ts`) + +**Product Analytics & Error Tracking (PostHog):** +- **PostHog** — product analytics, heatmaps, error tracking (EU region) + - Client: `posthog-js` ^1.342.1 (init in `instrumentation-client.ts` with `api_host: "/data"`, GDPR `cookieless_mode: "on_reject"`, `opt_out_capturing_by_default: true`, `capture_exceptions: true`, `person_profiles: "always"`, `capture_heatmaps: true`, defaults `"2026-01-30"`) + - Reverse proxy rewrites in `next.config.ts`: `/data/static/:path*` → `https://eu-assets.i.posthog.com/static/:path*`; `/data/:path*` → `https://eu.i.posthog.com/:path*` + - Server helpers: `lib/posthog-server.ts`, `lib/posthog-ai-shared.ts`, `lib/posthog-ai.ts`, `lib/posthog-search.ts` + - Consent banner: `components/cookie-consent-banner.tsx` (gated on `NEXT_PUBLIC_POSTHOG_KEY`) + - Env vars: `NEXT_PUBLIC_POSTHOG_KEY`, `NEXT_PUBLIC_POSTHOG_HOST`, `POSTHOG_KEY`, `POSTHOG_HOST` + +**Google Analytics:** +- **Google Analytics (GA4)** — via `@next/third-parties` ^16.2.2 + - Component: `components/google-analytics.tsx` (consent-aware; only in `NODE_ENV=production`) + - Env var: `NEXT_PUBLIC_GA_ID` ## Data Storage -**Database:** -- Convex - Primary database (document-oriented, real-time) - - Schema: `convex/schema.ts` (20+ tables) - - Core tables: `users`, `credits`, `creditTransactions`, `subscriptions`, `billingCustomers` - - Feature tables: `extractionJobs`, `extractionPapers`, `extractionResults`, `extractionQuestions`, `extractionEvidenceUnits` - - Library tables: `libraryItems` (with full-text search index), `collections`, `libraryItemCollections` - - Integration tables: `apiKeys`, `zoteroConnections`, `zoteroOAuthTokens` - - Audit: `auditLogs`, `stripeEventLogs` - - Rate limiting: `rateLimitTables` from convex-helpers +**Primary Database (Convex):** +- **Convex Cloud** — reactive DB + functions (`convex` ^1.34.1) + - Schema: `convex/schema.ts` (defines `models`, `featureFlags`, `users`, `credits`, `creditTransactions`, `subscriptions`, `billingCustomers`, plus `...rateLimitTables` from `convex-helpers`, extraction tables, library tables, wallet tables, etc.) + - Components registered in `convex/convex.config.ts`: `stripe`, `rag`, `workflow`, `workpool`, `screeningWorkpool` (second workpool instance) + - Key tables (non-exhaustive): `users` (synced from Clerk by `clerkId`), `credits` (free+paid balances), `creditTransactions` (Stripe idempotency via `stripeInvoiceId`, `stripePaymentIntentId`, `stripeChargeId`, `stripeCheckoutSessionId`), `subscriptions` (plans `free`/`go`/`pro`/`enterprise`, Stripe IDs), `billingCustomers` (user ↔ Stripe customer mapping), `models` (OpenRouter catalog), `featureFlags` + - Env vars: `NEXT_PUBLIC_CONVEX_URL`, `NEXT_PUBLIC_CONVEX_SITE_URL`, `CONVEX_CLOUD_URL`, optional self-hosted: `CONVEX_SELF_HOSTED_URL`, `CONVEX_SELF_HOSTED_ADMIN_KEY` + - Client initialization: `ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!)` in `components/providers/convex-provider.tsx` + - Auth bridge: `ConvexProviderWithClerk` from `convex/react-clerk` -**File Storage:** -- Convex file storage (`_storage`) - PDF storage for extraction pipeline - - Referenced by `extractionPapers.storageId` +**Retrieval-Augmented Generation:** +- `@convex-dev/rag` ^0.7.2 — vector/RAG storage component (registered in `convex/convex.config.ts`) — used for document chunking/retrieval during extraction (`convex/extraction/chunking.ts`, `convex/extraction/evidence_units.ts`) -**Search / RAG:** -- `@convex-dev/rag` ^0.7.0 - Vector search for extraction pipeline - - Config: `convex/convex.config.ts` (registered as component) - - Used for PDF content indexing and retrieval during data extraction - - Papers indexed via `extractionPapers.ragEntryId` / `isIndexed` +**File Storage:** +- Convex file storage (uploads via `convex/extraction/uploads.ts` — PDF uploads for extraction pipeline) +- No S3/GCS/Azure Blob integration detected **Caching:** -- SWR (client-side) - React data fetching with caching -- Convex reactive queries - Real-time subscriptions (implicit caching) +- SWR ^2.3.3 — client-side caching/revalidation +- Convex reactive queries — server-side real-time cache +- No Redis/Memcached detected ## Authentication & Identity -**Auth Provider:** -- Clerk - Authentication and user management - - SDK: `@clerk/nextjs` ^6.38.2 - - Middleware: `proxy.ts` (Clerk middleware with locale detection) - - Convex auth config: `convex/auth.config.ts` (JWT issuer domain from env) - - Webhook sync: `convex/webhooks/clerk.ts` - Syncs Clerk user events to Convex `users` table - - Webhook endpoint: `/webhooks/clerk` (POST) - - Webhook verification: `svix` ^1.86.0 - - Route protection: `lib/auth/proxy-policy.ts` (`shouldProtectPath`) - - Sign-in/up routes: `app/sign-in/`, `app/sign-up/` - - Localizations: `@clerk/localizations` ^3.37.0 - - Themes: `@clerk/themes` ^2.4.55 - - Testing: `@clerk/testing` ^1.14.1, `@clerk/backend` ^2.32.1 - -**Encryption:** -- AES-256-GCM encryption for stored API keys and Zotero credentials - - Implementation: `convex/lib/crypto.ts` (`encrypt`, `decrypt`, `decryptApiKey`) - - Key: `ENCRYPTION_KEY` env var (32-byte hex) +**Primary Provider:** Clerk +- Integration pattern: `ClerkProvider` → `ConvexProviderWithClerk` → `FeatureFlagProvider` → app (`components/providers/convex-provider.tsx`) +- Local user sync: `api.users.mutations.ensureUser` called from `AuthReadinessProvider` with exponential-backoff retry (base 1s, cap 30s, max 6 attempts) +- Users table single source of truth in Convex (`users` in `convex/schema.ts`, indexed `by_clerk_id`, `by_email`, `by_state`) +- Route protection: `proxy.ts` checks `shouldProtectPath` and calls `auth.protect()` +- JWT issuer validated by Convex via `CLERK_JWT_ISSUER_DOMAIN` -## Monitoring & Observability +**Secrets Encryption:** +- Application-level symmetric encryption for user-supplied API keys and OAuth tokens +- Key: `ENCRYPTION_KEY` env var +- Implementation: `convex/lib/crypto.ts` (`encrypt`, `decryptApiKey`, `getKeyPrefix`) with structured audit logging on decryption (see `resolveZoteroApiKey` in `convex/zotero/actions.ts`) -**Product Analytics:** -- PostHog (EU instance) - - Client init: `instrumentation-client.ts` - - Proxied through Next.js rewrites to `eu.i.posthog.com` (privacy-friendly) - - GDPR compliant: `cookieless_mode: "on_reject"`, `opt_out_capturing_by_default: true` - - Features: exception capture, heatmaps, person profiles - - AI tracking: `lib/posthog-server.ts` (`captureAIGenerationServer`) - tracks all AI operations - - Search tracking: `lib/posthog-search.ts` - - Consent management: `lib/consent-storage.ts`, `components/cookie-consent-banner.tsx` +## Monitoring & Observability **Error Tracking:** -- PostHog Error Tracking (`capture_exceptions: true`) +- PostHog Error Tracking via `posthog-js` (`capture_exceptions: true` in `instrumentation-client.ts`) **Logs:** -- Console logging in Convex functions (structured `[TAG]` prefixes) -- Audit logs stored in `auditLogs` table for security-relevant events -- Stripe event logs in `stripeEventLogs` table (lifecycle tracking: received -> processed/failed) +- `console.log`/`console.error` throughout Convex functions (e.g. `convex/http.ts` Stripe webhook logs: `[StripeWebhook] checkout.session.completed ...`) +- Audit logs: `internal.lib.audit.writeAuditLog` mutation (`convex/lib/audit.ts`) — used for env-validation failures, decryption events, webhook outcomes +- Stripe event log: `stripeEventLogs` table tracked via `markStripeEventProcessed`, `markStripeEventFailed`, `markStripeEventRetrying`, `recordStripeEventReceived` (`convex/subscriptions/internal.ts`) + +**Health Checks / Crons (`convex/crons.ts`):** +- `cleanup deleted users` — daily (`internal.maintenance.mutations.cleanupDeletedUsers`) +- `check subscription status` — hourly corrective sync (`internal.maintenance.internal.checkSubscriptionStatus`) +- `monitor failed stripe events` — hourly flagging (`internal.maintenance.mutations.monitorFailedStripeEvents`) +- `reconcile stripe paid invoices` — hourly (`internal.credits.actions.reconcileRecentPaidInvoicesFromStripe`) +- `cleanup expired zotero oauth tokens` — hourly (`internal.zotero.mutations.cleanupExpiredOAuthTokens`) +- `sync openrouter models` — daily (`internal.models.sync.syncFromOpenRouter`) +- `validate required env vars` — daily (`internal.lib.envValidation.checkRequiredEnvVars`) ## CI/CD & Deployment **Hosting:** -- Next.js frontend: Deployment target not explicitly configured (likely Vercel) -- Convex backend: Convex Cloud (deploy via `npx convex deploy`) - -**CI Pipeline:** -- Test commands configured in `package.json`: - - `test:ci` - Unit tests + build + E2E auth tests - - `test:all` - Full suite including billing E2E - - `test:billing:live:ci` - Live Stripe billing tests with Convex push -- Playwright CI config: 2 retries, 1 worker, GitHub reporter - -**Dev Process Management:** -- PM2 via `ecosystem.config.js` - Runs `next dev` and `convex dev` concurrently -- Start with `npm run dev:all` - -## Billing & Payments - -**Stripe Integration:** -- SDK: `stripe` ^20.3.0 -- Convex component: `@convex-dev/stripe` ^0.1.3 - - Config: `convex/stripe.ts` (StripeSubscriptions client) - - Convex config: `convex/convex.config.ts` -- Webhook endpoint: `/webhooks/stripe` (POST) - - Handler: `convex/http.ts` (registered via `registerRoutes`) - - Secret: `STRIPE_WEBHOOK_SECRET` env var - - Event handlers with idempotency contracts (INFRA-03): - - `checkout.session.completed` - Subscription checkout completion - - `payment_intent.succeeded` - Credit top-up purchases - - `charge.refunded` - Refund processing - - `invoice.paid` - Monthly credit grants - - `invoice.payment_failed` - Payment failure handling - - `customer.subscription.created/updated/deleted` - Subscription lifecycle - - All events logged to `stripeEventLogs` table - - Webhook handlers in `convex/lib/stripeWebhookHandlers.ts` -- Plans: free, go, pro, enterprise (price IDs: `STRIPE_GO_PRICE_ID`, `STRIPE_PRO_PRICE_ID`) -- Credit system: `convex/credits/` - Free + paid balances, usage tracking, transactions -- Customer mapping: `billingCustomers` table (durable user-to-Stripe identity) -- Billing preflight: `scripts/billing-preflight.mjs` - -## Webhooks & Callbacks - -**Incoming:** -- `/webhooks/clerk` (POST) - Clerk user lifecycle events (create, update, delete) - - Handler: `convex/webhooks/clerk.ts` - - Mappers: `convex/webhooks/clerk_mappers.ts` -- `/webhooks/stripe` (POST) - Stripe billing events - - Handler: `convex/http.ts` via `@convex-dev/stripe` registerRoutes -- `/api/zotero/callback` (GET) - Zotero OAuth 1.0a callback - - Handler: `convex/http.ts` inline httpAction - -**Outgoing:** -- PostHog event capture (analytics) -- Stripe API calls (subscription management, invoice reconciliation) -- AI provider API calls (OpenAI, Anthropic, Google, DeepSeek, Azure, OpenRouter) -- OpenAlex API calls (paper search/metadata) -- Zotero API calls (library access) - -## Scheduled Jobs (Crons) - -Defined in `convex/crons.ts`: -- **Every 24h:** Cleanup soft-deleted users (`maintenance.mutations.cleanupDeletedUsers`) -- **Every 1h:** Check subscription status / corrective sync (`maintenance.internal.checkSubscriptionStatus`) -- **Every 1h:** Monitor failed Stripe events (`maintenance.mutations.monitorFailedStripeEvents`) -- **Every 1h:** Reconcile Stripe paid invoices (`credits.actions.reconcileRecentPaidInvoicesFromStripe`) -- **Every 1h:** Cleanup expired Zotero OAuth tokens (`zotero.mutations.cleanupExpiredOAuthTokens`) -- **Every 24h:** Validate required env vars (`lib.envValidation.checkRequiredEnvVars`) +- **Vercel** — Next.js deployment, project `openalex-count` (`.vercel/project.json`) +- **Convex Cloud** — backend deployment (`NEXT_PUBLIC_CONVEX_URL`) + +**CI Pipeline (GitHub Actions):** +- `.github/workflows/ci.yml`: + - Job `unit-and-build` — Node 22, `npm ci`, `npm run test`, `npm run build` with placeholder Clerk + Convex env + - Job `e2e-auth` — depends on unit-and-build; runs `npm run test:e2e:auth` with secrets `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`, `CLERK_SECRET_KEY`, `NEXT_PUBLIC_CLERK_SIGN_IN_URL`, `NEXT_PUBLIC_CLERK_SIGN_UP_URL`, `NEXT_PUBLIC_CONVEX_URL`, `CLERK_JWT_ISSUER_DOMAIN`, `CLERK_WEBHOOK_SIGNING_SECRET`, `E2E_CLERK_USER_EMAIL`, `E2E_CLERK_USER_PASSWORD` +- `.github/workflows/billing-nightly.yml` — nightly billing live tests + +**Test Suites:** +- Unit / contract (Vitest): `tests/**` + `convex/**/*.test.ts` +- Convex function tests in edge-runtime (`convex-test` inlined dep) +- E2E (Playwright): `e2e/auth.spec.ts`, `e2e/billing/**` (serial, workers=1) +- Billing live: `tests/live-billing/*.test.ts` (separate config `vitest.live.config.ts`) +- Billing preflight: `scripts/billing-preflight.mjs` (`npm run test:billing:preflight`; `--push-convex` mode supported via `BILLING_LIVE_PUSH_CONVEX`) ## Environment Configuration -**Required env vars (validated by cron):** -- `STRIPE_SECRET_KEY` - Stripe API key -- `ENCRYPTION_KEY` - AES-256-GCM key for API key/credential encryption -- `STRIPE_GO_PRICE_ID` - Stripe price ID for Go plan -- `STRIPE_PRO_PRICE_ID` - Stripe price ID for Pro plan -- `STRIPE_WEBHOOK_SECRET` - Stripe webhook signing secret -- `CLERK_JWT_ISSUER_DOMAIN` - Clerk JWT issuer for Convex auth - -**Additional required env vars (not in validation list but used):** -- `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` - Clerk frontend key -- `NEXT_PUBLIC_POSTHOG_KEY` - PostHog project API key -- `NEXT_PUBLIC_POSTHOG_HOST` - PostHog UI host -- `NEXT_PUBLIC_APP_URL` - Application URL (fallback to localhost in dev) - -**Optional env vars:** -- `AI_PROVIDER` - Server AI provider (default: `deepseek`) -- `AI_MODEL` - Server AI model (default: `deepseek-chat`) -- `OPENROUTER_PROVIDER_ORDER` - Comma-separated provider routing for OpenRouter -- `OPENROUTER_ALLOW_FALLBACKS` - Enable/disable OpenRouter fallbacks (default: true) -- Provider-specific API keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_GENERATIVE_AI_API_KEY`, `DEEPSEEK_API_KEY`, `AZURE_OPENAI_API_KEY`, `OPENROUTER_API_KEY` +**Required env vars (validated by `convex/lib/envValidation.ts`):** +- `STRIPE_SECRET_KEY` +- `ENCRYPTION_KEY` +- `STRIPE_GO_PRICE_ID` +- `STRIPE_PRO_PRICE_ID` +- `STRIPE_WEBHOOK_SECRET` +- `CLERK_JWT_ISSUER_DOMAIN` + +**Additional env vars referenced in code:** +- **Clerk**: `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`, `CLERK_SECRET_KEY`, `NEXT_PUBLIC_CLERK_SIGN_IN_URL`, `NEXT_PUBLIC_CLERK_SIGN_UP_URL`, `CLERK_WEBHOOK_SIGNING_SECRET` +- **Convex**: `NEXT_PUBLIC_CONVEX_URL`, `NEXT_PUBLIC_CONVEX_SITE_URL`, `CONVEX_CLOUD_URL`, `CONVEX_SELF_HOSTED_URL`, `CONVEX_SELF_HOSTED_ADMIN_KEY` +- **Stripe**: `STRIPE_ENTERPRISE_PRICE_ID`, `STRIPE_CREDITS_PRODUCT_ID`, `CREDITS_PER_USD` +- **AI**: `AI_PROVIDER`, `AI_MODEL`, `OPENROUTER_PROVIDER_ORDER`, `OPENROUTER_ALLOW_FALLBACKS`, `EXTRACTION_EMBEDDING_USD_PER_1M_TOKENS` +- **Zotero**: `ZOTERO_CLIENT_KEY`, `ZOTERO_CLIENT_SECRET` +- **OpenAlex**: `OPENALEX_CONTACT_EMAIL` +- **PostHog**: `NEXT_PUBLIC_POSTHOG_KEY`, `NEXT_PUBLIC_POSTHOG_HOST`, `POSTHOG_KEY`, `POSTHOG_HOST` +- **Google Analytics**: `NEXT_PUBLIC_GA_ID` +- **App URL**: `NEXT_PUBLIC_APP_URL`, `NEXT_PUBLIC_URL` (fallback to `http://localhost:3000` in dev; see `convex/lib/env.ts::requireAppUrl`) +- **E2E**: `E2E_BASE_URL`, `PLAYWRIGHT_WEB_SERVER_COMMAND`, `E2E_CLERK_USER_EMAIL`, `E2E_CLERK_USER_PASSWORD` +- **Billing live**: `BILLING_LIVE_PUSH_CONVEX` **Secrets location:** -- `.env.local` (local development) -- Convex dashboard environment variables (production) +- Local: `.env.local` (present at repo root; not inspected) +- Convex: pushed via `sync-env.sh` → `npx convex env set` (skips `NEXT_PUBLIC_CONVEX_URL`, `CONVEX_SELF_HOSTED_*`) +- CI: GitHub Actions secrets (`secrets.*` in `.github/workflows/ci.yml`) + +## Webhooks & Callbacks + +**Incoming (handled by Convex HTTP router `convex/http.ts`):** +- `POST /webhooks/clerk` — Clerk user lifecycle webhook (`clerkWebhook` in `convex/webhooks/clerk.ts`) + - Signature verification via `svix` ^1.86.0 (`convex/webhooks/actions.ts` — requires `svix-id`, `svix-timestamp`, `svix-signature` headers and `CLERK_WEBHOOK_SIGNING_SECRET` starting with `whsec_`) + - Handled events: `user.created`, `user.updated`, `user.deleted` → `internal.users.internal.upsertUserFromClerk`, `markUserDeletedFromClerk` +- `POST /webhooks/stripe` — Stripe subscription/billing webhook (registered via `@convex-dev/stripe` `registerRoutes` with `STRIPE_WEBHOOK_SECRET` normalized through `normalizeStripeWebhookSecret`) + - Handled events: `checkout.session.completed`, `payment_intent.succeeded`, `charge.refunded`, `invoice.created`, `invoice.finalized`, `invoice.paid`, `invoice.payment_succeeded`, `invoice.payment_failed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted` + - All handlers wrapped with `runAuditedStripeHandler` (idempotent — logged to `stripeEventLogs`); `onEvent` callback records every received event via `internal.subscriptions.internal.recordStripeEventReceived` + - Idempotency contracts documented inline (INFRA-03, CRED-01, SUB-02) +- `GET /api/zotero/callback` — Zotero OAuth 1.0a callback (`convex/http.ts`); redirects to `${NEXT_PUBLIC_APP_URL}/?zotero_connected=true` or `?zotero_error=...` via `ctx.runAction(internal.zotero.actions.completeOAuth, ...)` + +**Wallet AI Gateway (OpenAI-compatible surface, `convex/http.ts` + `convex/wallet/gateway/handler.ts`):** +- `POST /api/wallet/v1/chat/completions` + `OPTIONS` — `handleChatCompletions` / `handleCors` +- `GET /api/wallet/v1/models` + `OPTIONS` — `handleModelsV1` / `handleCors` +- `GET /api/wallet/balance` + `OPTIONS` — `handleBalance` / `handleCors` +- Bearer-token auth via `extractBearerToken` → `internal.wallet.nodeActions.validateKey` +- CORS via `corsHeaders(origin)` helper +- Error format mimics OpenAI (`openAIError(message, type, status, origin)`) +- Backed by `ai` ^6.0.62 (`streamText`, `generateText`) and `lib/ai/server/providers.ts::getProviderModel` + +**Next.js Route Handlers (`app/api/`):** +- `GET /api/openalex/search` — proxies OpenAlex search with shared `createSearchParameters` from `lib/utils.ts` (`app/api/openalex/search/route.ts`) + +**Outgoing HTTP calls:** +- OpenRouter: `https://openrouter.ai/api/v1/models` (daily model sync) +- OpenAlex: `https://api.openalex.org/works` (paper extraction) +- Zotero: `https://www.zotero.org/oauth/*`, `https://api.zotero.org` +- Stripe API: via `stripe` Node SDK (`new Stripe(process.env.STRIPE_SECRET_KEY)`) +- AI providers: via `@ai-sdk/*` factories (OpenAI, Anthropic, Google, Azure, DeepSeek, OpenRouter) +- PostHog EU ingest: `https://eu.i.posthog.com` (via Next.js rewrite from `/data`) --- -*Integration audit: 2026-03-06* +*Integration audit: 2026-04-14* diff --git a/.planning/codebase/STACK.md b/.planning/codebase/STACK.md index abfb6b74b..64851a372 100644 --- a/.planning/codebase/STACK.md +++ b/.planning/codebase/STACK.md @@ -1,158 +1,186 @@ # Technology Stack -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## Languages **Primary:** -- TypeScript ^5 - All application code (frontend, backend, shared libs) +- TypeScript ~5 (strict mode enabled) — application code, Convex functions, tests +- TSX (React 19) — UI components and pages under `app/`, `components/` **Secondary:** -- JavaScript - PM2 config (`ecosystem.config.js`) +- JavaScript (ESM) — `ecosystem.config.js`, `scripts/billing-preflight.mjs`, `postcss.config.mjs` +- Bash — `sync-env.sh` (Convex env sync helper) ## Runtime **Environment:** -- Node.js (version not pinned; no `.nvmrc` or `.node-version` detected) -- Convex backend runtime (edge-runtime for Convex functions, Node.js for `"use node"` actions) +- Node.js 22 (pinned in `.github/workflows/ci.yml`) +- Convex Deno-like runtime for backend functions in `convex/` (isolated from Node); selected files opt into Node via `"use node";` directive (e.g. `convex/zotero/actions.ts`, `convex/models/sync.ts`, `convex/webhooks/actions.ts`, `convex/credits/actions.ts`) +- Edge Runtime for Convex HTTP actions and tests (via `@edge-runtime/vm`) **Package Manager:** -- npm +- npm (inferred from `package-lock.json` and `npm ci` usage in CI) - Lockfile: `package-lock.json` present +- Process manager for combined dev: PM2 via `ecosystem.config.js` (runs `next` + `convex` concurrently) ## Frameworks **Core:** -- Next.js ^16.1.6 - Full-stack React framework (App Router, RSC enabled) -- React ^19.2.4 - UI library -- Convex ^1.31.7 - Backend-as-a-service (database, functions, file storage, scheduling) - -**UI:** -- Radix UI ^1.4.3 - Headless component primitives -- shadcn/ui (new-york style) - Component library (`components.json`) -- Tailwind CSS ^4 - Utility-first CSS -- Lucide React ^0.487.0 - Icon library -- Motion ^12.23.12 - Animation library (Framer Motion successor) -- Vaul ^1.1.2 - Drawer component -- cmdk ^1.1.1 - Command palette +- Next.js ^16.1.6 — App Router, React Server Components, Turbopack dev (`next dev --turbopack`), React Compiler enabled (`reactCompiler: true` in `next.config.ts`) +- React ^19.2.4 + React DOM ^19.2.4 — with `babel-plugin-react-compiler` ^1.0.0 +- Convex ^1.34.1 — reactive backend (database, queries, mutations, actions, HTTP endpoints, crons, workflows) **Testing:** -- Vitest ^3.2.4 - Unit/integration test runner (config: `vitest.config.ts`) -- convex-test ^0.0.41 - Convex function testing (edge-runtime environment) -- Testing Library (React ^16.3.2, DOM ^10.4.1, User Event ^14.6.1, jest-dom ^6.9.1) - Component testing -- Playwright ^1.58.2 - E2E testing (config: `playwright.config.ts`) -- jsdom ^28.1.0 - DOM simulation for hook/component tests -- @edge-runtime/vm ^5.0.0 - Edge runtime simulation for Convex tests +- Vitest ^3.2.4 — unit + contract test runner (`vitest.config.ts`, `vitest.live.config.ts`) +- `@vitejs/plugin-react` ^5.1.4 — React support in Vitest +- `convex-test` ^0.0.46 — Convex function testing harness (runs in `edge-runtime` env) +- `@edge-runtime/vm` ^5.0.0 — edge runtime emulation for Convex tests +- `jsdom` ^28.1.0 — DOM env for React hook/component tests under `tests/hooks/**`, `tests/components/**` +- `@testing-library/react` ^16.3.2, `@testing-library/dom` ^10.4.1, `@testing-library/jest-dom` ^6.9.1, `@testing-library/user-event` ^14.6.1 +- Playwright ^1.58.2 (`@playwright/test`) — e2e tests (`playwright.config.ts`, `e2e/`); projects: `default`, `billing` **Build/Dev:** -- Turbopack - Dev server (`next dev --turbopack`) -- React Compiler (babel-plugin-react-compiler ^1.0.0) - Auto-memoization (`reactCompiler: true` in `next.config.ts`) -- PostCSS with @tailwindcss/postcss ^4 -- PM2 - Local dev process management (`ecosystem.config.js` runs Next.js + Convex dev) -- Knip ^5.84.1 - Dead code detection (`knip.json`) +- Turbopack — dev bundler (`next dev --turbopack`) +- Next.js bundler — production build (`next build`) +- TypeScript ^5 — type-checking (`tsc` via `tsconfig.json`, separate `convex/tsconfig.json`) +- Knip ^5.84.1 — unused code detection (`knip.json`) +- shadcn ^3.8.5 CLI — component scaffolding (config at `components.json`, style "new-york", base color neutral, Lucide icons) ## Key Dependencies **Critical:** -- `ai` ^6.0.62 (Vercel AI SDK) - Core AI orchestration layer -- `@ai-sdk/openai` ^3.0.23 - OpenAI provider -- `@ai-sdk/anthropic` ^3.0.31 - Anthropic provider -- `@ai-sdk/google` ^3.0.18 - Google AI provider -- `@ai-sdk/deepseek` ^2.0.15 - DeepSeek provider -- `@ai-sdk/azure` ^3.0.26 - Azure OpenAI provider -- `@openrouter/ai-sdk-provider` ^6.0.0-alpha.1 - OpenRouter provider -- `@sickrin/openalex-sdk` ^1.0.0 - OpenAlex academic paper API client -- `stripe` ^20.3.0 - Stripe billing SDK -- `@clerk/nextjs` ^6.38.2 - Authentication - -**Infrastructure (Convex Components):** -- `@convex-dev/stripe` ^0.1.3 - Stripe webhook integration for Convex -- `@convex-dev/rag` ^0.7.0 - RAG (Retrieval-Augmented Generation) pipeline -- `@convex-dev/workflow` ^0.3.4 - Durable workflow execution -- `@convex-dev/workpool` ^0.3.1 - Parallel job processing with concurrency control -- `convex-helpers` ^0.1.111 - Rate limiting tables, utilities - -**State & Data:** -- `zustand` ^5.0.5 - Client-side state management -- `nuqs` ^2.6.0 - URL query string state (with Next.js adapter) -- `swr` ^2.3.3 - Data fetching/caching -- `zod` ^4.3.6 - Runtime schema validation - -**Content & Export:** -- `pdfjs-dist` ^5.4.296 / `react-pdf` ^10.1.0 - PDF rendering -- `exceljs` ^4.4.0 - Excel export -- `react-markdown` ^10.1.0 / `remark-gfm` ^4.0.1 - Markdown rendering -- `jsonrepair` ^3.13.2 - JSON repair for AI output - -**Internationalization:** -- `next-intl` ^4.8.2 - i18n framework -- `@clerk/localizations` ^3.37.0 - Clerk UI translations -- `@formatjs/intl-localematcher` ^0.8.1 - Locale matching -- Supported locales: en-US, en-GB, zh, fr, hi, ja (config: `i18n/config.ts`) -- Translation files: `messages/{locale}.json` - -**Analytics:** -- `posthog-js` ^1.342.1 - Product analytics, error tracking, heatmaps - -**Other:** -- `svix` ^1.86.0 - Webhook signature verification (Clerk webhooks) -- `sonner` ^2.0.7 - Toast notifications -- `date-fns` ^4.1.0 - Date utilities -- `next-themes` ^0.4.6 - Dark/light theme -- `class-variance-authority` ^0.7.1 / `clsx` ^2.1.1 / `tailwind-merge` ^3.4.1 - CSS class utilities -- `react-day-picker` ^9.13.2 - Date picker component +- `@clerk/nextjs` ^6.38.2 — authentication provider wrapper +- `@clerk/backend` ^2.32.1 — server-side Clerk SDK (dev dependency for tests) +- `@clerk/localizations` ^3.37.0, `@clerk/themes` ^2.4.55 — Clerk UI localization/appearance +- `@clerk/testing` ^1.14.1 — Playwright Clerk auth fixtures +- `convex` ^1.34.1 — backend client and server runtime +- `convex-helpers` ^0.1.114 — rate limiting (`rateLimitTables`) and utilities +- `@convex-dev/stripe` ^0.1.4 — Stripe subscriptions component for Convex +- `@convex-dev/rag` ^0.7.2 — retrieval-augmented generation component +- `@convex-dev/workflow` ^0.3.9 — durable workflow manager (`convex/workflow.ts`) +- `@convex-dev/workpool` ^0.3.2 — bounded-parallelism worker pools (`convex/workpool.ts`, used as `workpool` and named `screeningWorkpool`) +- `stripe` ^20.3.0 — Stripe Node SDK (used in `convex/credits/actions.ts`, `convex/subscriptions/actions.ts`, `convex/maintenance/internal.ts`, `convex/lib/stripeCustomer.ts`, `scripts/billing-preflight.mjs`, `tests/live-billing/support.ts`, `e2e/billing/stripe-helpers.ts`) +- `svix` ^1.86.0 — Clerk webhook signature verification (`convex/webhooks/actions.ts`) +- `ai` ^6.0.62 — Vercel AI SDK core (`streamText`, `generateText`) +- `@ai-sdk/openai` ^3.0.23, `@ai-sdk/anthropic` ^3.0.31, `@ai-sdk/google` ^3.0.18, `@ai-sdk/azure` ^3.0.26, `@ai-sdk/deepseek` ^2.0.15 — AI provider adapters (see `lib/ai/server/providers.ts`) +- `@openrouter/ai-sdk-provider` ^6.0.0-alpha.1 — OpenRouter provider with custom routing +- `@sickrin/openalex-sdk` ^1.0.0 — OpenAlex API client (`lib/openalex.ts`) +- `next-intl` ^4.8.2 — i18n plugin and runtime (`i18n/request.ts`, wired via `next.config.ts`) + +**UI / State / Frontend:** +- `radix-ui` ^1.4.3 — unstyled UI primitives +- `lucide-react` ^0.487.0 — icon library +- `class-variance-authority` ^0.7.1, `clsx` ^2.1.1, `tailwind-merge` ^3.4.1 — class composition helpers +- `tailwindcss` ^4, `@tailwindcss/postcss` ^4, `tw-animate-css` ^1.4.0 — styling +- `cmdk` ^1.1.1 — command palette +- `vaul` ^1.1.2 — drawer component +- `sonner` ^2.0.7 — toast notifications +- `next-themes` ^0.4.6 — theme switcher (light/dark) +- `react-day-picker` ^9.13.2 — date picker (overridden to React 19 in `package.json.overrides`) +- `react-markdown` ^10.1.0 + `remark-gfm` ^4.0.1 — markdown rendering +- `react-pdf` ^10.1.0 + `pdfjs-dist` ^5.4.296 — in-browser PDF viewer (`components/extraction/pdf-viewer.tsx`) +- `motion` ^12.23.12 — spring-based animations (Motion) +- `nuqs` ^2.6.0 — URL query-param state (`NuqsAdapter` in `app/layout.tsx`) +- `zustand` ^5.0.5 — client store (`lib/store.ts`, `lib/store/`) +- `swr` ^2.3.3 — client data fetching +- `zod` ^4.3.6 — schema validation +- `date-fns` ^4.1.0 — date utilities + +**Infrastructure / Utilities:** +- `exceljs` ^4.4.0 — Excel export (dynamically imported; see `.planning/research/PITFALLS.md`) +- `jsonrepair` ^3.13.2 — tolerant JSON parsing +- `glob` ^13.0.6 — file matching +- `@formatjs/intl-localematcher` ^0.8.1 — locale negotiation +- `@next/third-parties` ^16.2.2 — Google Analytics wrapper +- `posthog-js` ^1.342.1 — product analytics + error tracking (client) + server helpers in `lib/posthog-server.ts` ## Configuration -**Environment:** -- `.env.local` present (contains secrets - never read) -- Required env vars validated by cron (`convex/lib/envValidation.ts`): - - `STRIPE_SECRET_KEY` - - `ENCRYPTION_KEY` (AES-256-GCM for API key encryption) - - `STRIPE_GO_PRICE_ID` - - `STRIPE_PRO_PRICE_ID` - - `STRIPE_WEBHOOK_SECRET` - - `CLERK_JWT_ISSUER_DOMAIN` -- Additional env vars used: - - `NEXT_PUBLIC_APP_URL` / `NEXT_PUBLIC_URL` - Frontend URL - - `NEXT_PUBLIC_POSTHOG_KEY` - PostHog project key - - `NEXT_PUBLIC_POSTHOG_HOST` - PostHog host - - `AI_PROVIDER` - Default AI provider (defaults to `deepseek`) - - `AI_MODEL` - Default AI model (defaults to `deepseek-chat`) - - `OPENROUTER_PROVIDER_ORDER` - Comma-separated provider routing - - `OPENROUTER_ALLOW_FALLBACKS` - OpenRouter fallback toggle - - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` / `CLERK_PUBLISHABLE_KEY` -- Sync script: `sync-env.sh` - **TypeScript:** -- Config: `tsconfig.json` -- Target: ES2017, Module: ESNext, Module Resolution: Bundler -- Strict mode enabled -- Path alias: `@/*` maps to project root -- Separate Convex tsconfig: `convex/tsconfig.json` - -**Build:** -- `next.config.ts` - Next.js config with next-intl plugin, PostHog proxy rewrites, React Compiler -- `postcss.config.mjs` - PostCSS with Tailwind -- `vitest.config.ts` - Unit tests (environment-matched: edge-runtime for Convex, jsdom for React) -- `vitest.live.config.ts` - Live billing integration tests -- `playwright.config.ts` - E2E tests (120s timeout, 2 projects: default + billing) +- Root: `tsconfig.json` — `strict: true`, `target: ES2017`, `moduleResolution: bundler`, path alias `@/*` → `./*`, includes `next-env.d.ts`, `**/*.ts`, `**/*.tsx`, `.next/types/**/*.ts` +- Convex: `convex/tsconfig.json` — `target: ESNext`, `lib: [ES2021, dom]`, strict, excludes `_generated/` +- Next type plugin: `{ "name": "next" }` +- Global types: `global.d.ts`, `next-env.d.ts` + +**Next.js (`next.config.ts`):** +- `reactCompiler: true` — React Compiler enabled +- `devIndicators: false`, `poweredByHeader: false` +- Security headers: `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, `Strict-Transport-Security` (HSTS preload), `Permissions-Policy` (camera/mic/geolocation disabled), `X-DNS-Prefetch-Control: off` +- Rewrites: `/data/static/:path*` → `https://eu-assets.i.posthog.com/static/:path*` and `/data/:path*` → `https://eu.i.posthog.com/:path*` (PostHog reverse-proxy) +- `skipTrailingSlashRedirect: true` (required for PostHog) +- Wrapped with `createNextIntlPlugin("./i18n/request.ts")` for i18n + +**PostCSS (`postcss.config.mjs`):** +- Plugins: `@tailwindcss/postcss` + +**Environment Sync:** +- `sync-env.sh` — reads `.env.local` and pushes vars to Convex via `npx convex env set` (skips `CONVEX_SELF_HOSTED_URL`, `CONVEX_SELF_HOSTED_ADMIN_KEY`, `NEXT_PUBLIC_CONVEX_URL`) +- Convex env validation cron: `internal.lib.envValidation.checkRequiredEnvVars` (daily, `convex/crons.ts`) +- Required env vars (per `convex/lib/envValidation.ts`): `STRIPE_SECRET_KEY`, `ENCRYPTION_KEY`, `STRIPE_GO_PRICE_ID`, `STRIPE_PRO_PRICE_ID`, `STRIPE_WEBHOOK_SECRET`, `CLERK_JWT_ISSUER_DOMAIN` + +**shadcn (`components.json`):** +- Style: `new-york`, RSC enabled, Tailwind CSS file `app/globals.css`, base color `neutral`, CSS variables on +- Icon library: `lucide` +- Aliases: `components` → `@/components`, `utils` → `@/lib/utils`, `ui` → `@/components/ui`, `lib` → `@/lib`, `hooks` → `@/hooks` + +**Knip (`knip.json`):** +- Ignores `ecosystem.config.js` + +**Playwright (`playwright.config.ts`):** +- Test dir `./e2e`, global setup `./e2e/global.setup.ts` +- `webServer` runs `npm run build && npm run start -- --port 3000` (overridable via `PLAYWRIGHT_WEB_SERVER_COMMAND`) +- Projects: `default` (ignores billing) and `billing` (`e2e/billing`, workers=1, serial) +- CI retries=2, workers=1 + +**Vitest (`vitest.config.ts`):** +- Alias `@` → project root +- Default env `node` +- `environmentMatchGlobs`: `convex/**/*.test.ts` → `edge-runtime`; `tests/hooks/**`, `tests/components/**`, `tests/*.test.tsx` → `jsdom` +- `server.deps.inline: ["convex-test"]` +- Includes `tests/**/*.test.ts(x)` and `convex/**/*.test.ts`; excludes `tests/live-billing/**/*.test.ts` +- Setup: `./tests/setup.ts` +- Separate live config: `vitest.live.config.ts` for billing live tests + +**Internationalization (`i18n/config.ts`):** +- Locales: `en-US`, `en-GB`, `zh`, `fr`, `hi`, `ja` +- Default: `en-US` +- Messages in `messages/*.json`; request config at `i18n/request.ts` ## Platform Requirements **Development:** -- Node.js (recent LTS recommended for Next.js 16 / React 19) -- npm for package management -- PM2 for running Next.js + Convex dev servers concurrently (`npm run dev:all`) -- Convex CLI for backend development (`npx convex dev`) +- Node.js 22 +- npm +- Convex CLI (`npx convex`) — for `dev:convex`, env sync, deploy +- PM2 (optional) — for `dev:all` script running Next.js + Convex concurrently +- Browser compatible with ES2017+ for local preview +- Environment file: `.env.local` (present at repo root; contents not inspected for secrets) **Production:** -- Next.js deployment target (Vercel or similar) -- Convex cloud for backend (database, functions, file storage, scheduling, crons) -- Stripe account for billing -- Clerk account for authentication -- PostHog instance (EU region, proxied through Next.js rewrites) +- **Hosting**: Vercel (project `prj_Af8JZymOKzufVYDzFngyWpJyXNN2`, team `team_yToPjppvYYuxEAh1JZiBKH9c`, `openalex-count` — see `.vercel/project.json`) +- **Backend**: Convex Cloud (reactive DB, HTTP, crons, workflows, workpools) +- **CI**: GitHub Actions — `.github/workflows/ci.yml` (unit + build + e2e auth), `.github/workflows/billing-nightly.yml` (nightly billing) +- **Instrumentation**: `instrumentation-client.ts` wires PostHog on the client + +**Scripts (`package.json`):** +- `dev` — `next dev --turbopack` +- `dev:convex` — `convex dev` +- `dev:all` — `pm2 start ecosystem.config.js` +- `build` — `next build` +- `start` — `next start` +- `sync:env` — `./sync-env.sh` +- `test` — `vitest run` +- `test:billing:preflight` — `node ./scripts/billing-preflight.mjs` +- `test:billing:live` — `vitest run --config vitest.live.config.ts tests/live-billing/required.test.ts` +- `test:billing:live:ci` — preflight w/ `--push-convex` then live +- `test:billing:extended` / `test:billing:extended:ci` — extended billing live tests +- `test:billing:e2e` — `playwright test --project=billing` +- `test:e2e:auth` — `playwright test e2e/auth.spec.ts` +- `test:ci` — `test` + `build` + `test:e2e:auth` +- `test:all` — `test:ci` + `test:billing:e2e` +- `wallet-cli` — `tsx scripts/wallet-cli.ts` --- -*Stack analysis: 2026-03-06* +*Stack analysis: 2026-04-14* diff --git a/.planning/codebase/STRUCTURE.md b/.planning/codebase/STRUCTURE.md index 4ec43f639..3d6b96818 100644 --- a/.planning/codebase/STRUCTURE.md +++ b/.planning/codebase/STRUCTURE.md @@ -1,344 +1,417 @@ # Codebase Structure -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## Directory Layout ``` openalex-count/ -├── app/ # Next.js App Router pages and API routes -│ ├── layout.tsx # Root layout with provider tree -│ ├── page.tsx # Home / search entry page -│ ├── globals.css # Global styles (Tailwind) -│ ├── actions/ # Next.js server actions -│ ├── api/openalex/search/ # OpenAlex search proxy API route -│ ├── auth/ # Auth flow pages (signin, signout, callback, access-token) -│ ├── sign-in/[[...sign-in]]/ # Clerk sign-in page -│ ├── sign-up/[[...sign-up]]/ # Clerk sign-up page -│ ├── results/ # Search results page -│ │ └── [searchId]/ # Dynamic search result with history -│ ├── library/ # User paper library -│ ├── bookmarks/ # Saved bookmarks page -│ ├── history/ # Search history page -│ ├── extraction/ # Extraction jobs list and detail -│ │ ├── new/ # Create new extraction job -│ │ └── [jobId]/ # Extraction job detail -│ ├── settings/ # User settings -│ │ ├── ai/ # AI provider settings (BYOK) -│ │ └── billing/ # Billing/subscription settings -│ ├── pricing/ # Pricing page -│ ├── admin/cleanup/ # Admin cleanup tools -│ ├── privacy/ # Privacy policy -│ └── cookie-policy/ # Cookie policy -├── components/ # React components -│ ├── ui/ # Shadcn/ui primitives (button, dialog, etc.) -│ ├── shared/ # Shared components across features -│ ├── layout/ # Layout components -│ ├── providers/ # Context providers (Convex, etc.) -│ ├── auth/ # Auth-related components -│ ├── home/ # Home page components -│ ├── library/ # Library feature components -│ ├── extraction/ # Extraction feature components -│ ├── settings/ # Settings page components -│ ├── billing/ # Billing/subscription components -│ ├── command-center/ # Command palette -│ ├── search-command-center/ # Search-specific command palette -│ ├── bookmarks-command-center/ # Bookmarks command palette -│ ├── paper-card/ # Paper card display components -│ ├── focus-mode/ # Focus mode components -│ ├── icons/ # Custom icon components -│ └── *.tsx # Feature-level components (sidebar, navbar, filters, etc.) -├── convex/ # Convex backend (all server-side logic) -│ ├── schema.ts # Database schema (all tables) -│ ├── convex.config.ts # Convex app config (Stripe, RAG, workflow, workpool components) -│ ├── auth.config.ts # Clerk JWT auth config -│ ├── http.ts # HTTP router (webhooks: Clerk, Stripe, Zotero OAuth) -│ ├── crons.ts # Scheduled cron jobs -│ ├── workflow.ts # WorkflowManager instance -│ ├── workpool.ts # Workpool instance for PDF processing -│ ├── stripe.ts # Stripe client config -│ ├── _generated/ # Auto-generated Convex types and API refs -│ ├── lib/ # Shared backend utilities -│ │ ├── auth.ts # Auth helpers (requireUser, etc.) -│ │ ├── errors.ts # Structured error factory -│ │ ├── crypto.ts # Encryption for API keys -│ │ ├── env.ts # Environment variable helpers -│ │ ├── envValidation.ts # Env var validation (cron-checked) -│ │ ├── featureFlags.ts # Feature flag system -│ │ ├── rateLimit.ts # Rate limiting config -│ │ ├── audit.ts # Audit logging -│ │ ├── constants.ts # Backend constants -│ │ ├── validators.ts # Shared validators -│ │ ├── freeCredits.ts # Free credit grant logic -│ │ ├── creditTopups.ts # Credit top-up pricing -│ │ ├── userCreation.ts # User creation helper -│ │ └── stripeWebhook*.ts # Stripe webhook utilities -│ ├── users/ # User domain (queries, mutations, internal) -│ ├── subscriptions/ # Subscription domain (queries, actions, internal, lib/) -│ ├── credits/ # Credits domain (queries, actions, internal, lib/) -│ ├── extraction/ # Extraction domain (workflow, actions, mutations, queries, prompts, etc.) -│ ├── ai/ # AI config and actions (server-side) -│ ├── library/ # Library domain (queries, mutations, collections) -│ ├── apiKeys/ # BYOK API key management -│ ├── zotero/ # Zotero integration (OAuth, queries, mutations) -│ ├── webhooks/ # Webhook handlers (Clerk user sync) -│ ├── maintenance/ # Maintenance cron handlers -│ └── testing/ # Test helpers for Convex -├── lib/ # Shared frontend utilities and business logic -│ ├── types/ # TypeScript type definitions -│ │ ├── index.ts # Re-exports -│ │ ├── search.types.ts # Search-related types -│ │ ├── ai.types.ts # AI provider types -│ │ ├── extraction.types.ts # Extraction types -│ │ ├── library.types.ts # Library types -│ │ └── screening.types.ts # Screening types -│ ├── search/ # Search system -│ │ ├── provider.tsx # SearchProvider context (core search state) -│ │ ├── types.ts # Search context types -│ │ ├── actions.ts # Search action helpers -│ │ ├── index.ts # Re-exports -│ │ └── initializer.tsx # Search state initializer -│ ├── search-params/ # URL param parsing (nuqs) -│ ├── ai/ # AI integration -│ │ ├── client/ # Client-side AI (executor, router, mode routing) -│ │ ├── core/ # Core AI logic (prompts, schemas, batch, cost, types) -│ │ └── server/ # Server-side AI providers -│ ├── store/ # Zustand store modules -│ │ └── extraction.ts # Extraction-specific store -│ ├── store.ts # Main Zustand stores (ratings, search history, bookmarks, AI, etc.) -│ ├── extraction/ # Extraction feature utilities -│ ├── filters/ # Filter utilities -│ ├── auth/ # Auth utilities (Clerk UI config, public routes, hooks) -│ ├── billing/ # Billing entitlements -│ ├── credits/ # Credit feature flags -│ ├── subscriptions/ # Subscription feature flags -│ ├── library/ # Library utilities -│ ├── toast/ # Toast notification helpers -│ ├── hooks/ # Custom React hooks -│ ├── constants/ # Constants -│ ├── pdf/ # PDF utilities -│ ├── i18n/ # i18n utilities -│ ├── ui/ # UI utilities -│ ├── utils.ts # General utilities (cn, createSearchParameters, etc.) -│ ├── openalex.ts # OpenAlex SDK client -│ ├── constants.ts # App-wide constants -│ ├── format.ts # Formatting utilities -│ └── posthog-*.ts # PostHog analytics helpers -├── hooks/ # Top-level React hooks -│ ├── use-batch-operation.ts # Batch operation hook -│ ├── use-batch-screening.ts # Batch screening hook -│ ├── use-batch-translation.ts# Batch translation hook -│ ├── use-country-filter.ts # Country filter hook -│ └── use-mobile.tsx # Mobile detection hook -├── i18n/ # Internationalization config -│ ├── config.ts # i18n configuration -│ ├── locale.ts # Locale utilities -│ ├── locale-detection.ts # Browser locale detection -│ └── request.ts # next-intl request config -├── messages/ # Translation files -│ ├── en-US.json # English (US) -│ ├── en-GB.json # English (GB) -│ ├── fr.json # French -│ ├── hi.json # Hindi -│ ├── ja.json # Japanese -│ └── zh.json # Chinese -├── content/ # Static content (legal pages) -│ ├── cookie-policy/ # Cookie policy markdown -│ └── privacy-policy/ # Privacy policy markdown -├── tests/ # Test files -│ ├── factories/ # Test data factories -│ ├── extraction/ # Extraction feature tests -│ ├── library/ # Library feature tests -│ └── live-billing/ # Live billing integration tests -├── e2e/ # Playwright E2E tests -│ ├── auth.spec.ts # Auth flow E2E tests -│ ├── billing/ # Billing E2E tests -│ └── global.setup.ts # Global E2E setup -├── scripts/ # Build/CI scripts -│ ├── billing-preflight.mjs # Billing test preflight checks +├── app/ # Next.js 16 App Router (pages, route handlers, server actions) +│ ├── actions/ # `"use server"` server actions (OpenAlex proxy) +│ ├── api/ # Route handlers (currently only /api/openalex/search) +│ ├── bookmarks/ # /bookmarks page +│ ├── connect/ # Wallet OAuth-style consent page +│ ├── cookie-policy/ # /cookie-policy legal page +│ ├── extraction/ # /extraction list, /extraction/new creator, /extraction/[jobId] detail +│ ├── history/ # /history page +│ ├── library/ # /library page +│ ├── pricing/ # /pricing page +│ ├── privacy/ # /privacy legal page +│ ├── results/ # /results/[searchId] + nested /history +│ ├── settings/ # /settings (ai, billing, connections, root) +│ ├── sign-in/ # Clerk sign-in catch-all +│ ├── sign-up/ # Clerk sign-up catch-all +│ ├── layout.tsx # Root layout — providers + gates +│ ├── page.tsx # Home +│ ├── globals.css # Tailwind v4 tokens, OKLCH palette +│ ├── error.tsx # Route error boundary +│ ├── global-error.tsx # Root error boundary +│ └── not-found.tsx # 404 +│ +├── components/ # All React components (UI + feature folders) +│ ├── ai/ # AI setup gate +│ ├── auth/ # Auth route gate + panels +│ ├── billing/ # Credit balance, top-up, upgrade dialog +│ ├── bookmarks-command-center/ +│ ├── command-center/ # Shared command center layout primitives +│ ├── extraction/ # Extraction feature UI (viewer, results, builders) +│ ├── focus-mode/ # Focus mode reader +│ ├── history-command-center/ +│ ├── home/ # Hero, ambient background, search input, mode toggle +│ ├── icons/ # Custom SVG icons +│ ├── layout/ # Two-column layout +│ ├── library/ # Library command center + filters +│ ├── paper-card/ # Paper result card +│ ├── providers/ # Convex + Clerk provider wrapper +│ ├── screening/ # Screening dialogs, jobs, scoring UI +│ ├── search-command-center/ +│ ├── settings/ # Settings sub-pages UI +│ ├── shared/ # Shared building blocks (sidebar-layout, etc.) +│ ├── ui/ # shadcn/ui primitives (button, dialog, sonner, table, …) +│ ├── app-sidebar.tsx # Left nav with Motion animations +│ ├── auth-button.tsx # Auth control in sidebar +│ ├── cookie-consent-banner.tsx +│ ├── mobile-navbar.tsx +│ ├── PageContent.tsx # Home page client content +│ ├── PageWrapper.tsx +│ ├── Pricing.tsx +│ ├── results-list.tsx +│ ├── results-page-content.tsx +│ ├── search-filter-sidebar.tsx +│ ├── search-history*.tsx # History command center siblings +│ └── theme-provider.tsx / theme-toggle.tsx +│ +├── convex/ # Convex backend +│ ├── _generated/ # Generated API + data model (DO NOT EDIT) +│ ├── ai/ # Credit-billed AI helpers (actions, config, helpers, lib/creditBilling) +│ ├── apiKeys/ # BYOK key management (actions, mutations, queries) +│ ├── credits/ # Credit ledger (actions, internal, queries, lib policies) +│ ├── extraction/ # Extraction pipeline (queries, mutations, actions, workflow, workpoolActions, prompts, evidence_units, pdfjs_extract, validators, types, etc.) +│ ├── featureFlags/ # Flag reads + guard + internal setters +│ ├── lib/ # Shared backend utilities (auth, errors, crypto, rateLimit, env, envValidation, stripeWebhookHandlers, audit, validators, …) +│ ├── library/ # User library collections + backfill +│ ├── maintenance/ # Cron-driven maintenance mutations +│ ├── models/ # Model catalog sync from OpenRouter +│ ├── screening/ # Screening workflow + mutations/queries/scoring/validators +│ ├── subscriptions/ # Stripe-backed subscription logic + lib policies +│ ├── testing/ # Test-only helpers +│ ├── users/ # ensureUser, mutations, queries, internal helpers +│ ├── wallet/ # Wallet keys, nodeActions, gateway/* (OpenAI-compatible HTTP) +│ ├── webhooks/ # Clerk webhook + mappers +│ ├── zotero/ # Zotero OAuth + actions/mutations/queries +│ ├── schema.ts # Every table + index in one file +│ ├── convex.config.ts # Components: stripe, rag, workflow, workpool × 2 +│ ├── http.ts # HTTP router (webhooks + wallet API) +│ ├── crons.ts # Scheduled jobs +│ ├── workflow.ts # WorkflowManager config +│ ├── workpool.ts # pdfProcessingPool + screeningPool +│ ├── stripe.ts # Stripe client factory +│ ├── auth.config.ts # Clerk issuer for Convex auth +│ └── tsconfig.json +│ +├── lib/ # Shared TS lib (client-safe + server-neutral) +│ ├── ai/ +│ │ ├── client/ # Router hook, executor, mode-routing, hook-factory +│ │ ├── core/ # Provider-neutral schemas, prompts, types, validate, batch, cost, configs, execute +│ │ └── server/ # `getProviderModel` factory for @ai-sdk providers +│ ├── auth/ # Public routes, proxy policy, Clerk UI config, auth query hooks +│ ├── billing/ # Entitlements +│ ├── constants/ # View mode constants +│ ├── credits/ # Feature flags for credits +│ ├── extraction/ # UI helpers: filtering, grouping, citations, thresholds, insights, reviews, export, pdfjs-text, pdf-highlight +│ ├── feature-flags/ # Registry, provider, hook, resolve +│ ├── filters/ # Filter builder/config/types +│ ├── hooks/ # use-cooldown, use-debounced-value, use-selection, use-url-state +│ ├── i18n/ # Locale map helpers +│ ├── library/ # Library export, download handlers, param codecs +│ ├── openalex/ # Abstract reconstruction +│ ├── pdf/ # PDF download helper +│ ├── screening/ # Export helper +│ ├── search/ # SearchProvider, actions, detect-mode, initializer, types +│ ├── search-params/ # nuqs parsers + serializers + converters + regions +│ ├── store/ # extraction store slice +│ ├── subscriptions/ # Subscription feature flags +│ ├── toast/ # Styled toast system (core, error-resolver, action-routing, use-app-toast) +│ ├── types/ # Central type re-exports (ai, extraction, library, screening, search) +│ ├── ui/ # sidebar-motion config +│ ├── ai-models.ts # Client AI model catalog +│ ├── animation-config.ts # Motion spring presets +│ ├── confirmation.tsx # Global confirmation host +│ ├── consent-storage.ts +│ ├── constants.ts # Large constants (21KB) +│ ├── convex-site.ts +│ ├── format.ts +│ ├── hooks.ts # Large cross-cutting hooks file (14KB) +│ ├── keyword-validation.ts +│ ├── legal-content.ts +│ ├── openalex.ts # OpenAlex SDK singleton +│ ├── posthog-*.ts # PostHog wrappers (ai, server, search, shared) +│ ├── search-actions.ts # Download/export search result handlers +│ ├── search-utils.ts +│ ├── store.ts # Zustand root store (42KB) +│ ├── utils.ts # Tailwind cn, createSearchParameters, etc. (20KB) +│ └── zotero-utils.ts +│ +├── hooks/ # App-level hooks not under lib/ +│ ├── use-batch-operation.ts +│ ├── use-batch-screening.ts +│ ├── use-batch-translation.ts +│ ├── use-country-filter.ts +│ └── use-mobile.tsx +│ +├── i18n/ # next-intl config +│ ├── config.ts # Locale list +│ ├── locale.ts +│ ├── locale-detection.ts +│ └── request.ts # getRequestConfig +│ +├── messages/ # next-intl translation bundles +│ ├── en-US.json +│ ├── en-GB.json +│ ├── zh.json +│ ├── fr.json +│ ├── hi.json +│ └── ja.json +│ +├── content/ # Markdown legal content +│ ├── cookie-policy/ +│ └── privacy-policy/ +│ +├── tests/ # Vitest unit + component tests +│ ├── components/ # Component test helpers +│ ├── extraction/ # Extraction-specific tests +│ ├── factories/ # Test data factories +│ ├── library/ # Library feature tests +│ ├── live-billing/ # Live Stripe billing tests (separate config) +│ ├── setup.ts # Vitest setup +│ └── *.test.ts(x) # Unit/integration tests +│ +├── e2e/ # Playwright tests +│ ├── auth.spec.ts +│ ├── billing/ # Billing e2e specs +│ └── global.setup.ts +│ +├── scripts/ # Operational scripts +│ ├── billing-preflight.mjs │ ├── verify-legal-markdown-parity.mjs -│ └── verify-no-any.sh # TypeScript `any` usage check -├── public/ # Static assets -├── docs/ # Documentation -│ └── plans/ # Planning documents -├── .github/ # GitHub Actions -├── package.json # Dependencies and scripts -├── next.config.ts # Next.js config (react compiler, PostHog proxy, next-intl) -├── tsconfig.json # TypeScript config -├── vitest.config.ts # Vitest config (unit tests) -├── vitest.live.config.ts # Vitest config (live billing tests) -├── playwright.config.ts # Playwright config (E2E tests) -├── postcss.config.mjs # PostCSS (Tailwind) -├── components.json # Shadcn/ui config -├── ecosystem.config.js # PM2 config (dev:all runs next + convex) -├── proxy.ts # Dev proxy script -├── knip.json # Dead code detection config -└── global.d.ts # Global type declarations +│ ├── verify-no-any.sh +│ └── wallet-cli.ts +│ +├── skills/ # GSD skill definitions +├── docs/ # Internal docs + plans +├── public/ # Static assets +│ +├── proxy.ts # Next.js edge middleware (renamed from middleware.ts) +├── next.config.ts # Next.js config (React Compiler, headers, rewrites, next-intl plugin) +├── tsconfig.json # TS config (paths: "@/*" → "./*") +├── vitest.config.ts # Default Vitest config +├── vitest.live.config.ts # Live-billing Vitest config +├── playwright.config.ts +├── knip.json # knip dead-code config +├── postcss.config.mjs # Tailwind v4 via @tailwindcss/postcss +├── components.json # shadcn/ui config +├── instrumentation-client.ts# PostHog instrumentation +├── ecosystem.config.js # pm2 config (`npm run dev:all`) +├── global.d.ts +├── next-env.d.ts +├── AGENTS.md # Agent instructions +├── CLAUDE.md # Design context + conventions +├── package.json +└── README.md ``` ## Directory Purposes **`app/`:** -- Purpose: Next.js App Router pages and API routes -- Contains: Page components (`page.tsx`), layouts (`layout.tsx`), route handlers (`route.ts`), server actions -- Key files: `app/layout.tsx` (root layout + provider tree), `app/page.tsx` (home), `app/results/[searchId]/page.tsx` (search results) +- Purpose: Next.js 16 App Router — pages, layouts, route handlers, server actions, error boundaries. +- Contains: `layout.tsx` + `page.tsx` per route, a single route handler under `app/api/openalex/search/route.ts`, and one server action file `app/actions/openalex.ts`. +- Key files: `app/layout.tsx` (all providers), `app/page.tsx` (home), `app/results/[searchId]/page.tsx`, `app/extraction/[jobId]/page.tsx`, `app/settings/layout.tsx`. **`components/`:** -- Purpose: All React components organized by feature -- Contains: UI primitives (shadcn), feature components, layout components, providers -- Key files: `components/ui/` (shadcn primitives), `components/providers/convex-provider.tsx` (auth + Convex) +- Purpose: All React components. No nested route-scoped component folders inside `app/`. +- Contains: Feature folders (`extraction/`, `library/`, `screening/`, `home/`, `billing/`, `ai/`, `auth/`, `search-command-center/`, `bookmarks-command-center/`, `history-command-center/`, `command-center/`, `layout/`, `paper-card/`, `focus-mode/`, `shared/`), `ui/` (shadcn primitives), `providers/`, `icons/`, and many top-level `.tsx` feature components. +- Key files: `components/app-sidebar.tsx` (32KB nav), `components/results-list.tsx` (18KB), `components/Pricing.tsx` (27KB), `components/search-sidebar.tsx` (18KB), `components/providers/convex-provider.tsx`. **`convex/`:** -- Purpose: Entire backend - database schema, server functions, webhooks, cron jobs -- Contains: Domain modules (users, credits, subscriptions, extraction, library, zotero, apiKeys), shared libs -- Key files: `convex/schema.ts` (database), `convex/http.ts` (HTTP routes), `convex/crons.ts` (scheduled jobs) +- Purpose: Authoritative backend — schema, queries, mutations, actions, workflows, HTTP routes, crons. +- Contains: One folder per domain plus shared `lib/`. Root files hold cross-domain config. +- Key files: `convex/schema.ts` (all tables/indexes), `convex/http.ts` (webhooks + wallet API), `convex/convex.config.ts` (components), `convex/workflow.ts`, `convex/workpool.ts`, `convex/crons.ts`, `convex/lib/auth.ts`, `convex/lib/errors.ts`, `convex/lib/stripeWebhookHandlers.ts`. **`lib/`:** -- Purpose: Shared utilities, business logic, type definitions used by both pages and components -- Contains: Search system, AI integration, stores, types, utilities, feature flags -- Key files: `lib/store.ts` (Zustand stores), `lib/search/provider.tsx` (search context), `lib/utils.ts` (utilities) +- Purpose: Client/server neutral TypeScript shared by `app/`, `components/`, and some `convex/` files. +- Contains: Subfolders per domain/concern plus top-level helper files. +- Key files: `lib/store.ts` (Zustand root, 42KB), `lib/search/provider.tsx`, `lib/search-params/parsers.ts`, `lib/types/index.ts`, `lib/ai/server/providers.ts`, `lib/auth/public-routes.ts`, `lib/openalex.ts`, `lib/utils.ts`. **`hooks/`:** -- Purpose: Top-level custom React hooks for cross-cutting concerns -- Contains: Batch operations, mobile detection, country filtering -- Key files: `hooks/use-batch-operation.ts`, `hooks/use-mobile.tsx` +- Purpose: App-level hooks that don't fit inside `lib/hooks/`. Historical / batch hooks. +- Contains: `use-batch-*.ts`, `use-country-filter.ts`, `use-mobile.tsx`. +- Note: New shared hooks should go in `lib/hooks/` (co-located with their domain). + +**`i18n/`:** +- Purpose: `next-intl` setup — locale list, request config, detection, locale helpers. +- Key files: `i18n/config.ts`, `i18n/request.ts`, `i18n/locale-detection.ts`. + +**`messages/`:** +- Purpose: One JSON file per locale consumed by `next-intl`. + +**`content/`:** +- Purpose: Markdown source for legal pages. + +**`convex/_generated/`:** +- Purpose: Code generated by `convex dev`. Contains `api.d.ts`, `dataModel.d.ts`, `server.d.ts`, `api.js`, `server.js`. +- Generated: Yes (by Convex CLI). +- Committed: Yes. **`tests/`:** -- Purpose: Unit and integration tests (Vitest) -- Contains: Feature-specific test suites, test factories, live billing tests -- Key files: `tests/factories/` (test data), `tests/live-billing/` (Stripe integration tests) +- Purpose: Vitest unit and component tests with jsdom. `tests/setup.ts` wires Testing Library. +- Contains: Flat `*.test.ts(x)` files + domain subfolders (`extraction/`, `library/`, `components/`, `factories/`, `live-billing/`). **`e2e/`:** -- Purpose: End-to-end tests (Playwright) -- Contains: Auth flow tests, billing E2E tests -- Key files: `e2e/auth.spec.ts`, `e2e/billing/` +- Purpose: Playwright end-to-end tests. +- Key files: `e2e/auth.spec.ts`, `e2e/billing/*`, `e2e/global.setup.ts`. + +**`scripts/`:** +- Purpose: Node/TSX CLI utilities — billing preflight, legal parity check, wallet CLI. + +**`docs/`:** +- Purpose: Internal documentation and planning notes (`docs/plans/`). + +**`public/`:** +- Purpose: Static assets served by Next.js. ## Key File Locations **Entry Points:** -- `app/layout.tsx`: Root layout, provider tree, global UI shell -- `app/page.tsx`: Home page / search entry -- `convex/http.ts`: All HTTP endpoints (webhooks) -- `convex/crons.ts`: Scheduled background jobs +- `app/layout.tsx`: Root layout; sets up Clerk + Convex + next-intl + theme + nuqs + feature flags + sidebar + toasts. +- `app/page.tsx`: Home route; wraps `components/PageContent.tsx`. +- `proxy.ts`: Edge middleware (referred to as "proxy"); runs Clerk route protection and locale cookie detection. +- `convex/http.ts`: Convex HTTP router — webhooks + wallet gateway. +- `convex/crons.ts`: Scheduled tasks. +- `instrumentation-client.ts`: PostHog instrumentation entry. **Configuration:** -- `next.config.ts`: Next.js config (React Compiler, PostHog rewrites, next-intl) -- `convex/convex.config.ts`: Convex component registration (Stripe, RAG, Workflow, Workpool) -- `convex/auth.config.ts`: Clerk JWT auth for Convex -- `convex/schema.ts`: Complete database schema -- `tsconfig.json`: TypeScript config with `@/*` path alias -- `vitest.config.ts`: Unit test config -- `playwright.config.ts`: E2E test config +- `next.config.ts`: React Compiler on, security headers, PostHog rewrites, wraps with `next-intl` plugin. +- `tsconfig.json`: Path alias `@/*` → `./*`, strict mode. +- `convex/convex.config.ts`: Registers `@convex-dev/stripe`, `@convex-dev/rag`, `@convex-dev/workflow`, two `@convex-dev/workpool` instances. +- `convex/auth.config.ts`: Clerk JWT issuer for Convex. +- `vitest.config.ts`: Default Vitest. +- `vitest.live.config.ts`: Live-billing test config. +- `playwright.config.ts`: Playwright. +- `knip.json`: Dead code analysis. +- `components.json`: shadcn/ui config. +- `postcss.config.mjs`: Tailwind v4 plugin. +- `ecosystem.config.js`: pm2 (`npm run dev:all` starts Next + Convex). +- `i18n/config.ts`, `i18n/request.ts`: Locale config + request binding. **Core Logic:** -- `lib/search/provider.tsx`: Search state management (URL -> SWR -> context) -- `lib/store.ts`: All Zustand stores (ratings, search history, bookmarks, AI settings, screening) -- `convex/extraction/workflow.ts`: Extraction pipeline orchestration -- `convex/extraction/prompts.ts`: AI extraction prompt templates -- `convex/credits/internal.ts`: Credit grant/deduct/reverse logic -- `convex/subscriptions/actions.ts`: Subscription lifecycle management -- `lib/ai/client/router.ts`: AI provider routing (BYOK vs platform) -- `lib/ai/core/execute.ts`: AI execution engine +- `convex/schema.ts`: All Convex tables + indexes (source of truth for data model). +- `lib/search/provider.tsx`: URL-driven search state (single SWR instance). +- `lib/search-params/parsers.ts`: nuqs parsers and serializers. +- `lib/store.ts`: Zustand root (history, UI, focus, keywords, AI config, sidebar). +- `lib/ai/core/schemas.ts`, `lib/ai/core/prompts.ts`, `lib/ai/core/validate.ts`: Shared AI contracts. +- `lib/ai/server/providers.ts`: `getProviderModel` factory for `@ai-sdk/*`. +- `convex/extraction/workflow.ts` + `convex/extraction/workpoolActions.ts`: Extraction pipeline. +- `convex/wallet/gateway/handler.ts`: OpenAI-compatible HTTP wallet gateway. +- `convex/lib/auth.ts`: `requireAuth`, `getCurrentUser`, etc. +- `convex/lib/errors.ts`: Typed `ErrorCode` union + `createError` helper. +- `convex/lib/stripeWebhookHandlers.ts`: Audited Stripe webhook wrapper. **Testing:** -- `tests/`: Vitest unit/integration tests -- `e2e/`: Playwright E2E tests -- `convex/testing/`: Convex test utilities -- `convex/extraction/*.test.ts`: Co-located Convex tests +- `tests/setup.ts`: Vitest + Testing Library setup. +- `tests/factories/`: Reusable test data builders. +- `tests/live-billing/`: Live-billing suite (runs under `vitest.live.config.ts`). +- `e2e/global.setup.ts`: Playwright global setup (Clerk test harness). ## Naming Conventions **Files:** -- React components: `PascalCase.tsx` (e.g., `PageContent.tsx`, `Pricing.tsx`) -- Non-component modules: `kebab-case.ts` (e.g., `search-utils.ts`, `feature-flags.ts`) -- Convex domain files: `camelCase.ts` following Convex convention (e.g., `queries.ts`, `mutations.ts`, `actions.ts`) -- Test files: `*.test.ts` (e.g., `deduct-credits.test.ts`, `collections.test.ts`) -- E2E test files: `*.spec.ts` (e.g., `auth.spec.ts`) -- Type definition files: `*.types.ts` (e.g., `search.types.ts`, `ai.types.ts`) +- Components: `kebab-case.tsx` (e.g., `components/search-filter-sidebar.tsx`, `components/results-list.tsx`). + - Exceptions: a few PascalCase legacy files — `components/PageContent.tsx`, `components/PageWrapper.tsx`, `components/Pricing.tsx`, and `components/home/HomeHero.tsx`/`AmbientBackground.tsx`/`SearchInput.tsx`/`ModeToggle.tsx`. +- shadcn primitives: lowercase, dash-separated (`components/ui/dropdown-menu.tsx`, `components/ui/alert-dialog.tsx`). +- Hooks: `use-*.ts` / `use-*.tsx` (e.g., `hooks/use-batch-screening.ts`, `lib/hooks/use-debounced-value.ts`). +- Convex functions: `queries.ts`, `mutations.ts`, `actions.ts`, `workflow.ts`, `workpoolActions.ts`, `validators.ts`, `internal.ts` per domain folder. +- Tests: `*.test.ts` / `*.test.tsx` colocated under `tests/` (not next to source), live-billing under `tests/live-billing/`. +- Playwright: `*.spec.ts` under `e2e/`. **Directories:** -- Feature domains: `kebab-case` (e.g., `command-center/`, `paper-card/`) -- Convex domains: `camelCase` (e.g., `apiKeys/`, `library/`) +- Feature folders under `components/` and `convex/` use `kebab-case` (`search-command-center/`) or `camelCase` in Convex (`featureFlags/`, `apiKeys/`). Matching folder names between `lib//`, `convex//`, and `components//` is preferred. +- Route segments: Next.js `[searchId]`, `[[...sign-in]]` conventions. -**Convex Module Pattern:** -- Each domain has: `queries.ts`, `mutations.ts`, `actions.ts`, optionally `internal.ts`, `lib/` -- Internal functions use `internalQuery`/`internalMutation`/`internalAction` -- Public functions use `query`/`mutation`/`action` +**Code:** +- Functions/hooks/variables: `camelCase`. +- Types/interfaces/React components: `PascalCase`. +- Constants: `UPPER_SNAKE_CASE` (e.g., `PUBLIC_UNAUTHENTICATED_PATHS`, `DEFAULT_SEARCH_PARAMS`). +- Convex error codes: `UPPER_SNAKE_CASE` string union in `convex/lib/errors.ts`. +- Zustand stores: `useXxxStore` (e.g., `useSearchHistoryStore`, `useUIStore`, `useKeywordExpansionStore`, `useAIConfigStore`, `useCurrentQueryStore`). ## Where to Add New Code -**New Page/Route:** -- Create directory under `app/` following App Router conventions -- Add `page.tsx` for the page component -- Use `layout.tsx` if the page needs a custom layout -- Dynamic routes: `app/[paramName]/page.tsx` - -**New Feature (full-stack):** -- Backend: Create new directory under `convex/` with `queries.ts`, `mutations.ts`, `actions.ts` -- Frontend components: Create new directory under `components/` -- Shared types: Add to `lib/types/` as `feature.types.ts` -- Feature utilities: Create directory under `lib/` -- Tests: Add to `tests/` or co-locate in `convex/` for backend tests - -**New Component:** -- UI primitive (reusable): `components/ui/` (use `npx shadcn add`) -- Feature-specific: `components/{feature-name}/` -- Shared across features: `components/shared/` - -**New Convex Function:** -- Public query/mutation: Add to existing `queries.ts`/`mutations.ts` in the relevant domain directory -- Internal function: Add to `internal.ts` in the domain directory -- Shared backend utility: Add to `convex/lib/` +**New App Page:** +- Folder: `app//page.tsx` (+ optional `layout.tsx`, `error.tsx`, `loading.tsx`). +- Client content: extract into `components//-page-client.tsx` or a feature folder under `components/`. +- Register in `lib/auth/public-routes.ts` if unauthenticated access is needed. +- Add translations under `messages/*.json`. -**New Hook:** -- Feature-specific: `lib/hooks/` or inline in feature directory -- Cross-cutting: `hooks/` (top-level) +**New UI Component:** +- Feature-specific: `components//.tsx`. +- Shared primitive: `components/ui/.tsx` (run `shadcn` CLI; config in `components.json`). +- Shared feature-agnostic: `components/shared/.tsx`. -**New Store:** -- Add to `lib/store.ts` (main stores file) or create a module in `lib/store/` +**New Server Action:** +- Create a file under `app/actions/.ts` with `"use server"` at the top. +- Prefer Convex mutations/actions for authenticated work. Use Next.js server actions only for public/unauthenticated work like OpenAlex proxying. -**New API Route:** -- Create `app/api/{path}/route.ts` +**New Next.js Route Handler:** +- `app/api//route.ts` with HTTP method exports. Currently used only for `app/api/openalex/search/route.ts`. -**New Server Action:** -- Add to `app/actions/` +**New Convex Domain:** +- Add `convex//queries.ts`, `mutations.ts`, `actions.ts` (and `internal.ts` for internal-only helpers). +- Long-running work: add `workflow.ts` + `workpoolActions.ts` and wire a new workpool if needed in `convex/workpool.ts`. +- Shared helpers: `convex//lib/*.ts`. +- Add tables to `convex/schema.ts` — all tables live in one file. +- Add validators in `convex//validators.ts` if shared. +- If HTTP-exposed: register route in `convex/http.ts`. +- If scheduled: register in `convex/crons.ts`. + +**New Convex Helper (cross-domain):** +- `convex/lib/.ts`. + +**New Shared Lib Module:** +- Folder `lib//` with `index.ts` and named files. +- If types only: add to `lib/types/.types.ts` and re-export from `lib/types/index.ts`. +- AI additions: `lib/ai/core/` for provider-neutral contracts, `lib/ai/client/` for React hooks, `lib/ai/server/` for server-only factories. + +**New Hook:** +- Domain-specific: `lib/hooks/.ts` or `lib//hooks/*`. +- App-level batch hooks (historical): `hooks/*.ts` (prefer `lib/hooks/` for new code). **New Test:** -- Unit test: `tests/{feature}/` with `*.test.ts` extension -- Live billing test: `tests/live-billing/` -- E2E test: `e2e/` with `*.spec.ts` extension -- Convex backend test: Co-locate as `*.test.ts` in `convex/{domain}/` +- Unit/integration (Vitest): `tests/.test.ts(x)`. Use `tests/factories/` for builders and `tests/setup.ts` for global setup. +- Live-billing: `tests/live-billing/*` (runs under `vitest.live.config.ts`). +- E2E (Playwright): `e2e/*.spec.ts`. + +**New Locale Key:** +- Add to all `messages/.json` files (coverage is enforced by tests in `tests/extraction-i18n-coverage.test.ts`). + +**New Feature Flag:** +- Register in `lib/feature-flags/registry.ts`; consume with `useFeatureFlag` from `lib/feature-flags/hook.ts`; seed via `convex/featureFlags/internal.ts`; enforce server-side with `convex/featureFlags/guard.ts`. -**Translations:** -- Add keys to all files in `messages/` (en-US.json, fr.json, etc.) +**New Stripe Webhook Handler:** +- Add the event inside `registerRoutes` in `convex/http.ts`, wrap with `runAuditedStripeHandler`, document an idempotency contract in a JSDoc block, and route real work into `convex/credits/` or `convex/subscriptions/`. + +**New Wallet Gateway Endpoint:** +- Add handler in `convex/wallet/gateway/handler.ts`, register with `http.route` in `convex/http.ts`, add a matching `OPTIONS` CORS route. ## Special Directories **`convex/_generated/`:** -- Purpose: Auto-generated Convex types, API references, data model types -- Generated: Yes (by `convex dev` or `convex deploy`) -- Committed: Yes - -**`.next/`:** -- Purpose: Next.js build output -- Generated: Yes -- Committed: No +- Purpose: Convex CLI output (`api`, `internal`, `dataModel`, `components`). +- Generated: Yes (by `convex dev` / `convex deploy`). +- Committed: Yes. -**`node_modules/`:** -- Purpose: NPM dependencies -- Generated: Yes -- Committed: No +**`messages/`:** +- Purpose: next-intl translation JSON. +- Generated: No. +- Committed: Yes. All locales must stay in sync. **`.planning/`:** -- Purpose: GSD planning documents and codebase analysis -- Generated: By tooling -- Committed: Yes +- Purpose: GSD planning artifacts (phases, research, codebase maps, milestones, state). +- Generated: Partly (by GSD commands). +- Committed: Yes. -**`content/`:** -- Purpose: Static legal content (privacy policy, cookie policy) in markdown -- Generated: No -- Committed: Yes +**`public/`:** +- Purpose: Static assets. +- Generated: No. +- Committed: Yes. + +**`.next/`, `node_modules/`, `test-results/`, `tsconfig.tsbuildinfo`:** +- Generated: Yes. +- Committed: No. + +**`skills/`:** +- Purpose: GSD/agent skill definitions referenced by `skills-lock.json`. +- Committed: Yes. --- -*Structure analysis: 2026-03-06* +*Structure analysis: 2026-04-14* diff --git a/.planning/codebase/TESTING.md b/.planning/codebase/TESTING.md index 6f5f024b2..60d14bec6 100644 --- a/.planning/codebase/TESTING.md +++ b/.planning/codebase/TESTING.md @@ -1,92 +1,116 @@ # Testing Patterns -**Analysis Date:** 2026-03-06 +**Analysis Date:** 2026-04-14 ## Test Framework **Runner:** -- Vitest 3.x for unit and integration tests -- Config: `vitest.config.ts` (main), `vitest.live.config.ts` (live billing) -- Playwright 1.x for E2E tests -- Config: `playwright.config.ts` +- Vitest `^3.2.4` +- Configs: + - `vitest.config.ts` — primary config for unit, integration, and Convex tests + - `vitest.live.config.ts` — separate config for long-running live billing tests (300s timeouts) +- Playwright `^1.58.2` for browser-based end-to-end tests + - Config: `playwright.config.ts` + - Test directory: `e2e/` + - Two named projects: `default` and `billing` (the latter is serial, longer-timeout, locale-pinned) **Assertion Library:** -- Vitest built-in `expect` with `@testing-library/jest-dom/vitest` matchers -- Playwright built-in `expect` with web-first assertions +- Built-in Vitest expect (Jest-compatible matchers) +- `@testing-library/jest-dom` matchers extended via `tests/setup.ts` (`import "@testing-library/jest-dom/vitest"`) **Run Commands:** ```bash -npm run test # Run all unit/integration tests (vitest run) -npm run test:billing:live # Run live billing tests against real Stripe -npm run test:billing:live:ci # Live billing with Convex deploy -npm run test:billing:extended # Extended live billing suite -npm run test:billing:e2e # Playwright billing E2E specs -npm run test:e2e:auth # Playwright auth E2E specs -npm run test:ci # Unit tests + build + auth E2E -npm run test:all # Full suite: test:ci + billing E2E +npm run test # Run all unit/integration tests (vitest run) +npm run test:billing:preflight # Validate Stripe/Convex env before live billing +npm run test:billing:live # Run required live billing regressions +npm run test:billing:extended # Run extended live billing scenarios +npm run test:billing:e2e # Playwright billing E2E project +npm run test:e2e:auth # Playwright auth flow only (e2e/auth.spec.ts) +npm run test:ci # Full unit + build + auth E2E (CI gate) +npm run test:all # CI gate + billing E2E ``` ## Test File Organization -**Location:** -- Unit/integration tests: `tests/` directory (separate from source) -- Convex function tests: Co-located at `convex/**/*.test.ts` -- E2E tests: `e2e/` directory -- Live billing tests: `tests/live-billing/` +**Location pattern (mixed):** +- Co-located unit tests next to source for Convex modules (e.g., `convex/library/queries.test.ts`, `convex/wallet/wallet.test.ts`, `convex/credits/deduct-credits.test.ts`) +- Centralized `tests/` directory for application-level unit and integration tests (97 files at the time of analysis) +- Subdirectories inside `tests/` for grouping: + - `tests/components/` — React component unit tests (jsdom) + - `tests/extraction/` — extraction-specific integration tests + - `tests/library/` — library helper tests + - `tests/factories/` — shared test factories (not test files themselves) + - `tests/live-billing/` — long-running Stripe/Convex live regression tests +- Playwright specs live under `e2e/` (`e2e/auth.spec.ts`, `e2e/billing/specs/*`) **Naming:** -- Unit/integration: `tests/{feature-name}.test.ts` (kebab-case) -- Convex function tests: `convex/{domain}/queries.test.ts` -- E2E specs: `e2e/{feature}.spec.ts` or `e2e/billing/specs/{scenario}.spec.ts` +- Vitest tests use `*.test.ts` / `*.test.tsx` +- Playwright tests use `*.spec.ts` **Structure:** ``` tests/ - setup.ts # Global test setup (jest-dom, cleanup) - factories/ # Shared test factories - index.ts # Barrel export - convex-context.ts # Mock Convex ctx factories - convex-ids.ts # ID generation helpers - stripe-events.ts # Mock Stripe event/invoice factories - live-billing/ - support.ts # Live billing test utilities - required.test.ts # Required regression tests - extended.test.ts # Extended regression tests - *.test.ts # Individual test files +├── setup.ts # Jest-DOM extension + RTL cleanup hook +├── factories/ # Reusable mock builders +│ ├── index.ts +│ ├── convex-context.ts +│ ├── convex-ids.ts +│ └── stripe-events.ts +├── components/ # React component tests (jsdom) +│ └── grouped-answer-row.test.tsx +├── extraction/ # Feature-area integration +├── library/ # Library helpers +├── live-billing/ # Long-running live billing regressions +│ ├── required.test.ts +│ ├── extended.test.ts +│ └── support.ts +├── auth-state-machine.test.ts # Mocked unit tests +├── credit-grant-policy.test.ts +├── ai-cost.test.ts +└── ... (97 files total) convex/ - library/queries.test.ts # Co-located Convex function tests - library/collections.test.ts +├── library/queries.test.ts # Co-located Convex test (convexTest) +├── wallet/wallet.test.ts +├── credits/deduct-credits.test.ts +└── extraction/job-stats.test.ts e2e/ - global.setup.ts # Playwright global setup (Clerk user provisioning) - auth.spec.ts # Auth flow E2E tests - billing/ - fixtures.ts # Playwright fixture composition - stripe-helpers.ts # Stripe API helpers for E2E - webhook-waiter.ts # Polls Convex for webhook processing - pages/ # Page Object Models - billing-page.ts - pricing-page.ts - specs/ # Billing E2E specs - subscribe.spec.ts - upgrade.spec.ts - downgrade.spec.ts - cancel.spec.ts - credits.spec.ts - credit-grants.spec.ts +├── auth.spec.ts # Playwright clerk auth flows +├── global.setup.ts # Clerk user provisioning +└── billing/ # Billing E2E flows + ├── fixtures.ts + ├── pages/ + ├── specs/ + ├── stripe-helpers.ts + └── webhook-waiter.ts ``` -## Environment Configuration +## Vitest Environment Routing -**Vitest environments (per-glob matching in `vitest.config.ts`):** -- Default: `node` for pure logic tests -- `edge-runtime` for Convex function tests (`convex/**/*.test.ts`) -- required by `convex-test` -- `jsdom` for React hook/component tests (`tests/hooks/**`, `tests/components/**`) +`vitest.config.ts` selects environment per file glob via `environmentMatchGlobs`: -**Setup file:** `tests/setup.ts` -```typescript +| Glob | Environment | Reason | +|---|---|---| +| `convex/**/*.test.ts` | `edge-runtime` | Required by `convex-test` | +| `tests/hooks/**/*.test.ts(x)` | `jsdom` | DOM APIs for React hooks | +| `tests/components/**/*.test.tsx` | `jsdom` | RTL component rendering | +| `tests/*.test.tsx` (root level) | `jsdom` | Top-level component test files | +| Everything else | `node` | Pure logic & policy tests | + +Notes: +- `convex-test` is force-inlined via `server.deps.inline: ["convex-test"]` +- Live billing tests excluded from default config: `exclude: ["tests/live-billing/**/*.test.ts"]` +- Path alias `@/*` mirrored from `tsconfig.json` + +## Test Setup + +`tests/setup.ts`: +```ts +// Extend Vitest expect with jest-dom matchers (safe everywhere) import "@testing-library/jest-dom/vitest"; + import { afterEach } from "vitest"; +// Cleanup React Testing Library renders after each test afterEach(async () => { if (typeof globalThis.document !== "undefined") { const { cleanup } = await import("@testing-library/react"); @@ -95,336 +119,272 @@ afterEach(async () => { }); ``` -**Exclusions:** `tests/live-billing/**/*.test.ts` excluded from default `vitest run` (uses separate config with 300s timeout) - ## Test Structure -**Suite Organization:** -```typescript -import { describe, expect, it } from "vitest"; +**Suite organization:** +```ts +import { describe, it, expect, vi } from "vitest"; +import { processClerkWebhookEvent } from "../convex/webhooks/clerk"; -describe("functionUnderTest", () => { - it("returns correct result for normal input", () => { - const result = functionUnderTest(normalInput); - expect(result).toEqual(expectedOutput); - }); +describe("clerk webhook handler", () => { + it("dispatches user.created to upsert mutation", async () => { + const mutationRefs = { + upsertUserFromClerk: Symbol("upsertUserFromClerk"), + markUserDeletedFromClerk: Symbol("markUserDeletedFromClerk"), + }; + const runMutation = vi.fn().mockImplementation(...); - it("handles edge case", () => { - expect(functionUnderTest(edgeInput)).toBe(expectedEdge); - }); + const outcome = await processClerkWebhookEvent({ ... }); - describe("nested group for sub-behavior", () => { - it("does specific sub-thing", () => { - // ... - }); + expect(outcome).toEqual({ status: 200, body: "OK" }); + expect(runMutation).toHaveBeenCalledTimes(1); }); }); ``` -**Patterns:** -- Flat `describe` blocks for each exported function -- Nested `describe` for logical sub-groups (e.g., filter sections) -- `it` descriptions start with verb: "returns", "creates", "throws", "handles" -- Use `it.each()` for parameterized tests (see `tests/ai-cost.test.ts`) -- No `beforeEach`/`afterEach` in pure unit tests -- setup inline -- `beforeEach` used for mock reset in tests with `vi.fn()` mocks - -## Mocking - -**Framework:** Vitest built-in `vi.fn()` and `vi.mock()` - -**Patterns - Manual Mocks via Factory Functions:** -```typescript -// tests/factories/convex-context.ts -import { vi } from "vitest"; - -export function createMockActionCtx(overrides?: DeepPartial): ActionCtx { - const base = { - runMutation: vi.fn(), - runAction: vi.fn(), - scheduler: { runAfter: vi.fn(), runAt: vi.fn() }, - auth: { getUserIdentity: vi.fn().mockResolvedValue(null) }, - }; - return deepMerge(base, overrides) as unknown as ActionCtx; +**Patterns observed:** +- Single top-level `describe` per behavior under test, with nested `describe` blocks for grouped scenarios (see `convex/credits/deduct-credits.test.ts` which nests `describe("single deduction")` inside `describe("deductCredits")`) +- Test names start with a verb describing observable behavior ("returns", "throws", "dispatches", "renders", "rejects") +- `it.each(pricingCases)` for parameterized tests (`tests/ai-cost.test.ts`) +- For sequenced live tests: `describe.sequential(...)` with `beforeAll` / `beforeEach` / `afterAll` lifecycle hooks (`tests/live-billing/required.test.ts`) + +**Async error testing:** +```ts +try { + await requireAuth(ctx); + expect.fail("Should have thrown"); +} catch (err) { + expect(err).toBeInstanceOf(ConvexError); + const convexErr = err as ConvexError<{ code: string; message: string }>; + expect(convexErr.data.code).toBe("FORBIDDEN"); } ``` +(See `tests/auth-state-machine.test.ts` for the canonical example.) -```typescript -// tests/factories/stripe-events.ts -export function createMockStripeEvent(overrides?: Record): Stripe.Event { - const base = { - id: "evt_test_123", - type: "invoice.paid", - api_version: "2024-12-18.acacia", - // ...defaults - ...overrides, - }; - return base as unknown as Stripe.Event; -} -``` - -**Usage in tests:** -```typescript -import { createMockActionCtx, createMockStripeEvent } from "./factories"; +## Mocking -const ctx = createMockActionCtx({ - runMutation: vi.fn().mockResolvedValue(undefined), +**Framework:** Vitest `vi.fn()`, `vi.mock()`, `vi.spyOn()` + +**Module mocks (top of file):** +```ts +// Mock i18n — return key as value +vi.mock("next-intl", () => ({ + useTranslations: () => (key: string) => key, +})); + +// Mock icons +vi.mock("lucide-react", () => ({ + ChevronDown: () => null, + ChevronRight: () => null, +})); + +// Mock heavy children to avoid deep-render chains in component tests +vi.mock("../components/extraction/bar-visualization", () => ({ + BarVisualization: ({ answers }: { answers: unknown[] }) => ( +
+ ), +})); +``` +(See `tests/components/grouped-answer-row.test.tsx`, `tests/extraction-insights-overview.test.tsx`, `tests/extraction-insights-question-panel.test.tsx`.) + +**Function-reference mocks (Convex):** +```ts +const mutationRefs = { + upsertUserFromClerk: Symbol("upsertUserFromClerk"), + markUserDeletedFromClerk: Symbol("markUserDeletedFromClerk"), +}; +const runMutation = vi.fn().mockImplementation(async (mutation, _args) => { + if (mutation !== mutationRefs.upsertUserFromClerk) { + throw new Error("expected upsertUserFromClerk mutation"); + } + return null; }); -const event = createMockStripeEvent({ id: "evt_custom" }); ``` +Symbols are used as opaque function-reference stand-ins so the handler can identify which Convex internal it dispatched to without importing the real `internal.*` ref. **What to Mock:** -- Convex context objects (`QueryCtx`, `MutationCtx`, `ActionCtx`) via factory functions -- Stripe event/invoice objects via factory functions -- External API calls and side effects +- External SDKs (`next-intl`, `lucide-react`, dynamic imports like `BarVisualization`) +- Auth identity (`createMockIdentity`) +- Convex contexts (`createMockQueryCtx`, `createMockMutationCtx`, `createMockActionCtx` from `tests/factories/convex-context.ts`) +- Heavy/expensive child components in component tests +- Convex function references via `Symbol` placeholders for unit-level dispatch tests **What NOT to Mock:** -- Pure business logic functions (test directly) -- Convex validators and schema (use `convex-test` instead) -- Data transformation utilities - -## Convex Function Testing - -**Framework:** `convex-test` package with real Convex schema - -**Pattern:** -```typescript -import { convexTest } from "convex-test"; -import { api } from "../_generated/api"; -import schema from "../schema"; - -describe("browseLibrary", () => { - it("returns paginated results for authenticated user", async () => { - const t = convexTest(schema); - const user = await seedUser(t, "clerk_user1", "user1@test.com"); - const asUser = t.withIdentity({ subject: "clerk_user1" }); - - await seedLibraryItem(t, user!._id, { title: "Paper A" }); +- Logic under test +- Pure functions (test directly with literal inputs) +- The Convex DB layer in tests using `convexTest()` — use real seeded data via `t.run(...)` instead - const result = await asUser.query(api.library.queries.browseLibrary, { - sortBy: "savedAt", - sortOrder: "desc", - paginationOpts: { numItems: 10, cursor: null }, - }); - - expect(result.page).toHaveLength(1); - }); -}); -``` - -**Key conventions for `convex-test`:** -- Create new `convexTest(schema)` instance per test (fresh DB) -- Seed data via `t.run(async (ctx) => { await ctx.db.insert(...) })` -- Authenticate with `t.withIdentity({ subject: "clerk_user1" })` -- Call functions via `asUser.query(api.module.fn, args)` or `asUser.mutation(...)` -- Requires `edge-runtime` environment (configured in `vitest.config.ts`) -- Helper seed functions defined at top of test file (e.g., `seedUser()`, `seedLibraryItem()`) - -## E2E Testing - -**Framework:** Playwright with Clerk testing integration - -**Global Setup (`e2e/global.setup.ts`):** -- Loads env from `.env.local` / `.env` -- Normalizes Clerk env vars -- Calls `clerkSetup()` for Playwright Clerk integration -- Creates/updates disposable Clerk test user - -**Fixture Composition (billing E2E):** -```typescript -// e2e/billing/fixtures.ts -export const test = base.extend({ - clerkUser: async ({ page }, use) => { - // Create fresh Clerk user, sign in, cleanup on teardown - }, - stripeClient: async ({}, use) => { - await use(createStripeClient()); - }, - webhookWaiter: async ({ clerkUser }, use) => { - // Discover Convex userId, create WebhookWaiter - }, - billingPage: async ({ page }, use) => { - await use(new BillingPage(page)); - }, -}); -``` +## Fixtures and Factories -**Page Object Model Pattern:** -```typescript -// e2e/billing/pages/billing-page.ts -export class BillingPage { - readonly planName: Locator; - readonly statusBadge: Locator; +**Centralized factories:** `tests/factories/` - constructor(page: Page) { - this.planName = page.locator('[data-testid="billing-plan-name"]'); - this.statusBadge = page.locator('[data-testid="billing-status-badge"]'); - } +**Convex context factories (`tests/factories/convex-context.ts`):** +- `createMockQueryCtx(overrides?)` — returns a `QueryCtx` with mocked `db.query(...).withIndex(...).unique()` and `auth.getUserIdentity()` +- `createMockMutationCtx(overrides?)` — extends QueryCtx with `db.insert/patch/delete/replace` and `scheduler.runAfter/runAt` +- `createMockActionCtx(overrides?)` — has `runMutation`, `runAction`, `scheduler`, `auth` +- All factories accept a `DeepPartial` overrides argument and use a `deepMerge` helper (overrides win, no array merging) +- `createMockIdentity(overrides?)` — stub Clerk identity object - async goto(): Promise { - await this.page.goto("/settings/billing"); - await this.planName.waitFor({ state: "visible", timeout: 30_000 }); - } +**Branded ID and Doc factories (`tests/factories/convex-ids.ts`):** +```ts +export function mockId(table: T, suffix = "1"): Id { + return `mock_${table}_${suffix}` as unknown as Id; } -``` - -**E2E conventions:** -- Use `data-testid` attributes for element selection -- Page Object Models in `e2e/billing/pages/` -- Fixtures compose user lifecycle, API clients, and page objects -- Numbered step comments in test body: `// 1. Subscribe`, `// 2. Wait`, `// 3. Assert` -- Cleanup Stripe objects in test teardown -- `WebhookWaiter` polls Convex to confirm async webhook processing - -**Playwright configuration highlights:** -- Timeout: 120s default, 180s for billing -- Retries: 2 in CI, 0 locally -- Workers: 1 in CI (sequential) -- Traces/screenshots/video on failure only -- Web server auto-started via `npm run build && npm run start` -## Live Billing Tests - -**Purpose:** Integration tests against real Stripe test-mode API - -**Config:** `vitest.live.config.ts` with 300s timeout - -**Patterns:** -- `describe.sequential()` to enforce test ordering -- Real Stripe API calls via `createStripeClient()` -- Test clock manipulation for time-dependent billing logic -- Convex function calls via CLI (`npx convex run`) -- Artifact logging for debugging: `appendBillingArtifactLog()` -- `waitForCondition()` polling for async Stripe/Convex state -- Full setup/teardown lifecycle: create user, reset state, cleanup Stripe - -## Fixtures and Factories - -**Test Data (Unit tests):** -```typescript -// tests/factories/stripe-events.ts -export function createMockStripeEvent(overrides?) { /* ... */ } -export function createMockStripeInvoice(overrides?) { /* ... */ } -export function createMockMutationRefs() { /* ... */ } -export function createMockGrantRefs() { /* ... */ } - -// tests/factories/convex-context.ts -export function createMockQueryCtx(overrides?) { /* ... */ } -export function createMockMutationCtx(overrides?) { /* ... */ } -export function createMockActionCtx(overrides?) { /* ... */ } -export function createMockIdentity(overrides?) { /* ... */ } +export function createMockUser(overrides?: UserOverrides): Doc<"users"> { ... } +export function createMockSubscription(overrides?: SubscriptionOverrides): Doc<"subscriptions"> { ... } ``` -**Location:** -- Shared factories in `tests/factories/` with barrel export via `tests/factories/index.ts` -- Inline seed helpers in Convex test files (e.g., `seedUser()`, `seedLibraryItem()` in `convex/library/queries.test.ts`) -- E2E helpers in `e2e/billing/stripe-helpers.ts` and `e2e/billing/webhook-waiter.ts` +**Stripe factories (`tests/factories/stripe-events.ts`):** +- `createMockStripeEvent`, `createMockStripeInvoice` +- `createMockMutationRefs()` and `createMockGrantRefs()` for typed `FunctionReference<"mutation" | "action", "internal">` placeholders -**Factory design pattern:** -- Accept optional `overrides` parameter for selective customization -- Return typed objects with sensible defaults -- Use `as unknown as Type` cast for partial mock objects -- Deep merge for nested override support (`createMockActionCtx`) +**Seed helpers (per-test-file pattern for Convex tests):** +Files using `convex-test` define local `seedUser`, `seedUserWithCredits`, `seedWalletKey`, `seedJobWithPapers` helpers. These run inside `t.run(async (ctx) => ctx.db.insert(...))` so they exercise the real schema. Each test file owns its own seeds rather than importing them globally — keeps tests close to the schema they verify. ## Coverage -**Requirements:** None enforced (no coverage thresholds configured) +**Requirements:** +- No coverage threshold enforced in `vitest.config.ts` +- CI gate is `npm run test:ci` (unit + build + auth E2E) — coverage is informational only **View Coverage:** ```bash -npx vitest run --coverage # Not configured by default but available +npx vitest run --coverage ``` ## Test Types -**Unit Tests (tests/*.test.ts):** -- Test pure functions, validators, and business logic -- No network calls or database access -- Direct import of source modules -- ~75 test files covering filters, AI, billing, auth, export, extraction - -**Convex Function Tests (convex/**/*.test.ts):** -- Test Convex queries/mutations with `convex-test` mock database -- Validate auth requirements, data isolation, pagination, filtering -- Run in edge-runtime environment - -**Live Integration Tests (tests/live-billing/*.test.ts):** -- Test against real Stripe test-mode API -- Verify webhook processing, credit grants, subscription lifecycle -- Sequential execution with long timeouts (300s) -- Separate vitest config to avoid running in normal test suite - -**E2E Tests (e2e/*.spec.ts):** -- Full browser tests with Playwright -- Clerk auth integration for real sign-in/sign-out flows -- Stripe checkout bypass for billing scenarios -- Page Object Model for UI assertions +**Unit tests:** +- Pure logic (`tests/ai-cost.test.ts`, `tests/credit-grant-policy.test.ts`, `tests/extraction-i18n-coverage.test.ts`) +- React components in jsdom (`tests/components/grouped-answer-row.test.tsx`, `tests/extraction-insights-overview.test.tsx`) +- Convex handlers with mocked context (`tests/auth-state-machine.test.ts`, `tests/clerk-webhook-handler.test.ts`) + +**Integration tests:** +- Convex modules using real schema via `convexTest(schema)` (`convex/library/queries.test.ts`, `convex/credits/deduct-credits.test.ts`, `convex/wallet/wallet.test.ts`, `convex/extraction/job-stats.test.ts`) +- Use `t.run(async ctx => ...)` to seed data and `t.mutation(internal.X.Y, args)` / `t.query(api.X.Y, args)` to invoke +- Use `t.withIdentity({ subject: "clerk_user1" })` to simulate authenticated requests +- Some "integration" tests verify source code shape via `readFileSync` and regex checks (`tests/extraction/rate-limit.test.ts`, `tests/credit-grant-policy.test.ts`) — useful for enforcing structural invariants without runtime instantiation + +**Source-shape tests:** +Pattern: read a `.ts` source file with `node:fs` and assert against its text content. Used to lock in: +- Validator argument shape (e.g., `convex/lib/rateLimit.ts` must use `v.union(v.literal(...))` for the `consume` mutation `name` arg) +- Cross-file enforcement (e.g., `convex/credits/internal.ts` must reference `classifyMonthlyCreditInvoice` and `markStripeEventFailed`) +- "No `as any`" budget enforcement + +**Live billing tests (`tests/live-billing/`):** +- Real Stripe API + real Convex deployment +- Uses Stripe test clocks, customers, payment methods (`createClockedCustomer`, `attachDefaultVisaPaymentMethod`) +- 300-second test/hook timeouts via `vitest.live.config.ts` +- Sequenced via `describe.sequential(...)` +- Persistent artifact logging (`appendBillingArtifactLog`, `writeBillingArtifactJson`) +- Per-test cleanup via `cleanupStripeForTestUser` and `resetBillingStateForUser` +- Optional Convex code push gated by `BILLING_LIVE_PUSH_CONVEX=true` + +**E2E tests (`e2e/`):** +- Playwright + `@clerk/testing/playwright` +- Global setup (`e2e/global.setup.ts`): + - Loads `.env.local` / `.env` via `process.loadEnvFile` + - Calls `clerkSetup()` + - Provisions a disposable Clerk user via `createClerkClient(...).users.{getUserList,createUser,updateUser,deleteUser}` to ensure deterministic state + - Cleans up duplicate test users +- Playwright config: + - `webServer` runs `npm run build && npm run start -- --port 3000` (override via `PLAYWRIGHT_WEB_SERVER_COMMAND`) + - `baseURL` from `E2E_BASE_URL` (default `http://127.0.0.1:3000`) + - CI: 2 retries, single worker, `github` reporter + - Trace `retain-on-failure`, screenshot `only-on-failure`, video `retain-on-failure` +- Two projects: + - `default` — ignores `**/billing/**` + - `billing` — only `e2e/billing/`, serial workers, longer timeout, `en-US` locale ## Common Patterns -**Async Testing:** -```typescript -it("throws FORBIDDEN when trying to delete another user's item", async () => { +**Async testing:** +```ts +it("returns paginated results for authenticated user", async () => { const t = convexTest(schema); - // ... setup ... - await expect( - asUser1.mutation(api.library.mutations.removeFromLibrary, { itemId }) - ).rejects.toThrow(); + const user = await seedUser(t, "clerk_user1", "user1@test.com"); + const asUser = t.withIdentity({ subject: "clerk_user1" }); + + await seedLibraryItem(t, user!._id, { title: "Paper A", savedAt: 1000 }); + + const result = await asUser.query(api.library.queries.browseLibrary, { ... }); + expect(result.items).toHaveLength(1); }); ``` -**Error Testing:** -```typescript -it("calls markStripeEventFailed and re-throws on handler error", async () => { - const handler = vi.fn().mockRejectedValue(new Error("handler boom")); +**Error testing (ConvexError discriminated codes):** +```ts +try { + await requireAuth(ctx); + expect.fail("Should have thrown"); +} catch (err) { + expect(err).toBeInstanceOf(ConvexError); + const convexErr = err as ConvexError<{ code: string; message: string }>; + expect(convexErr.data.code).toBe("FORBIDDEN"); + expect(convexErr.data.message).toBe("Account suspended"); +} +``` - await expect( - runAuditedStripeHandler(ctx, event, handler, mutationRefs), - ).rejects.toThrow("handler boom"); +**Component interaction:** +```ts +import { render, screen, fireEvent } from "@testing-library/react"; - const runMutation = ctx.runMutation as ReturnType; - expect(runMutation).toHaveBeenCalledTimes(1); -}); +render(); +fireEvent.click(screen.getByRole("button")); +expect(screen.getByText("True")).toBeTruthy(); ``` -**Parameterized Testing:** -```typescript -it.each(providerCases)( - "returns correct cost for $provider / $modelId", - ({ provider, modelId, inputPrice, outputPrice }) => { - const cost = calculateCostInDollars(usage, provider, modelId); - expect(cost).toBeCloseTo(inputPrice + outputPrice, 6); - } -); +**Source-shape assertion:** +```ts +const source = fs.readFileSync(path.resolve(process.cwd(), "convex/lib/rateLimit.ts"), "utf-8"); +expect(source).toContain('v.literal("start-extraction")'); +expect(source).not.toMatch(/name:\s*v\.string\(\)/); ``` -**Source Code Verification (policy tests):** -```typescript -// Verify implementation uses the policy function -it("is enforced by monthly grant implementation", () => { - const source = readFileSync(path.resolve(process.cwd(), "convex/credits/internal.ts"), "utf8"); - expect(source).toMatch(/classifyMonthlyCreditInvoice/); +**Parameterized cases:** +```ts +const pricingCases = [ + { label: "cheap model", pricing: { input: 0.05, output: 0.4 } }, + { label: "mid-range model", pricing: { input: 0.25, output: 1.25 } }, +]; + +it.each(pricingCases)("returns correct cost for $label", ({ pricing }) => { + const cost = calculateCostInDollars({ promptTokens: 1_000_000, completionTokens: 1_000_000 }, pricing); + expect(cost).toBeCloseTo(pricing.input + pricing.output, 6); }); ``` -**Convex auth testing:** -```typescript -// Test user isolation -it("does NOT return items belonging to other users", async () => { - const t = convexTest(schema); - const user1 = await seedUser(t, "clerk_user1", "user1@test.com"); - const user2 = await seedUser(t, "clerk_user2", "user2@test.com"); - const asUser1 = t.withIdentity({ subject: "clerk_user1" }); +**Live test lifecycle:** +```ts +describe.sequential("live billing required regressions", () => { + let userId: string; - await seedLibraryItem(t, user1!._id, { title: "User1 paper" }); - await seedLibraryItem(t, user2!._id, { title: "User2 paper" }); + beforeAll(async () => { + resetBillingArtifacts(); + const ensured = await ensureBillingTestUser({ env, push: env.shouldPushConvexCode }); + userId = ensured.userId; + }); + + beforeEach(async () => { + await cleanupStripeForTestUser({ stripe, ... }); + await resetBillingStateForUser(userId); + }); - const result = await asUser1.query(api.library.queries.browseLibrary, { /* ... */ }); - expect(result.page).toHaveLength(1); - expect(result.page[0].title).toBe("User1 paper"); + afterAll(async () => { + const finalSnapshot = await getBillingSnapshotForUser(userId); + writeBillingArtifactJson("final-snapshot.json", finalSnapshot); + }); }); ``` +## Test Counts (snapshot) + +- 97 Vitest test files under `tests/` +- 13 co-located Convex test files under `convex/` +- 1 auth E2E spec (`e2e/auth.spec.ts`) plus billing specs under `e2e/billing/specs/` +- 2 live-billing test files (`tests/live-billing/required.test.ts`, `tests/live-billing/extended.test.ts`) + --- -*Testing analysis: 2026-03-06* +*Testing analysis: 2026-04-14* From bf15f585a498add8a3e2252f9ba9d19d3568b46e Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:06:35 +0100 Subject: [PATCH 002/421] docs: start milestone v6.0 Extraction MVP Rebuild --- .planning/PROJECT.md | 25 ++++++++++++++++++++-- .planning/STATE.md | 49 ++++++++++++++++++++++++++------------------ 2 files changed, 52 insertions(+), 22 deletions(-) diff --git a/.planning/PROJECT.md b/.planning/PROJECT.md index 7b3605b58..5d6e65e08 100644 --- a/.planning/PROJECT.md +++ b/.planning/PROJECT.md @@ -143,7 +143,28 @@ Reliable, well-tested academic search and AI extraction — every major code pat ### Active -(None yet — define in next milestone) +## Current Milestone: v6.0 Extraction MVP Rebuild + +**Goal:** Hot-swap the extraction pipeline with a clean, MVP-grade implementation — cheap OpenRouter models, free upstream full-text sources, deterministic citation grounding, and zero crash surfaces. Delete all legacy extraction code, tables, and data. + +**Target features:** +- Scorched-earth teardown of all legacy extraction code and data (~9.6K LoC, 9 tables, RAG component, 8 debug modules) +- Free-first parsing waterfall: OpenAlex metadata → Europe PMC `fullTextXML` → arXiv HTML → `unpdf` → Gemini-as-PDF-parser → abstract-only fallback +- Cheap cascade via OpenRouter + AI SDK 6: Gemini 2.5 Flash Lite pre-screen → Gemini 3 Flash default → Claude Haiku 4.5 escalation; `response-healing` plugin, provider-order fallback +- Whole-paper extraction in 1M context (no chunking, no RAG, no vector DB) +- Deterministic citation grounding: flat 7-field Zod schema, `propertyOrdering` (reasoning-before-answer), `superRefine` + `fastest-levenshtein` 85% verification, UI always renders `chunk.text.slice()` +- Critic-pass hallucination gate reused for online quality sampling +- New durable workflow/workpool with per-job workpoolId tracking, targeted cancel, retryable/permanent error taxonomy, idempotent result save +- Crash-prevention sweep: segment error boundaries, `useQuery` null/undefined audit, Clerk visibility-change retry, `AbortSignal.timeout` on all LLM calls, prompt-injection delimiters, PDF page cap +- MVP eval loop: `vitest-evals` + `autoevals`, 20-case hand-labeled golden set, hourly Convex cron production sampling with auto-flag → human-review queue +- Structured JSON logging + two metrics only: recall-on-include + citation-validity-rate + +**Key constraints:** +- Legacy is DEAD. Destructive rebuild. No backward compat, no data migration — wipe tables and delete code. +- Convex backend only; Vercel hosts frontend only. +- Small user base — skip hot/cold split, sharded counters, circuit breaker, dead-letter table, Langfuse, Docling/MinerU/olmOCR, Contextual Retrieval, idempotency holds. +- Models: Gemini 3 Flash / 2.5 Flash Lite / 3.1 Flash Lite / Haiku 4.5 via OpenRouter. Grok 4.1 Fast excluded (92.89% JSON validity is a dealbreaker for strict schemas). +- Target cost: <$50/month total for MVP volume. ### Out of Scope @@ -295,4 +316,4 @@ Maintenance: Hourly cron for expired OAuth token cleanup, 24h env var validation | IIFE pattern for grouping computation in JSX | synonymMap built once, shared by answer and disagreement transforms | ✓ Good — avoids double computation | --- -*Last updated: 2026-03-10 after v5.0 milestone completed* +*Last updated: 2026-04-14 after v6.0 Extraction MVP Rebuild milestone started* diff --git a/.planning/STATE.md b/.planning/STATE.md index c213462af..85adf5b42 100644 --- a/.planning/STATE.md +++ b/.planning/STATE.md @@ -1,36 +1,36 @@ --- gsd_state_version: 1.0 -milestone: v5.0 -milestone_name: Extraction Insights Overhaul -status: completed -stopped_at: Milestone v5.0 completed and archived -last_updated: "2026-03-10T11:15:00.000Z" -last_activity: 2026-03-10 — v5.0 milestone completed and archived +milestone: v6.0 +milestone_name: Extraction MVP Rebuild +status: active +stopped_at: Defining requirements +last_updated: "2026-04-14T00:00:00.000Z" +last_activity: 2026-04-14 — Milestone v6.0 started progress: - total_phases: 5 - completed_phases: 5 - total_plans: 14 - completed_plans: 14 - percent: 100 + total_phases: 0 + completed_phases: 0 + total_plans: 0 + completed_plans: 0 + percent: 0 --- # Project State ## Project Reference -See: .planning/PROJECT.md (updated 2026-03-10) +See: .planning/PROJECT.md (updated 2026-04-14) **Core value:** Reliable, well-tested academic search and AI extraction -**Current focus:** Planning next milestone +**Current focus:** v6.0 Extraction MVP Rebuild — hot-swap the extraction pipeline with a clean, MVP-grade implementation ## Current Position -Phase: -- (milestone complete) -Plan: -- -Status: Milestone v5.0 shipped -Last activity: 2026-03-10 — v5.0 Extraction Insights Overhaul completed and archived +Phase: Not started (defining requirements) +Plan: — +Status: Defining requirements +Last activity: 2026-04-14 — Milestone v6.0 started -Progress: [##########] 100% +Progress: [ ] 0% ## Performance Metrics @@ -64,6 +64,15 @@ Progress: [##########] 100% See PROJECT.md Key Decisions table for full log. +**v6.0-specific direction (locked):** +- Legacy extraction code and data are DEAD — wipe tables, delete files, no migration, no backward compat +- OpenRouter via Vercel AI SDK 6 is the only LLM surface +- Gemini 3 Flash / 2.5 Flash Lite / Haiku 4.5 — NO Grok 4.1 Fast (92.89% JSON validity dealbreaker) +- No chunking, no RAG, no vector DB — 1M-context whole-paper extraction +- Deterministic quoting via `fastest-levenshtein` 85% threshold is the hallucination defense +- Europe PMC + arXiv HTML + Gemini-as-PDF-parser replaces Docling/MinerU/olmOCR (free tier, MVP-appropriate) +- `vitest-evals` + `autoevals` + 20-case golden set is the MVP eval loop — no Langfuse, no Braintrust + ### Pending Todos None. @@ -95,6 +104,6 @@ None. ## Session Continuity -Last activity: 2026-03-10 -- v5.0 milestone completed and archived -Stopped at: Milestone v5.0 completed +Last activity: 2026-04-14 — Milestone v6.0 Extraction MVP Rebuild started +Stopped at: Defining requirements Resume file: None From c2ecb26a3f2bb742739d2e822d4af08ede9b0f93 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:12:35 +0100 Subject: [PATCH 003/421] docs: define milestone v6.0 requirements --- .planning/REQUIREMENTS.md | 244 +++++++++++++++++++++++++++++++++----- 1 file changed, 212 insertions(+), 32 deletions(-) diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md index 48545e573..0baeffda9 100644 --- a/.planning/REQUIREMENTS.md +++ b/.planning/REQUIREMENTS.md @@ -1,53 +1,233 @@ -# Requirements: OpenAlex Count +# Requirements: OpenAlex Count — v6.0 Extraction MVP Rebuild -**Defined:** 2026-03-12 -**Core Value:** Reliable, well-tested academic search and AI extraction +**Defined:** 2026-04-14 +**Core Value:** Reliable, well-tested academic search and AI extraction — every major code path has tests, and every new feature is built test-first. -## v5.1 Requirements +## v6.0 Milestone Context -Requirements for Smart Grouping & PDF-Disabled Cleanup milestone. +Hot-swap the extraction pipeline with a clean, MVP-grade implementation. Delete all legacy extraction code and data. Cheap OpenRouter models, free upstream full-text sources, deterministic citation grounding, zero crash surfaces. No chunking, no RAG, no vector DB. Target cost <$50/month for MVP volume. -### Answer Clustering +**Legacy is DEAD.** Destructive rebuild. No backward compat, no migration, no dual-read fallbacks. -- [ ] **GROUP-01**: After extraction completes, system runs one LLM call per question to cluster unique answers into canonical semantic groups -- [ ] **GROUP-02**: Clustered groups stored in DB and used by frontend instead of static synonym map -- [ ] **GROUP-03**: Existing completed jobs can be re-clustered on demand (backfill) +## v6.0 Requirements -### PDF-Disabled Cleanup +### Teardown -- [ ] **PDF-01**: Papers without abstracts silently excluded when PDF disabled — never inserted into DB -- [ ] **PDF-02**: No confidence cap (0.7) or citation penalty (best_effort) in abstract-only mode when PDF feature disabled -- [ ] **PDF-03**: PDF-specific UI elements (citation status bars, grounded rate, indexed/PDF badges) hidden when feature flag off -- [ ] **PDF-04**: Neutral i18n messages replacing PDF-specific text across all 6 locales -- [ ] **PDF-05**: All PDF cleanup changes verified with passing test suite (1077+ tests) +- [ ] **TEAR-01**: Developer deletes all legacy extraction tables from `convex/schema.ts` (extractionJobs, extractionPapers, extractionQuestions, extractionEvidenceUnits, extractionResults, extractionResultReviews, extractionSavedViews, extractionWorkflowTemplates, extractionReportSnapshots, extractionJobStats, extractionRunDiffs) +- [ ] **TEAR-02**: Developer deletes `convex/extraction/` directory entirely (~9.6K LoC across 30+ files including mutations.ts, queries.ts, workpoolActions.ts, workflow.ts, evidence_units.ts, chunking.ts, guard.ts, prompts.ts, pdfjs_extract.ts, validators.ts, 8 debug_*.ts files, test_*.ts files, uploads.ts, cascade-delete.test.ts, job-stats.test.ts) +- [ ] **TEAR-03**: Developer deletes `lib/extraction/` directory entirely (answer-grouping, card-thresholds, citation-panel, citations, confidence-messages, export, feature-flags, filtering, insights, pdf-highlight, pdfjs-text, question-status, reviews, status-filter-options, types) +- [ ] **TEAR-04**: Developer removes `@convex-dev/rag` component from `convex/convex.config.ts` and uninstalls from `package.json` +- [ ] **TEAR-05**: Developer removes `pdfProcessingPool` and `screeningPool` workpool registrations in favor of new slim workpool setup +- [ ] **TEAR-06**: Developer removes all extraction-related entries from `lib/pdf/download.ts`, keeping only what the new pipeline needs, or deletes the file entirely +- [ ] **TEAR-07**: Developer removes all extraction UI routes, pages, and components from `app/extraction/` and `components/extraction/` +- [ ] **TEAR-08**: Developer removes all extraction-related i18n keys from all 6 locale files (`messages/en.json`, `messages/fr.json`, etc.) +- [ ] **TEAR-09**: Developer removes `uploadedPdfs` Convex file storage entries from legacy extraction flow (no users to migrate) +- [ ] **TEAR-10**: TypeScript compiles (`tsc --noEmit` zero errors) after teardown with only new extraction code referenced — no dangling imports, no dead exports + +### Parsing Waterfall + +- [ ] **PARSE-01**: User's screening job fetches OpenAlex metadata for each paper (DOI, abstract inverted index, `best_oa_location.pdf_url`, `ids.pmcid`, arXiv ID extraction) +- [ ] **PARSE-02**: User's screening job retrieves full body text from Europe PMC `fullTextXML` endpoint when `ids.pmcid` is present, parsing JATS XML via `fast-xml-parser` +- [ ] **PARSE-03**: User's screening job retrieves full body text from arXiv HTML (`arxiv.org/html/{id}`) when an arXiv ID is detected, parsing via `linkedom` +- [ ] **PARSE-04**: User's screening job downloads and parses PDFs via `unpdf` (serverless-bundled PDF.js v5) when an OA PDF URL exists and upstream sources did not resolve +- [ ] **PARSE-05**: User's screening job falls back to Gemini-as-PDF-parser via Vercel AI SDK `filePart` with `media_resolution: 'low'` when `unpdf` returns fewer than 1500 characters or throws +- [ ] **PARSE-06**: User's screening job marks a paper as `abstract_only` when all parsing tiers fail, surfacing the limitation in the UI +- [ ] **PARSE-07**: User sees per-paper parsing source (`pmc` / `arxiv` / `unpdf` / `gemini` / `abstract_only`) on the results card +- [ ] **PARSE-08**: Node.js runtime is pinned to version 22 via `convex.json` so `unpdf` runs without polyfills +- [ ] **PARSE-09**: Each parsing tier has an `AbortSignal.timeout` ceiling (20s fetch, 30s XML parse, 60s unpdf, 120s Gemini) with graceful fallthrough on timeout +- [ ] **PARSE-10**: Parsing pipeline rejects PDFs with more than 200 pages to prevent action-timeout starvation + +### Extraction + +- [ ] **EXTR-01**: User's screening job sends whole-paper text (not chunks) to Gemini 3 Flash via OpenRouter for extraction — no RAG, no vector DB, no Reciprocal Rank Fusion +- [ ] **EXTR-02**: User's extraction call uses a flat 7-field Zod schema: `{answer, confidence, evidence_quote, evidence_source_id, evidence_start_char, evidence_end_char, reasoning}` with `propertyOrdering` forcing `reasoning` before `answer` +- [ ] **EXTR-03**: User's extraction enforces deterministic quoting via Zod `.superRefine()` + `fastest-levenshtein` — rejects any answer whose `evidence_quote` doesn't substring-match the source at ≥0.85 similarity +- [ ] **EXTR-04**: UI always renders the verbatim quote from `source.text.slice(start_char, end_char)` — never the LLM's `evidence_quote` field +- [ ] **EXTR-05**: User's screening job runs a critic pass (same cheap model, T=0) asking "Does this quote appear verbatim and support this answer?" — rejects answers where the critic returns `unsupported` +- [ ] **EXTR-06**: User's screening pipeline uses a three-tier OpenRouter cascade via `@openrouter/ai-sdk-provider` with `plugins: [{id: 'response-healing'}]`: Gemini 2.5 Flash Lite pre-screen → Gemini 3 Flash default → Claude Haiku 4.5 on schema failure or low confidence +- [ ] **EXTR-07**: User's cost per run is minimized via Gemini automatic caching, OpenRouter `provider.order` + `allow_fallbacks`, and `temperature: 0` +- [ ] **EXTR-08**: User sees `insufficient_evidence` as a first-class answer state when retrieval/critic can't support a decision — confidence capped, UI surfaces reason +- [ ] **EXTR-09**: Extraction results include `{answer, confidence: "high"|"medium"|"low", evidence: {quote, source_id, start, end}, reasoning, model_used, critic_verdict, parsing_source}` shape returned to the UI +- [ ] **EXTR-10**: Per-question extraction is parallelized via `Promise.allSettled` with concurrency cap 5 and per-question `AbortSignal.timeout(60000)` — one question's failure does not kill siblings + +### Workflow & Orchestration + +- [ ] **WORK-01**: Developer creates a slim durable workflow via `@convex-dev/workflow` that orchestrates per-paper stages (parse → extract → critic → persist) with one journaled step per stage, not per paper +- [ ] **WORK-02**: Developer registers a single `extractionPool` workpool with conservative `maxParallelism` (3-5) for MVP scale +- [ ] **WORK-03**: Each paper's workpoolId is persisted on the paper row so `cancelExtraction` can iterate and cancel targeted items (no `cancelAll` cross-user blast) +- [ ] **WORK-04**: User can cancel a running job via a button; cancellation stops the workflow, cancels each paper's workpool item, and marks remaining papers as `cancelled` +- [ ] **WORK-05**: Workflow steps classify errors as retryable (network, 5xx, 429, timeout) vs permanent (404, 400, validation) — retryable errors throw so workpool retry fires, permanent errors return `{success: false}` and are not retried +- [ ] **WORK-06**: Workflow enqueues all paper jobs via a single batched mutation (`enqueueAllPapers`) — not 500 sequential journaled steps +- [ ] **WORK-07**: Results save is idempotent — uses the `by_paper_question` index to skip inserts if a result row already exists, preventing `onComplete` double-fire corruption +- [ ] **WORK-08**: All workflow-facing actions early-return when `job.status === "cancelled" | "failed"` — no wasted LLM tokens on cancelled jobs +- [ ] **WORK-09**: Workflow emits real-time progress updates visible to the user via Convex reactive subscriptions (papers processed / failed / remaining) + +### Crash Prevention + +- [ ] **CRASH-01**: User clicking anywhere in the app never crashes the full UI — every route segment has an `error.tsx` boundary (`app/extraction/[jobId]/error.tsx`, `app/results/[searchId]/error.tsx`, `app/settings/error.tsx` at minimum) +- [ ] **CRASH-02**: Every `useQuery` call site in extraction UI handles `undefined` (loading) and `null` (not found) states before destructuring — no bare `const { foo } = useQuery(...)` patterns +- [ ] **CRASH-03**: Clerk authentication sync retries once on browser tab visibility change, recovering from the "came back and app is broken" stranding pattern +- [ ] **CRASH-04**: Every user-facing `useMutation` call-site catches rejections and routes them to a toast, so an uncaught rejection can never bubble to the error boundary +- [ ] **CRASH-05**: Prompt injection via PDF text is blocked via per-request random UUID delimiters around evidence blocks, with the system prompt instructing the model to trust only delimiter-wrapped content +- [ ] **CRASH-06**: Every external `fetch` (OpenRouter, PMC, arXiv, OA PDF hosts) has `AbortSignal.timeout` and is wrapped so a single stuck request cannot lock a Convex action to timeout +- [ ] **CRASH-07**: Zustand persist migration ladder in `lib/store.ts` is collapsed to version 1 so a malformed localStorage payload cannot crash the sidebar tree + +### Evaluation & Quality + +- [ ] **EVAL-01**: Developer maintains a 20-case hand-labeled golden set in `tests/evals/screening-golden.ts` (paper + question + expected answer + expected source span), covering include/exclude/insufficient cases and at least 3 parsing sources (PMC, arXiv, PDF fallback) +- [ ] **EVAL-02**: Developer runs the golden set via `vitest-evals` + `autoevals` with a Factuality scorer and citation-substring-match scorer, gated by `RUN_EVALS=1`, on every PR touching `convex/extraction/**` or `lib/extraction/**` +- [ ] **EVAL-03**: CI blocks merges when recall-on-include drops below 95% or citation-validity-rate drops below 98% on the golden set +- [ ] **EVAL-04**: A Convex cron runs hourly, samples 1 production screening answer, runs the critic pass against it, and writes `{answerId, verdict, judgeModel, timestamp}` to a `qualityChecks` table +- [ ] **EVAL-05**: User can see a 7-day rolling pass-rate dashboard query (`getQualityTrend`) returning `{supported, unsupported, partial}` counts +- [ ] **EVAL-06**: Production samples flagged `unsupported` automatically land in a human-review queue that doubles as the golden-set growth pipeline + +### Observability + +- [ ] **OBS-01**: Every extraction stage emits a single structured `console.info` JSON line with `{traceId, jobId, paperId, stage, model, tokensIn, tokensOut, costUsd, latencyMs, status}` — no ad-hoc `console.log` strings +- [ ] **OBS-02**: `traceId` (ULID) generated in the top-level `startExtraction` mutation is propagated through every workflow step, workpool enqueue context, and LLM call +- [ ] **OBS-03**: Failures are logged via `console.error` with the same JSON shape plus `{errorMessage, errorCategory, retryable}` — grep-friendly for incident triage before Sentry is wired up +- [ ] **OBS-04**: User sees per-job metrics in the UI (papers processed, average latency, estimated cost, errors) fed by a typed Convex query +- [ ] **OBS-05**: Two SLO metrics are tracked and persisted per run: recall-on-include (from golden set) and citation-validity-rate (from Levenshtein verification) + +### UI Polish + +- [ ] **UI-01**: User sees a clean extraction job creation flow with question builder, model tier selector (auto/cheap/accurate), estimated cost preview, and start button +- [ ] **UI-02**: User sees a live job progress view with per-paper status badges (parsing/extracting/done/failed), real-time counters, and a cancel button +- [ ] **UI-03**: User sees results on a per-paper card with the clickable verbatim quote highlighted at the source character range +- [ ] **UI-04**: User can export results as CSV, JSON, or XLSX via the existing download helper (reuse from library export — no new infrastructure) +- [ ] **UI-05**: All new extraction UI strings are seeded in 6 locale files upfront (en, fr, es, de, ar, zh) before component development, per v5.0 discipline +- [ ] **UI-06**: New extraction pages match the Clean/Friendly/Approachable design personality — OKLCH color tokens, Outfit variable font, spring-based Framer Motion, WCAG AAA contrast + +## Future Requirements + +Deferred to later milestones. Tracked but not in current roadmap. + +### Scale Hardening (v6.1+) + +- **SCALE-01**: Hot/cold split of `extractionJobs` table with sharded progress counters to raise `maxParallelism` beyond 5 +- **SCALE-02**: `@convex-dev/rate-limiter` component applied to every user-facing extraction surface with token-bucket per-provider limits +- **SCALE-03**: Per-provider circuit breaker backed by a Convex table, failing fast during OpenRouter / Gemini outages +- **SCALE-04**: Dead-letter table with admin replay UI for papers that exceed retry budget +- **SCALE-05**: Provider failover to Claude / DeepSeek when Gemini is over quota, beyond the cascade already in EXTR-06 + +### Advanced Retrieval (v7+) + +- **RETR-01**: Anthropic Contextual Retrieval on chunk pipeline for 49–67% retrieval recall improvement +- **RETR-02**: Chunk-aware evidence extraction with dense + BM25 hybrid search and reranker for papers exceeding 200k token context +- **RETR-03**: Multi-paper synthesis queries for literature reviews spanning corpora + +### Production Observability (v6.1+) + +- **OBS-FUT-01**: Sentry integration for exception capture in extraction actions +- **OBS-FUT-02**: Langfuse or self-hosted equivalent for LLM trace aggregation via Vercel AI SDK `experimental_telemetry` +- **OBS-FUT-03**: PostHog funnel dashboards for extraction job lifecycle +- **OBS-FUT-04**: Promptfoo CLI integration alongside `vitest-evals` for heavier regression testing + +### Advanced Parsing (v6.1+) + +- **PARSE-FUT-01**: Docling / MinerU / olmOCR Python sidecar for math-heavy and scanned PDFs beyond Gemini's capability +- **PARSE-FUT-02**: GROBID sidecar for bibliographic reference graph extraction +- **PARSE-FUT-03**: Tesseract.js or Gemini-vision OCR fallback integrated into the parsing waterfall ## Out of Scope +Explicitly excluded. Documented to prevent scope creep. + | Feature | Reason | |---------|--------| -| Fuzzy string matching (Levenshtein) | LLM clustering supersedes; string similarity can't link "banking" → "finance" | -| User-driven manual merge/unmerge UI | Deferred to v5.2+; LLM clustering handles 80% case | -| Re-extraction with controlled vocabulary | Requires prompt changes and re-running all jobs; clustering is non-destructive | -| PDF re-enablement testing | PDF is disabled for the foreseeable future | +| Backward compatibility with legacy extraction data | User explicitly said legacy is DEAD — destructive rebuild, no migration | +| Chunking + vector retrieval for MVP scope | 1M-context Flash models + free upstream full-text make chunking unnecessary at MVP scale | +| Docling / MinerU / olmOCR Python sidecars | Premature for MVP — Gemini-as-parser covers 95%+ of papers at ~$0.0005 each | +| Anthropic Contextual Retrieval | Adds ~$1/M tokens and a new chunk preprocessing pipeline — premature for MVP | +| Langfuse / Braintrust / Phoenix / Promptfoo | `vitest-evals` + `autoevals` + 20-case golden set is enough for MVP — add observability services when paying customers exist | +| `@convex-dev/rate-limiter` saturation coverage | Current extraction surfaces are low-traffic — apply only to the new `startExtraction` mutation | +| Circuit breaker component | Single LLM provider (OpenRouter) at MVP — add when there are two providers and failover logic | +| Dead-letter replay UI | A `failed` paper IS the dead-letter at this scale — user retries manually | +| Idempotency holds with provider idempotency-key headers | Credit misbilling happens rarely at MVP scale — handle manually if it fires | +| Sharded progress counters / hot-cold schema split | OCC contention is not observed at `maxParallelism: 3-5` — defer until it fires | +| `@convex-dev/workflow` restart/cleanup machinery | Current workflows run once and complete — restart matters for multi-day workflows | +| Grok 4.1 Fast in the hot path | 92.89% baseline JSON validity → 5% schema-break rate is a dealbreaker for `Output.object` under strict Zod schemas | +| Two-stage workpool chain with onComplete handoff | New pipeline uses a single-stage workflow step per paper — simpler, fewer race conditions | +| Legacy `pdfjs-dist/legacy/build/pdf.mjs` | Replaced by `unpdf` (serverless-bundled PDF.js v5) | +| OpenAlex `/ngrams` endpoint or body-text fields | Endpoint retired by OpenAlex, no body text returned — metadata-only usage | +| Prompt versioning service | Prompts live in TypeScript consts in-repo — sufficient for MVP | +| Multi-tenant fairness / per-user pool isolation | Single shared pool is fine until user base grows | ## Traceability +Which phases cover which requirements. Updated during roadmap creation. + | Requirement | Phase | Status | |-------------|-------|--------| -| GROUP-01 | TBD | Pending | -| GROUP-02 | TBD | Pending | -| GROUP-03 | TBD | Pending | -| PDF-01 | TBD | Complete (implemented) | -| PDF-02 | TBD | Complete (implemented) | -| PDF-03 | TBD | Complete (implemented) | -| PDF-04 | TBD | Complete (implemented) | -| PDF-05 | TBD | Pending (needs deploy verification) | +| TEAR-01 | TBD | Pending | +| TEAR-02 | TBD | Pending | +| TEAR-03 | TBD | Pending | +| TEAR-04 | TBD | Pending | +| TEAR-05 | TBD | Pending | +| TEAR-06 | TBD | Pending | +| TEAR-07 | TBD | Pending | +| TEAR-08 | TBD | Pending | +| TEAR-09 | TBD | Pending | +| TEAR-10 | TBD | Pending | +| PARSE-01 | TBD | Pending | +| PARSE-02 | TBD | Pending | +| PARSE-03 | TBD | Pending | +| PARSE-04 | TBD | Pending | +| PARSE-05 | TBD | Pending | +| PARSE-06 | TBD | Pending | +| PARSE-07 | TBD | Pending | +| PARSE-08 | TBD | Pending | +| PARSE-09 | TBD | Pending | +| PARSE-10 | TBD | Pending | +| EXTR-01 | TBD | Pending | +| EXTR-02 | TBD | Pending | +| EXTR-03 | TBD | Pending | +| EXTR-04 | TBD | Pending | +| EXTR-05 | TBD | Pending | +| EXTR-06 | TBD | Pending | +| EXTR-07 | TBD | Pending | +| EXTR-08 | TBD | Pending | +| EXTR-09 | TBD | Pending | +| EXTR-10 | TBD | Pending | +| WORK-01 | TBD | Pending | +| WORK-02 | TBD | Pending | +| WORK-03 | TBD | Pending | +| WORK-04 | TBD | Pending | +| WORK-05 | TBD | Pending | +| WORK-06 | TBD | Pending | +| WORK-07 | TBD | Pending | +| WORK-08 | TBD | Pending | +| WORK-09 | TBD | Pending | +| CRASH-01 | TBD | Pending | +| CRASH-02 | TBD | Pending | +| CRASH-03 | TBD | Pending | +| CRASH-04 | TBD | Pending | +| CRASH-05 | TBD | Pending | +| CRASH-06 | TBD | Pending | +| CRASH-07 | TBD | Pending | +| EVAL-01 | TBD | Pending | +| EVAL-02 | TBD | Pending | +| EVAL-03 | TBD | Pending | +| EVAL-04 | TBD | Pending | +| EVAL-05 | TBD | Pending | +| EVAL-06 | TBD | Pending | +| OBS-01 | TBD | Pending | +| OBS-02 | TBD | Pending | +| OBS-03 | TBD | Pending | +| OBS-04 | TBD | Pending | +| OBS-05 | TBD | Pending | +| UI-01 | TBD | Pending | +| UI-02 | TBD | Pending | +| UI-03 | TBD | Pending | +| UI-04 | TBD | Pending | +| UI-05 | TBD | Pending | +| UI-06 | TBD | Pending | **Coverage:** -- v5.1 requirements: 8 total -- Mapped to phases: 0 (pending roadmap) -- Unmapped: 8 +- v6.0 requirements: 59 total +- Mapped to phases: 0 (populated by roadmapper) +- Unmapped: 59 ⚠️ --- -*Requirements defined: 2026-03-12* -*Last updated: 2026-03-12 after milestone v5.1 definition* +*Requirements defined: 2026-04-14* +*Last updated: 2026-04-14 after v6.0 milestone initial definition* From ebaaedb8bdd24293a6ec598ca3febdbacdebe092 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:21:11 +0100 Subject: [PATCH 004/421] docs: create milestone v6.0 roadmap (10 phases) --- .planning/REQUIREMENTS.md | 146 ++++++++++++++++++++----------------- .planning/ROADMAP.md | 150 ++++++++++++++++++++++++++++++++++++++ .planning/STATE.md | 26 ++++--- 3 files changed, 244 insertions(+), 78 deletions(-) diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md index 0baeffda9..5d4bad84d 100644 --- a/.planning/REQUIREMENTS.md +++ b/.planning/REQUIREMENTS.md @@ -159,75 +159,87 @@ Which phases cover which requirements. Updated during roadmap creation. | Requirement | Phase | Status | |-------------|-------|--------| -| TEAR-01 | TBD | Pending | -| TEAR-02 | TBD | Pending | -| TEAR-03 | TBD | Pending | -| TEAR-04 | TBD | Pending | -| TEAR-05 | TBD | Pending | -| TEAR-06 | TBD | Pending | -| TEAR-07 | TBD | Pending | -| TEAR-08 | TBD | Pending | -| TEAR-09 | TBD | Pending | -| TEAR-10 | TBD | Pending | -| PARSE-01 | TBD | Pending | -| PARSE-02 | TBD | Pending | -| PARSE-03 | TBD | Pending | -| PARSE-04 | TBD | Pending | -| PARSE-05 | TBD | Pending | -| PARSE-06 | TBD | Pending | -| PARSE-07 | TBD | Pending | -| PARSE-08 | TBD | Pending | -| PARSE-09 | TBD | Pending | -| PARSE-10 | TBD | Pending | -| EXTR-01 | TBD | Pending | -| EXTR-02 | TBD | Pending | -| EXTR-03 | TBD | Pending | -| EXTR-04 | TBD | Pending | -| EXTR-05 | TBD | Pending | -| EXTR-06 | TBD | Pending | -| EXTR-07 | TBD | Pending | -| EXTR-08 | TBD | Pending | -| EXTR-09 | TBD | Pending | -| EXTR-10 | TBD | Pending | -| WORK-01 | TBD | Pending | -| WORK-02 | TBD | Pending | -| WORK-03 | TBD | Pending | -| WORK-04 | TBD | Pending | -| WORK-05 | TBD | Pending | -| WORK-06 | TBD | Pending | -| WORK-07 | TBD | Pending | -| WORK-08 | TBD | Pending | -| WORK-09 | TBD | Pending | -| CRASH-01 | TBD | Pending | -| CRASH-02 | TBD | Pending | -| CRASH-03 | TBD | Pending | -| CRASH-04 | TBD | Pending | -| CRASH-05 | TBD | Pending | -| CRASH-06 | TBD | Pending | -| CRASH-07 | TBD | Pending | -| EVAL-01 | TBD | Pending | -| EVAL-02 | TBD | Pending | -| EVAL-03 | TBD | Pending | -| EVAL-04 | TBD | Pending | -| EVAL-05 | TBD | Pending | -| EVAL-06 | TBD | Pending | -| OBS-01 | TBD | Pending | -| OBS-02 | TBD | Pending | -| OBS-03 | TBD | Pending | -| OBS-04 | TBD | Pending | -| OBS-05 | TBD | Pending | -| UI-01 | TBD | Pending | -| UI-02 | TBD | Pending | -| UI-03 | TBD | Pending | -| UI-04 | TBD | Pending | -| UI-05 | TBD | Pending | -| UI-06 | TBD | Pending | +| TEAR-01 | Phase 88 | Pending | +| TEAR-02 | Phase 88 | Pending | +| TEAR-03 | Phase 88 | Pending | +| TEAR-04 | Phase 88 | Pending | +| TEAR-05 | Phase 88 | Pending | +| TEAR-06 | Phase 88 | Pending | +| TEAR-07 | Phase 88 | Pending | +| TEAR-08 | Phase 88 | Pending | +| TEAR-09 | Phase 88 | Pending | +| TEAR-10 | Phase 88 | Pending | +| PARSE-01 | Phase 90 | Pending | +| PARSE-02 | Phase 90 | Pending | +| PARSE-03 | Phase 90 | Pending | +| PARSE-04 | Phase 90 | Pending | +| PARSE-05 | Phase 90 | Pending | +| PARSE-06 | Phase 90 | Pending | +| PARSE-07 | Phase 90 | Pending | +| PARSE-08 | Phase 90 | Pending | +| PARSE-09 | Phase 90 | Pending | +| PARSE-10 | Phase 90 | Pending | +| EXTR-01 | Phase 91 | Pending | +| EXTR-02 | Phase 91 | Pending | +| EXTR-03 | Phase 92 | Pending | +| EXTR-04 | Phase 92 | Pending | +| EXTR-05 | Phase 92 | Pending | +| EXTR-06 | Phase 91 | Pending | +| EXTR-07 | Phase 91 | Pending | +| EXTR-08 | Phase 92 | Pending | +| EXTR-09 | Phase 91 | Pending | +| EXTR-10 | Phase 91 | Pending | +| WORK-01 | Phase 89 | Pending | +| WORK-02 | Phase 89 | Pending | +| WORK-03 | Phase 93 | Pending | +| WORK-04 | Phase 93 | Pending | +| WORK-05 | Phase 93 | Pending | +| WORK-06 | Phase 89 | Pending | +| WORK-07 | Phase 89 | Pending | +| WORK-08 | Phase 93 | Pending | +| WORK-09 | Phase 93 | Pending | +| CRASH-01 | Phase 94 | Pending | +| CRASH-02 | Phase 94 | Pending | +| CRASH-03 | Phase 94 | Pending | +| CRASH-04 | Phase 94 | Pending | +| CRASH-05 | Phase 94 | Pending | +| CRASH-06 | Phase 94 | Pending | +| CRASH-07 | Phase 94 | Pending | +| EVAL-01 | Phase 96 | Pending | +| EVAL-02 | Phase 96 | Pending | +| EVAL-03 | Phase 96 | Pending | +| EVAL-04 | Phase 96 | Pending | +| EVAL-05 | Phase 96 | Pending | +| EVAL-06 | Phase 96 | Pending | +| OBS-01 | Phase 95 | Pending | +| OBS-02 | Phase 95 | Pending | +| OBS-03 | Phase 95 | Pending | +| OBS-04 | Phase 95 | Pending | +| OBS-05 | Phase 95 | Pending | +| UI-01 | Phase 97 | Pending | +| UI-02 | Phase 97 | Pending | +| UI-03 | Phase 97 | Pending | +| UI-04 | Phase 97 | Pending | +| UI-05 | Phase 97 | Pending | +| UI-06 | Phase 97 | Pending | **Coverage:** -- v6.0 requirements: 59 total -- Mapped to phases: 0 (populated by roadmapper) -- Unmapped: 59 ⚠️ +- v6.0 requirements: 63 total (10 TEAR + 10 PARSE + 10 EXTR + 9 WORK + 7 CRASH + 6 EVAL + 5 OBS + 6 UI) +- Mapped to phases: 63 ✓ +- Unmapped: 0 ✓ + +**Phase distribution:** +- Phase 88 (Teardown): 10 requirements +- Phase 89 (Core Schema & Workflow Skeleton): 4 requirements +- Phase 90 (Parsing Waterfall): 10 requirements +- Phase 91 (Extraction Cascade Core): 6 requirements +- Phase 92 (Deterministic Citation Grounding): 4 requirements +- Phase 93 (Workflow Cancel, Retry, Progress): 5 requirements +- Phase 94 (Crash Prevention): 7 requirements +- Phase 95 (Observability & SLO Metrics): 5 requirements +- Phase 96 (Eval Loop & Quality Sampling): 6 requirements +- Phase 97 (UI Polish): 6 requirements --- *Requirements defined: 2026-04-14* -*Last updated: 2026-04-14 after v6.0 milestone initial definition* +*Last updated: 2026-04-14 after v6.0 roadmap created (63 requirements mapped across phases 88-97)* diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md index da82ed730..01f4ccceb 100644 --- a/.planning/ROADMAP.md +++ b/.planning/ROADMAP.md @@ -17,6 +17,7 @@ - v4.0 Bulk Screening & Auto-Rating -- Phases 75-78 (shipped 2026-03-09) - v4.1 Screening Export -- Phases 79-82 (shipped 2026-03-09) - v5.0 Extraction Insights Overhaul -- Phases 83-87 (shipped 2026-03-10) +- v6.0 Extraction MVP Rebuild -- Phases 88-97 (in progress) ## Phases @@ -227,8 +228,147 @@ Full details: `.planning/milestones/v5.0-ROADMAP.md` +### v6.0 Extraction MVP Rebuild (In Progress) + +**Milestone Goal:** Hot-swap the extraction pipeline with a clean, MVP-grade implementation — cheap OpenRouter models, free upstream full-text sources, deterministic citation grounding, and zero crash surfaces. Delete all legacy extraction code, tables, and data. + +- [ ] **Phase 88: Scorched-Earth Teardown** - Delete all legacy extraction code, tables, UI, and RAG component so nothing dangles after +- [ ] **Phase 89: Core Schema & Workflow Skeleton** - Stand up the new slim schema, durable workflow, and batched enqueue so downstream phases have rails to build on +- [ ] **Phase 90: Free-First Parsing Waterfall** - Resolve full-text via OpenAlex metadata, Europe PMC, arXiv HTML, unpdf, and Gemini-as-PDF-parser with abort-signal ceilings and a 200-page cap +- [ ] **Phase 91: Extraction Cascade Core** - Send whole-paper text to the three-tier OpenRouter cascade with flat 7-field Zod schema, Gemini caching, and per-question parallelism +- [ ] **Phase 92: Deterministic Citation Grounding** - Enforce substring-match quoting, critic pass, insufficient_evidence state, and UI-rendered verbatim quotes +- [ ] **Phase 93: Workflow Cancel, Retry, and Progress** - Targeted cancel, retryable/permanent error taxonomy, early-return on cancelled jobs, and reactive progress updates +- [ ] **Phase 94: Crash Prevention Sweep** - Segment error boundaries, useQuery null handling, Clerk visibility retry, mutation rejection routing, prompt-injection delimiters, fetch timeouts, and Zustand persist reset +- [ ] **Phase 95: Structured Observability & SLO Metrics** - ULID traceId propagation, structured JSON logging, per-job UI metrics, and recall/citation-validity SLO persistence +- [ ] **Phase 96: Eval Loop & Quality Sampling** - 20-case golden set, vitest-evals gating, hourly production sampling cron, and human-review queue +- [ ] **Phase 97: Extraction UI Polish** - Job creation flow, live progress with cancel, verbatim quote rendering, export reuse, 6-locale seed, and brand-aligned design + +## Phase Details + +### Phase 88: Scorched-Earth Teardown +**Goal**: Delete all legacy extraction code, schema tables, UI surfaces, and the RAG component so the repo compiles cleanly against an empty extraction namespace — the destructive foundation every downstream phase builds on. +**Depends on**: Nothing (milestone start) +**Requirements**: TEAR-01, TEAR-02, TEAR-03, TEAR-04, TEAR-05, TEAR-06, TEAR-07, TEAR-08, TEAR-09, TEAR-10 +**Success Criteria** (what must be TRUE): + 1. `convex/extraction/` and `lib/extraction/` directories no longer exist on disk + 2. `convex/schema.ts` contains zero legacy extraction tables (extractionJobs, extractionPapers, extractionQuestions, extractionEvidenceUnits, extractionResults, extractionResultReviews, extractionSavedViews, extractionWorkflowTemplates, extractionReportSnapshots, extractionJobStats, extractionRunDiffs) + 3. `@convex-dev/rag` is absent from `convex/convex.config.ts` and uninstalled from `package.json` + 4. `tsc --noEmit` returns zero errors with no dangling imports or dead exports referencing deleted modules + 5. All six locale files (`messages/{en,fr,es,de,ar,zh}.json`) contain zero `extraction.*` keys left over from the legacy UI +**Plans**: TBD + +### Phase 89: Core Schema & Workflow Skeleton +**Goal**: Define the new slim extraction schema (job, paper, question, result tables with `by_paper_question` unique index), register the single `extractionPool` workpool, and stand up a durable `@convex-dev/workflow` whose stages enqueue all papers in one batched mutation and save results idempotently — the rails downstream phases run on. +**Depends on**: Phase 88 +**Requirements**: WORK-01, WORK-02, WORK-06, WORK-07 +**Success Criteria** (what must be TRUE): + 1. Starting a new extraction job creates exactly one workflow run with per-stage journaled steps (parse → extract → critic → persist), not per-paper journaled steps + 2. `extractionPool` workpool is registered with `maxParallelism` between 3 and 5 and is the only extraction-related pool in `convex.config.ts` + 3. Enqueueing 200 papers fires exactly one batched `enqueueAllPapers` mutation, verified by a test asserting a single Convex write + 4. Persisting the same `(paperId, questionId)` twice is a no-op — a convex-test asserts only one row exists after a double-save, backed by the `by_paper_question` index +**Plans**: TBD + +### Phase 90: Free-First Parsing Waterfall +**Goal**: Given a paper with an OpenAlex record, retrieve body text through the cheapest upstream source possible — PMC JATS → arXiv HTML → unpdf → Gemini-as-PDF-parser → abstract-only — with hard abort-signal ceilings, a 200-page cap, and a per-paper `parsing_source` tag surfaced to the UI. +**Depends on**: Phase 89 +**Requirements**: PARSE-01, PARSE-02, PARSE-03, PARSE-04, PARSE-05, PARSE-06, PARSE-07, PARSE-08, PARSE-09, PARSE-10 +**Success Criteria** (what must be TRUE): + 1. A paper with `ids.pmcid` resolves to full body text via Europe PMC `fullTextXML` parsed by `fast-xml-parser`, verified by a fixture-backed test + 2. A paper with an arXiv ID resolves to full body text via `arxiv.org/html/{id}` parsed by `linkedom`, verified by a fixture-backed test + 3. A paper with only `best_oa_location.pdf_url` resolves via `unpdf`, and on <1500 chars or throw falls through to Gemini `filePart` with `media_resolution: 'low'` + 4. `convex.json` pins Node.js runtime to version 22 so `unpdf` runs without polyfills, verified in the committed config file + 5. A PDF with more than 200 pages is rejected before parsing and every tier has a matching `AbortSignal.timeout` (20s fetch / 30s XML / 60s unpdf / 120s Gemini) — a timeout test for each tier passes + 6. Each paper row records `parsing_source` as one of `pmc`/`arxiv`/`unpdf`/`gemini`/`abstract_only` and the result card renders it verbatim +**Plans**: TBD + +### Phase 91: Extraction Cascade Core +**Goal**: Given parsed source text, send the whole paper (no chunking, no RAG, no vector DB) through the three-tier OpenRouter cascade — Gemini 2.5 Flash Lite pre-screen → Gemini 3 Flash default → Claude Haiku 4.5 escalation — using a flat 7-field Zod schema with `propertyOrdering` forcing `reasoning` before `answer`, parallelized per-question with concurrency cap 5, and returning the documented result shape to the UI. +**Depends on**: Phase 90 +**Requirements**: EXTR-01, EXTR-02, EXTR-06, EXTR-07, EXTR-09, EXTR-10 +**Success Criteria** (what must be TRUE): + 1. An extraction call sends the full parsed source text (no slicing, no embedding, no retrieval) and the committed schema file defines a single 7-field Zod object with `propertyOrdering` enforcing `reasoning` before `answer` + 2. The cascade escalates from Gemini 2.5 Flash Lite → Gemini 3 Flash → Claude Haiku 4.5 through `@openrouter/ai-sdk-provider` with `plugins: [{id: 'response-healing'}]`, verified by a mocked-provider test + 3. OpenRouter calls pin `temperature: 0`, set `provider.order` with `allow_fallbacks`, and rely on Gemini automatic caching — verified by inspecting the built request payload in tests + 4. 10 questions on one paper run via `Promise.allSettled` with concurrency cap 5 and per-question `AbortSignal.timeout(60000)`, and a failure in one question does not abort the other nine — verified by a test + 5. Returned results match `{answer, confidence: "high"|"medium"|"low", evidence: {quote, source_id, start, end}, reasoning, model_used, critic_verdict, parsing_source}` shape, enforced by the Convex result validator +**Plans**: TBD + +### Phase 92: Deterministic Citation Grounding +**Goal**: Prevent hallucinated quotes and false-positive answers by rejecting any extraction whose `evidence_quote` fails 85% Levenshtein similarity against the source span, running a critic pass that must return `supported`, emitting `insufficient_evidence` as a first-class answer, and rendering only the verbatim `source.text.slice(start, end)` in the UI. +**Depends on**: Phase 91 +**Requirements**: EXTR-03, EXTR-04, EXTR-05, EXTR-08 +**Success Criteria** (what must be TRUE): + 1. An extraction whose `evidence_quote` is <85% Levenshtein-similar to the source substring is rejected at the Zod `.superRefine()` boundary — verified by a unit test with a fabricated quote + 2. A critic-pass prompt runs at `T=0` with the same cheap model and any `unsupported` verdict flips the result to `insufficient_evidence` — verified by a mocked-critic test + 3. The extraction result UI renders `source.text.slice(evidence_start_char, evidence_end_char)` and never the model's `evidence_quote` field — verified by a component test asserting the rendered string + 4. `insufficient_evidence` is a first-class answer state with confidence capped and a UI reason line rendered on the result card +**Plans**: TBD + +### Phase 93: Workflow Cancel, Retry, and Progress +**Goal**: Make a running extraction job fully controllable: persist each paper's `workpoolId` for targeted cancel (no `cancelAll` blast radius), classify errors as retryable vs permanent so workpool retry fires only on transient failures, early-return cancelled/failed jobs to save LLM spend, and emit real-time progress through Convex reactive queries. +**Depends on**: Phase 92 +**Requirements**: WORK-03, WORK-04, WORK-05, WORK-08, WORK-09 +**Success Criteria** (what must be TRUE): + 1. Cancelling a running job from the UI iterates persisted `workpoolId` values on paper rows, cancels each targeted item, and marks remaining papers as `cancelled` — verified by an integration test + 2. Network/5xx/429/timeout errors are thrown so workpool retry fires, while 404/400/validation errors return `{success: false}` and are not retried — verified by a classification test + 3. Any workflow-facing action early-returns when `job.status === "cancelled" | "failed"` with zero LLM tokens consumed — verified by a test that asserts the LLM mock is never called for a cancelled job + 4. Reactive Convex subscriptions stream `{processed, failed, remaining}` counters to the UI in under a second on paper completion — verified in the live progress E2E +**Plans**: TBD + +### Phase 94: Crash Prevention Sweep +**Goal**: Eliminate every crash surface that can drop a user out of the app — route-segment error boundaries, defensive `useQuery` null/undefined handling, Clerk visibility-change retry, mutation rejection routed to toasts, UUID-delimited prompt injection fence, universal `AbortSignal.timeout` on external fetches, and a Zustand persist migration reset. +**Depends on**: Phase 93 +**Requirements**: CRASH-01, CRASH-02, CRASH-03, CRASH-04, CRASH-05, CRASH-06, CRASH-07 +**Success Criteria** (what must be TRUE): + 1. Every extraction/results/settings route segment has an `error.tsx` that renders a recovery UI instead of the Next.js crash screen — verified by an E2E that throws inside each segment + 2. Every `useQuery` call site in extraction UI handles both `undefined` (loading) and `null` (not found) before destructuring — verified by a grep-backed lint rule or test + 3. Every user-facing `useMutation` call-site catches rejections and routes them to a toast, so an uncaught rejection cannot bubble to the error boundary — verified by an integration test + 4. PDF body text is wrapped in per-request UUID delimiters and the system prompt instructs the model to trust only delimiter-wrapped content — verified by a prompt snapshot test + 5. Every external `fetch` (OpenRouter, PMC, arXiv, OA PDF hosts) has `AbortSignal.timeout` and a Zustand persist migration ladder collapsed to version 1 — verified by a grep test and a store migration test +**Plans**: TBD + +### Phase 95: Structured Observability & SLO Metrics +**Goal**: Give future-us grep-friendly incident triage without a paid observability vendor — every extraction stage emits one structured `console.info` JSON line with ULID `traceId`, failures log with `{errorMessage, errorCategory, retryable}`, the UI shows per-job metrics, and two SLO metrics (recall-on-include, citation-validity-rate) are persisted per run. +**Depends on**: Phase 94 +**Requirements**: OBS-01, OBS-02, OBS-03, OBS-04, OBS-05 +**Success Criteria** (what must be TRUE): + 1. Every extraction stage emits exactly one structured `console.info` JSON line with `{traceId, jobId, paperId, stage, model, tokensIn, tokensOut, costUsd, latencyMs, status}` — verified by a log-capture test + 2. A ULID `traceId` generated in `startExtraction` propagates through every workflow step, workpool context, and LLM call — verified by a test asserting identical `traceId` across stages + 3. Failures log via `console.error` with the same JSON shape plus `{errorMessage, errorCategory, retryable}` — verified by a failure-path test + 4. The UI shows per-job papers-processed, average latency, estimated cost, and error counts fed by a typed Convex query (not `v.any()`) + 5. Each run persists `recall-on-include` and `citation-validity-rate` SLO metrics queryable via a typed Convex query +**Plans**: TBD + +### Phase 96: Eval Loop & Quality Sampling +**Goal**: Prevent model regressions and surface production quality drift by maintaining a 20-case hand-labeled golden set, running `vitest-evals` + `autoevals` with CI gating at 95% recall / 98% citation validity, and sampling one production answer per hour into a human-review queue that doubles as the golden-set growth pipeline. +**Depends on**: Phase 95 +**Requirements**: EVAL-01, EVAL-02, EVAL-03, EVAL-04, EVAL-05, EVAL-06 +**Success Criteria** (what must be TRUE): + 1. `tests/evals/screening-golden.ts` contains a 20-case hand-labeled golden set with include/exclude/insufficient cases spanning at least PMC, arXiv, and PDF-fallback parsing sources + 2. `RUN_EVALS=1 pnpm test` runs the golden set via `vitest-evals` + `autoevals` with Factuality and citation-substring-match scorers, and a CI job executes it on every PR touching `convex/extraction/**` or `lib/extraction/**` + 3. CI blocks merges when recall-on-include drops below 95% or citation-validity-rate drops below 98% on the golden set — verified by a deliberately-failing canary branch + 4. An hourly Convex cron samples 1 production answer, runs the critic, and writes `{answerId, verdict, judgeModel, timestamp}` to a `qualityChecks` table + 5. A `getQualityTrend` query returns 7-day rolling `{supported, unsupported, partial}` counts and flagged `unsupported` samples land in a human-review queue table that doubles as the golden-set growth pipeline +**Plans**: TBD + +### Phase 97: Extraction UI Polish +**Goal**: Ship the user-facing extraction experience on top of the stabilized backend — clean job creation flow, live progress with per-paper badges and cancel, results cards with clickable verbatim quote highlight, CSV/JSON/XLSX export reusing the library download helper, 6-locale i18n seeded upfront, and brand-aligned Clean/Friendly/Approachable design (OKLCH, Outfit, Framer Motion, WCAG AAA). +**Depends on**: Phase 96 +**Requirements**: UI-01, UI-02, UI-03, UI-04, UI-05, UI-06 +**Success Criteria** (what must be TRUE): + 1. User can create an extraction job via a question builder, model tier selector (auto/cheap/accurate), estimated cost preview, and start button — verified by an E2E flow + 2. User sees a live job view with per-paper status badges (parsing/extracting/done/failed), real-time counters, and a working cancel button — verified by an E2E flow + 3. User sees results on a per-paper card with the clickable verbatim quote highlighted at the source character range — verified by a component test + 4. User exports results as CSV, JSON, or XLSX via the existing library download helper with no new export infrastructure — verified by a reuse test + 5. All extraction UI strings land in all six locale files (en, fr, es, de, ar, zh) BEFORE component development and pages use OKLCH color tokens, Outfit variable font, spring-based Framer Motion, and WCAG AAA contrast +**Plans**: TBD +**UI hint**: yes + ## Progress +**Execution Order:** +Phases execute in numeric order: 88 → 89 → 90 → 91 → 92 → 93 → 94 → 95 → 96 → 97 + | Phase | Milestone | Plans Complete | Status | Completed | |-------|-----------|----------------|--------|-----------| | 1-3 | v1.0 | 7/7 | Complete | 2026-02-27 | @@ -246,3 +386,13 @@ Full details: `.planning/milestones/v5.0-ROADMAP.md` | 75-78 | v4.0 | 9/9 | Complete | 2026-03-09 | | 79-82 | v4.1 | 5/5 | Complete | 2026-03-09 | | 83-87 | v5.0 | 14/14 | Complete | 2026-03-10 | +| 88. Scorched-Earth Teardown | v6.0 | 0/TBD | Not started | - | +| 89. Core Schema & Workflow Skeleton | v6.0 | 0/TBD | Not started | - | +| 90. Free-First Parsing Waterfall | v6.0 | 0/TBD | Not started | - | +| 91. Extraction Cascade Core | v6.0 | 0/TBD | Not started | - | +| 92. Deterministic Citation Grounding | v6.0 | 0/TBD | Not started | - | +| 93. Workflow Cancel, Retry, and Progress | v6.0 | 0/TBD | Not started | - | +| 94. Crash Prevention Sweep | v6.0 | 0/TBD | Not started | - | +| 95. Structured Observability & SLO Metrics | v6.0 | 0/TBD | Not started | - | +| 96. Eval Loop & Quality Sampling | v6.0 | 0/TBD | Not started | - | +| 97. Extraction UI Polish | v6.0 | 0/TBD | Not started | - | diff --git a/.planning/STATE.md b/.planning/STATE.md index 85adf5b42..2a12d3968 100644 --- a/.planning/STATE.md +++ b/.planning/STATE.md @@ -3,11 +3,11 @@ gsd_state_version: 1.0 milestone: v6.0 milestone_name: Extraction MVP Rebuild status: active -stopped_at: Defining requirements +stopped_at: Roadmap approved, ready to plan Phase 88 last_updated: "2026-04-14T00:00:00.000Z" -last_activity: 2026-04-14 — Milestone v6.0 started +last_activity: 2026-04-14 — Roadmap created for v6.0 (10 phases, 63 requirements mapped) progress: - total_phases: 0 + total_phases: 10 completed_phases: 0 total_plans: 0 completed_plans: 0 @@ -21,14 +21,14 @@ progress: See: .planning/PROJECT.md (updated 2026-04-14) **Core value:** Reliable, well-tested academic search and AI extraction -**Current focus:** v6.0 Extraction MVP Rebuild — hot-swap the extraction pipeline with a clean, MVP-grade implementation +**Current focus:** v6.0 Extraction MVP Rebuild — Phase 88 Scorched-Earth Teardown ## Current Position -Phase: Not started (defining requirements) -Plan: — -Status: Defining requirements -Last activity: 2026-04-14 — Milestone v6.0 started +Phase: 88 of 97 (Scorched-Earth Teardown) +Plan: — (not yet planned) +Status: Ready to plan +Last activity: 2026-04-14 — Roadmap created, 63 v6.0 requirements mapped across 10 phases Progress: [ ] 0% @@ -72,6 +72,10 @@ See PROJECT.md Key Decisions table for full log. - Deterministic quoting via `fastest-levenshtein` 85% threshold is the hallucination defense - Europe PMC + arXiv HTML + Gemini-as-PDF-parser replaces Docling/MinerU/olmOCR (free tier, MVP-appropriate) - `vitest-evals` + `autoevals` + 20-case golden set is the MVP eval loop — no Langfuse, no Braintrust +- Target cost <$50/month total for MVP volume +- Phase 88 MUST be first (teardown) — all subsequent phases depend on a clean slate +- Parsing (Phase 90) must land before extraction (Phase 91) — extraction reads parsed text +- UI polish (Phase 97) is last — built against stable backend ### Pending Todos @@ -79,7 +83,7 @@ None. ### Roadmap Evolution -None yet. +2026-04-14 — v6.0 roadmap created with 10 phases (88-97) mapping all 63 v6.0 requirements. ### Blockers/Concerns @@ -104,6 +108,6 @@ None. ## Session Continuity -Last activity: 2026-04-14 — Milestone v6.0 Extraction MVP Rebuild started -Stopped at: Defining requirements +Last activity: 2026-04-14 — v6.0 roadmap created (10 phases, 63 requirements mapped) +Stopped at: Roadmap approved, ready to plan Phase 88 (Scorched-Earth Teardown) Resume file: None From ac5542559cab81698e1765bd1464f0a4b0b3a493 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:25:03 +0100 Subject: [PATCH 005/421] docs(88): capture phase context --- .../88-scorched-earth-teardown/88-CONTEXT.md | 116 ++++++++++++++++++ .../88-DISCUSSION-LOG.md | 73 +++++++++++ 2 files changed, 189 insertions(+) create mode 100644 .planning/phases/88-scorched-earth-teardown/88-CONTEXT.md create mode 100644 .planning/phases/88-scorched-earth-teardown/88-DISCUSSION-LOG.md diff --git a/.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md b/.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md new file mode 100644 index 000000000..e5de21043 --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md @@ -0,0 +1,116 @@ +# Phase 88: Scorched-Earth Teardown - Context + +**Gathered:** 2026-04-14 +**Status:** Ready for planning + + +## Phase Boundary + +Delete all legacy extraction code, schema tables, UI surfaces, i18n keys, and the RAG component so the repo compiles cleanly against an empty extraction namespace. This is purely destructive — no new code is written, no migration logic, no backward compat. The only "new" work is fixing dangling imports and dead exports that surface after deletion. + + + + +## Implementation Decisions + +### Deletion Order +- **D-01:** Schema-last approach — remove consumers before providers to avoid intermediate tsc breaks. Order: UI routes/pages → components → lib helpers → convex functions → schema tables → convex.config.ts component removal → package.json uninstalls. +- **D-02:** Each deletion layer should compile cleanly before moving to the next. Plan should be structured as sequential layers, not one monolithic delete. + +### Screening Pipeline Boundaries +- **D-03:** Remove ONLY `pdfProcessingPool` from `convex/workpool.ts`. Keep `screeningPool` intact — it powers the working v4.0 bulk screening feature and is NOT part of the legacy extraction pipeline. +- **D-04:** TEAR-05's "remove pdfProcessingPool and screeningPool workpool registrations in favor of new slim workpool setup" should be interpreted as: `pdfProcessingPool` is the legacy extraction pool being replaced by the new `extractionPool` (Phase 89). `screeningPool` serves screening (v4.0), not extraction — preserve it. If TEAR-05 truly intends to remove screeningPool, that should be deferred to Phase 89 when the new extractionPool is registered as a replacement. +- **D-05:** All `convex/screening/` code stays untouched. Only `convex/extraction/` is deleted. + +### Shared Dependencies +- **D-06:** Surgical removal of extraction-only content from shared files. Delete extraction-only files wholesale. Strip extraction imports/exports from shared files. Leave non-extraction functionality intact. +- **D-07:** `lib/store.ts` — remove the extraction store slice and any extraction-related types/actions. Keep all other slices (search, history, UI, focus, keywords, AI config, sidebar). +- **D-08:** `lib/types/extraction.types.ts` — delete entirely (extraction types are gone). +- **D-09:** `lib/types/index.ts` — remove extraction re-exports, keep all others. +- **D-10:** `lib/pdf/download.ts` — evaluate at deletion time. If it serves ONLY extraction, delete. If shared with screening or other features, strip extraction-only helpers and keep the rest. +- **D-11:** `convex/crons.ts` — remove any extraction-related scheduled jobs. Keep screening, maintenance, billing, and env validation crons. +- **D-12:** `convex/http.ts` — remove any extraction-related HTTP routes. Keep webhook, wallet, and other routes. + +### Test Cleanup Scope +- **D-13:** Delete `tests/extraction/` directory entirely. +- **D-14:** Delete extraction-specific test files at any location: cascade-delete tests for extraction, job-stats tests, extraction insight component tests, extraction i18n coverage tests. +- **D-15:** Preserve ALL screening tests (`tests/screening/` or screening-related test files). +- **D-16:** Preserve ALL non-extraction tests. Test count may drop — acceptable for teardown. +- **D-17:** After deletion, run `pnpm test` to verify no remaining tests reference deleted extraction modules. + +### Claude's Discretion +- Order of file deletion within each layer is Claude's choice — optimize for minimal intermediate breakage. +- Whether to use a single git commit per layer or per directory is Claude's choice — optimize for clean, reviewable history. +- Whether `lib/pdf/download.ts` is deleted or surgically edited depends on what the file contains at execution time. + + + + +## Canonical References + +**Downstream agents MUST read these before planning or implementing.** + +### Schema & Tables +- `convex/schema.ts` — Contains all legacy extraction tables to remove (extractionJobs, extractionPapers, extractionQuestions, extractionEvidenceUnits, extractionResults, extractionResultReviews, extractionSavedViews, extractionWorkflowTemplates, extractionReportSnapshots, extractionJobStats, extractionRunDiffs) + +### Component Configuration +- `convex/convex.config.ts` — Contains `@convex-dev/rag` component registration to remove, plus workpool registrations to evaluate +- `convex/workpool.ts` — Contains `pdfProcessingPool` (remove) and `screeningPool` (keep) + +### Extraction Code (all to be deleted) +- `convex/extraction/` — ~9.6K LoC, 30+ files (mutations, queries, actions, workflow, workpoolActions, prompts, evidence_units, chunking, guard, pdfjs_extract, validators, debug_*.ts, test_*.ts) +- `lib/extraction/` — UI helpers (answer-grouping, card-thresholds, citation-panel, citations, confidence-messages, export, feature-flags, filtering, insights, pdf-highlight, pdfjs-text, question-status, reviews, status-filter-options, types) +- `app/extraction/` — Extraction UI routes and pages +- `components/extraction/` — Extraction feature components + +### Shared Files (surgical editing needed) +- `lib/store.ts` — Zustand root store, extraction slice must be removed +- `lib/types/index.ts` — Re-exports extraction types +- `lib/pdf/download.ts` — May serve extraction only or be shared +- `convex/crons.ts` — May contain extraction-related cron jobs +- `convex/http.ts` — May contain extraction-related HTTP routes +- `messages/{en-US,en-GB,zh,fr,hi,ja}.json` — Contain `extraction.*` i18n keys to remove + +### Requirements +- `.planning/REQUIREMENTS.md` — TEAR-01 through TEAR-10 define exact teardown scope + + + + +## Existing Code Insights + +### Reusable Assets +- None for this phase — this is purely destructive. + +### Established Patterns +- `convex/schema.ts` is the single source of truth for all tables — removal there is definitive. +- `convex/convex.config.ts` manages all component registrations — removal there unregisters the component. +- `lib/types/index.ts` is the central type re-export file — removal of extraction exports there breaks the import chain. +- Locale files are at `messages/{en-US,en-GB,zh,fr,hi,ja}.json` (6 files per STRUCTURE.md, though REQUIREMENTS says en/fr/es/de/ar/zh — the actual file list at execution time determines which 6 to edit). + +### Integration Points +- `convex/workflow.ts` — WorkflowManager config may reference extraction workflow +- `app/layout.tsx` — Root layout providers; unlikely to reference extraction directly +- `components/app-sidebar.tsx` — 32KB nav component likely has extraction nav entries to remove +- `package.json` — `@convex-dev/rag` dependency to uninstall, possibly `pdfjs-dist` evaluation + + + + +## Specific Ideas + +No specific requirements — the REQUIREMENTS.md TEAR-01 through TEAR-10 are exhaustive. Follow them literally. + + + + +## Deferred Ideas + +None — discussion stayed within phase scope. + + + +--- + +*Phase: 88-scorched-earth-teardown* +*Context gathered: 2026-04-14* diff --git a/.planning/phases/88-scorched-earth-teardown/88-DISCUSSION-LOG.md b/.planning/phases/88-scorched-earth-teardown/88-DISCUSSION-LOG.md new file mode 100644 index 000000000..972b1ee4c --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-DISCUSSION-LOG.md @@ -0,0 +1,73 @@ +# Phase 88: Scorched-Earth Teardown - Discussion Log + +> **Audit trail only.** Do not use as input to planning, research, or execution agents. +> Decisions are captured in CONTEXT.md — this log preserves the alternatives considered. + +**Date:** 2026-04-14 +**Phase:** 88-scorched-earth-teardown +**Areas discussed:** Deletion Order, Screening Pipeline Boundaries, Shared Dependencies, Test Cleanup Scope +**Mode:** --auto (all decisions auto-selected) + +--- + +## Deletion Order + +| Option | Description | Selected | +|--------|-------------|----------| +| Schema-last approach | Remove consumers before providers: UI → components → lib → convex → schema → config | ✓ | +| Schema-first approach | Remove tables first, then fix all dangling refs in one pass | | +| Monolithic delete | Delete everything at once, fix all tsc errors in one sweep | | + +**User's choice:** [auto] Schema-last approach (recommended default) +**Notes:** Removing consumers before providers avoids intermediate tsc breaks and enables layer-by-layer verification. + +--- + +## Screening Pipeline Boundaries + +| Option | Description | Selected | +|--------|-------------|----------| +| Remove only pdfProcessingPool | Keep screeningPool intact, it powers the working v4.0 feature | ✓ | +| Remove both pools | Follow TEAR-05 literally, replace both in Phase 89 | | +| Keep both pools | Defer all pool changes to Phase 89 | | + +**User's choice:** [auto] Remove only pdfProcessingPool (recommended — destroying screening would break a shipped feature) +**Notes:** TEAR-05 wording is ambiguous but the intent is to replace the extraction pool, not the screening pool. screeningPool powers v4.0 bulk screening which is a separate, working feature. + +--- + +## Shared Dependencies + +| Option | Description | Selected | +|--------|-------------|----------| +| Surgical removal | Delete extraction-only files, strip extraction from shared files, preserve non-extraction | ✓ | +| Aggressive cleanup | Delete any file that touches extraction, rebuild shared files from scratch | | +| Minimal removal | Delete only the directories listed in TEAR-02/TEAR-03, fix imports manually | | + +**User's choice:** [auto] Surgical removal (recommended — aligns with TEAR-10 zero dangling imports requirement) +**Notes:** Shared files like lib/store.ts, lib/types/index.ts, and potentially lib/pdf/download.ts need case-by-case evaluation rather than wholesale deletion. + +--- + +## Test Cleanup Scope + +| Option | Description | Selected | +|--------|-------------|----------| +| Delete extraction tests, preserve all others | Remove tests/extraction/ and extraction-specific files, keep screening and all other tests | ✓ | +| Delete all extraction-related tests aggressively | Include edge-case tests that happen to use extraction fixtures | | +| Keep extraction test skeletons | Convert to skipped tests as documentation of what was tested | | + +**User's choice:** [auto] Delete extraction tests, preserve all others (recommended) +**Notes:** Test count drop is acceptable for a teardown phase. Final pnpm test run validates no remaining tests reference deleted modules. + +--- + +## Claude's Discretion + +- File deletion order within each layer +- Git commit granularity (per layer vs per directory) +- lib/pdf/download.ts disposition (delete vs surgical edit) based on runtime analysis + +## Deferred Ideas + +None — discussion stayed within phase scope. From 2598ca0cc5d8b3a0b7a7760002694eb3a2e4b7e3 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:25:13 +0100 Subject: [PATCH 006/421] docs(state): record phase 88 context session --- .planning/STATE.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/.planning/STATE.md b/.planning/STATE.md index 2a12d3968..88a4469e1 100644 --- a/.planning/STATE.md +++ b/.planning/STATE.md @@ -2,10 +2,10 @@ gsd_state_version: 1.0 milestone: v6.0 milestone_name: Extraction MVP Rebuild -status: active -stopped_at: Roadmap approved, ready to plan Phase 88 -last_updated: "2026-04-14T00:00:00.000Z" -last_activity: 2026-04-14 — Roadmap created for v6.0 (10 phases, 63 requirements mapped) +status: planning +stopped_at: Phase 88 context gathered +last_updated: "2026-04-14T22:25:09.241Z" +last_activity: 2026-04-14 — Roadmap created, 63 v6.0 requirements mapped across 10 phases progress: total_phases: 10 completed_phases: 0 @@ -35,6 +35,7 @@ Progress: [ ] 0% ## Performance Metrics **Velocity:** + - Total plans completed: 179 (v1.0: 7, v1.1: 6, v1.2: 11, v2.0: 17, v2.1: 15, v2.2: 7, v2.3: 14, v2.4: 7, v2.5: 15, v3.0: 11, v3.1: 20, v3.2: 4, v4.0: 9, v4.1: 5, v5.0: 14, cleanup: 2, quick: 15) - Total milestones shipped: 15 @@ -65,6 +66,7 @@ Progress: [ ] 0% See PROJECT.md Key Decisions table for full log. **v6.0-specific direction (locked):** + - Legacy extraction code and data are DEAD — wipe tables, delete files, no migration, no backward compat - OpenRouter via Vercel AI SDK 6 is the only LLM surface - Gemini 3 Flash / 2.5 Flash Lite / Haiku 4.5 — NO Grok 4.1 Fast (92.89% JSON validity dealbreaker) @@ -109,5 +111,5 @@ None. ## Session Continuity Last activity: 2026-04-14 — v6.0 roadmap created (10 phases, 63 requirements mapped) -Stopped at: Roadmap approved, ready to plan Phase 88 (Scorched-Earth Teardown) -Resume file: None +Stopped at: Phase 88 context gathered +Resume file: .planning/phases/88-scorched-earth-teardown/88-CONTEXT.md From 374c630c79c1496b3b984d96a90c6f0c380bde0a Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:34:33 +0100 Subject: [PATCH 007/421] docs(88): research phase domain --- .../88-scorched-earth-teardown/88-RESEARCH.md | 413 ++++++++++++++++++ 1 file changed, 413 insertions(+) create mode 100644 .planning/phases/88-scorched-earth-teardown/88-RESEARCH.md diff --git a/.planning/phases/88-scorched-earth-teardown/88-RESEARCH.md b/.planning/phases/88-scorched-earth-teardown/88-RESEARCH.md new file mode 100644 index 000000000..30d9b860a --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-RESEARCH.md @@ -0,0 +1,413 @@ +# Phase 88: Scorched-Earth Teardown - Research + +**Researched:** 2026-04-14 +**Domain:** Legacy code deletion, Convex schema removal, dependency uninstall, TypeScript compilation cleanup +**Confidence:** HIGH + +## Summary + +Phase 88 is a purely destructive teardown of the legacy extraction pipeline. The codebase currently contains approximately 9,610 lines of backend code in `convex/extraction/` (32 files), 15 UI helper files in `lib/extraction/`, 39 UI components in `components/extraction/`, 7 route files in `app/extraction/`, a dedicated Zustand store in `lib/store/extraction.ts`, extraction types in `lib/types/extraction.types.ts`, and 23+ extraction-specific test files. All of this code must be deleted, along with 11 legacy schema tables, the `@convex-dev/rag` component, the `pdfProcessingPool` workpool, and extraction i18n keys across 6 locale files. + +The critical complexity is not the deletion itself but the surgical editing of shared files that mix extraction and non-extraction concerns. Six shared files require careful editing: `convex/schema.ts` (which imports `searchFiltersValidator` from the extraction module being deleted), `convex/convex.config.ts`, `convex/workpool.ts`, `lib/store.ts`, `lib/types/index.ts`, and `components/app-sidebar.tsx`. Additionally, several shared Convex modules (`convex/maintenance/mutations.ts`, `convex/ai/actions.ts`, `convex/lib/rateLimit.ts`, `convex/featureFlags/internal.ts`, `convex/lib/queryBounds.ts`, `convex/lib/constants.ts`) contain extraction-specific code that must be surgically removed. + +**Primary recommendation:** Follow the schema-last deletion order (D-01) strictly. The most dangerous operation is the `searchFiltersValidator` import in `convex/schema.ts` -- this validator is defined in `convex/extraction/validators.ts` which is being deleted. The validator must either be relocated to a shared location or inlined into schema.ts before the extraction directory is removed. + + +## User Constraints (from CONTEXT.md) + +### Locked Decisions +- **D-01:** Schema-last approach -- remove consumers before providers to avoid intermediate tsc breaks. Order: UI routes/pages -> components -> lib helpers -> convex functions -> schema tables -> convex.config.ts component removal -> package.json uninstalls. +- **D-02:** Each deletion layer should compile cleanly before moving to the next. Plan should be structured as sequential layers, not one monolithic delete. +- **D-03:** Remove ONLY `pdfProcessingPool` from `convex/workpool.ts`. Keep `screeningPool` intact -- it powers the working v4.0 bulk screening feature and is NOT part of the legacy extraction pipeline. +- **D-04:** TEAR-05's "remove pdfProcessingPool and screeningPool workpool registrations" should be interpreted as: `pdfProcessingPool` is the legacy extraction pool being replaced. `screeningPool` serves screening (v4.0), not extraction -- preserve it. +- **D-05:** All `convex/screening/` code stays untouched. Only `convex/extraction/` is deleted. +- **D-06:** Surgical removal of extraction-only content from shared files. Delete extraction-only files wholesale. Strip extraction imports/exports from shared files. Leave non-extraction functionality intact. +- **D-07:** `lib/store.ts` -- remove the extraction store slice and any extraction-related types/actions. Keep all other slices. +- **D-08:** `lib/types/extraction.types.ts` -- delete entirely. +- **D-09:** `lib/types/index.ts` -- remove extraction re-exports, keep all others. +- **D-10:** `lib/pdf/download.ts` -- evaluate at deletion time. If it serves ONLY extraction, delete. If shared, strip extraction-only helpers and keep. +- **D-11:** `convex/crons.ts` -- remove any extraction-related scheduled jobs. Keep the rest. +- **D-12:** `convex/http.ts` -- remove any extraction-related HTTP routes. Keep the rest. +- **D-13:** Delete `tests/extraction/` directory entirely. +- **D-14:** Delete extraction-specific test files at any location. +- **D-15:** Preserve ALL screening tests. +- **D-16:** Preserve ALL non-extraction tests. Test count may drop -- acceptable for teardown. +- **D-17:** After deletion, run `pnpm test` to verify no remaining tests reference deleted extraction modules. + +### Claude's Discretion +- Order of file deletion within each layer is Claude's choice -- optimize for minimal intermediate breakage. +- Whether to use a single git commit per layer or per directory is Claude's choice. +- Whether `lib/pdf/download.ts` is deleted or surgically edited depends on what the file contains at execution time. + +### Deferred Ideas (OUT OF SCOPE) +None -- discussion stayed within phase scope. + + + +## Phase Requirements + +| ID | Description | Research Support | +|----|-------------|------------------| +| TEAR-01 | Delete all legacy extraction tables from `convex/schema.ts` | 11 tables identified at lines 319-781 of schema.ts. `searchFiltersValidator` import from `convex/extraction/validators` must be relocated first. | +| TEAR-02 | Delete `convex/extraction/` directory entirely | 32 files, 9,610 LoC confirmed. Public API surface in `index.ts` exports to `_generated/api.d.ts`. | +| TEAR-03 | Delete `lib/extraction/` directory entirely | 15 files confirmed (answer-grouping through types). `lib/store/extraction.ts` is a separate store file also to delete. | +| TEAR-04 | Remove `@convex-dev/rag` from `convex.config.ts` and `package.json` | Only two import sites: `convex.config.ts:3` and `convex/extraction/workpoolActions.ts:7`. Package at line 33 of package.json. | +| TEAR-05 | Remove `pdfProcessingPool` workpool registration | Per D-03/D-04, remove ONLY `pdfProcessingPool`. Keep `screeningPool` and its `screeningWorkpool` component. Remove default `workpool` component from config. | +| TEAR-06 | Remove extraction entries from `lib/pdf/download.ts` | File is ONLY consumed by `convex/extraction/workpoolActions.ts` -- zero non-extraction consumers. Delete entirely per D-10. | +| TEAR-07 | Remove extraction UI routes, pages, components | `app/extraction/` (7 files), `components/extraction/` (39 files + 5 in results-views subdirectory). | +| TEAR-08 | Remove extraction i18n keys from all 6 locale files | 6 locale files: `en-US.json`, `en-GB.json`, `zh.json`, `fr.json`, `hi.json`, `ja.json`. Two top-level sections (`extraction`, `extractionView`) plus scattered keys in `common`, `toast`, `errorPages`, `jobStatus`. | +| TEAR-09 | Remove `uploadedPdfs` Convex file storage entries | Storage IDs (`_storage` references) exist only in extraction code. No migration needed -- just code deletion removes all references. | +| TEAR-10 | TypeScript compiles with zero errors | After deletion, `tsc --noEmit` must pass. Shared file surgery is the critical path (schema.ts, store.ts, types/index.ts, sidebar, ai/actions.ts, maintenance/mutations.ts, featureFlags/internal.ts, lib/rateLimit.ts, lib/queryBounds.ts, lib/constants.ts, search.types.ts). | + + +## Architectural Responsibility Map + +| Capability | Primary Tier | Secondary Tier | Rationale | +|------------|-------------|----------------|-----------| +| Schema table deletion | Database / Storage | -- | Tables are defined in `convex/schema.ts`, deployed to Convex backend | +| Backend function deletion | API / Backend | -- | Mutations, queries, actions in `convex/extraction/` | +| UI route deletion | Browser / Client | Frontend Server (SSR) | Next.js pages in `app/extraction/`, SSR layout files | +| Component deletion | Browser / Client | -- | React components in `components/extraction/` | +| Lib helper deletion | Browser / Client | API / Backend | `lib/extraction/` used by both client and convex imports | +| i18n key removal | Browser / Client | -- | Locale JSON files consumed by `next-intl` | +| Dependency uninstall | Build artifacts | -- | `package.json` changes, `node_modules` cleanup | +| Shared file surgery | All tiers | -- | Affects schema, store, types, sidebar, AI actions, maintenance | + +## Verified Deletion Inventory + +### Wholesale Directory Deletions + +| Directory | Files | LoC | Action | +|-----------|-------|-----|--------| +| `convex/extraction/` | 32 | 9,610 | `rm -rf` [VERIFIED: ls + wc -l] | +| `lib/extraction/` | 15 | ~2,100 | `rm -rf` [VERIFIED: ls] | +| `components/extraction/` | 44 (incl. subdirectory) | ~8,500 | `rm -rf` [VERIFIED: ls -laR] | +| `app/extraction/` | 7 (incl. subdirectories) | ~1,800 | `rm -rf` [VERIFIED: ls -laR] | +| `tests/extraction/` | 2 | ~128 | `rm -rf` [VERIFIED: ls] | + +### Wholesale File Deletions + +| File | Reason | Action | +|------|--------|--------| +| `lib/types/extraction.types.ts` | Extraction types -- zero non-extraction consumers | Delete [VERIFIED: grep] | +| `lib/store/extraction.ts` | Extraction Zustand store -- zero non-extraction consumers | Delete [VERIFIED: grep] | +| `lib/pdf/download.ts` | Only consumer is `convex/extraction/workpoolActions.ts` | Delete per D-10 [VERIFIED: grep] | +| `convex/debug.ts` | Queries `extractionPapers` table | Delete [VERIFIED: read] | +| `convex/debug_papers.ts` | Queries `extractionPapers` table | Delete [VERIFIED: read] | + +### Extraction Test Files to Delete + +| File | Imports From | +|------|-------------| +| `tests/answer-grouping.test.ts` | `lib/extraction/answer-grouping` | +| `tests/card-thresholds.test.ts` | `lib/extraction/card-thresholds` | +| `tests/confidence-badge.test.tsx` | `components/extraction/confidence-badge` | +| `tests/confidence-messages.test.ts` | `lib/extraction/confidence-messages` | +| `tests/export-answer-formatters.test.ts` | `lib/extraction/export` | +| `tests/export-citations.test.ts` | `lib/extraction/citations` | +| `tests/export-extraction-options.test.ts` | `lib/extraction/filtering`, `lib/extraction/export` | +| `tests/extraction-citation-panel.test.ts` | `lib/extraction/citation-panel` | +| `tests/extraction-feature-flags.test.ts` | `convex/extraction/content` | +| `tests/extraction-filtering.test.ts` | `lib/extraction/filtering` | +| `tests/extraction-i18n-coverage.test.ts` | Extraction i18n keys | +| `tests/extraction-insights-overview.test.tsx` | `components/extraction/insights-overview` | +| `tests/extraction-insights-question-panel.test.tsx` | `components/extraction/insights-question-panel` | +| `tests/extraction-insights.test.ts` | `lib/extraction/insights` | +| `tests/extraction-v3-evidence.test.ts` | `convex/extraction/evidence_units` | +| `tests/extraction-v3-integration.test.ts` | `convex/extraction/workpoolActions` | +| `tests/extraction-v3-prompts.test.ts` | `convex/extraction/prompts` | +| `tests/highlight-text.test.ts` | `components/extraction/results-views/highlighted-text` | +| `tests/question-list-item.test.tsx` | `components/extraction/question-list-item` | +| `tests/question-status.test.ts` | `lib/extraction/question-status` | +| `tests/stacked-answer-bars.test.tsx` | `components/extraction/stacked-answer-bars` | +| `tests/summary-cards.test.tsx` | `components/extraction/summary-cards` | +| `tests/components/grouped-answer-row.test.tsx` | `components/extraction/grouped-answer-row` | + +**Total: 23 test files + 2 in `tests/extraction/` directory = 25 extraction test files** [VERIFIED: find + grep] + +### Shared Files Requiring Surgical Editing + +| File | What to Remove | What to Keep | +|------|---------------|--------------| +| `convex/schema.ts` | Import of `searchFiltersValidator` from `./extraction/validators` (line 4). All 11 extraction tables (lines 319-781): `extractionJobs`, `extractionQuestions`, `extractionPapers`, `extractionEvidenceUnits`, `extractionResults`, `extractionResultReviews`, `extractionSavedViews`, `extractionWorkflowTemplates`, `extractionReportSnapshots`, `extractionJobStats`, `extractionRunDiffs`. | All other tables (models, featureFlags, users, credits, creditTransactions, subscriptions, billingCustomers, stripeEventLogs, auditLogs, walletAllowedOrigins, walletKeys, apiKeys, zoteroConnections, zoteroOAuthTokens, screeningJobs, etc.) | +| `convex/convex.config.ts` | `import rag from "@convex-dev/rag/convex.config.js"` (line 3), `import workpool from "@convex-dev/workpool/convex.config.js"` (line 5), `app.use(rag)` (line 10), `app.use(workpool)` (line 12) | `stripe`, `workflow`, `screeningWorkpool` components | +| `convex/workpool.ts` | `pdfProcessingPool` const (lines 5-14), `import { components }` may need adjustment | `screeningPool` const (lines 17-25), `components` import | +| `lib/store.ts` | `ExtractionSortBy` import (line 15), `extractionViewMode` state field (line 86), `extractionSortBy` state field (line 87), `setExtractionViewMode` action (line 99), `setExtractionSortBy` action (line 100), implementation lines 595-596 and 614-615, persist whitelist entries 654-655 | All non-extraction slices (search, history, UI, focus, keywords, AI config, sidebar, screening) | +| `lib/types/index.ts` | Lines 40-60: entire extraction type re-export block | AI types, screening types, search types | +| `lib/types/search.types.ts` | `ExtractionSortBy` type definition (line 205) | All other types | +| `components/app-sidebar.tsx` | Lines 374, 376, 438-439, 523-528: extraction feature flag check, extraction plan check, extraction nav entry | All other nav entries (search, history, bookmarks, screening, etc.) | +| `convex/maintenance/mutations.ts` | Lines 38-52: extraction job cascade delete logic referencing `internal.extraction.mutations.deleteExtractionInternal` | All other user cleanup logic | +| `convex/ai/actions.ts` | Lines 5-78: `getExtractionQuestionsConfig` import and `generateExtractionQuestions` action | All other AI actions (translateQuery, translatePaperContent, screening, etc.) | +| `convex/lib/rateLimit.ts` | Line 18: `"start-extraction"` rate limit key, and its corresponding validator literal (line 58) | All other rate limit keys | +| `convex/featureFlags/internal.ts` | Lines 47-53: all `extraction.*` feature flag seeds | All other feature flag seeds | +| `convex/lib/constants.ts` | Extraction-related constants and comments (lines 3, 9-14, 30) | Non-extraction constants | +| `convex/lib/queryBounds.ts` | Extraction-related query bound constants (lines 9, 14, 30) | Non-extraction bounds | +| `lib/ai/core/configs.ts` | `getExtractionQuestionsConfig` function (lines 94-118) and its related imports/schema | All other config functions | +| `lib/ai/client/executor.ts` | Lines 11 and 134: `getExtractionQuestionsConfig` import and usage | All other executor logic | + +## Critical Pattern: searchFiltersValidator Relocation + +**The most dangerous operation in this phase.** + +`convex/schema.ts` line 4 imports `searchFiltersValidator` from `./extraction/validators`. This validator is used by three extraction tables in schema.ts (`extractionJobs` at lines 335/374, `extractionWorkflowTemplates` at line 626). Since all three tables are being deleted, the import AND all usages disappear together. + +**Verification:** `searchFiltersValidator` is NOT used by any non-extraction table. [VERIFIED: grep of `convex/screening/` returned zero matches] The import can be deleted along with the tables. + +**Risk level:** LOW -- clean removal since all consumers of the validator are also being removed. + +## Don't Hand-Roll + +| Problem | Don't Build | Use Instead | Why | +|---------|-------------|-------------|-----| +| Tracking deleted files | Custom deletion manifest | `git diff --stat` after each layer | Git already tracks what was deleted | +| Validating clean compile | Custom lint script | `tsc --noEmit` | TypeScript compiler is the authoritative check | +| Finding dangling imports | Manual file reading | `tsc --noEmit` error output | Compiler finds ALL dangling imports, not just obvious ones | +| Verifying test suite | Manual test enumeration | `pnpm test` (vitest run) | Test runner validates all imports at collection time | + +## Common Pitfalls + +### Pitfall 1: Convex Generated API Cache +**What goes wrong:** After deleting `convex/extraction/`, the `convex/_generated/api.d.ts` file still references extraction types and functions, causing type errors. +**Why it happens:** The generated API file is auto-generated by Convex dev/deploy. If not regenerated, stale types persist. +**How to avoid:** Run `npx convex dev` or `npx convex codegen` after deleting extraction code to regenerate the API type file. [ASSUMED] +**Warning signs:** Type errors referencing `api.extraction.*` paths. + +### Pitfall 2: searchFiltersValidator Import Ordering +**What goes wrong:** Deleting `convex/extraction/validators.ts` before removing the import from `convex/schema.ts` breaks the schema, which breaks ALL Convex operations. +**Why it happens:** Schema is the foundational file -- a broken schema means zero Convex functions work. +**How to avoid:** Remove the `searchFiltersValidator` import and all extraction table definitions from schema.ts BEFORE deleting the extraction directory, not after. +**Warning signs:** `tsc --noEmit` errors in `convex/schema.ts` referencing missing module. + +### Pitfall 3: Locale File JSON Syntax Errors +**What goes wrong:** Removing keys from the middle of a JSON object leaves trailing commas or breaks JSON structure. +**Why it happens:** JSON does not allow trailing commas. When removing a key that precedes a closing brace, the preceding entry's trailing comma must also be removed. +**How to avoid:** After editing locale files, validate JSON syntax: `node -e "JSON.parse(require('fs').readFileSync('messages/en-US.json', 'utf8'))"`. Or use programmatic removal instead of manual editing. +**Warning signs:** Runtime parse errors, locale loading failures. + +### Pitfall 4: Workpool Component Left Orphaned in Config +**What goes wrong:** The default `workpool` component in `convex.config.ts` (line 5, 12) is the one backing `pdfProcessingPool`. If only `pdfProcessingPool` is removed from `workpool.ts` but the component registration stays in `convex.config.ts`, the component deploys to Convex but has no consumer. +**Why it happens:** `components.workpool` is referenced by `pdfProcessingPool` while `components.screeningWorkpool` is referenced by `screeningPool`. When `pdfProcessingPool` is deleted, the default `workpool` component import and `app.use(workpool)` become dead code. +**How to avoid:** Remove both the import and `app.use(workpool)` from `convex.config.ts` when removing `pdfProcessingPool`. Keep `screeningWorkpool` import and registration. +**Warning signs:** Convex dashboard showing an unused `workpool` component. + +### Pitfall 5: Extraction Store Slice in Zustand Persist Migration +**What goes wrong:** `lib/store.ts` has a `persist` configuration that whitelists specific fields (lines 654-655 include `extractionViewMode` and `extractionSortBy`). If these fields are removed from the state shape but left in the persist whitelist (or vice versa), the store throws at hydration. +**Why it happens:** Zustand persist stores serialized state in localStorage. Stale persisted state may include extraction fields that no longer exist in the type. +**How to avoid:** Remove extraction fields from both the state interface AND the persist whitelist. Bump the persist version number to force a clean migration. +**Warning signs:** Console errors about unknown state fields, sidebar tree crashes (CRASH-07). + +### Pitfall 6: Maintenance Mutations Scheduler Reference +**What goes wrong:** `convex/maintenance/mutations.ts` calls `internal.extraction.mutations.deleteExtractionInternal`. After deletion, this reference breaks at compile time. +**Why it happens:** The maintenance module cascades user deletion through extraction job cleanup. +**How to avoid:** Remove the entire extraction job cleanup block (lines 38-52 of maintenance/mutations.ts). Since extraction tables no longer exist, there is nothing to cascade-delete. +**Warning signs:** `tsc --noEmit` error in `convex/maintenance/mutations.ts`. + +### Pitfall 7: pdfjs-dist Left in Package.json +**What goes wrong:** `pdfjs-dist` is at line 57 of `package.json`. It is ONLY imported by `convex/extraction/pdfjs_extract.ts` and `components/extraction/pdf-viewer.tsx` -- both being deleted. +**Why it happens:** Easy to forget transitive dependencies when the direct consumer directories are wholesale-deleted. +**How to avoid:** After deletion, check whether `pdfjs-dist` has any remaining importers. If none, uninstall it alongside `@convex-dev/rag`. [VERIFIED: only 2 import sites, both in extraction code] +**Warning signs:** Unused dependency in `package.json`, wasted bundle size. + +## Architecture Patterns + +### Deletion Layer Order (from D-01) + +``` +Layer 1: UI Routes & Pages + app/extraction/ [7 files] + +Layer 2: UI Components + components/extraction/ [44 files] + +Layer 3: Lib Helpers + lib/extraction/ [15 files] + lib/store/extraction.ts [1 file] + lib/types/extraction.types.ts [1 file] + lib/pdf/download.ts [1 file, per D-10 evaluation] + +Layer 4: Shared File Surgery + lib/store.ts [remove extraction slice] + lib/types/index.ts [remove extraction re-exports] + lib/types/search.types.ts [remove ExtractionSortBy] + components/app-sidebar.tsx [remove extraction nav] + lib/ai/core/configs.ts [remove extraction config] + lib/ai/client/executor.ts [remove extraction import] + +Layer 5: Convex Functions + Shared Convex Surgery + convex/extraction/ [32 files] + convex/debug.ts [delete] + convex/debug_papers.ts [delete] + convex/maintenance/mutations.ts [surgery] + convex/ai/actions.ts [surgery] + convex/lib/rateLimit.ts [surgery] + convex/featureFlags/internal.ts [surgery] + convex/lib/constants.ts [surgery] + convex/lib/queryBounds.ts [surgery] + +Layer 6: Schema Tables + convex/schema.ts [remove import + 11 tables] + +Layer 7: Component Config & Package Cleanup + convex/convex.config.ts [remove rag + default workpool] + convex/workpool.ts [remove pdfProcessingPool] + package.json [uninstall @convex-dev/rag, pdfjs-dist] + +Layer 8: i18n Cleanup + messages/en-US.json [remove extraction/extractionView sections + scattered keys] + messages/en-GB.json [same] + messages/zh.json [same] + messages/fr.json [same] + messages/hi.json [same] + messages/ja.json [same] + +Layer 9: Test Cleanup + tests/extraction/ [2 files] + tests/extraction-*.test.* [12 files] + tests/answer-grouping.test.ts, etc. [11 additional files] +``` + +### Anti-Patterns to Avoid +- **Monolithic delete:** Do NOT delete everything in one shot. The resulting error count will be overwhelming and hide real issues behind cascading import failures. +- **Schema-first deletion:** Do NOT remove schema tables before removing the functions and types that reference them. Schema is the provider; everything else is the consumer. +- **Partial workpool removal:** Do NOT remove the `screeningPool` or the `screeningWorkpool` component registration. These are live production infrastructure for v4.0 screening. + +## i18n Key Structure + +Each of the 6 locale files has the same structure. Keys to remove: + +| Location | Type | Example Keys | +|----------|------|-------------| +| Top-level `"extraction"` section | Object (~140 keys) | `extraction.searchJobs`, `extraction.startExtraction`, `extraction.exportResults`, etc. | +| Top-level `"extractionView"` section | Object (~14 keys) | `extractionView.extractionResults`, `extractionView.insights`, etc. | +| `common.extraction` | String | Nav label "Extraction" | +| `common.extractionError` | String | Error label | +| `toast.extractionPlanRequired` | String | Plan gate toast | +| `errorPages.extractionUnavailable` | String | Error page title | +| `errorPages.extractionErrorDescription` | String | Error page description | +| `jobStatus.extractionProgress` | String | Progress label | +| `jobStatus.loadingExtractionResults` | String | Loading state | +| `pricing.proDescription` | String (contains "extraction" text) | Evaluate -- may keep if text is about the product tier, not the feature | +| `pricing.proFeature2` | String | "Data extraction (Pro-only)" | + +[VERIFIED: python3 JSON parsing of en-US.json] + +**Actual locale files (differ from REQUIREMENTS.md):** +- REQUIREMENTS says: `en.json, fr.json, es.json, de.json, ar.json, zh.json` +- CONTEXT says: `en-US, en-GB, zh, fr, hi, ja` +- **On disk:** `en-US.json, en-GB.json, zh.json, fr.json, hi.json, ja.json` [VERIFIED: ls messages/] + +The planner should use the on-disk file list, not the REQUIREMENTS.md list. + +## Verified Shared File Reference Counts + +Comprehensive extraction reference map for files OUTSIDE the extraction directories: + +| File | References | Type | +|------|-----------|------| +| `convex/schema.ts` | 1 import + 11 table definitions | Import + schema | +| `convex/convex.config.ts` | 2 imports + 2 `app.use()` calls | Config | +| `convex/workpool.ts` | 1 const definition (pdfProcessingPool) | Export | +| `convex/maintenance/mutations.ts` | 1 scheduler call + surrounding logic | Runtime reference | +| `convex/ai/actions.ts` | 1 import + 1 action definition | Import + export | +| `convex/lib/rateLimit.ts` | 1 key definition + 1 validator literal | Config | +| `convex/featureFlags/internal.ts` | 7 feature flag seed entries | Data | +| `convex/lib/constants.ts` | 3 comments referencing extraction | Comments only | +| `convex/lib/queryBounds.ts` | 3 constants referencing extraction | Constants | +| `convex/debug.ts` | Entire file queries extractionPapers | Delete wholesale | +| `convex/debug_papers.ts` | Entire file queries extractionPapers | Delete wholesale | +| `lib/store.ts` | 2 state fields + 2 actions + 1 import + persist entries | State + import | +| `lib/types/index.ts` | 20-line extraction re-export block | Re-exports | +| `lib/types/search.types.ts` | 1 type definition (ExtractionSortBy) | Type | +| `lib/ai/core/configs.ts` | 1 function definition (getExtractionQuestionsConfig) | Export | +| `lib/ai/client/executor.ts` | 1 import + 1 usage | Import | +| `components/app-sidebar.tsx` | 2 hooks + 2 conditionals + 1 nav entry | UI logic | +| `convex/_generated/api.d.ts` | Auto-generated -- will regenerate after deletion | Generated | + +[VERIFIED: grep across entire codebase] + +## Environment Availability + +| Dependency | Required By | Available | Version | Fallback | +|------------|------------|-----------|---------|----------| +| TypeScript (`tsc`) | TEAR-10 compilation check | Checked via `pnpm test` | Via project | -- | +| Vitest | Test verification (D-17) | Yes | Via project | -- | +| Node.js | All tooling | Yes | System | -- | +| pnpm | Package management | Yes | Via project | npm | + +Step 2.6: No new external dependencies needed. This phase is code/config deletion only. + +## Validation Architecture + +### Test Framework +| Property | Value | +|----------|-------| +| Framework | Vitest (via project config) | +| Config file | `vitest.config.ts` | +| Quick run command | `pnpm test` | +| Full suite command | `pnpm test` | + +### Phase Requirements -> Test Map +| Req ID | Behavior | Test Type | Automated Command | File Exists? | +|--------|----------|-----------|-------------------|-------------| +| TEAR-01 | Schema has zero extraction tables | smoke | `grep -c "extractionJobs\|extractionPapers\|extractionQuestions\|extractionEvidenceUnits\|extractionResults\|extractionResultReviews\|extractionSavedViews\|extractionWorkflowTemplates\|extractionReportSnapshots\|extractionJobStats\|extractionRunDiffs" convex/schema.ts` should return 0 | N/A (shell check) | +| TEAR-02 | `convex/extraction/` does not exist | smoke | `test ! -d convex/extraction && echo PASS` | N/A (shell check) | +| TEAR-03 | `lib/extraction/` does not exist | smoke | `test ! -d lib/extraction && echo PASS` | N/A (shell check) | +| TEAR-04 | `@convex-dev/rag` absent from config and package.json | smoke | `grep -c "@convex-dev/rag" convex/convex.config.ts package.json` should return 0 | N/A (shell check) | +| TEAR-05 | `pdfProcessingPool` absent, `screeningPool` present | smoke | `grep -c "pdfProcessingPool" convex/workpool.ts` = 0 AND `grep -c "screeningPool" convex/workpool.ts` > 0 | N/A (shell check) | +| TEAR-06 | `lib/pdf/download.ts` deleted or extraction-free | smoke | `test ! -f lib/pdf/download.ts && echo PASS` | N/A (shell check) | +| TEAR-07 | `app/extraction/` and `components/extraction/` do not exist | smoke | `test ! -d app/extraction -a ! -d components/extraction && echo PASS` | N/A (shell check) | +| TEAR-08 | Zero extraction i18n keys in locale files | smoke | `grep -rl '"extraction"' messages/` should return 0 lines | N/A (shell check) | +| TEAR-09 | No file storage references to extraction uploads | smoke | Covered by TEAR-02 (extraction code is the only consumer) | N/A | +| TEAR-10 | `tsc --noEmit` returns zero errors | integration | `npx tsc --noEmit` | N/A (compiler check) | + +### Sampling Rate +- **Per task commit:** `pnpm test` (4.76s currently, will be faster after deletion) +- **Per wave merge:** `pnpm test && npx tsc --noEmit` +- **Phase gate:** Full suite green + tsc --noEmit zero errors + +### Wave 0 Gaps +None -- existing test infrastructure (`vitest.config.ts`, `pnpm test`) covers all validation needs. All verification for this phase is shell-based smoke checks and compiler validation, not new test files. + +## Assumptions Log + +| # | Claim | Section | Risk if Wrong | +|---|-------|---------|---------------| +| A1 | Running `npx convex dev` or `npx convex codegen` regenerates `_generated/api.d.ts` after extraction deletion | Pitfall 1 | Medium -- stale generated types would cause false tsc errors. Fixable by checking Convex docs for exact regeneration command. | +| A2 | `pdfjs-dist` has zero non-extraction importers and can be safely uninstalled | Pitfall 7 | Low -- verified via grep that only 2 import sites exist, both in extraction code. | + +## Open Questions + +1. **`pdfjs-dist` removal vs. Phase 90 reuse** + - What we know: `pdfjs-dist` is currently only imported by extraction code. Phase 90 introduces `unpdf` (serverless-bundled PDF.js v5) as the replacement. + - What's unclear: Whether `unpdf` completely replaces `pdfjs-dist` or whether some of the download utility logic in `lib/pdf/download.ts` would be useful to Phase 90. + - Recommendation: Delete both `pdfjs-dist` and `lib/pdf/download.ts` in this phase. Phase 90 will build fresh with `unpdf` per requirements. The download utility is tightly coupled to the old extraction flow. + +2. **`lib/ai/core/configs.ts` -- extraction question generation** + - What we know: The `getExtractionQuestionsConfig` function and its prompts are extraction-specific. The `convex/ai/actions.ts` `generateExtractionQuestions` action uses it. + - What's unclear: Whether the new extraction pipeline (Phase 91+) will reuse this AI config or build new prompts. + - Recommendation: Delete it. The v6.0 extraction pipeline uses a completely different approach (Gemini 3 Flash via OpenRouter, flat 7-field Zod schema). Old prompt engineering is not reusable. + +## Sources + +### Primary (HIGH confidence) +- Codebase grep and file reads across all referenced files +- Direct verification of all import chains and reference counts +- `vitest run` confirming 108 test files, 1435 tests passing +- `ls`, `wc -l`, JSON parsing of locale files + +### Secondary (MEDIUM confidence) +- None -- all findings verified via codebase inspection + +### Tertiary (LOW confidence) +- A1: Convex codegen behavior (assumed from training knowledge, not verified against Convex docs) + +## Metadata + +**Confidence breakdown:** +- Deletion inventory: HIGH -- every file and reference verified via grep/read +- Shared file surgery: HIGH -- all extraction references enumerated with line numbers +- Pitfalls: HIGH -- based on verified structural analysis of the codebase +- i18n cleanup: HIGH -- JSON structure parsed programmatically + +**Research date:** 2026-04-14 +**Valid until:** 2026-05-14 (stable -- codebase structure unlikely to change before this phase executes) From 2cc46a4dec901e523f1bae3ff611c3059147b564 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:35:37 +0100 Subject: [PATCH 008/421] docs(phase-88): add validation strategy --- .../88-VALIDATION.md | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 .planning/phases/88-scorched-earth-teardown/88-VALIDATION.md diff --git a/.planning/phases/88-scorched-earth-teardown/88-VALIDATION.md b/.planning/phases/88-scorched-earth-teardown/88-VALIDATION.md new file mode 100644 index 000000000..e1921d363 --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-VALIDATION.md @@ -0,0 +1,78 @@ +--- +phase: 88 +slug: scorched-earth-teardown +status: draft +nyquist_compliant: false +wave_0_complete: false +created: 2026-04-14 +--- + +# Phase 88 — Validation Strategy + +> Per-phase validation contract for feedback sampling during execution. + +--- + +## Test Infrastructure + +| Property | Value | +|----------|-------| +| **Framework** | vitest + tsc | +| **Config file** | `vitest.config.ts` | +| **Quick run command** | `pnpm tsc --noEmit` | +| **Full suite command** | `pnpm tsc --noEmit && pnpm test` | +| **Estimated runtime** | ~45 seconds | + +--- + +## Sampling Rate + +- **After every task commit:** Run `pnpm tsc --noEmit` +- **After every plan wave:** Run `pnpm tsc --noEmit && pnpm test` +- **Before `/gsd-verify-work`:** Full suite must be green +- **Max feedback latency:** 45 seconds + +--- + +## Per-Task Verification Map + +| Task ID | Plan | Wave | Requirement | Threat Ref | Secure Behavior | Test Type | Automated Command | File Exists | Status | +|---------|------|------|-------------|------------|-----------------|-----------|-------------------|-------------|--------| +| 88-01-01 | 01 | 1 | TEAR-01 | — | N/A | compile | `pnpm tsc --noEmit` | ✅ | ⬜ pending | +| 88-01-02 | 01 | 1 | TEAR-02 | — | N/A | compile | `pnpm tsc --noEmit` | ✅ | ⬜ pending | +| 88-01-03 | 01 | 1 | TEAR-06 | — | N/A | compile | `pnpm tsc --noEmit` | ✅ | ⬜ pending | +| 88-02-01 | 02 | 2 | TEAR-03 | — | N/A | compile | `pnpm tsc --noEmit` | ✅ | ⬜ pending | +| 88-02-02 | 02 | 2 | TEAR-04 | — | N/A | compile | `pnpm tsc --noEmit` | ✅ | ⬜ pending | +| 88-02-03 | 02 | 2 | TEAR-05 | — | N/A | compile+grep | `pnpm tsc --noEmit && ! grep -r pdfProcessingPool convex/` | ✅ | ⬜ pending | +| 88-03-01 | 03 | 3 | TEAR-07 | — | N/A | grep | `! grep -r "extraction" messages/*.json` | ✅ | ⬜ pending | +| 88-03-02 | 03 | 3 | TEAR-08 | — | N/A | test | `pnpm test` | ✅ | ⬜ pending | +| 88-03-03 | 03 | 3 | TEAR-09, TEAR-10 | — | N/A | compile+test | `pnpm tsc --noEmit && pnpm test` | ✅ | ⬜ pending | + +*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky* + +--- + +## Wave 0 Requirements + +*Existing infrastructure covers all phase requirements. This phase deletes code — no new test infrastructure needed.* + +--- + +## Manual-Only Verifications + +| Behavior | Requirement | Why Manual | Test Instructions | +|----------|-------------|------------|-------------------| +| Convex dashboard shows no extraction tables | TEAR-03 | Requires Convex dashboard inspection | After `npx convex deploy`, verify extraction tables absent from dashboard | + +--- + +## Validation Sign-Off + +- [ ] All tasks have `` verify or Wave 0 dependencies +- [ ] Sampling continuity: no 3 consecutive tasks without automated verify +- [ ] Wave 0 covers all MISSING references +- [ ] No watch-mode flags +- [ ] Feedback latency < 45s +- [ ] `nyquist_compliant: true` set in frontmatter + +**Approval:** pending From c56e9cea7794c2f777b0534c63df1693f97ba38d Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:41:38 +0100 Subject: [PATCH 009/421] docs(88): add pattern mapping --- .../88-scorched-earth-teardown/88-PATTERNS.md | 696 ++++++++++++++++++ 1 file changed, 696 insertions(+) create mode 100644 .planning/phases/88-scorched-earth-teardown/88-PATTERNS.md diff --git a/.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md b/.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md new file mode 100644 index 000000000..7ec0811b1 --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md @@ -0,0 +1,696 @@ +# Phase 88: Scorched-Earth Teardown - Pattern Map + +**Mapped:** 2026-04-14 +**Files analyzed:** 48 files to delete/modify across 9 deletion layers +**Analogs found:** N/A (destructive phase -- no new files created) + +## Nature of This Phase + +This phase is **purely destructive**. No new files are created. The pattern map therefore focuses on: +1. **Surgical edit patterns** -- exact line ranges and code blocks to remove from shared files +2. **Wholesale deletion inventory** -- directories and standalone files to `rm -rf` +3. **Cross-cutting cleanup** -- imports, re-exports, and scattered references + +There are no "analogs" in the traditional sense. Instead, each shared file is documented with the exact extraction code to remove and the surrounding non-extraction code that must be preserved. + +## File Classification + +| File/Directory | Role | Action | Layer | +|----------------|------|--------|-------| +| `app/extraction/` (7 files) | route | `rm -rf` | 1 | +| `components/extraction/` (44 files) | component | `rm -rf` | 2 | +| `lib/extraction/` (15 files) | utility | `rm -rf` | 3 | +| `lib/store/extraction.ts` | store | delete file | 3 | +| `lib/types/extraction.types.ts` | type-def | delete file | 3 | +| `lib/pdf/download.ts` | utility | delete file | 3 | +| `lib/store.ts` | store | surgical edit | 4 | +| `lib/types/index.ts` | type-def | surgical edit | 4 | +| `lib/types/search.types.ts` | type-def | surgical edit | 4 | +| `components/app-sidebar.tsx` | component | surgical edit | 4 | +| `lib/ai/core/configs.ts` | config | surgical edit | 4 | +| `lib/ai/client/executor.ts` | service | surgical edit | 4 | +| `lib/ai/core/types.ts` | type-def | surgical edit | 4 | +| `lib/ai/core/schemas.ts` | config | surgical edit | 4 | +| `lib/ai/core/prompts.ts` | config | surgical edit | 4 | +| `convex/extraction/` (32 files) | backend | `rm -rf` | 5 | +| `convex/debug.ts` | backend | delete file | 5 | +| `convex/debug_papers.ts` | backend | delete file | 5 | +| `convex/maintenance/mutations.ts` | backend | surgical edit | 5 | +| `convex/ai/actions.ts` | backend | surgical edit | 5 | +| `convex/lib/rateLimit.ts` | backend | surgical edit | 5 | +| `convex/featureFlags/internal.ts` | backend | surgical edit | 5 | +| `convex/lib/constants.ts` | backend | surgical edit | 5 | +| `convex/lib/queryBounds.ts` | backend | surgical edit | 5 | +| `convex/schema.ts` | schema | surgical edit | 6 | +| `convex/convex.config.ts` | config | surgical edit | 7 | +| `convex/workpool.ts` | backend | surgical edit | 7 | +| `package.json` | config | uninstall deps | 7 | +| `messages/en-US.json` | i18n | surgical edit | 8 | +| `messages/en-GB.json` | i18n | surgical edit | 8 | +| `messages/zh.json` | i18n | surgical edit | 8 | +| `messages/fr.json` | i18n | surgical edit | 8 | +| `messages/hi.json` | i18n | surgical edit | 8 | +| `messages/ja.json` | i18n | surgical edit | 8 | +| `tests/extraction/` (2 files) | test | `rm -rf` | 9 | +| 23 test files in `tests/` | test | delete files | 9 | + +## Surgical Edit Patterns + +Each section below documents exact code to remove from a shared file, with line numbers verified against the current codebase. + +--- + +### `convex/schema.ts` (schema, Layer 6) + +**Remove import** (line 4): +```typescript +import { searchFiltersValidator } from "./extraction/validators"; +``` +This import is ONLY consumed by extraction tables being deleted. Verified: zero non-extraction usage of `searchFiltersValidator`. + +**Remove 11 extraction tables** (lines 316-781): +Remove everything from the `// EXTRACTION JOBS` comment block through the end of the `extractionRunDiffs` table definition (ending at line 781 with the last `.index(...)` call). The next retained table starts at line 783: +```typescript + // ═══════════════════════════════════════════════════════════════ + // SCREENING JOBS - bulk screening job records + // ═══════════════════════════════════════════════════════════════ + screeningJobs: defineTable({ +``` + +**Tables to delete:** `extractionJobs`, `extractionQuestions`, `extractionPapers`, `extractionEvidenceUnits`, `extractionResults`, `extractionResultReviews`, `extractionSavedViews`, `extractionWorkflowTemplates`, `extractionReportSnapshots`, `extractionJobStats`, `extractionRunDiffs`. + +**Keep:** All tables before line 316 (models, featureFlags, users, credits, etc.) and all tables after line 781 (screeningJobs, etc.). + +--- + +### `convex/convex.config.ts` (config, Layer 7) + +**Current file (complete -- 15 lines):** +```typescript +import { defineApp } from "convex/server"; +import stripe from "@convex-dev/stripe/convex.config.js"; +import rag from "@convex-dev/rag/convex.config.js"; // REMOVE +import workflow from "@convex-dev/workflow/convex.config.js"; +import workpool from "@convex-dev/workpool/convex.config.js"; // REMOVE +import screeningWorkpool from "@convex-dev/workpool/convex.config.js"; + +const app = defineApp(); +app.use(stripe); +app.use(rag); // REMOVE +app.use(workflow); +app.use(workpool); // REMOVE +app.use(screeningWorkpool, { name: "screeningWorkpool" }); + +export default app; +``` + +**Remove lines:** 3 (`rag` import), 5 (`workpool` import), 10 (`app.use(rag)`), 12 (`app.use(workpool)`). + +**After edit, file should be:** +```typescript +import { defineApp } from "convex/server"; +import stripe from "@convex-dev/stripe/convex.config.js"; +import workflow from "@convex-dev/workflow/convex.config.js"; +import screeningWorkpool from "@convex-dev/workpool/convex.config.js"; + +const app = defineApp(); +app.use(stripe); +app.use(workflow); +app.use(screeningWorkpool, { name: "screeningWorkpool" }); + +export default app; +``` + +--- + +### `convex/workpool.ts` (backend, Layer 7) + +**Current file (complete -- 25 lines):** +```typescript +import { Workpool } from "@convex-dev/workpool"; +import { components } from "./_generated/api"; + +// For PDF processing - limited to avoid overwhelming external services +// Reduced to 3 to prevent database conflicts with onComplete handlers +export const pdfProcessingPool = new Workpool(components.workpool, { // REMOVE + maxParallelism: 3, // REMOVE + retryActionsByDefault: true, // REMOVE + defaultRetryBehavior: { // REMOVE + maxAttempts: 3, // REMOVE + initialBackoffMs: 2000, // REMOVE + base: 2, // REMOVE + }, // REMOVE +}); // REMOVE + +// For bulk screening - separate from extraction to avoid cross-cancellation on cancelAll() +export const screeningPool = new Workpool(components.screeningWorkpool, { + maxParallelism: 5, + retryActionsByDefault: true, + defaultRetryBehavior: { + maxAttempts: 3, + initialBackoffMs: 2000, + base: 2, + }, +}); +``` + +**Remove lines 4-14:** The `pdfProcessingPool` constant and its comments. Note: after removing `components.workpool` from `convex.config.ts`, the `components` import still works because `components.screeningWorkpool` is still used by `screeningPool`. + +**Update comment on line 16:** Remove "separate from extraction to avoid cross-cancellation" reference. Replace with a simple comment like `// For bulk screening operations`. + +--- + +### `lib/store.ts` (store, Layer 4) + +**Remove import** (line 15): +```typescript + ExtractionSortBy, +``` +Remove from the `import type { ... } from './types'` block at lines 3-17. + +**Remove interface fields** (lines 86-87 in UIState): +```typescript + extractionViewMode: ViewMode + extractionSortBy: ExtractionSortBy +``` + +**Remove interface methods** (lines 99-100 in UIState): +```typescript + setExtractionViewMode: (mode: ViewMode) => void + setExtractionSortBy: (sort: ExtractionSortBy) => void +``` + +**Remove state defaults** (lines 595-596 in useUIStore): +```typescript + extractionViewMode: 'list-detail', + extractionSortBy: 'recent', +``` + +**Remove action implementations** (lines 614-615 in useUIStore): +```typescript + setExtractionViewMode: (mode) => set({ extractionViewMode: mode }), + setExtractionSortBy: (sort) => set({ extractionSortBy: sort }), +``` + +**Remove persist whitelist entries** (lines 654-655 in useUIStore): +```typescript + extractionViewMode: state.extractionViewMode, + extractionSortBy: state.extractionSortBy, +``` + +**Remove entire ExtractionCitationPanel section** (lines 1194-1234): +Remove the constants, interface, store, and dimension helper: +```typescript +// Extraction citation panel store +const EXTRACTION_CITATION_PANEL_WIDTH_EXPANDED = 460; +const EXTRACTION_CITATION_PANEL_WIDTH_COLLAPSED = 48; + +interface ExtractionCitationPanelState { ... } + +export const useExtractionCitationPanelStore = create()( ... ); + +export const getExtractionCitationPanelDimensions = (isCollapsed: boolean) => ({ ... }); +``` + +Lines 1194-1234 inclusive. The next retained code is `useTransientScreeningStore` at line 1236. + +--- + +### `lib/types/index.ts` (type-def, Layer 4) + +**Current file (61 lines). Remove lines 34, 41-60:** + +Remove `ExtractionSortBy` from the search types re-export (line 34): +```typescript + ExtractionSortBy, // REMOVE this line from the re-export block +``` + +Remove entire extraction type block (lines 40-60): +```typescript +// Extraction Types +export type { + ExtractionQuestionType, + ExtractionQuestion, + ExtractionSourceType, + ExtractionHistorySource, + ExtractionZoteroItem, + ExtractionZoteroSelection, + ExtractionManualItem, + ExtractionJob, + ExtractionJobStatus, + ExtractionPaper, + ExtractionPaperStatus, + ExtractionResult, + ExtractionJobDetails, + CreateExtractionJobInput, + ExtractionSavedView, + ExtractionWorkflowTemplate, + ExtractionReportSnapshot, + ExtractionRunDiff, +} from './extraction.types'; +``` + +--- + +### `lib/types/search.types.ts` (type-def, Layer 4) + +**Remove lines 203-205:** +```typescript +/** + * Sort options for extraction jobs + */ +export type ExtractionSortBy = 'recent' | 'oldest' | 'name' | 'status'; +``` + +--- + +### `components/app-sidebar.tsx` (component, Layer 4) + +**Remove import** (line 46, from lucide-react import block): +```typescript + Database, +``` + +**Remove hooks** (lines 374, 376): +```typescript + const extractionEnabled = useFeatureFlag("extraction.enabled"); + // ... + const hasExtractionPlan = subscriptionState.resolvedPlan === "pro" || subscriptionState.resolvedPlan === "enterprise"; +``` + +**Remove from getCurrentPage function** (lines 438-439): +```typescript + if ((extractionEnabled || hasExtractionPlan) && pathname.includes("/extraction")) + return "extraction"; +``` + +**Remove extraction nav entry** (lines 523-533): +```typescript + {(extractionEnabled || hasExtractionPlan) && ( + + )} +``` + +After removing this, check whether `useFeatureFlag` import (line 35) is still used elsewhere in the file. If `extraction.enabled` was the only feature flag check, the import can be removed too. Grep for `useFeatureFlag` in the file to decide. + +--- + +### `convex/ai/actions.ts` (backend, Layer 5) + +**Remove from import block** (line 8): +```typescript + getExtractionQuestionsConfig, +``` +Remove from the `import { ... } from "../../lib/ai/core/configs"` block at lines 6-12. + +**Remove entire action** (lines 61-78): +```typescript +export const generateExtractionQuestions = createAIAction( + { + jobName: v.string(), + sourceContext: v.string(), + existingQuestions: v.array(v.string()), + responseLanguage: v.optional(v.string()), + }, + v.object({ + questions: v.array(v.object({ + question: v.string(), + type: v.union(v.literal("string"), v.literal("boolean"), v.literal("number"), v.literal("array")), + description: v.optional(v.string()), + })), + }), + "Generate extraction questions", + getExtractionQuestionsConfig, + (output) => ({ questions: output.questions }) +); +``` + +--- + +### `lib/ai/core/configs.ts` (config, Layer 4) + +**Remove from import block** (line 5): +```typescript + extractionQuestionsSchema, +``` + +**Remove from import block** (line 11): +```typescript + buildExtractionQuestionsPrompts, +``` + +**Remove from import block** (line 20): +```typescript + GenerateExtractionQuestionsInput, +``` + +**Remove entire function** (lines 94-118): +```typescript +export function getExtractionQuestionsConfig( + input: GenerateExtractionQuestionsInput +): OperationConfig> { + return { + schema: extractionQuestionsSchema, + buildPrompts: (input) => buildExtractionQuestionsPrompts(input), + input, + repairStrategy: { type: 'full-json' }, + temperature: 0.7, + postProcess: (output, input) => { + const newQuestions = output.questions.filter((newQ) => { + const normalizedNew = newQ.question.toLowerCase().trim() + return !input.existingQuestions.some((existingQuestion: string) => { + const normalizedExisting = existingQuestion.toLowerCase().trim() + return ( + normalizedExisting === normalizedNew || + normalizedExisting.includes(normalizedNew) || + normalizedNew.includes(normalizedExisting) + ) + }) + }) + return { questions: newQuestions } + }, + } +} +``` + +--- + +### `lib/ai/client/executor.ts` (service, Layer 4) + +**Remove from import block** (line 11): +```typescript + getExtractionQuestionsConfig, +``` + +**Remove from type import block** (line 28): +```typescript + GenerateExtractionQuestionsInput, +``` + +**Remove executor export** (lines 133-137): +```typescript +export const generateExtractionQuestions = createClientExecutor( + getExtractionQuestionsConfig, + (output) => ({ questions: output.questions }), + 'generate_extraction_questions' +) +``` + +--- + +### `lib/ai/core/types.ts` (type-def, Layer 4) + +**Remove extraction types** (lines 79-92): +```typescript +export interface GenerateExtractionQuestionsInput { + jobName: string; + sourceContext: string; + existingQuestions: string[]; + responseLanguage?: string; +} + +export interface GenerateExtractionQuestionsOutput { + questions: Array<{ + question: string; + type: "string" | "boolean" | "number" | "array"; + description?: string; + }>; +} +``` + +Also remove the comment on line 94: `// AI types only - extraction removed`. + +--- + +### `lib/ai/core/schemas.ts` (config, Layer 4) + +**Remove extraction schema** (lines 52-64): +```typescript +export const extractionQuestionsSchema = z.object({ + questions: z + .array( + z.object({ + question: z.string().describe("The data extraction question"), + type: z.enum(["string", "boolean", "number", "array"]).describe("Expected answer type"), + description: z.string().optional().describe("Optional context/instructions for the AI extractor"), + }) + ) + .min(1) + .max(10) + .describe("3-7 data extraction questions with their expected types"), +}) +``` + +--- + +### `lib/ai/core/prompts.ts` (config, Layer 4) + +**Remove from import** (line 1): +```typescript +GenerateExtractionQuestionsInput, +``` +Remove from the `import type { ..., GenerateExtractionQuestionsInput, ... }` list. + +**Remove entire function** (lines 227-278, end of file): +```typescript +export function buildExtractionQuestionsPrompts(input: GenerateExtractionQuestionsInput) { + // ... entire function body through end of file +} +``` + +--- + +### `convex/maintenance/mutations.ts` (backend, Layer 5) + +**Remove extraction cleanup block** (lines 38-54): +```typescript + // Delete extraction jobs (cascade to papers, results, evidence units, etc.) + // Uses existing deleteExtractionInternal which handles all 9 child tables + const extractionJobs = await ctx.db + .query("extractionJobs") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .take(BATCH_SIZE); + for (const job of extractionJobs) { + await ctx.scheduler.runAfter(0, internal.extraction.mutations.deleteExtractionInternal, { + jobId: job._id, + }); + } + + // If we found a full batch of extraction jobs, there may be more. + // Don't delete the user yet -- re-schedule to handle remaining jobs. + if (extractionJobs.length === BATCH_SIZE) { + continue; // Skip user delete, process on next run + } +``` + +**Keep:** Everything before line 38 (API key cleanup) and everything after line 54 (Zotero connection cleanup). The `internal` import on line 3 stays because it is still used at line 79 for `internal.maintenance.mutations.cleanupDeletedUsers`. + +--- + +### `convex/lib/rateLimit.ts` (backend, Layer 5) + +**Remove rate limit definition** (lines 18-23): +```typescript + "start-extraction": { + kind: "token bucket", + rate: 5, + period: HOUR, + capacity: 3, + }, +``` + +**Remove from consume validator** (line 58): +```typescript + v.literal("start-extraction"), +``` + +--- + +### `convex/featureFlags/internal.ts` (backend, Layer 5) + +**Remove 7 extraction feature flag seeds** (lines 47-53): +```typescript + { key: "extraction.enabled", enabled: true, minimumTier: 0, description: "Master switch for the extraction feature" }, + { key: "extraction.pdf", enabled: true, minimumTier: 0, description: "PDF processing in extraction pipelines" }, + { key: "extraction.insights", enabled: true, minimumTier: 20, description: "AI-powered insights panel in extraction results" }, + { key: "extraction.reviewQueue", enabled: false, minimumTier: 20, description: "Manual review queue for extraction results" }, + { key: "extraction.reportBuilder", enabled: false, minimumTier: 20, description: "Report builder for extraction jobs" }, + { key: "extraction.start", enabled: true, minimumTier: 20, description: "Start new extraction jobs (Pro+)" }, + { key: "extraction.templates", enabled: true, minimumTier: 20, description: "Workflow template management (Pro+)" }, +``` + +**Keep:** `credits.enabled`, `credits.topups`, `subscriptions.enabled` seeds and all function definitions. + +--- + +### `convex/lib/constants.ts` (backend, Layer 5) + +**Remove extraction comment fragment** (line 3 -- the JSDoc for `FREE_SIGNUP_CREDIT_GRANT`): +```typescript + * Lets free users experience server-side AI (including extraction) before committing to a plan. +``` +Change to: `Lets free users experience server-side AI before committing to a plan.` + +**Remove extraction reference from line 14** (JSDoc for `ESTIMATED_CREDITS_PER_PAPER`): +```typescript + * Estimated credit cost per paper for batch AI operations (screening, translation, extraction). +``` +Change to: `Estimated credit cost per paper for batch AI operations (screening, translation).` + +No structural code changes needed -- comments only. + +--- + +### `convex/lib/queryBounds.ts` (backend, Layer 5) + +**Remove extraction-specific constants** (lines 9-10, 13-14): +```typescript +/** Maximum extraction jobs listed per user. + * Users accumulate jobs over time; 500 is generous for any reasonable usage. */ +export const MAX_EXTRACTION_JOBS_PER_USER = 500; + +/** Maximum evidence units loaded per paper. + * Each extraction run produces evidence; 200 per paper is generous. */ +export const MAX_EVIDENCE_UNITS_PER_PAPER = 200; + +/** Maximum reviews loaded in a single batch by job. + * Worst case: 500 papers x 20 questions = 10,000 reviews. */ +export const MAX_REVIEWS_PER_JOB = 10_000; +``` + +Lines 9-19 inclusive. Keep `MAX_LIBRARY_BROWSE`, `MAX_COLLECTION_MEMBERS`, `MAX_CREDIT_TRANSACTIONS`, `MAX_SCREENING_PAPERS_PER_JOB`, `MAX_SCREENING_JOBS_PER_USER`. + +**Remove extraction reference from line 30** (comment on `MAX_SCREENING_JOBS_PER_USER`): +```typescript +/** Maximum screening jobs listed per user. + * Matches extraction job limit for consistency. */ +``` +Change to: `/** Maximum screening jobs listed per user. */` + +--- + +### `messages/*.json` (i18n, Layer 8) + +**Pattern for all 6 locale files** (`en-US.json`, `en-GB.json`, `zh.json`, `fr.json`, `hi.json`, `ja.json`): + +Remove these top-level JSON sections entirely: +- `"extraction"` object (~140 keys) +- `"extractionView"` object (~14 keys) + +Remove these individual keys scattered across other sections: +- `common.extraction` +- `common.extractionError` +- `toast.extractionPlanRequired` +- `errorPages.extractionUnavailable` +- `errorPages.extractionErrorDescription` +- `jobStatus.extractionProgress` +- `jobStatus.loadingExtractionResults` +- `pricing.proFeature2` (if it says "Data extraction (Pro-only)" -- evaluate per locale) + +**Validate JSON after edit:** Use `node --input-type=module -e "import{readFileSync as r}from'node:fs';JSON.parse(r('messages/en-US.json','utf8'))"` for each file. Watch for trailing commas after key removal. + +--- + +### Extraction Test Files to Delete (Layer 9) + +Delete `tests/extraction/` directory, then delete these 23 individual test files: + +| File | +|------| +| `tests/answer-grouping.test.ts` | +| `tests/card-thresholds.test.ts` | +| `tests/confidence-badge.test.tsx` | +| `tests/confidence-messages.test.ts` | +| `tests/export-answer-formatters.test.ts` | +| `tests/export-citations.test.ts` | +| `tests/export-extraction-options.test.ts` | +| `tests/extraction-citation-panel.test.ts` | +| `tests/extraction-feature-flags.test.ts` | +| `tests/extraction-filtering.test.ts` | +| `tests/extraction-i18n-coverage.test.ts` | +| `tests/extraction-insights-overview.test.tsx` | +| `tests/extraction-insights-question-panel.test.tsx` | +| `tests/extraction-insights.test.ts` | +| `tests/extraction-v3-evidence.test.ts` | +| `tests/extraction-v3-integration.test.ts` | +| `tests/extraction-v3-prompts.test.ts` | +| `tests/highlight-text.test.ts` | +| `tests/question-list-item.test.tsx` | +| `tests/question-status.test.ts` | +| `tests/stacked-answer-bars.test.tsx` | +| `tests/summary-cards.test.tsx` | +| `tests/components/grouped-answer-row.test.tsx` | + +--- + +## Shared Patterns (Cross-Cutting) + +### Verification After Each Layer + +**Apply to:** Every layer boundary (D-02 requires clean compile between layers). + +After each deletion layer completes, run: +```bash +npx tsc --noEmit +``` +If errors appear, they are dangling references from the just-completed deletion that need surgical fixes in the current layer before proceeding. + +### JSON Validation for i18n + +**Apply to:** All 6 locale files after Layer 8 edits. +```bash +for f in messages/en-US.json messages/en-GB.json messages/zh.json messages/fr.json messages/hi.json messages/ja.json; do + node --input-type=module -e "import{readFileSync as r}from'node:fs';JSON.parse(r('$f','utf8'))" && echo "$f OK" || echo "$f BROKEN" +done +``` + +### Package Cleanup (Layer 7) + +After removing `@convex-dev/rag` and `pdfjs-dist` from `package.json`: +```bash +pnpm install +``` +This regenerates the lockfile and cleans `node_modules`. + +### Convex Codegen (After Layer 6) + +After schema table deletion, regenerate Convex types: +```bash +npx convex codegen +``` +This updates `convex/_generated/api.d.ts` to remove stale `api.extraction.*` references. + +--- + +## Files With No Extraction References (Confirmed Clean) + +These shared files were checked and contain **zero** extraction references: + +| File | Verified | +|------|----------| +| `convex/crons.ts` | No extraction cron jobs | +| `convex/http.ts` | No extraction HTTP routes | +| `lib/ai/core/index.ts` | No extraction exports | + +--- + +## No Analog Found + +Not applicable. This phase creates no new files, so no analogs are needed. All work is deletion and surgical editing of existing files. + +--- + +## Metadata + +**Analog search scope:** Entire codebase (all files containing "extraction" references) +**Files scanned:** 48 files classified for deletion/modification +**Pattern extraction date:** 2026-04-14 +**Verification method:** Every shared file was read in full; extraction references identified by line number via grep and direct reading From 92a79afdd0f498df4d2fd44f37cbec9586eb5af8 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:52:35 +0100 Subject: [PATCH 010/421] docs(88): create phase plan --- .planning/ROADMAP.md | 9 +- .../88-scorched-earth-teardown/88-01-PLAN.md | 284 ++++++++++++++ .../88-scorched-earth-teardown/88-02-PLAN.md | 318 +++++++++++++++ .../88-scorched-earth-teardown/88-03-PLAN.md | 325 +++++++++++++++ .../88-scorched-earth-teardown/88-04-PLAN.md | 370 ++++++++++++++++++ 5 files changed, 1304 insertions(+), 2 deletions(-) create mode 100644 .planning/phases/88-scorched-earth-teardown/88-01-PLAN.md create mode 100644 .planning/phases/88-scorched-earth-teardown/88-02-PLAN.md create mode 100644 .planning/phases/88-scorched-earth-teardown/88-03-PLAN.md create mode 100644 .planning/phases/88-scorched-earth-teardown/88-04-PLAN.md diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md index 01f4ccceb..6f7e53350 100644 --- a/.planning/ROADMAP.md +++ b/.planning/ROADMAP.md @@ -255,7 +255,12 @@ Full details: `.planning/milestones/v5.0-ROADMAP.md` 3. `@convex-dev/rag` is absent from `convex/convex.config.ts` and uninstalled from `package.json` 4. `tsc --noEmit` returns zero errors with no dangling imports or dead exports referencing deleted modules 5. All six locale files (`messages/{en,fr,es,de,ar,zh}.json`) contain zero `extraction.*` keys left over from the legacy UI -**Plans**: TBD +**Plans:** 4 plans +Plans: +- [ ] 88-01-PLAN.md — Wholesale deletion of extraction directories, standalone files, and test files +- [ ] 88-02-PLAN.md — Surgical removal of extraction from shared frontend files (store, types, sidebar, AI modules) +- [ ] 88-03-PLAN.md — Delete convex/extraction/, edit shared Convex modules, remove schema tables +- [ ] 88-04-PLAN.md — Config/package cleanup, i18n key removal, final compilation and test verification ### Phase 89: Core Schema & Workflow Skeleton **Goal**: Define the new slim extraction schema (job, paper, question, result tables with `by_paper_question` unique index), register the single `extractionPool` workpool, and stand up a durable `@convex-dev/workflow` whose stages enqueue all papers in one batched mutation and save results idempotently — the rails downstream phases run on. @@ -386,7 +391,7 @@ Phases execute in numeric order: 88 → 89 → 90 → 91 → 92 → 93 → 94 | 75-78 | v4.0 | 9/9 | Complete | 2026-03-09 | | 79-82 | v4.1 | 5/5 | Complete | 2026-03-09 | | 83-87 | v5.0 | 14/14 | Complete | 2026-03-10 | -| 88. Scorched-Earth Teardown | v6.0 | 0/TBD | Not started | - | +| 88. Scorched-Earth Teardown | v6.0 | 0/4 | Not started | - | | 89. Core Schema & Workflow Skeleton | v6.0 | 0/TBD | Not started | - | | 90. Free-First Parsing Waterfall | v6.0 | 0/TBD | Not started | - | | 91. Extraction Cascade Core | v6.0 | 0/TBD | Not started | - | diff --git a/.planning/phases/88-scorched-earth-teardown/88-01-PLAN.md b/.planning/phases/88-scorched-earth-teardown/88-01-PLAN.md new file mode 100644 index 000000000..201458dc1 --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-01-PLAN.md @@ -0,0 +1,284 @@ +--- +phase: 88-scorched-earth-teardown +plan: 01 +type: execute +wave: 1 +depends_on: [] +files_modified: + - app/extraction/ + - components/extraction/ + - lib/extraction/ + - lib/store/extraction.ts + - lib/types/extraction.types.ts + - lib/pdf/download.ts + - convex/debug.ts + - convex/debug_papers.ts + - tests/extraction/ + - tests/answer-grouping.test.ts + - tests/card-thresholds.test.ts + - tests/confidence-badge.test.tsx + - tests/confidence-messages.test.ts + - tests/export-answer-formatters.test.ts + - tests/export-citations.test.ts + - tests/export-extraction-options.test.ts + - tests/extraction-citation-panel.test.ts + - tests/extraction-feature-flags.test.ts + - tests/extraction-filtering.test.ts + - tests/extraction-i18n-coverage.test.ts + - tests/extraction-insights-overview.test.tsx + - tests/extraction-insights-question-panel.test.tsx + - tests/extraction-insights.test.ts + - tests/extraction-v3-evidence.test.ts + - tests/extraction-v3-integration.test.ts + - tests/extraction-v3-prompts.test.ts + - tests/highlight-text.test.ts + - tests/question-list-item.test.tsx + - tests/question-status.test.ts + - tests/stacked-answer-bars.test.tsx + - tests/summary-cards.test.tsx + - tests/components/grouped-answer-row.test.tsx +autonomous: true +requirements: + - TEAR-02 + - TEAR-03 + - TEAR-06 + - TEAR-07 + - TEAR-09 +must_haves: + truths: + - "app/extraction/ directory does not exist on disk" + - "components/extraction/ directory does not exist on disk" + - "lib/extraction/ directory does not exist on disk" + - "lib/store/extraction.ts does not exist on disk" + - "lib/types/extraction.types.ts does not exist on disk" + - "lib/pdf/download.ts does not exist on disk" + - "All 25 extraction test files are deleted" + artifacts: + - path: "app/extraction/" + provides: "Deleted -- must NOT exist" + - path: "components/extraction/" + provides: "Deleted -- must NOT exist" + - path: "lib/extraction/" + provides: "Deleted -- must NOT exist" + key_links: [] +--- + + +Delete all extraction-only directories, standalone extraction files, and extraction test files -- the wholesale deletion layer that removes the bulk of extraction code before surgical editing of shared files begins. + +Purpose: Per D-01 (schema-last, consumers before providers), UI routes/pages, components, lib helpers, and standalone files are the outermost consumers. Deleting them first is the safest order. Test files are also deleted here since they import exclusively from extraction modules being removed. + +Output: All extraction-only directories and files removed. The codebase will NOT compile at this point (expected -- shared files still reference deleted modules). Compilation is restored in Plans 02-04. + + + +@$HOME/.claude/get-shit-done/workflows/execute-plan.md +@$HOME/.claude/get-shit-done/templates/summary.md + + + +@.planning/PROJECT.md +@.planning/ROADMAP.md +@.planning/STATE.md +@.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md +@.planning/phases/88-scorched-earth-teardown/88-RESEARCH.md +@.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md + + + + + + Task 1: Delete extraction UI directories and standalone extraction files + + app/extraction/ (7 files -- rm -rf) + components/extraction/ (44 files -- rm -rf) + lib/extraction/ (15 files -- rm -rf) + lib/store/extraction.ts (delete) + lib/types/extraction.types.ts (delete) + lib/pdf/download.ts (delete) + convex/debug.ts (delete) + convex/debug_papers.ts (delete) + + + app/extraction/ (confirm directory exists before deleting) + components/extraction/ (confirm directory exists) + lib/extraction/ (confirm directory exists) + lib/store/extraction.ts (confirm file exists) + lib/types/extraction.types.ts (confirm file exists) + lib/pdf/download.ts (confirm file exists -- per D-10: only consumer is convex/extraction/workpoolActions.ts, so delete entirely) + convex/debug.ts (confirm file queries extractionPapers) + convex/debug_papers.ts (confirm file queries extractionPapers) + + +Delete all extraction-only directories and standalone files per D-01 Layers 1-3. Execute in this order: + +1. Delete UI routes and pages (Layer 1 per D-01): + ```bash + rm -rf app/extraction/ + ``` + +2. Delete UI components (Layer 2 per D-01): + ```bash + rm -rf components/extraction/ + ``` + +3. Delete lib helpers and standalone files (Layer 3 per D-01): + ```bash + rm -rf lib/extraction/ + rm lib/store/extraction.ts + rm lib/types/extraction.types.ts + rm lib/pdf/download.ts + ``` + +4. Delete debug files that query extraction tables: + ```bash + rm convex/debug.ts + rm convex/debug_papers.ts + ``` + +Per D-06: these are all extraction-only files with zero non-extraction consumers. Per D-10: lib/pdf/download.ts is only consumed by convex/extraction/workpoolActions.ts (verified in RESEARCH.md), so delete entirely. + +NOTE: The codebase will NOT compile after this task. Shared files (lib/store.ts, lib/types/index.ts, components/app-sidebar.tsx, convex/maintenance/mutations.ts, etc.) still import from deleted modules. This is expected per D-02 -- compilation is restored in Plans 02-04. + + + test ! -d app/extraction && test ! -d components/extraction && test ! -d lib/extraction && test ! -f lib/store/extraction.ts && test ! -f lib/types/extraction.types.ts && test ! -f lib/pdf/download.ts && test ! -f convex/debug.ts && test ! -f convex/debug_papers.ts && echo "ALL DELETED" + + + - `ls app/extraction/ 2>/dev/null` returns error (directory gone) + - `ls components/extraction/ 2>/dev/null` returns error (directory gone) + - `ls lib/extraction/ 2>/dev/null` returns error (directory gone) + - `ls lib/store/extraction.ts 2>/dev/null` returns nothing + - `ls lib/types/extraction.types.ts 2>/dev/null` returns nothing + - `ls lib/pdf/download.ts 2>/dev/null` returns nothing + - `ls convex/debug.ts 2>/dev/null` returns nothing + - `ls convex/debug_papers.ts 2>/dev/null` returns nothing + + All 6 extraction-only directories/files and 2 debug files are deleted from disk. + + + + Task 2: Delete all extraction test files + + tests/extraction/ (2 files -- rm -rf) + tests/answer-grouping.test.ts (delete) + tests/card-thresholds.test.ts (delete) + tests/confidence-badge.test.tsx (delete) + tests/confidence-messages.test.ts (delete) + tests/export-answer-formatters.test.ts (delete) + tests/export-citations.test.ts (delete) + tests/export-extraction-options.test.ts (delete) + tests/extraction-citation-panel.test.ts (delete) + tests/extraction-feature-flags.test.ts (delete) + tests/extraction-filtering.test.ts (delete) + tests/extraction-i18n-coverage.test.ts (delete) + tests/extraction-insights-overview.test.tsx (delete) + tests/extraction-insights-question-panel.test.tsx (delete) + tests/extraction-insights.test.ts (delete) + tests/extraction-v3-evidence.test.ts (delete) + tests/extraction-v3-integration.test.ts (delete) + tests/extraction-v3-prompts.test.ts (delete) + tests/highlight-text.test.ts (delete) + tests/question-list-item.test.tsx (delete) + tests/question-status.test.ts (delete) + tests/stacked-answer-bars.test.tsx (delete) + tests/summary-cards.test.tsx (delete) + tests/components/grouped-answer-row.test.tsx (delete) + + + tests/extraction/ (confirm directory exists) + + +Delete all 25 extraction test files per D-13/D-14/D-16. These tests import exclusively from extraction modules already deleted in Task 1. + +1. Delete the tests/extraction/ directory: + ```bash + rm -rf tests/extraction/ + ``` + +2. Delete the 23 individual extraction test files in tests/: + ```bash + rm -f tests/answer-grouping.test.ts + rm -f tests/card-thresholds.test.ts + rm -f tests/confidence-badge.test.tsx + rm -f tests/confidence-messages.test.ts + rm -f tests/export-answer-formatters.test.ts + rm -f tests/export-citations.test.ts + rm -f tests/export-extraction-options.test.ts + rm -f tests/extraction-citation-panel.test.ts + rm -f tests/extraction-feature-flags.test.ts + rm -f tests/extraction-filtering.test.ts + rm -f tests/extraction-i18n-coverage.test.ts + rm -f tests/extraction-insights-overview.test.tsx + rm -f tests/extraction-insights-question-panel.test.tsx + rm -f tests/extraction-insights.test.ts + rm -f tests/extraction-v3-evidence.test.ts + rm -f tests/extraction-v3-integration.test.ts + rm -f tests/extraction-v3-prompts.test.ts + rm -f tests/highlight-text.test.ts + rm -f tests/question-list-item.test.tsx + rm -f tests/question-status.test.ts + rm -f tests/stacked-answer-bars.test.tsx + rm -f tests/summary-cards.test.tsx + rm -f tests/components/grouped-answer-row.test.tsx + ``` + +Per D-15: preserve ALL screening tests (tests/screening/ and screening-related test files). +Per D-16: preserve ALL non-extraction tests. Test count will drop -- acceptable for teardown. + +After deletion, do a quick grep to confirm no remaining test files import from `lib/extraction/`, `components/extraction/`, or `convex/extraction/`: +```bash +grep -rl "lib/extraction\|components/extraction\|convex/extraction" tests/ 2>/dev/null +``` +If any files are found, they are additional extraction test files missed by the inventory -- delete them too. + + + test ! -d tests/extraction && test ! -f tests/answer-grouping.test.ts && test ! -f tests/extraction-v3-prompts.test.ts && test ! -f tests/components/grouped-answer-row.test.tsx && ! grep -rl "lib/extraction\|components/extraction\|convex/extraction" tests/ 2>/dev/null && echo "ALL TESTS DELETED" + + + - `ls tests/extraction/ 2>/dev/null` returns error (directory gone) + - `ls tests/answer-grouping.test.ts 2>/dev/null` returns nothing + - `ls tests/extraction-v3-prompts.test.ts 2>/dev/null` returns nothing + - `ls tests/components/grouped-answer-row.test.tsx 2>/dev/null` returns nothing + - `grep -rl "lib/extraction\|components/extraction\|convex/extraction" tests/ 2>/dev/null` returns no results + - `ls tests/screening/ 2>/dev/null` confirms screening tests still exist (per D-15) + + All 25 extraction test files deleted. Zero remaining test files reference deleted extraction modules. All screening and non-extraction tests preserved. + + + + + +## Trust Boundaries + +| Boundary | Description | +|----------|-------------| +| N/A | This plan is purely destructive deletion -- no new code, no new endpoints, no data flow changes | + +## STRIDE Threat Register + +| Threat ID | Category | Component | Disposition | Mitigation Plan | +|-----------|----------|-----------|-------------|-----------------| +| T-88-01 | Denial of Service | Compilation break from premature deletion | accept | Expected per D-02 -- shared files still reference deleted modules. Compilation restored in Plans 02-04. No production deployment until full phase completes. | +| T-88-02 | Information Disclosure | Git history retains deleted extraction code | accept | Acceptable -- no secrets in extraction code (API keys are in env vars, not source). Git history retention is standard. | + + + +After both tasks complete: +1. `test ! -d app/extraction && test ! -d components/extraction && test ! -d lib/extraction` -- all extraction directories gone +2. `test ! -f lib/store/extraction.ts && test ! -f lib/types/extraction.types.ts && test ! -f lib/pdf/download.ts` -- standalone files gone +3. `test ! -d tests/extraction && ! grep -rl "extraction" tests/ 2>/dev/null | grep -v screening` -- test files gone (excluding screening-related hits) +4. `ls tests/screening/ 2>/dev/null` -- screening tests preserved (per D-15) + + + +- All 6 extraction-only directories/files deleted (app/extraction, components/extraction, lib/extraction, lib/store/extraction.ts, lib/types/extraction.types.ts, lib/pdf/download.ts) +- Both debug files deleted (convex/debug.ts, convex/debug_papers.ts) +- All 25 extraction test files deleted +- Zero remaining test files reference deleted extraction modules +- All screening tests preserved +- All non-extraction tests preserved + + + +After completion, create `.planning/phases/88-scorched-earth-teardown/88-01-SUMMARY.md` + diff --git a/.planning/phases/88-scorched-earth-teardown/88-02-PLAN.md b/.planning/phases/88-scorched-earth-teardown/88-02-PLAN.md new file mode 100644 index 000000000..499212323 --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-02-PLAN.md @@ -0,0 +1,318 @@ +--- +phase: 88-scorched-earth-teardown +plan: 02 +type: execute +wave: 2 +depends_on: [88-01] +files_modified: + - lib/store.ts + - lib/types/index.ts + - lib/types/search.types.ts + - components/app-sidebar.tsx + - lib/ai/core/configs.ts + - lib/ai/client/executor.ts + - lib/ai/core/types.ts + - lib/ai/core/schemas.ts + - lib/ai/core/prompts.ts +autonomous: true +requirements: + - TEAR-10 +must_haves: + truths: + - "lib/store.ts contains zero extraction state fields, actions, or persist entries" + - "lib/types/index.ts contains zero extraction re-exports" + - "components/app-sidebar.tsx contains zero extraction nav entries or feature flag checks" + - "All lib/ai/* files contain zero extraction function definitions or imports" + artifacts: + - path: "lib/store.ts" + provides: "Zustand store with extraction slice removed" + contains: "useUIStore" + - path: "lib/types/index.ts" + provides: "Type re-exports with extraction block removed" + - path: "components/app-sidebar.tsx" + provides: "Sidebar nav with extraction entry removed" + - path: "lib/ai/core/configs.ts" + provides: "AI configs with extraction question config removed" + key_links: + - from: "lib/store.ts" + to: "lib/types/search.types.ts" + via: "import type" + pattern: "ExtractionSortBy removed from both" +--- + + +Surgically remove all extraction references from shared frontend files -- the Zustand store, type re-exports, sidebar navigation, and AI client/core modules. + +Purpose: Per D-01 Layer 4, shared frontend files that mix extraction and non-extraction concerns must be surgically edited to remove only extraction content. This restores the frontend compilation path after Plan 01's wholesale deletions. + +Output: All shared frontend files compile cleanly with zero extraction references. Non-extraction functionality (search, screening, history, AI translation, etc.) remains fully intact. + + + +@$HOME/.claude/get-shit-done/workflows/execute-plan.md +@$HOME/.claude/get-shit-done/templates/summary.md + + + +@.planning/PROJECT.md +@.planning/ROADMAP.md +@.planning/STATE.md +@.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md +@.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md + + + + +From lib/store.ts (extraction slice to remove): +- Import: `ExtractionSortBy` from `./types` (line 15) +- Interface fields: `extractionViewMode: ViewMode`, `extractionSortBy: ExtractionSortBy` (lines 86-87) +- Interface methods: `setExtractionViewMode`, `setExtractionSortBy` (lines 99-100) +- State defaults: `extractionViewMode: 'list-detail'`, `extractionSortBy: 'recent'` (lines 595-596) +- Action implementations: `setExtractionViewMode`, `setExtractionSortBy` (lines 614-615) +- Persist whitelist: `extractionViewMode`, `extractionSortBy` (lines 654-655) +- ExtractionCitationPanel store: lines 1194-1234 (constants, interface, store, dimension helper) + +From lib/types/index.ts (extraction re-exports to remove): +- `ExtractionSortBy` from search types re-export (line 34) +- Entire extraction type block (lines 40-60): 18 types re-exported from './extraction.types' + +From lib/types/search.types.ts (extraction type to remove): +- `ExtractionSortBy` type definition (lines 203-205) + +From components/app-sidebar.tsx (extraction nav to remove): +- `Database` import from lucide-react (line 46) +- `extractionEnabled` feature flag hook (line 374) +- `hasExtractionPlan` subscription check (line 376) +- Extraction branch in `getCurrentPage` (lines 438-439) +- Extraction NavItem block (lines 523-533) + +From lib/ai/core/configs.ts (extraction config to remove): +- `extractionQuestionsSchema` import (line 5) +- `buildExtractionQuestionsPrompts` import (line 11) +- `GenerateExtractionQuestionsInput` import (line 20) +- `getExtractionQuestionsConfig` function (lines 94-118) + +From lib/ai/client/executor.ts (extraction executor to remove): +- `getExtractionQuestionsConfig` import (line 11) +- `GenerateExtractionQuestionsInput` import (line 28) +- `generateExtractionQuestions` executor export (lines 133-137) + +From lib/ai/core/types.ts (extraction types to remove): +- `GenerateExtractionQuestionsInput` interface (lines 79-85) +- `GenerateExtractionQuestionsOutput` interface (lines 87-92) + +From lib/ai/core/schemas.ts (extraction schema to remove): +- `extractionQuestionsSchema` (lines 52-64) + +From lib/ai/core/prompts.ts (extraction prompts to remove): +- `GenerateExtractionQuestionsInput` import (line 1) +- `buildExtractionQuestionsPrompts` function (lines 227-278, end of file) + + + + + + + Task 1: Remove extraction from Zustand store, type files, and sidebar + + lib/store.ts + lib/types/index.ts + lib/types/search.types.ts + components/app-sidebar.tsx + + + lib/store.ts + lib/types/index.ts + lib/types/search.types.ts + components/app-sidebar.tsx + + +Surgically remove extraction-only content from 4 shared frontend files per D-06/D-07/D-09. + +**lib/store.ts (per D-07):** +1. Remove `ExtractionSortBy` from the `import type { ... } from './types'` block (around line 15). +2. Remove `extractionViewMode: ViewMode` and `extractionSortBy: ExtractionSortBy` from the UIState interface (around lines 86-87). +3. Remove `setExtractionViewMode: (mode: ViewMode) => void` and `setExtractionSortBy: (sort: ExtractionSortBy) => void` from the UIState interface (around lines 99-100). +4. Remove `extractionViewMode: 'list-detail',` and `extractionSortBy: 'recent',` from the useUIStore defaults (around lines 595-596). +5. Remove `setExtractionViewMode: (mode) => set({ extractionViewMode: mode }),` and `setExtractionSortBy: (sort) => set({ extractionSortBy: sort }),` from actions (around lines 614-615). +6. Remove `extractionViewMode: state.extractionViewMode,` and `extractionSortBy: state.extractionSortBy,` from persist whitelist (around lines 654-655). +7. Remove the ENTIRE `useExtractionCitationPanelStore` block (around lines 1194-1234): the constants `EXTRACTION_CITATION_PANEL_WIDTH_EXPANDED` and `EXTRACTION_CITATION_PANEL_WIDTH_COLLAPSED`, the `ExtractionCitationPanelState` interface, the `useExtractionCitationPanelStore` create call, and the `getExtractionCitationPanelDimensions` export. The next retained code after this block is `useTransientScreeningStore`. + +**lib/types/search.types.ts:** +1. Remove the `ExtractionSortBy` type definition (around lines 203-205): + ```typescript + // REMOVE: + export type ExtractionSortBy = 'recent' | 'oldest' | 'name' | 'status'; + ``` + Also remove its JSDoc comment if present (`/** Sort options for extraction jobs */`). + +**lib/types/index.ts (per D-09):** +1. Remove `ExtractionSortBy,` from the search types re-export block (around line 34). +2. Remove the entire extraction type re-export block (around lines 40-60) -- the `// Extraction Types` comment and all 18 `export type { ... } from './extraction.types'` entries. + +**components/app-sidebar.tsx:** +1. Remove `Database,` from the lucide-react import block (around line 46). +2. Remove `const extractionEnabled = useFeatureFlag("extraction.enabled");` (around line 374). +3. Remove `const hasExtractionPlan = subscriptionState.resolvedPlan === "pro" || subscriptionState.resolvedPlan === "enterprise";` (around line 376). +4. Remove the extraction branch in `getCurrentPage` (around lines 438-439): + ```typescript + // REMOVE: + if ((extractionEnabled || hasExtractionPlan) && pathname.includes("/extraction")) + return "extraction"; + ``` +5. Remove the extraction NavItem JSX block (around lines 523-533): + ```typescript + // REMOVE entire block: + {(extractionEnabled || hasExtractionPlan) && ( + + )} + ``` +6. After removal, check if `useFeatureFlag` is still used elsewhere in the file. If `extraction.enabled` was the ONLY feature flag check, remove the `useFeatureFlag` import too. If other feature flags are checked (e.g., `screening.enabled`), keep the import. + + + ! grep -n "ExtractionSortBy\|extractionViewMode\|extractionSortBy\|ExtractionCitationPanel\|getExtractionCitationPanelDimensions" lib/store.ts && ! grep -n "extraction" lib/types/index.ts && ! grep -n "ExtractionSortBy" lib/types/search.types.ts && ! grep -n "extraction" components/app-sidebar.tsx | grep -iv "// removed\|comment" && echo "CLEAN" + + + - `grep -c "ExtractionSortBy" lib/store.ts` returns 0 + - `grep -c "extractionViewMode" lib/store.ts` returns 0 + - `grep -c "extractionSortBy" lib/store.ts` returns 0 + - `grep -c "ExtractionCitationPanel" lib/store.ts` returns 0 + - `grep -c "getExtractionCitationPanelDimensions" lib/store.ts` returns 0 + - `grep -c "useTransientScreeningStore" lib/store.ts` returns at least 1 (screening store preserved) + - `grep -c "extraction" lib/types/index.ts` returns 0 + - `grep -c "ExtractionSortBy" lib/types/search.types.ts` returns 0 + - `grep -c "extraction" components/app-sidebar.tsx` returns 0 (case-insensitive excluding comments) + - `grep -c "Database" components/app-sidebar.tsx` returns 0 (lucide import removed) + - `grep -c "screening" components/app-sidebar.tsx` returns at least 1 (screening nav preserved per D-05) + + All 4 shared frontend files have zero extraction references. Zustand store, type re-exports, search types, and sidebar nav are clean. All non-extraction functionality preserved. + + + + Task 2: Remove extraction from AI client/core modules + + lib/ai/core/configs.ts + lib/ai/client/executor.ts + lib/ai/core/types.ts + lib/ai/core/schemas.ts + lib/ai/core/prompts.ts + + + lib/ai/core/configs.ts + lib/ai/client/executor.ts + lib/ai/core/types.ts + lib/ai/core/schemas.ts + lib/ai/core/prompts.ts + + +Surgically remove extraction-only content from 5 AI module files per D-06. The v6.0 extraction pipeline will build entirely new AI configs (Phase 91+) -- old extraction question generation is not reusable. + +**lib/ai/core/types.ts:** +1. Remove the `GenerateExtractionQuestionsInput` interface (around lines 79-85): + ```typescript + // REMOVE: + export interface GenerateExtractionQuestionsInput { + jobName: string; + sourceContext: string; + existingQuestions: string[]; + responseLanguage?: string; + } + ``` +2. Remove the `GenerateExtractionQuestionsOutput` interface (around lines 87-92): + ```typescript + // REMOVE: + export interface GenerateExtractionQuestionsOutput { + questions: Array<{ + question: string; + type: "string" | "boolean" | "number" | "array"; + description?: string; + }>; + } + ``` + +**lib/ai/core/schemas.ts:** +1. Remove the `extractionQuestionsSchema` export (around lines 52-64): + ```typescript + // REMOVE entire schema: + export const extractionQuestionsSchema = z.object({ + questions: z.array(z.object({ ... })).min(1).max(10).describe(...) + }) + ``` + +**lib/ai/core/prompts.ts:** +1. Remove `GenerateExtractionQuestionsInput` from the import type block (around line 1). +2. Remove the entire `buildExtractionQuestionsPrompts` function (around lines 227-278, end of file). + +**lib/ai/core/configs.ts:** +1. Remove `extractionQuestionsSchema` from the schemas import (around line 5). +2. Remove `buildExtractionQuestionsPrompts` from the prompts import (around line 11). +3. Remove `GenerateExtractionQuestionsInput` from the types import (around line 20). +4. Remove the entire `getExtractionQuestionsConfig` function (around lines 94-118). + +**lib/ai/client/executor.ts:** +1. Remove `getExtractionQuestionsConfig` from the configs import (around line 11). +2. Remove `GenerateExtractionQuestionsInput` from the type import (around line 28). +3. Remove the `generateExtractionQuestions` executor export (around lines 133-137): + ```typescript + // REMOVE: + export const generateExtractionQuestions = createClientExecutor( + getExtractionQuestionsConfig, + (output) => ({ questions: output.questions }), + 'generate_extraction_questions' + ) + ``` + +After all edits, verify no dangling import references remain in any of the 5 files. If removing an import from a destructured import list leaves it empty (e.g., `import { } from '...'`), remove the entire import statement. + + + ! grep -rn "extraction\|Extraction" lib/ai/core/configs.ts lib/ai/client/executor.ts lib/ai/core/types.ts lib/ai/core/schemas.ts lib/ai/core/prompts.ts && echo "AI MODULES CLEAN" + + + - `grep -c "getExtractionQuestionsConfig" lib/ai/core/configs.ts` returns 0 + - `grep -c "extractionQuestionsSchema" lib/ai/core/schemas.ts` returns 0 + - `grep -c "buildExtractionQuestionsPrompts" lib/ai/core/prompts.ts` returns 0 + - `grep -c "GenerateExtractionQuestionsInput" lib/ai/core/types.ts` returns 0 + - `grep -c "GenerateExtractionQuestionsOutput" lib/ai/core/types.ts` returns 0 + - `grep -c "generateExtractionQuestions" lib/ai/client/executor.ts` returns 0 + - `grep -c "getExtractionQuestionsConfig" lib/ai/client/executor.ts` returns 0 + - All 5 files still exist and contain non-extraction AI functions (translateQuery configs, screening configs, etc.) + + All 5 AI module files have zero extraction references. Translation, screening, and other AI configs/executors are fully preserved. + + + + + +## Trust Boundaries + +| Boundary | Description | +|----------|-------------| +| N/A | Surgical editing of shared files -- no new endpoints, no data flow changes | + +## STRIDE Threat Register + +| Threat ID | Category | Component | Disposition | Mitigation Plan | +|-----------|----------|-----------|-------------|-----------------| +| T-88-03 | Denial of Service | Over-deletion of shared store/type fields | mitigate | Read each file before editing; verify non-extraction fields/functions survive via grep for `screening`, `search`, `translate` after edit | +| T-88-04 | Denial of Service | Broken Zustand persist hydration | mitigate | Extraction fields removed from BOTH state interface AND persist whitelist simultaneously (Pitfall 5 from RESEARCH.md). Persist version bump considered but not required since field removal is backward-compatible with stale localStorage. | + + + +After both tasks complete: +1. `grep -rn "extraction\|Extraction" lib/store.ts lib/types/index.ts lib/types/search.types.ts components/app-sidebar.tsx lib/ai/core/configs.ts lib/ai/client/executor.ts lib/ai/core/types.ts lib/ai/core/schemas.ts lib/ai/core/prompts.ts` -- zero extraction references across all 9 files +2. `grep -c "screening" lib/store.ts` -- screening state preserved +3. `grep -c "screening" components/app-sidebar.tsx` -- screening nav preserved +4. `grep -c "translateQuery" lib/ai/core/configs.ts` -- translation AI config preserved + + + +- All 9 shared frontend files have zero extraction references +- lib/store.ts retains all non-extraction slices (search, history, UI, focus, keywords, AI config, sidebar, screening) +- lib/types/index.ts retains AI types and screening type re-exports +- components/app-sidebar.tsx retains search, history, bookmarks, screening nav entries +- All lib/ai/* files retain translation, screening, and other AI functions + + + +After completion, create `.planning/phases/88-scorched-earth-teardown/88-02-SUMMARY.md` + diff --git a/.planning/phases/88-scorched-earth-teardown/88-03-PLAN.md b/.planning/phases/88-scorched-earth-teardown/88-03-PLAN.md new file mode 100644 index 000000000..9f752151a --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-03-PLAN.md @@ -0,0 +1,325 @@ +--- +phase: 88-scorched-earth-teardown +plan: 03 +type: execute +wave: 3 +depends_on: [88-02] +files_modified: + - convex/extraction/ + - convex/maintenance/mutations.ts + - convex/ai/actions.ts + - convex/lib/rateLimit.ts + - convex/featureFlags/internal.ts + - convex/lib/constants.ts + - convex/lib/queryBounds.ts + - convex/schema.ts +autonomous: true +requirements: + - TEAR-01 + - TEAR-02 + - TEAR-10 +must_haves: + truths: + - "convex/extraction/ directory does not exist on disk" + - "convex/schema.ts contains zero legacy extraction table definitions" + - "convex/schema.ts has zero imports from ./extraction/*" + - "No shared convex module references extraction functions or tables" + artifacts: + - path: "convex/extraction/" + provides: "Deleted -- must NOT exist" + - path: "convex/schema.ts" + provides: "Schema with all 11 extraction tables removed" + contains: "screeningJobs" + - path: "convex/maintenance/mutations.ts" + provides: "User cleanup without extraction cascade" + key_links: + - from: "convex/schema.ts" + to: "convex/_generated/api.d.ts" + via: "Convex codegen regeneration" + pattern: "No api.extraction references after codegen" +--- + + +Delete the convex/extraction/ directory, surgically remove extraction references from shared Convex modules, and remove all 11 legacy extraction tables from convex/schema.ts -- the backend teardown that eliminates the extraction data model. + +Purpose: Per D-01 Layers 5-6, backend functions are deleted after their frontend consumers (Plans 01-02), and schema tables are deleted last since they are the providers. The searchFiltersValidator import in schema.ts disappears cleanly because all its consumers (3 extraction tables) are also being deleted. + +Output: Zero extraction code in the Convex backend. Schema contains only non-extraction tables. Convex codegen regenerated to remove stale api.extraction.* types. + + + +@$HOME/.claude/get-shit-done/workflows/execute-plan.md +@$HOME/.claude/get-shit-done/templates/summary.md + + + +@.planning/PROJECT.md +@.planning/ROADMAP.md +@.planning/STATE.md +@.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md +@.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md + + + + +From convex/maintenance/mutations.ts (extraction cascade to remove, lines 38-54): +```typescript +// REMOVE entire block: +// Delete extraction jobs (cascade to papers, results, evidence units, etc.) +const extractionJobs = await ctx.db + .query("extractionJobs") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .take(BATCH_SIZE); +for (const job of extractionJobs) { + await ctx.scheduler.runAfter(0, internal.extraction.mutations.deleteExtractionInternal, { + jobId: job._id, + }); +} +if (extractionJobs.length === BATCH_SIZE) { + continue; +} +``` +KEEP: API key cleanup before, Zotero cleanup after, `internal` import (still used for internal.maintenance.mutations.cleanupDeletedUsers). + +From convex/ai/actions.ts (extraction action to remove): +- `getExtractionQuestionsConfig` import from configs (line 8) +- `generateExtractionQuestions` action (lines 61-78) +KEEP: translateQuery, translatePaperContent, screening AI actions. + +From convex/lib/rateLimit.ts: +- `"start-extraction"` rate limit key (lines 18-23) +- `v.literal("start-extraction")` validator (line 58) + +From convex/featureFlags/internal.ts: +- 7 extraction feature flag seeds (lines 47-53): extraction.enabled, extraction.pdf, extraction.insights, extraction.reviewQueue, extraction.reportBuilder, extraction.start, extraction.templates + +From convex/lib/constants.ts: +- Extraction reference in JSDoc for FREE_SIGNUP_CREDIT_GRANT (line 3): "(including extraction)" -> remove +- Extraction reference in JSDoc for ESTIMATED_CREDITS_PER_PAPER (line 14): "extraction" -> remove from list + +From convex/lib/queryBounds.ts: +- MAX_EXTRACTION_JOBS_PER_USER (lines 9-10) +- MAX_EVIDENCE_UNITS_PER_PAPER (lines 13-14) +- MAX_REVIEWS_PER_JOB (lines 18-19) +- Extraction reference in comment on MAX_SCREENING_JOBS_PER_USER (line 30): "Matches extraction job limit for consistency" -> simplify + +From convex/schema.ts: +- `searchFiltersValidator` import from ./extraction/validators (line 4) +- 11 extraction tables (lines 316-781): extractionJobs, extractionQuestions, extractionPapers, extractionEvidenceUnits, extractionResults, extractionResultReviews, extractionSavedViews, extractionWorkflowTemplates, extractionReportSnapshots, extractionJobStats, extractionRunDiffs + + + + + + + Task 1: Delete convex/extraction/ and surgically edit shared Convex modules + + convex/extraction/ (32 files -- rm -rf) + convex/maintenance/mutations.ts (surgical edit) + convex/ai/actions.ts (surgical edit) + convex/lib/rateLimit.ts (surgical edit) + convex/featureFlags/internal.ts (surgical edit) + convex/lib/constants.ts (surgical edit) + convex/lib/queryBounds.ts (surgical edit) + + + convex/maintenance/mutations.ts + convex/ai/actions.ts + convex/lib/rateLimit.ts + convex/featureFlags/internal.ts + convex/lib/constants.ts + convex/lib/queryBounds.ts + + +Per D-01 Layer 5: delete the extraction backend directory AND surgically edit shared Convex modules BEFORE touching schema (Layer 6). + +**Step 1: Surgical edits to shared Convex modules** (do these BEFORE deleting convex/extraction/ so the `internal` import can still resolve): + +**convex/maintenance/mutations.ts:** +Remove the entire extraction job cascade delete block (around lines 38-54). This block: +- Queries `extractionJobs` table by user +- Schedules `internal.extraction.mutations.deleteExtractionInternal` for each job +- Has a batch continuation check +Remove it entirely. Keep the API key cleanup before it and the Zotero connection cleanup after it. The `internal` import on line 3 stays because it is still used for `internal.maintenance.mutations.cleanupDeletedUsers` (around line 79). + +**convex/ai/actions.ts:** +1. Remove `getExtractionQuestionsConfig` from the import block (around line 8) from `../../lib/ai/core/configs`. +2. Remove the entire `generateExtractionQuestions` action definition (around lines 61-78). +Keep all other AI actions (translateQuery, translatePaperContent, screening, etc.). + +**convex/lib/rateLimit.ts:** +1. Remove the `"start-extraction"` rate limit key definition (around lines 18-23): + ```typescript + // REMOVE: + "start-extraction": { + kind: "token bucket", + rate: 5, + period: HOUR, + capacity: 3, + }, + ``` +2. Remove the `v.literal("start-extraction")` from the consume validator union (around line 58). + +**convex/featureFlags/internal.ts:** +Remove 7 extraction feature flag seed entries (around lines 47-53): +```typescript +// REMOVE all 7 lines: +{ key: "extraction.enabled", ... }, +{ key: "extraction.pdf", ... }, +{ key: "extraction.insights", ... }, +{ key: "extraction.reviewQueue", ... }, +{ key: "extraction.reportBuilder", ... }, +{ key: "extraction.start", ... }, +{ key: "extraction.templates", ... }, +``` +Keep credits.*, subscriptions.* seeds and all function definitions. + +**convex/lib/constants.ts:** +1. In JSDoc for `FREE_SIGNUP_CREDIT_GRANT` (around line 3): change `"Lets free users experience server-side AI (including extraction) before committing to a plan."` to `"Lets free users experience server-side AI before committing to a plan."` +2. In JSDoc for `ESTIMATED_CREDITS_PER_PAPER` (around line 14): change `"batch AI operations (screening, translation, extraction)"` to `"batch AI operations (screening, translation)"` + +**convex/lib/queryBounds.ts:** +1. Remove `MAX_EXTRACTION_JOBS_PER_USER` constant and its JSDoc (around lines 9-10). +2. Remove `MAX_EVIDENCE_UNITS_PER_PAPER` constant and its JSDoc (around lines 13-14). +3. Remove `MAX_REVIEWS_PER_JOB` constant and its JSDoc (around lines 18-19). +4. Simplify `MAX_SCREENING_JOBS_PER_USER` comment (around line 30): change `"Matches extraction job limit for consistency."` to just `"Maximum screening jobs listed per user."` + +**Step 2: Delete convex/extraction/ directory:** +```bash +rm -rf convex/extraction/ +``` +This is 32 files, ~9,610 LoC. After deleting, the `internal.extraction.*` and `api.extraction.*` references in _generated/api.d.ts will be stale (regenerated in Task 2 via schema edit + codegen). + + + test ! -d convex/extraction && ! grep -n "extraction" convex/maintenance/mutations.ts && ! grep -n "getExtractionQuestionsConfig\|generateExtractionQuestions" convex/ai/actions.ts && ! grep -n "start-extraction" convex/lib/rateLimit.ts && ! grep -n "extraction\." convex/featureFlags/internal.ts && ! grep -n "MAX_EXTRACTION\|MAX_EVIDENCE\|MAX_REVIEWS" convex/lib/queryBounds.ts && echo "CONVEX CLEAN" + + + - `test ! -d convex/extraction` passes (directory gone) + - `grep -c "extractionJobs\|deleteExtractionInternal" convex/maintenance/mutations.ts` returns 0 + - `grep -c "internal" convex/maintenance/mutations.ts` returns at least 1 (internal import preserved for maintenance mutations) + - `grep -c "getExtractionQuestionsConfig\|generateExtractionQuestions" convex/ai/actions.ts` returns 0 + - `grep -c "translateQuery" convex/ai/actions.ts` returns at least 1 (translation action preserved) + - `grep -c "start-extraction" convex/lib/rateLimit.ts` returns 0 + - `grep -c "extraction\." convex/featureFlags/internal.ts` returns 0 + - `grep -c "credits.enabled" convex/featureFlags/internal.ts` returns at least 1 (non-extraction flags preserved) + - `grep -c "MAX_EXTRACTION\|MAX_EVIDENCE\|MAX_REVIEWS" convex/lib/queryBounds.ts` returns 0 + - `grep -c "MAX_SCREENING" convex/lib/queryBounds.ts` returns at least 1 (screening bounds preserved) + - `grep -c "extraction" convex/lib/constants.ts` returns 0 + + convex/extraction/ deleted. All 6 shared Convex modules surgically cleaned of extraction references. Non-extraction functionality (screening, billing, maintenance, translations) fully preserved. + + + + Task 2: Remove extraction tables from schema and regenerate Convex types + + convex/schema.ts + + + convex/schema.ts + + +Per D-01 Layer 6: remove the searchFiltersValidator import and all 11 legacy extraction tables from convex/schema.ts. This is the LAST deletion step for data model artifacts. + +**CRITICAL CONTEXT (from RESEARCH.md Pitfall 2):** The `searchFiltersValidator` import on line 4 is from `./extraction/validators` which was deleted in Task 1. The import AND all 11 tables that consume it are removed together. This is safe because `searchFiltersValidator` is NOT used by any non-extraction table (verified in RESEARCH.md). + +**Step 1: Remove import** (line 4): +```typescript +// REMOVE: +import { searchFiltersValidator } from "./extraction/validators"; +``` + +**Step 2: Remove all 11 extraction tables** (around lines 316-781): +Remove the entire block from the `// EXTRACTION JOBS` section header through the end of the `extractionRunDiffs` table definition. The 11 tables to remove are: +1. `extractionJobs` (with all its fields and indexes) +2. `extractionQuestions` (with all its fields and indexes) +3. `extractionPapers` (with all its fields and indexes) +4. `extractionEvidenceUnits` (with all its fields and indexes) +5. `extractionResults` (with all its fields and indexes) +6. `extractionResultReviews` (with all its fields and indexes) +7. `extractionSavedViews` (with all its fields and indexes) +8. `extractionWorkflowTemplates` (with all its fields and indexes) +9. `extractionReportSnapshots` (with all its fields and indexes) +10. `extractionJobStats` (with all its fields and indexes) +11. `extractionRunDiffs` (with all its fields and indexes) + +The next RETAINED table after the deletion block starts with the `// SCREENING JOBS` section: +```typescript +// Keep this and everything after: +screeningJobs: defineTable({ +``` + +Also keep everything BEFORE the extraction block (models, featureFlags, users, credits, creditTransactions, subscriptions, billingCustomers, stripeEventLogs, auditLogs, walletAllowedOrigins, walletKeys, apiKeys, zoteroConnections, zoteroOAuthTokens). + +**Step 3: Regenerate Convex types** (per RESEARCH.md Pitfall 1): +```bash +npx convex codegen +``` +This regenerates `convex/_generated/api.d.ts` to remove stale `api.extraction.*` references. If `npx convex codegen` fails, try `npx convex dev --once` or check Convex docs for the exact regeneration command. + +**Step 4: Verify clean compilation:** +```bash +npx tsc --noEmit 2>&1 | head -50 +``` +If there are errors, they represent dangling references missed in Plans 01-03. Fix them before proceeding. + + + ! grep -n "searchFiltersValidator\|extractionJobs\|extractionPapers\|extractionQuestions\|extractionEvidenceUnits\|extractionResults\|extractionResultReviews\|extractionSavedViews\|extractionWorkflowTemplates\|extractionReportSnapshots\|extractionJobStats\|extractionRunDiffs" convex/schema.ts && grep -q "screeningJobs" convex/schema.ts && echo "SCHEMA CLEAN" + + + - `grep -c "searchFiltersValidator" convex/schema.ts` returns 0 + - `grep -c "extractionJobs" convex/schema.ts` returns 0 + - `grep -c "extractionPapers" convex/schema.ts` returns 0 + - `grep -c "extractionQuestions" convex/schema.ts` returns 0 + - `grep -c "extractionEvidenceUnits" convex/schema.ts` returns 0 + - `grep -c "extractionResults" convex/schema.ts` returns 0 + - `grep -c "extractionResultReviews" convex/schema.ts` returns 0 + - `grep -c "extractionSavedViews" convex/schema.ts` returns 0 + - `grep -c "extractionWorkflowTemplates" convex/schema.ts` returns 0 + - `grep -c "extractionReportSnapshots" convex/schema.ts` returns 0 + - `grep -c "extractionJobStats" convex/schema.ts` returns 0 + - `grep -c "extractionRunDiffs" convex/schema.ts` returns 0 + - `grep -c "screeningJobs" convex/schema.ts` returns at least 1 (screening tables preserved) + - `grep -c "users" convex/schema.ts` returns at least 1 (user tables preserved) + + All 11 legacy extraction tables removed from schema. searchFiltersValidator import removed. Convex types regenerated. Schema contains only non-extraction tables. + + + + + +## Trust Boundaries + +| Boundary | Description | +|----------|-------------| +| Backend data model | Schema table definitions are the foundation of all Convex operations. Incorrect removal can break non-extraction queries. | + +## STRIDE Threat Register + +| Threat ID | Category | Component | Disposition | Mitigation Plan | +|-----------|----------|-----------|-------------|-----------------| +| T-88-05 | Denial of Service | Schema breakage from removing non-extraction tables | mitigate | Read convex/schema.ts before editing. Remove ONLY the 11 extraction tables (verified by exact table names in RESEARCH.md). Verify screeningJobs and all other tables survive via grep. | +| T-88-06 | Denial of Service | Stale _generated/api.d.ts after schema change | mitigate | Run `npx convex codegen` after schema edit to regenerate types (Pitfall 1 from RESEARCH.md). | +| T-88-07 | Denial of Service | Maintenance mutation break from removed internal.extraction reference | mitigate | Remove the entire extraction cascade block from maintenance/mutations.ts (Pitfall 6 from RESEARCH.md). Verify `internal` import survives for non-extraction uses. | + + + +After both tasks complete: +1. `test ! -d convex/extraction` -- extraction backend directory gone +2. `grep -c "extraction" convex/schema.ts` returns 0 -- zero extraction references in schema +3. `grep -c "screeningJobs" convex/schema.ts` returns >= 1 -- screening preserved +4. `grep -rn "extraction" convex/maintenance/ convex/ai/ convex/lib/rateLimit.ts convex/featureFlags/ convex/lib/constants.ts convex/lib/queryBounds.ts` returns 0 -- zero extraction references in shared Convex modules +5. `npx tsc --noEmit` -- should now pass or be close to passing (remaining issues resolved in Plan 04) + + + +- convex/extraction/ directory deleted (32 files, ~9,610 LoC) +- All 11 extraction tables removed from convex/schema.ts +- searchFiltersValidator import removed from convex/schema.ts +- All 6 shared Convex modules surgically cleaned of extraction references +- Convex types regenerated via codegen +- Non-extraction tables, functions, and configurations fully preserved + + + +After completion, create `.planning/phases/88-scorched-earth-teardown/88-03-SUMMARY.md` + diff --git a/.planning/phases/88-scorched-earth-teardown/88-04-PLAN.md b/.planning/phases/88-scorched-earth-teardown/88-04-PLAN.md new file mode 100644 index 000000000..33e026e8c --- /dev/null +++ b/.planning/phases/88-scorched-earth-teardown/88-04-PLAN.md @@ -0,0 +1,370 @@ +--- +phase: 88-scorched-earth-teardown +plan: 04 +type: execute +wave: 4 +depends_on: [88-03] +files_modified: + - convex/convex.config.ts + - convex/workpool.ts + - package.json + - messages/en-US.json + - messages/en-GB.json + - messages/zh.json + - messages/fr.json + - messages/hi.json + - messages/ja.json +autonomous: true +requirements: + - TEAR-04 + - TEAR-05 + - TEAR-08 + - TEAR-10 +must_haves: + truths: + - "@convex-dev/rag is absent from convex.config.ts and package.json" + - "pdfProcessingPool is absent from convex/workpool.ts" + - "screeningPool is present and functional in convex/workpool.ts" + - "Zero extraction i18n keys exist in any locale file" + - "tsc --noEmit returns zero errors" + - "pnpm test passes with no extraction test failures" + artifacts: + - path: "convex/convex.config.ts" + provides: "Component config with rag and default workpool removed" + contains: "screeningWorkpool" + - path: "convex/workpool.ts" + provides: "Workpool exports with only screeningPool" + contains: "screeningPool" + - path: "messages/en-US.json" + provides: "English locale with zero extraction keys" + key_links: + - from: "convex/convex.config.ts" + to: "convex/workpool.ts" + via: "components.screeningWorkpool" + pattern: "screeningWorkpool.*screeningPool" +--- + + +Remove RAG component and default workpool from Convex config, uninstall dead dependencies, clean all 6 locale files of extraction i18n keys, and run final compilation + test verification to confirm the entire teardown is clean. + +Purpose: Per D-01 Layers 7-8, component config and package cleanup happen after all code referencing those components is deleted (Plans 01-03). i18n cleanup is the final content layer. The phase gate is tsc --noEmit zero errors + pnpm test passing (TEAR-10, D-17). + +Output: Clean repo with zero extraction artifacts. TypeScript compiles. Tests pass. Ready for Phase 89 (Core Schema and Workflow Skeleton). + + + +@$HOME/.claude/get-shit-done/workflows/execute-plan.md +@$HOME/.claude/get-shit-done/templates/summary.md + + + +@.planning/PROJECT.md +@.planning/ROADMAP.md +@.planning/STATE.md +@.planning/phases/88-scorched-earth-teardown/88-CONTEXT.md +@.planning/phases/88-scorched-earth-teardown/88-PATTERNS.md + + + + +convex/convex.config.ts target state (after edit): +```typescript +import { defineApp } from "convex/server"; +import stripe from "@convex-dev/stripe/convex.config.js"; +import workflow from "@convex-dev/workflow/convex.config.js"; +import screeningWorkpool from "@convex-dev/workpool/convex.config.js"; + +const app = defineApp(); +app.use(stripe); +app.use(workflow); +app.use(screeningWorkpool, { name: "screeningWorkpool" }); + +export default app; +``` + +convex/workpool.ts target state (after edit): +```typescript +import { Workpool } from "@convex-dev/workpool"; +import { components } from "./_generated/api"; + +// For bulk screening operations +export const screeningPool = new Workpool(components.screeningWorkpool, { + maxParallelism: 5, + retryActionsByDefault: true, + defaultRetryBehavior: { + maxAttempts: 3, + initialBackoffMs: 2000, + base: 2, + }, +}); +``` + +i18n keys to remove from all 6 locale files: +- Entire top-level "extraction" object (~140 keys) +- Entire top-level "extractionView" object (~14 keys) +- common.extraction +- common.extractionError +- toast.extractionPlanRequired +- errorPages.extractionUnavailable +- errorPages.extractionErrorDescription +- jobStatus.extractionProgress +- jobStatus.loadingExtractionResults +- pricing.proFeature2 (if value is "Data extraction (Pro-only)" or equivalent) + +Packages to uninstall: +- @convex-dev/rag +- pdfjs-dist (only 2 import sites, both in deleted extraction code -- verified in RESEARCH.md) + + + + + + + Task 1: Remove RAG and workpool from config, uninstall dead dependencies + + convex/convex.config.ts + convex/workpool.ts + package.json + + + convex/convex.config.ts + convex/workpool.ts + package.json + + +Per D-01 Layer 7 and D-03/D-04: remove RAG component, default workpool component, and dead dependencies. + +**convex/convex.config.ts (per PATTERNS.md exact target state):** +Remove these 4 lines: +1. `import rag from "@convex-dev/rag/convex.config.js";` (line 3) +2. `import workpool from "@convex-dev/workpool/convex.config.js";` (line 5) +3. `app.use(rag);` (line 10) +4. `app.use(workpool);` (line 12) + +The resulting file should be exactly: +```typescript +import { defineApp } from "convex/server"; +import stripe from "@convex-dev/stripe/convex.config.js"; +import workflow from "@convex-dev/workflow/convex.config.js"; +import screeningWorkpool from "@convex-dev/workpool/convex.config.js"; + +const app = defineApp(); +app.use(stripe); +app.use(workflow); +app.use(screeningWorkpool, { name: "screeningWorkpool" }); + +export default app; +``` + +Per D-03/D-04: the default `workpool` component backed `pdfProcessingPool`. Since `pdfProcessingPool` was deleted, its component registration is dead code. The `screeningWorkpool` (named component) is KEPT because it backs the live `screeningPool`. Per RESEARCH.md Pitfall 4: removing both import and app.use prevents an orphaned component deploying to Convex. + +**convex/workpool.ts (per D-03, D-04, PATTERNS.md exact target state):** +Remove lines 4-14: the `pdfProcessingPool` constant, its JSDoc/comments, and the blank line. +Update the comment on the remaining `screeningPool` from `"separate from extraction to avoid cross-cancellation on cancelAll()"` to `"For bulk screening operations"`. + +The resulting file should be exactly: +```typescript +import { Workpool } from "@convex-dev/workpool"; +import { components } from "./_generated/api"; + +// For bulk screening operations +export const screeningPool = new Workpool(components.screeningWorkpool, { + maxParallelism: 5, + retryActionsByDefault: true, + defaultRetryBehavior: { + maxAttempts: 3, + initialBackoffMs: 2000, + base: 2, + }, +}); +``` + +**package.json -- uninstall dead dependencies:** +```bash +pnpm remove @convex-dev/rag pdfjs-dist +``` +Per RESEARCH.md: `@convex-dev/rag` has zero remaining import sites after convex.config.ts cleanup. `pdfjs-dist` has zero remaining import sites (only 2 existed: `convex/extraction/pdfjs_extract.ts` and `components/extraction/pdf-viewer.tsx`, both deleted in Plan 01). Per RESEARCH.md Pitfall 7: leaving unused dependencies wastes bundle size. + +After uninstall, verify lockfile is regenerated: +```bash +pnpm install +``` + + + ! grep -n "@convex-dev/rag" convex/convex.config.ts package.json && ! grep -n "pdfProcessingPool" convex/workpool.ts && grep -q "screeningPool" convex/workpool.ts && grep -q "screeningWorkpool" convex/convex.config.ts && ! grep -n "pdfjs-dist" package.json && echo "CONFIG CLEAN" + + + - `grep -c "@convex-dev/rag" convex/convex.config.ts` returns 0 + - `grep -c "@convex-dev/rag" package.json` returns 0 + - `grep -c "pdfjs-dist" package.json` returns 0 + - `grep -c "pdfProcessingPool" convex/workpool.ts` returns 0 + - `grep -c "app.use(workpool)" convex/convex.config.ts` returns 0 (default workpool removed) + - `grep -c "screeningPool" convex/workpool.ts` returns at least 1 (screening pool preserved per D-03) + - `grep -c "screeningWorkpool" convex/convex.config.ts` returns at least 1 (screening component preserved per D-04) + - `grep -c "stripe" convex/convex.config.ts` returns at least 1 (Stripe preserved) + - `grep -c "workflow" convex/convex.config.ts` returns at least 1 (Workflow preserved) + + RAG component and default workpool removed from config. pdfProcessingPool deleted from workpool.ts. screeningPool and screeningWorkpool fully preserved. @convex-dev/rag and pdfjs-dist uninstalled. + + + + Task 2: Clean extraction i18n keys from all 6 locale files + + messages/en-US.json + messages/en-GB.json + messages/zh.json + messages/fr.json + messages/hi.json + messages/ja.json + + + messages/en-US.json (read to understand the extraction key structure -- other locales mirror the same keys) + + +Per D-01 Layer 8 and TEAR-08: remove ALL extraction i18n keys from all 6 locale files. + +For EACH of the 6 locale files (`messages/en-US.json`, `messages/en-GB.json`, `messages/zh.json`, `messages/fr.json`, `messages/hi.json`, `messages/ja.json`): + +1. **Remove entire top-level "extraction" object** (~140 keys). This is a top-level JSON key containing all extraction UI strings. + +2. **Remove entire top-level "extractionView" object** (~14 keys). This is a separate top-level JSON key for extraction view mode strings. + +3. **Remove scattered extraction keys** from other sections: + - `common.extraction` (nav label) + - `common.extractionError` (error label) + - `toast.extractionPlanRequired` (plan gate toast) + - `errorPages.extractionUnavailable` (error page title) + - `errorPages.extractionErrorDescription` (error page description) + - `jobStatus.extractionProgress` (progress label) + - `jobStatus.loadingExtractionResults` (loading state) + - `pricing.proFeature2` -- evaluate per locale. If the value is specifically about "Data extraction" as a feature (e.g., "Data extraction (Pro-only)"), remove it. If the value describes the Pro tier generally without specifically mentioning extraction, keep it. + +4. **Validate JSON syntax** after editing each file. Per RESEARCH.md Pitfall 3: removing keys from the middle of a JSON object can leave trailing commas that break JSON parsing. + + After editing ALL 6 files, run: + ```bash + for f in messages/en-US.json messages/en-GB.json messages/zh.json messages/fr.json messages/hi.json messages/ja.json; do + node --input-type=module -e "import{readFileSync as r}from'node:fs';JSON.parse(r('$f','utf8'))" && echo "$f OK" || echo "$f BROKEN" + done + ``` + All 6 files must output "OK". + +NOTE: The actual locale files on disk are `en-US.json, en-GB.json, zh.json, fr.json, hi.json, ja.json` (verified in RESEARCH.md). The REQUIREMENTS.md lists different locale names (en, fr, es, de, ar, zh) -- use the on-disk file list. + + + ! grep -rl '"extraction"' messages/ && ! grep -rl '"extractionView"' messages/ && ! grep -rl 'extractionPlanRequired\|extractionUnavailable\|extractionErrorDescription\|extractionProgress\|loadingExtractionResults' messages/ && for f in messages/en-US.json messages/en-GB.json messages/zh.json messages/fr.json messages/hi.json messages/ja.json; do node --input-type=module -e "import{readFileSync as r}from'node:fs';JSON.parse(r('$f','utf8'))" || exit 1; done && echo "I18N CLEAN" + + + - `grep -rl '"extraction"' messages/` returns no files (zero extraction top-level keys) + - `grep -rl '"extractionView"' messages/` returns no files + - `grep -rl "extractionPlanRequired" messages/` returns no files + - `grep -rl "extractionUnavailable" messages/` returns no files + - `grep -rl "extractionProgress" messages/` returns no files + - Each of the 6 locale files passes JSON.parse validation without error + - `grep -c "screening" messages/en-US.json` returns at least 1 (screening keys preserved) + - `grep -c "common" messages/en-US.json` returns at least 1 (non-extraction common keys preserved) + + All 6 locale files have zero extraction i18n keys. All JSON files are syntactically valid. Non-extraction keys (screening, common, toast, pricing, etc.) are preserved. + + + + Task 3: Final compilation and test verification + None (verification only) + + convex/schema.ts (verify extraction tables are gone) + convex/convex.config.ts (verify clean config) + + +Run the full phase gate per TEAR-10 and D-17. + +**Step 1: TypeScript compilation check (TEAR-10):** +```bash +npx tsc --noEmit +``` +Must return zero errors. If errors exist, they are dangling references missed in Plans 01-04. Fix each one: +- Missing imports: remove the import line +- Dead exports: remove the export +- Type references to deleted modules: remove the type usage +- Any reference to `api.extraction.*` or `internal.extraction.*`: remove (these should have been regenerated by `npx convex codegen` in Plan 03) + +**Step 2: Test suite verification (D-17):** +```bash +pnpm test +``` +Must pass with zero failures. The test count will be lower than the pre-teardown count of 1435 tests (23+ extraction test files were deleted in Plan 01). This is expected per D-16. + +If any test fails because it imports from a deleted extraction module, that test was missed in Plan 01's deletion -- delete it now. + +**Step 3: Verify success criteria from ROADMAP.md:** +```bash +# 1. convex/extraction/ and lib/extraction/ directories no longer exist +test ! -d convex/extraction && test ! -d lib/extraction && echo "DIRS GONE" + +# 2. Zero legacy extraction tables in schema +grep -c "extractionJobs\|extractionPapers\|extractionQuestions\|extractionEvidenceUnits\|extractionResults\|extractionResultReviews\|extractionSavedViews\|extractionWorkflowTemplates\|extractionReportSnapshots\|extractionJobStats\|extractionRunDiffs" convex/schema.ts + +# 3. @convex-dev/rag absent +grep -c "@convex-dev/rag" convex/convex.config.ts package.json + +# 4. tsc --noEmit zero errors (done in Step 1) + +# 5. Zero extraction i18n keys +grep -rl "extraction" messages/ | grep -v ".bak" || echo "NO EXTRACTION KEYS" +``` + + + npx tsc --noEmit 2>&1 | tail -1 && pnpm test 2>&1 | tail -5 + + + - `npx tsc --noEmit` exits with code 0 (zero errors) + - `pnpm test` exits with code 0 (all remaining tests pass) + - `test ! -d convex/extraction && test ! -d lib/extraction` passes + - `grep -c "extractionJobs" convex/schema.ts` returns 0 + - `grep -c "@convex-dev/rag" convex/convex.config.ts package.json` returns 0 + - `grep -rl "extraction" messages/` returns no files + + Full phase gate passes: tsc --noEmit zero errors, pnpm test all green, all 5 ROADMAP success criteria verified. Phase 88 Scorched-Earth Teardown is complete. + + + + + +## Trust Boundaries + +| Boundary | Description | +|----------|-------------| +| Convex component registry | Removing components from convex.config.ts affects what deploys to Convex backend | +| i18n runtime | Locale file structure must remain valid JSON for next-intl | + +## STRIDE Threat Register + +| Threat ID | Category | Component | Disposition | Mitigation Plan | +|-----------|----------|-----------|-------------|-----------------| +| T-88-08 | Denial of Service | Orphaned workpool component in Convex | mitigate | Remove BOTH the import and app.use(workpool) together (Pitfall 4 from RESEARCH.md). Verify screeningWorkpool survives. | +| T-88-09 | Denial of Service | Broken locale JSON from trailing commas | mitigate | Validate every locale file with JSON.parse after editing (Pitfall 3 from RESEARCH.md). Automated check in verify block. | +| T-88-10 | Denial of Service | screeningPool accidentally removed | mitigate | Per D-03/D-04: ONLY remove pdfProcessingPool. Verify `grep -c screeningPool convex/workpool.ts` >= 1 in acceptance criteria. | +| T-88-11 | Denial of Service | pdfjs-dist needed by Phase 90 | accept | Phase 90 uses `unpdf` (serverless-bundled PDF.js v5), not `pdfjs-dist`. Clean break per RESEARCH.md Open Question 1 recommendation. | + + + +After all 3 tasks complete, the full ROADMAP.md success criteria are met: +1. `convex/extraction/` and `lib/extraction/` directories no longer exist on disk +2. `convex/schema.ts` contains zero legacy extraction tables +3. `@convex-dev/rag` is absent from `convex/convex.config.ts` and uninstalled from `package.json` +4. `tsc --noEmit` returns zero errors with no dangling imports or dead exports +5. All six locale files contain zero `extraction.*` keys + + + +- @convex-dev/rag and pdfjs-dist uninstalled from package.json +- RAG component and default workpool removed from convex.config.ts +- pdfProcessingPool removed from convex/workpool.ts; screeningPool preserved +- All 6 locale files have zero extraction i18n keys and valid JSON syntax +- `npx tsc --noEmit` returns zero errors (TEAR-10) +- `pnpm test` passes with zero failures (D-17) +- All 5 ROADMAP.md success criteria for Phase 88 verified + + + +After completion, create `.planning/phases/88-scorched-earth-teardown/88-04-SUMMARY.md` + From 3d04e7545f32c445f5c9f94b8b024917238b8f55 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 14 Apr 2026 23:59:53 +0100 Subject: [PATCH 011/421] feat(88-01): delete extraction UI directories and standalone files - Remove app/extraction/ (7 files -- UI routes and pages) - Remove components/extraction/ (44 files -- feature components) - Remove lib/extraction/ (15 files -- UI helpers) - Remove lib/store/extraction.ts (Zustand extraction store) - Remove lib/types/extraction.types.ts (extraction type definitions) - Remove lib/pdf/download.ts (extraction-only PDF download utility) - Remove convex/debug.ts and convex/debug_papers.ts (extraction debug queries) --- app/extraction/[jobId]/page.tsx | 1010 ----------------- app/extraction/error.tsx | 38 - app/extraction/layout.tsx | 27 - app/extraction/new/layout.tsx | 23 - app/extraction/new/page.tsx | 20 - app/extraction/page.tsx | 69 -- components/extraction/bar-visualization.tsx | 4 - components/extraction/bulk-actions-bar.tsx | 75 -- components/extraction/confidence-badge.tsx | 68 -- components/extraction/confidence-filter.tsx | 80 -- components/extraction/confidence-ring.tsx | 48 - components/extraction/disagreement-list.tsx | 141 --- components/extraction/export-dialog.tsx | 194 ---- .../extraction/extraction-access-gate.tsx | 47 - .../extraction-citation-sidebar.tsx | 149 --- .../extraction/extraction-command-center.tsx | 162 --- .../extraction/extraction-plan-gate.tsx | 165 --- .../extraction/extraction-results-shell.tsx | 111 -- components/extraction/grouped-answer-row.tsx | 78 -- components/extraction/history-selector.tsx | 106 -- components/extraction/insights-overview.tsx | 138 --- .../extraction/insights-question-panel.tsx | 249 ---- components/extraction/job-creator.tsx | 426 ------- components/extraction/job-list-item.tsx | 249 ---- components/extraction/manual-items.tsx | 172 --- components/extraction/pdf-citation-panel.tsx | 203 ---- components/extraction/pdf-page-controls.tsx | 98 -- components/extraction/pdf-toolbar.tsx | 124 -- components/extraction/pdf-viewer.tsx | 429 ------- components/extraction/question-builder.tsx | 645 ----------- components/extraction/question-list-item.tsx | 73 -- components/extraction/report-builder.tsx | 504 -------- components/extraction/results-toolbar.tsx | 197 ---- .../extraction/results-views/card-view.tsx | 359 ------ .../results-views/highlighted-text.tsx | 72 -- components/extraction/results-views/index.ts | 3 - .../extraction/results-views/split-view.tsx | 279 ----- .../extraction/results-views/table-view.tsx | 461 -------- components/extraction/review-queue.tsx | 427 ------- components/extraction/search-input.tsx | 62 - components/extraction/smart-pagination.tsx | 158 --- components/extraction/source-selector.tsx | 33 - components/extraction/source-summary.tsx | 18 - components/extraction/stacked-answer-bars.tsx | 117 -- components/extraction/status-filter.tsx | 129 --- components/extraction/summary-cards.tsx | 156 --- components/extraction/zotero-selector.tsx | 454 -------- convex/debug.ts | 23 - convex/debug_papers.ts | 23 - lib/extraction/answer-grouping.ts | 247 ---- lib/extraction/card-thresholds.ts | 77 -- lib/extraction/citation-panel.ts | 64 -- lib/extraction/citations.ts | 151 --- lib/extraction/confidence-messages.ts | 38 - lib/extraction/export.ts | 295 ----- lib/extraction/feature-flags.ts | 3 - lib/extraction/filtering.ts | 134 --- lib/extraction/insights.ts | 717 ------------ lib/extraction/pdf-highlight.ts | 27 - lib/extraction/pdfjs-text.ts | 57 - lib/extraction/question-status.ts | 46 - lib/extraction/reviews.ts | 42 - lib/extraction/status-filter-options.ts | 12 - lib/extraction/types.ts | 5 - lib/pdf/download.ts | 565 --------- lib/store/extraction.ts | 191 ---- lib/types/extraction.types.ts | 230 ---- 67 files changed, 11797 deletions(-) delete mode 100644 app/extraction/[jobId]/page.tsx delete mode 100644 app/extraction/error.tsx delete mode 100644 app/extraction/layout.tsx delete mode 100644 app/extraction/new/layout.tsx delete mode 100644 app/extraction/new/page.tsx delete mode 100644 app/extraction/page.tsx delete mode 100644 components/extraction/bar-visualization.tsx delete mode 100644 components/extraction/bulk-actions-bar.tsx delete mode 100644 components/extraction/confidence-badge.tsx delete mode 100644 components/extraction/confidence-filter.tsx delete mode 100644 components/extraction/confidence-ring.tsx delete mode 100644 components/extraction/disagreement-list.tsx delete mode 100644 components/extraction/export-dialog.tsx delete mode 100644 components/extraction/extraction-access-gate.tsx delete mode 100644 components/extraction/extraction-citation-sidebar.tsx delete mode 100644 components/extraction/extraction-command-center.tsx delete mode 100644 components/extraction/extraction-plan-gate.tsx delete mode 100644 components/extraction/extraction-results-shell.tsx delete mode 100644 components/extraction/grouped-answer-row.tsx delete mode 100644 components/extraction/history-selector.tsx delete mode 100644 components/extraction/insights-overview.tsx delete mode 100644 components/extraction/insights-question-panel.tsx delete mode 100644 components/extraction/job-creator.tsx delete mode 100644 components/extraction/job-list-item.tsx delete mode 100644 components/extraction/manual-items.tsx delete mode 100644 components/extraction/pdf-citation-panel.tsx delete mode 100644 components/extraction/pdf-page-controls.tsx delete mode 100644 components/extraction/pdf-toolbar.tsx delete mode 100644 components/extraction/pdf-viewer.tsx delete mode 100644 components/extraction/question-builder.tsx delete mode 100644 components/extraction/question-list-item.tsx delete mode 100644 components/extraction/report-builder.tsx delete mode 100644 components/extraction/results-toolbar.tsx delete mode 100644 components/extraction/results-views/card-view.tsx delete mode 100644 components/extraction/results-views/highlighted-text.tsx delete mode 100644 components/extraction/results-views/index.ts delete mode 100644 components/extraction/results-views/split-view.tsx delete mode 100644 components/extraction/results-views/table-view.tsx delete mode 100644 components/extraction/review-queue.tsx delete mode 100644 components/extraction/search-input.tsx delete mode 100644 components/extraction/smart-pagination.tsx delete mode 100644 components/extraction/source-selector.tsx delete mode 100644 components/extraction/source-summary.tsx delete mode 100644 components/extraction/stacked-answer-bars.tsx delete mode 100644 components/extraction/status-filter.tsx delete mode 100644 components/extraction/summary-cards.tsx delete mode 100644 components/extraction/zotero-selector.tsx delete mode 100644 convex/debug.ts delete mode 100644 convex/debug_papers.ts delete mode 100644 lib/extraction/answer-grouping.ts delete mode 100644 lib/extraction/card-thresholds.ts delete mode 100644 lib/extraction/citation-panel.ts delete mode 100644 lib/extraction/citations.ts delete mode 100644 lib/extraction/confidence-messages.ts delete mode 100644 lib/extraction/export.ts delete mode 100644 lib/extraction/feature-flags.ts delete mode 100644 lib/extraction/filtering.ts delete mode 100644 lib/extraction/insights.ts delete mode 100644 lib/extraction/pdf-highlight.ts delete mode 100644 lib/extraction/pdfjs-text.ts delete mode 100644 lib/extraction/question-status.ts delete mode 100644 lib/extraction/reviews.ts delete mode 100644 lib/extraction/status-filter-options.ts delete mode 100644 lib/extraction/types.ts delete mode 100644 lib/pdf/download.ts delete mode 100644 lib/store/extraction.ts delete mode 100644 lib/types/extraction.types.ts diff --git a/app/extraction/[jobId]/page.tsx b/app/extraction/[jobId]/page.tsx deleted file mode 100644 index 05e08fed8..000000000 --- a/app/extraction/[jobId]/page.tsx +++ /dev/null @@ -1,1010 +0,0 @@ -"use client"; - -import { useMutation } from "convex/react"; -import { api } from "@/convex/_generated/api"; -import type { Id } from "@/convex/_generated/dataModel"; -import { useParams, useRouter } from "next/navigation"; -import { useTranslations, useLocale, useFormatter, useNow } from "next-intl"; -import { Button } from "@/components/ui/button"; -import { - Loader2, - FileText, - RefreshCw, - Trash2, - XCircle, - ChevronLeft, -} from "lucide-react"; -import Link from "next/link"; -import { motion } from "motion/react"; -import { PageWrapper } from "@/components/PageWrapper"; -import { CommandCenterContainer } from "@/components/command-center"; -import { TwoColumnLayout } from "@/components/layout/two-column-layout"; -import { cn } from "@/lib/utils"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -} from "@/components/ui/alert-dialog"; -import { useState, useEffect, useMemo, useCallback, useRef } from "react"; -import { useAppToast } from "@/lib/toast"; -import { ResultsToolbar, type ResultsSortBy } from "@/components/extraction/results-toolbar"; -import { TableView, CardView, SplitView } from "@/components/extraction/results-views"; -import { SmartPagination } from "@/components/extraction/smart-pagination"; -import { BulkActionsBar } from "@/components/extraction/bulk-actions-bar"; -import { ExportDialog } from "@/components/extraction/export-dialog"; -import { InsightsOverview } from "@/components/extraction/insights-overview"; -import { InsightsQuestionPanel } from "@/components/extraction/insights-question-panel"; -import { ReviewQueue } from "@/components/extraction/review-queue"; -import { ReportBuilder } from "@/components/extraction/report-builder"; -import { ExtractionResultsShell } from "@/components/extraction/extraction-results-shell"; -import { ExtractionCitationSidebar } from "@/components/extraction/extraction-citation-sidebar"; -import { useSelection } from "@/lib/hooks/use-selection"; -import { useIsMobile } from "@/lib/hooks"; -import { useUrlState } from "@/lib/hooks/use-url-state"; -import { useDebouncedValue } from "@/lib/hooks/use-debounced-value"; -import { useFeatureFlag } from "@/lib/feature-flags/hook"; -import type { Infer } from "convex/values"; -import type { extractionSavedViewValidator } from "@/convex/extraction/validators"; -import type { CitationPanelPayload } from "@/lib/extraction/citation-panel"; -import { useExtractionCitationPanelStore } from "@/lib/store"; -import { AuthStatePanel } from "@/components/auth/auth-state-panel"; -import { - useProtectedPaginatedQuery, - useProtectedQuery, -} from "@/lib/auth/use-auth-query"; -import { - defaultFilters, - filterPapers, - preprocessPapers, - type FilterState, - type PaperWithResults, - type Question, -} from "@/lib/extraction/filtering"; -import { getAuthSensitiveListRenderState } from "@/lib/auth/list-render-state"; -import { resolveEffectivePlan } from "@/lib/billing/entitlements"; - -export default function JobDetailPage() { - const toast = useAppToast(); - const tError = useTranslations('errorPages'); - const tJob = useTranslations('jobStatus'); - const tConfirm = useTranslations('confirmations'); - const tView = useTranslations('extractionView'); - const tExtraction = useTranslations('extraction'); - const tc = useTranslations('common'); - const tPdf = useTranslations('pdfViewer'); - const locale = useLocale(); - const format = useFormatter(); - const now = useNow(); - - const params = useParams(); - const router = useRouter(); - const isMobile = useIsMobile(); - const jobId = params.jobId as Id<"extractionJobs">; - - const pdfEnabled = useFeatureFlag("extraction.pdf"); - const insightsEnabled = useFeatureFlag("extraction.insights"); - const reviewQueueEnabled = useFeatureFlag("extraction.reviewQueue"); - const reportBuilderEnabled = useFeatureFlag("extraction.reportBuilder"); - const templatesEnabled = useFeatureFlag("extraction.templates"); - - const viewModeSerialize = useCallback((v: 'table' | 'cards' | 'split') => v, []); - const viewModeDeserialize = useCallback((v: string) => v as 'table' | 'cards' | 'split', []); - - const [viewMode, setViewMode] = useUrlState<'table' | 'cards' | 'split'>( - 'view', - 'table', - viewModeSerialize, - viewModeDeserialize - ); - - const [filters, setFilters] = useState(defaultFilters); - const [searchQueryResetKey, setSearchQueryResetKey] = useState(0); - const debouncedFilters = useDebouncedValue(filters, 150); - - const [currentPage, setCurrentPage] = useState(1); - const [pageSize, setPageSize] = useState(50); - - const [activeTab, setActiveTab] = useState< - "results" | "insights" | "review" | "report" | "overview" - >("results"); - const [selectedInsightsQuestion, setSelectedInsightsQuestion] = useState(undefined); - const [resultsSortBy, setResultsSortBy] = useState('default'); - const [exportDialogOpen, setExportDialogOpen] = useState(false); - const [exportMode, setExportMode] = useState<'all' | 'selected'>('all'); - const [citationPanelPayload, setCitationPanelPayload] = useState(null); - const [mobilePane, setMobilePane] = useState<"results" | "citation">("results"); - const { expand: expandCitationPanel } = useExtractionCitationPanelStore(); - - const questionTypeLabels = useMemo(() => ({ - boolean: tExtraction('typeYesNo'), - string: tExtraction('typeText'), - number: tExtraction('typeNumber'), - array: tExtraction('typeList'), - }), [tExtraction]); - - const cancelJob = useMutation(api.extraction.mutations.cancelExtraction); - const deleteJob = useMutation(api.extraction.mutations.deleteExtraction); - const duplicateJob = useMutation( - api.extraction.mutations.duplicateExtraction, - ); - - const jobDetailsQuery = useProtectedQuery(api.extraction.queries.getJobDetails, { - jobId, - }); - const jobDetails = jobDetailsQuery.data; - const canReadJob = jobDetails?.status === "ok"; - const subscriptionQuery = useProtectedQuery(api.subscriptions.queries.getMy, {}); - const subscription = subscriptionQuery.data; - const subscriptionSettlement = subscriptionQuery.settlement; - const jobProgressQuery = useProtectedQuery( - api.extraction.queries.subscribeToJobProgress, - canReadJob ? { jobId } : "skip", - ); - const jobProgress = jobProgressQuery.data; - - const { - results: allPapers, - status: paginationStatus, - loadMore, - isDeferred: isResultsDeferred, - settlement: resultsSettlement, - hasLoadedFirstPage, - } = useProtectedPaginatedQuery( - api.extraction.queries.getJobResultsPaginated, - canReadJob ? { jobId } : "skip", - { initialNumItems: 200 }, - ); - - const isLoadingRef = useRef(false); - const hasAttemptedLoadRef = useRef(false); - useEffect(() => { - if (paginationStatus !== "LoadingMore") { - isLoadingRef.current = false; - } - }, [paginationStatus]); - - useEffect(() => { - if (!canReadJob) return; - if (paginationStatus !== "CanLoadMore") return; - if (allPapers.length >= 200) return; - if (isLoadingRef.current || hasAttemptedLoadRef.current) return; - - isLoadingRef.current = true; - hasAttemptedLoadRef.current = true; - loadMore(200); - }, [canReadJob, paginationStatus, allPapers.length, loadMore]); - - const questions: Question[] = useMemo(() => { - if (jobDetails?.status !== "ok") return []; - return jobDetails.questions.map((q: { key: string; question: string; type: string; description?: string }) => ({ - key: q.key, - question: q.question, - type: q.type as 'boolean' | 'string' | 'array' | 'number', - description: q.description, - })); - }, [jobDetails]); - - const effectiveSelectedInsightsQuestion = - selectedInsightsQuestion && questions.some((q) => q.key === selectedInsightsQuestion) - ? selectedInsightsQuestion - : questions[0]?.key; - - const papersWithResults = useMemo( - () => allPapers as PaperWithResults[], - [allPapers] - ); - - const preprocessedData = useMemo( - () => preprocessPapers(papersWithResults), - [papersWithResults] - ); - - const filteredPapers = useMemo( - () => filterPapers(papersWithResults, debouncedFilters, questions, preprocessedData, pdfEnabled), - [papersWithResults, debouncedFilters, questions, preprocessedData, pdfEnabled] - ); - - const sortedPapers = useMemo(() => { - if (resultsSortBy === 'default') return filteredPapers; - const sorted = [...filteredPapers]; - switch (resultsSortBy) { - case 'title-asc': - return sorted.sort((a, b) => (a.title || '').localeCompare(b.title || '')); - case 'title-desc': - return sorted.sort((a, b) => (b.title || '').localeCompare(a.title || '')); - case 'confidence-high': { - const avgConf = (p: PaperWithResults) => { - if (!p.results.length) return 0; - return p.results.reduce((sum, r) => sum + (r.confidence || 0), 0) / p.results.length; - }; - return sorted.sort((a, b) => avgConf(b) - avgConf(a)); - } - case 'confidence-low': { - const avgConf = (p: PaperWithResults) => { - if (!p.results.length) return 0; - return p.results.reduce((sum, r) => sum + (r.confidence || 0), 0) / p.results.length; - }; - return sorted.sort((a, b) => avgConf(a) - avgConf(b)); - } - default: - return sorted; - } - }, [filteredPapers, resultsSortBy]); - - const hasActiveResultFilters = useMemo( - () => - debouncedFilters.searchQuery.trim().length > 0 || - debouncedFilters.confidenceRange[0] > 0 || - debouncedFilters.confidenceRange[1] < 100 || - debouncedFilters.statusFilters.size > 0 || - debouncedFilters.questionFilters.size > 0, - [ - debouncedFilters.confidenceRange, - debouncedFilters.questionFilters, - debouncedFilters.searchQuery, - debouncedFilters.statusFilters, - ], - ); - const resultsRenderState = getAuthSensitiveListRenderState({ - settlement: resultsSettlement, - hasLoadedFirstPage, - visibleCount: sortedPapers.length, - hasActiveFilter: hasActiveResultFilters, - }); - - const totalPages = Math.ceil(sortedPapers.length / pageSize); - const displayedPapers = useMemo( - () => sortedPapers.slice( - (currentPage - 1) * pageSize, - currentPage * pageSize - ), - [sortedPapers, currentPage, pageSize] - ); - - - const paperIds = useMemo( - () => papersWithResults.map(p => p._id), - [papersWithResults] - ); - - const { - selectedIds, - clearSelection, - setSelection, - } = useSelection(paperIds); - - const selectedPapers = useMemo( - () => papersWithResults.filter(p => selectedIds.has(p._id)), - [papersWithResults, selectedIds] - ); - - const handleTableSelectionChange = useCallback((newIds: Set) => { - setSelection(newIds); - }, [setSelection]); - - const handleCardSelectionChange = useCallback((newIds: Set) => { - setSelection(newIds); - }, [setSelection]); - - const openCitationPanel = useCallback((payload: CitationPanelPayload) => { - setCitationPanelPayload(payload); - expandCitationPanel(); - setMobilePane("citation"); - }, [expandCitationPanel]); - - const handleCancel = async () => { - try { - await cancelJob({ jobId }); - } catch (error) { - toast.job.cancelFailed(); - } - }; - - const handleDelete = async () => { - try { - await deleteJob({ jobId }); - router.push("/extraction"); - } catch (error) { - toast.job.deleteFailed(); - } - }; - - const handleDuplicate = async () => { - try { - const result = await duplicateJob({ jobId }); - router.push(`/extraction/${result.jobId}`); - } catch (error) { - toast.job.createFailed(error); - } - }; - - const handleApplySavedView = useCallback( - (view: Infer) => { - setFilters({ - searchQuery: view?.filters?.searchQuery || "", - confidenceRange: Array.isArray(view?.filters?.confidenceRange) - ? (view.filters.confidenceRange as [number, number]) - : [0, 100], - statusFilters: new Set(view?.filters?.statusFilters || []), - questionFilters: new Map(), - }); - if (view?.sortBy) { - setResultsSortBy(view.sortBy as ResultsSortBy); - } - if (view?.viewMode && ["table", "cards", "split"].includes(view.viewMode)) { - setViewMode(view.viewMode as "table" | "cards" | "split"); - } - setCurrentPage(1); - setActiveTab("results"); - setSearchQueryResetKey((k) => k + 1); - }, - [setViewMode, setFilters, setResultsSortBy, toast, tJob, tc] - ); - - if (jobDetailsQuery.isDeferred || isResultsDeferred || jobDetails === undefined) { - return ( - - - - ); - } - - if (jobDetails.status === "unauthenticated") { - return ( - -
- -
-
- ); - } - - if (jobDetails.status === "no_access") { - return ( - -
- -
-
- ); - } - - const { job, progress } = jobDetails; - const jobProgressSafe = jobProgress?.status === "ok" ? jobProgress : null; - const resolvedProgress = jobProgressSafe - ? { - total: job.totalPapers, - processed: jobProgressSafe.statusCounts.completed, - failed: - jobProgressSafe.statusCounts.failed + - jobProgressSafe.statusCounts.download_failed + - jobProgressSafe.statusCounts.indexing_failed, - percentage: - job.totalPapers > 0 - ? Math.round( - ((jobProgressSafe.statusCounts.completed + - jobProgressSafe.statusCounts.failed + - jobProgressSafe.statusCounts.download_failed + - jobProgressSafe.statusCounts.indexing_failed) / - job.totalPapers) * - 100, - ) - : 0, - } - : progress; - - const isProcessing = - job.status === "pending" || - job.status === "downloading_pdfs" || - job.status === "extracting"; - const resolvedPlan = - subscriptionSettlement === "ready" - ? resolveEffectivePlan(subscription ?? null) - : null; - const hasProFeatures = - resolvedPlan === "pro" || resolvedPlan === "enterprise"; - return ( -
- - ) - } - rightColumn={ - -
- - {/* Header Section */} -
- {/* Breadcrumb */} - - - - {tc('extraction')} - - / - {job.name} - - -
-
- {/* Gradient icon */} -
- -
- -
- - {job.name} - - - -
- - - {( - { - pending: tJob("statusPending"), - downloading_pdfs: tJob("statusDownloadingPdfs"), - extracting: tJob("statusExtracting"), - completed: tJob("statusCompleted"), - failed: tJob("statusFailed"), - cancelled: tJob("statusCancelled"), - } as Record - )[job.status] ?? job.status.replace(/_/g, " ")} - -
- - - -
- - {tJob('papersCount', { count: format.number(job.totalPapers) })} -
- - - -
- - {tJob('updated', { timeAgo: format.relativeTime(new Date(job.updatedAt), now) })} -
-
-
-
- - {/* Action Buttons */} - - - - {isProcessing && ( - - - - - - - {tConfirm('cancelJob')} - - {tConfirm('cancelJobDescription')} - - - - {tConfirm('keepRunning')} - - {tConfirm('yesCancel')} - - - - - )} - - - - - - - - {tConfirm('deleteJob')} - - {tConfirm('deleteJobDescription')} - - - - {tc('cancel')} - - {tConfirm('yesDelete')} - - - - - -
-
- - {/* Stats Section */} - -
-
-

- {tJob('totalPapers')} -

-

- {format.number(job.totalPapers)} -

-
- -
-

- {tJob('processed')} -

-

- {format.number(resolvedProgress.processed)} -

-
- -
-

- {tJob('successRate')} -

-
-

- {resolvedProgress.percentage}% -

- {isProcessing && ( - - )} -
-
- -
-

- {tJob('questions')} -

-

- {questions.length} -

-
-
- - {/* Progress Bar */} -
-
- {tJob('extractionProgress')} - - {tJob('progressOfPapers', { - processed: resolvedProgress.processed + resolvedProgress.failed, - total: resolvedProgress.total, - })} - -
-
- -
-
-
- - {/* Tab Navigation */} -
-
- - {insightsEnabled && ( - - )} - {reviewQueueEnabled && ( - - )} - {reportBuilderEnabled && ( - - )} - -
-
- - {/* Content Section */} -
- {activeTab === 'results' ? ( - - - { - setFilters(f); - setCurrentPage(1); - }} - viewMode={viewMode} - onViewModeChange={setViewMode} - totalCount={papersWithResults.length} - filteredCount={sortedPapers.length} - questions={questions} - sortBy={resultsSortBy} - onSortChange={setResultsSortBy} - onExportAll={() => { - setExportMode('all'); - setExportDialogOpen(true); - }} - /> - -
- {resultsRenderState === "loading" ? ( -
-
- -

- {tJob('loadingExtractionResults')} -

-
-
- ) : resultsRenderState === "empty" || - resultsRenderState === "filtered_empty" ? ( -
- -

- {resultsRenderState === "filtered_empty" - ? tJob('noMatches') - : tc('noResultsFound')} -

-

- {resultsRenderState === "filtered_empty" - ? tc('tryAdjustingSearch') - : papersWithResults.length === 0 - ? job.status === "completed" - ? tPdf('noResultsDescription') - : tPdf('resultsWillAppear') - : tPdf('resultsWillAppear')} -

- {resultsRenderState === "filtered_empty" && ( - - )} -
- ) : ( - <> - {viewMode === 'table' && ( - - )} - {viewMode === 'cards' && ( - - )} - {viewMode === 'split' && ( - - )} - - )} -
- - {sortedPapers.length > 0 && viewMode !== 'split' && ( - - )} - - {viewMode !== 'split' && ( - - )} - - -
-
- ) : activeTab === "insights" ? ( - - - { - const target = papersWithResults.find((paper) => paper._id === paperId); - if (!target) return; - setFilters((prev) => ({ - ...prev, - searchQuery: target.title, - })); - setActiveTab("results"); - setCurrentPage(1); - }} - /> - - ) : activeTab === "review" ? ( - - - - - - ) : activeTab === "report" ? ( - - - - ) : ( - - {/* Questions Section */} -
-
-

- {tView('extractionQuestions')} -

-

- {tView('schemaDefinedDescription')} -

-
-
- {questions.map((q, idx) => ( - -
-
-

{q.question}

- {q.description && ( -

{q.description}

- )} -
- - {questionTypeLabels[q.type] ?? q.type} - -
-
- ))} -
-
-
- )} -
-
-
-
- } - /> -
- ); -} diff --git a/app/extraction/error.tsx b/app/extraction/error.tsx deleted file mode 100644 index 875893765..000000000 --- a/app/extraction/error.tsx +++ /dev/null @@ -1,38 +0,0 @@ -"use client"; - -import { useEffect } from "react"; -import { useTranslations } from "next-intl"; -import Link from "next/link"; -import { AlertTriangle } from "lucide-react"; -import { Button } from "@/components/ui/button"; - -export default function ExtractionErrorPage({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { - const t = useTranslations("errorPages"); - const tc = useTranslations("common"); - - useEffect(() => { - console.error("[app/extraction/error]", error); - }, [error]); - - return ( -
-
- -

{t("extractionUnavailable")}

-

{t("extractionErrorDescription")}

-
- - -
-
-
- ); -} diff --git a/app/extraction/layout.tsx b/app/extraction/layout.tsx deleted file mode 100644 index 32e710501..000000000 --- a/app/extraction/layout.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import type { Metadata } from "next"; -import { getTranslations } from "next-intl/server"; -import { ExtractionAccessGate } from "@/components/extraction/extraction-access-gate"; - -export async function generateMetadata(): Promise { - const [t, tc, te] = await Promise.all([ - getTranslations("metadata"), - getTranslations("common"), - getTranslations("extraction"), - ]); - - return { - title: { - default: tc("extraction"), - template: `%s | ${t("siteName")}`, - }, - description: te("extractDescription"), - }; -} - -export default function ExtractionLayout({ - children, -}: { - children: React.ReactNode; -}) { - return {children}; -} diff --git a/app/extraction/new/layout.tsx b/app/extraction/new/layout.tsx deleted file mode 100644 index ffe47b026..000000000 --- a/app/extraction/new/layout.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import type { Metadata } from "next"; -import { getTranslations } from "next-intl/server"; - -export async function generateMetadata(): Promise { - const [t, tc, te] = await Promise.all([ - getTranslations("metadata"), - getTranslations("common"), - getTranslations("extraction"), - ]); - - return { - title: `${tc("new")} | ${t("siteName")}`, - description: te("extractDescription"), - }; -} - -export default function NewExtractionLayout({ - children, -}: { - children: React.ReactNode; -}) { - return children; -} diff --git a/app/extraction/new/page.tsx b/app/extraction/new/page.tsx deleted file mode 100644 index 107fd38f0..000000000 --- a/app/extraction/new/page.tsx +++ /dev/null @@ -1,20 +0,0 @@ -"use client"; - -import { Suspense } from "react"; -import { PageWrapper } from "@/components/PageWrapper"; -import { CommandCenterContainer } from "@/components/command-center"; -import { JobCreator } from "@/components/extraction/job-creator"; - -export default function NewExtractionPage() { - return ( - -
- - - - - -
-
- ); -} diff --git a/app/extraction/page.tsx b/app/extraction/page.tsx deleted file mode 100644 index 562d92911..000000000 --- a/app/extraction/page.tsx +++ /dev/null @@ -1,69 +0,0 @@ -"use client"; - -import { Suspense, useEffect } from "react"; -import { useRouter } from "next/navigation"; -import { useTranslations } from "next-intl"; -import { api } from "@/convex/_generated/api"; -import { Database, Loader2 } from "lucide-react"; -import { ExtractionCommandCenter } from "@/components/extraction/extraction-command-center"; -import { PageWrapper } from "@/components/PageWrapper"; -import { CommandCenterContainer, CommandCenterHeader } from "@/components/command-center"; -import { useSearchParams } from "next/navigation"; -import { useAppToast } from "@/lib/toast"; -import { useProtectedQuery } from "@/lib/auth/use-auth-query"; - -export default function ExtractionPage() { - const router = useRouter(); - const tc = useTranslations('common'); - const te = useTranslations('extraction'); - const tcc = useTranslations('commandCenter'); - const { data: jobs, isDeferred } = useProtectedQuery( - api.extraction.queries.getMyJobs, - {}, - ); - - return ( - -
- - - - - - - -
- {isDeferred || jobs === undefined ? ( -
- -
- ) : ( - router.push("/extraction/new")} /> - )} -
-
-
-
- ); -} - -function ZoteroCallbackToast() { - const searchParams = useSearchParams(); - const toast = useAppToast(); - - useEffect(() => { - const error = searchParams.get("zotero_error"); - if (error) { - toast.zotero.failed(error); - } - }, [searchParams, toast]); - - return null; -} diff --git a/components/extraction/bar-visualization.tsx b/components/extraction/bar-visualization.tsx deleted file mode 100644 index 14ecd7184..000000000 --- a/components/extraction/bar-visualization.tsx +++ /dev/null @@ -1,4 +0,0 @@ -"use client"; - -export { StackedAnswerBars as BarVisualization } from "./stacked-answer-bars"; -export type { StackedAnswerBarsProps as BarVisualizationProps } from "./stacked-answer-bars"; diff --git a/components/extraction/bulk-actions-bar.tsx b/components/extraction/bulk-actions-bar.tsx deleted file mode 100644 index 764fe3554..000000000 --- a/components/extraction/bulk-actions-bar.tsx +++ /dev/null @@ -1,75 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { motion, AnimatePresence } from "motion/react"; -import { Download } from "lucide-react"; -import { useTranslations } from "next-intl"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent } from "@/components/ui/card"; -import { ExportDialog } from "./export-dialog"; -import type { PaperWithResults, Question } from "@/lib/extraction/filtering"; - -interface BulkActionsBarProps { - selectedIds: Set; - papers: PaperWithResults[]; - questions: Question[]; - onClearSelection: () => void; -} - -export function BulkActionsBar({ - selectedIds, - papers, - questions, - onClearSelection, -}: BulkActionsBarProps) { - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - const [exportDialogOpen, setExportDialogOpen] = useState(false); - - return ( - <> - - {selectedIds.size > 0 && ( - - - - - {t("nPapersSelected", { count: selectedIds.size })} - -
- -
- - - - - )} - - - - - ); -} diff --git a/components/extraction/confidence-badge.tsx b/components/extraction/confidence-badge.tsx deleted file mode 100644 index 0568e1c72..000000000 --- a/components/extraction/confidence-badge.tsx +++ /dev/null @@ -1,68 +0,0 @@ -"use client"; - -import { HelpCircle } from "lucide-react"; -import { useTranslations } from "next-intl"; -import { Badge } from "@/components/ui/badge"; -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { BADGE_COLOR_CLASSES, getConfidenceColor } from "@/lib/extraction/card-thresholds"; -import { getConfidenceTooltipKey } from "@/lib/extraction/confidence-messages"; -import { useFeatureFlag } from "@/lib/feature-flags/hook"; - -export interface ConfidenceBadgeProps { - value: number; - abstractOnlyCount: number; - noContentCount: number; - totalPapers: number; -} - -export function ConfidenceBadge({ - value, - abstractOnlyCount, - noContentCount, - totalPapers, -}: ConfidenceBadgeProps) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const t: any = useTranslations("extraction"); - const pdfEnabled = useFeatureFlag("extraction.pdf"); - const color = getConfidenceColor(value); - const tooltipKey = getConfidenceTooltipKey(abstractOnlyCount, noContentCount, totalPapers, pdfEnabled); - const colorClasses = BADGE_COLOR_CLASSES[color]; - const percentage = Math.round(value * 100); - - return ( - - - - {percentage}% - - - - {tooltipKey === "confidenceAbstractOnly" ? ( -
-

{t("confidenceAbstractOnly")}

-

{t("confidenceCapExplained")}

-
- ) : tooltipKey === "confidenceNoContent" ? ( -

{t("confidenceNoContent")}

- ) : ( -

{t("confidenceCapExplained")}

- )} -
-
- ); -} diff --git a/components/extraction/confidence-filter.tsx b/components/extraction/confidence-filter.tsx deleted file mode 100644 index 776241920..000000000 --- a/components/extraction/confidence-filter.tsx +++ /dev/null @@ -1,80 +0,0 @@ -"use client"; - -import { Filter } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { Label } from "@/components/ui/label"; -import { Slider } from "@/components/ui/slider"; -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover"; -import { cn } from "@/lib/utils"; -import { useTranslations } from "next-intl"; - -interface ConfidenceFilterProps { - range: [number, number]; - onChange: (range: [number, number]) => void; -} - -export function ConfidenceFilter({ range, onChange }: ConfidenceFilterProps) { - const t = useTranslations('filters'); - const tc = useTranslations('common'); - const presets = [ - { label: tc('all'), value: [0, 100] as [number, number] }, - { label: tc('high'), value: [80, 100] as [number, number] }, - { label: tc('medium'), value: [50, 80] as [number, number] }, - { label: tc('low'), value: [0, 50] as [number, number] }, - ]; - const isFiltered = range[0] !== 0 || range[1] !== 100; - - return ( - - - - - -
-
- - onChange(value as [number, number])} - min={0} - max={100} - step={5} - className="mt-2" - /> -
- {range[0]}% - {range[1]}% -
-
- -
- -
- {presets.map(preset => ( - - ))} -
-
-
-
-
- ); -} diff --git a/components/extraction/confidence-ring.tsx b/components/extraction/confidence-ring.tsx deleted file mode 100644 index f4f2a3731..000000000 --- a/components/extraction/confidence-ring.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { cn } from "@/lib/utils"; - -interface ConfidenceRingProps { - value: number; - size?: number; - className?: string; -} - -export function ConfidenceRing({ value, size = 48, className }: ConfidenceRingProps) { - const percentage = Math.round(value * 100); - const radius = (size / 2) - 4; - const circumference = 2 * Math.PI * radius; - const offset = circumference - (value * circumference); - - const color = - value >= 0.8 ? 'text-green-500' : - value >= 0.5 ? 'text-yellow-500' : - 'text-red-500'; - - return ( -
- - - - -
- - {percentage}% - -
-
- ); -} diff --git a/components/extraction/disagreement-list.tsx b/components/extraction/disagreement-list.tsx deleted file mode 100644 index 89b961467..000000000 --- a/components/extraction/disagreement-list.tsx +++ /dev/null @@ -1,141 +0,0 @@ -"use client"; - -import { useMemo, useState } from "react"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { useTranslations } from "next-intl"; - -type DisagreementCluster = { - normalizedAnswer: string; - displayAnswer: string; - count: number; - avgConfidence: number; - examples: Array<{ - paperId: string; - title: string; - openalexId: string; - answer: string | boolean | number | string[] | null | undefined; - confidence?: number; - }>; -}; - -interface DisagreementListProps { - clusters: DisagreementCluster[]; - viewMode?: "disagreement" | "answer_profiles"; - suppressedSingletonCount?: number; - maxInitial?: number; - onJumpToExample?: (paperId: string) => void; -} - -function truncateText(value: string, limit = 160) { - if (value.length <= limit) return value; - return `${value.slice(0, limit)}...`; -} - -export function DisagreementList({ - clusters, - viewMode = "disagreement", - suppressedSingletonCount = 0, - maxInitial = 10, - onJumpToExample, -}: DisagreementListProps) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const t: any = useTranslations("extraction"); - const [visibleCount, setVisibleCount] = useState(() => maxInitial); - const [expandedAnswers, setExpandedAnswers] = useState>({}); - - const visibleClusters = useMemo( - () => clusters.slice(0, visibleCount), - [clusters, visibleCount] - ); - - const isAnswerProfiles = viewMode === "answer_profiles"; - if (viewMode === "disagreement" && clusters.length <= 1) { - return ( -
- {t("noDisagreementClusters")} -
- ); - } - - if (isAnswerProfiles && clusters.length === 0) { - return ( -
- {t("noAnswerProfiles")} -
- ); - } - - return ( -
- {suppressedSingletonCount > 0 ? ( -
- {t("suppressedSingletonProfiles", { count: suppressedSingletonCount })} -
- ) : null} - - {visibleClusters.map((cluster, index) => { - const key = `${cluster.normalizedAnswer}-${index}`; - const isExpanded = Boolean(expandedAnswers[key]); - const longAnswer = cluster.displayAnswer.length > 160; - return ( -
-
-
- - {isExpanded ? cluster.displayAnswer : truncateText(cluster.displayAnswer)} - - {longAnswer ? ( - - ) : null} -
-
- {t("disagreementPapers", { count: cluster.count })} - {t("disagreementAvgConfidence", { percent: Math.round(cluster.avgConfidence * 100) })} -
-
- -
- {cluster.examples.slice(0, 3).map((example) => ( -
-
-
{example.title}
-
- {t("disagreementAnswer")}{" "} - - {Array.isArray(example.answer) ? example.answer.join("; ") : String(example.answer)} - -
-
- {onJumpToExample ? ( - - ) : null} -
- ))} -
-
- ); - })} - - {clusters.length > visibleCount ? ( -
- -
- ) : null} -
- ); -} diff --git a/components/extraction/export-dialog.tsx b/components/extraction/export-dialog.tsx deleted file mode 100644 index dd2cc7a65..000000000 --- a/components/extraction/export-dialog.tsx +++ /dev/null @@ -1,194 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { FileSpreadsheet, FileJson } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { Label } from "@/components/ui/label"; -import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; -import { Checkbox } from "@/components/ui/checkbox"; -import { exportToCSV, exportToJSON, exportToExcel } from "@/lib/extraction/export"; -import type { PaperWithResults, Question } from "@/lib/extraction/filtering"; -import { useTranslations } from "next-intl"; - -interface ExportDialogProps { - open: boolean; - onOpenChange: (open: boolean) => void; - papers: PaperWithResults[]; - questions: Question[]; - label?: string; -} - -export function ExportDialog({ - open, - onOpenChange, - papers, - questions, - label, -}: ExportDialogProps) { - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - - const [format, setFormat] = useState<"csv" | "json" | "excel">("csv"); - const [includeMetadata, setIncludeMetadata] = useState(true); - const [includeConfidence, setIncludeConfidence] = useState(true); - const [includeReasoning, setIncludeReasoning] = useState(false); - const [includeCitations, setIncludeCitations] = useState(false); - - const handleExport = async () => { - const options = { - includeMetadata, - includeConfidence, - includeReasoning, - includeCitations, - }; - - if (format === "csv") { - exportToCSV(papers, questions, options); - } else if (format === "json") { - exportToJSON(papers, questions, options); - } else { - await exportToExcel(papers, questions, options); - } - - onOpenChange(false); - }; - - const displayLabel = - label ?? tc("paperCount", { count: papers.length }); - - return ( - - - - {t("exportResults")} - - {t("exportDescription", { label: displayLabel })} - - -
-
- - setFormat(v as "csv" | "json" | "excel")} - > -
- - -
-
- - -
-
- - -
-
-
-
- -
-
- - setIncludeMetadata(checked as boolean) - } - /> - -
-
- - setIncludeConfidence(checked as boolean) - } - /> - -
- {format === "json" && ( - <> -
- - setIncludeReasoning(checked as boolean) - } - /> - -
-
- - setIncludeCitations(checked as boolean) - } - /> - -
- - )} -
-
-
- - - - -
-
- ); -} diff --git a/components/extraction/extraction-access-gate.tsx b/components/extraction/extraction-access-gate.tsx deleted file mode 100644 index cebdac182..000000000 --- a/components/extraction/extraction-access-gate.tsx +++ /dev/null @@ -1,47 +0,0 @@ -"use client"; - -import type { ReactNode } from "react"; -import { Loader2 } from "lucide-react"; -import { PageWrapper } from "@/components/PageWrapper"; -import { CommandCenterContainer } from "@/components/command-center"; -import { useSubscriptionState } from "@/lib/auth/use-subscription-state"; -import { ExtractionPlanGate } from "./extraction-plan-gate"; - -type ExtractionAccessGateProps = { - children: ReactNode; -}; - -export function ExtractionAccessGate({ children }: ExtractionAccessGateProps) { - const subscriptionState = useSubscriptionState(); - const hasProAccess = - subscriptionState.resolvedPlan === "pro" || - subscriptionState.resolvedPlan === "enterprise"; - - if (subscriptionState.isSettling) { - return ( - -
- -
- -
-
-
-
- ); - } - - if (!hasProAccess) { - return ( - -
- - - -
-
- ); - } - - return <>{children}; -} diff --git a/components/extraction/extraction-citation-sidebar.tsx b/components/extraction/extraction-citation-sidebar.tsx deleted file mode 100644 index 80b07ef4a..000000000 --- a/components/extraction/extraction-citation-sidebar.tsx +++ /dev/null @@ -1,149 +0,0 @@ -"use client"; - -import { FileSearch } from "lucide-react"; -import { motion, AnimatePresence } from "motion/react"; -import { useTranslations } from "next-intl"; -import { Button } from "@/components/ui/button"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -import { cn } from "@/lib/utils"; -import { PdfCitationPanel } from "@/components/extraction/pdf-citation-panel"; -import type { CitationPanelPayload } from "@/lib/extraction/citation-panel"; -import { - useExtractionCitationPanelStore, - getExtractionCitationPanelDimensions, -} from "@/lib/store"; -import { sidebarSpring, hoverSpring } from "@/lib/ui/sidebar-motion"; - -type ExtractionCitationSidebarProps = { - panelPayload: CitationPanelPayload | null; -}; - -export function ExtractionCitationSidebar({ - panelPayload, -}: ExtractionCitationSidebarProps) { - const t = useTranslations(); - const { isCollapsed, setCollapsed, toggle, _hasHydrated } = - useExtractionCitationPanelStore(); - const { expandedWidth, collapsedWidth } = - getExtractionCitationPanelDimensions(isCollapsed); - - if (!_hasHydrated) return null; - - const hasPayload = panelPayload !== null; - const width = !hasPayload ? 0 : isCollapsed ? collapsedWidth : expandedWidth; - const translateX = isCollapsed ? -(expandedWidth - collapsedWidth) : 0; - - return ( -
- - {/* Gradient overlay */} -
- - {/* Floating controls — expanded state */} -
- - - - - - - {t("accessibility.collapsePanel")} - -
- - {/* Scrollable content */} -
- -
- - - {/* Collapsed strip controls */} - - {isCollapsed && hasPayload && ( - - - - - - - - {t("accessibility.expandPanel")} - - - {/* Page number badge */} - {panelPayload?.citations?.[0]?.page != null && ( - - - p.{panelPayload.citations[0].page} - - - )} - - )} - -
- ); -} diff --git a/components/extraction/extraction-command-center.tsx b/components/extraction/extraction-command-center.tsx deleted file mode 100644 index 0e56224a9..000000000 --- a/components/extraction/extraction-command-center.tsx +++ /dev/null @@ -1,162 +0,0 @@ -"use client"; - -import React, { useState, useMemo } from "react"; -import { useTranslations } from "next-intl"; -import { parseAsInteger, useQueryState } from "nuqs"; -import { Database, Plus } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { useUIStore } from "@/lib/store"; -import { COMMAND_CENTER_ITEMS_PER_PAGE } from "@/lib/constants/view-modes"; -import type { ExtractionSortBy } from "@/lib/types"; -import type { Doc } from "@/convex/_generated/dataModel"; -import { - CommandCenterToolbar, - CommandCenterList, - CommandCenterPagination, -} from "@/components/command-center"; -import { JobListItem } from "./job-list-item"; -import type { ViewMode } from "@/lib/types"; - -function createExtractionJobListItem(viewMode: ViewMode) { - return function ExtractionJobListItem({ - item, - index, - }: { - item: ExtractionJob; - index: number; - }) { - return ; - }; -} - -type ExtractionJob = Doc<"extractionJobs">; - -interface ExtractionCommandCenterProps { - jobs: ExtractionJob[]; - onNewJob: () => void; -} - -const STATUS_ORDER: Record = { - pending: 0, - downloading_pdfs: 1, - extracting: 2, - completed: 3, - failed: 4, - cancelled: 5, -}; - -export function ExtractionCommandCenter({ jobs, onNewJob }: ExtractionCommandCenterProps) { - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - - const SORT_OPTIONS: { value: ExtractionSortBy; label: string }[] = [ - { value: "recent", label: tc("recent") }, - { value: "oldest", label: tc("oldest") }, - { value: "name", label: tc("name") }, - { value: "status", label: tc("status") }, - ]; - const [searchFilter, setSearchFilter] = useState(""); - const [currentPage, setCurrentPage] = useQueryState( - "page", - parseAsInteger.withDefault(1).withOptions({ scroll: true }), - ); - - const { - extractionViewMode, - setExtractionViewMode, - extractionSortBy, - setExtractionSortBy, - } = useUIStore(); - - // Filter jobs - const filteredJobs = useMemo(() => { - if (!searchFilter.trim()) return jobs; - const query = searchFilter.toLowerCase(); - return jobs.filter( - (job) => - job.name.toLowerCase().includes(query) || - (job.description?.toLowerCase().includes(query) ?? false) - ); - }, [jobs, searchFilter]); - - // Sort jobs - const sortedJobs = useMemo(() => { - const sorted = [...filteredJobs]; - switch (extractionSortBy) { - case "oldest": - return sorted.sort((a, b) => a.createdAt - b.createdAt); - case "name": - return sorted.sort((a, b) => a.name.localeCompare(b.name)); - case "status": - return sorted.sort( - (a, b) => (STATUS_ORDER[a.status] ?? 99) - (STATUS_ORDER[b.status] ?? 99) - ); - case "recent": - default: - return sorted.sort((a, b) => b.createdAt - a.createdAt); - } - }, [filteredJobs, extractionSortBy]); - - // Pagination - const totalPages = Math.ceil(sortedJobs.length / COMMAND_CENTER_ITEMS_PER_PAGE); - const paginatedJobs = useMemo(() => { - const start = (currentPage - 1) * COMMAND_CENTER_ITEMS_PER_PAGE; - return sortedJobs.slice(start, start + COMMAND_CENTER_ITEMS_PER_PAGE); - }, [sortedJobs, currentPage]); - - // Reset to page 1 when filter changes - React.useEffect(() => { - if (currentPage > totalPages && totalPages > 0) { - setCurrentPage(1); - } - }, [currentPage, totalPages, setCurrentPage]); - - return ( - <> - {/* Toolbar */} - - - {tc("new")} - - } - /> - - {/* List */} -
- job._id} - emptyIcon={Database} - emptyTitle={t("noExtractionJobs")} - emptyDescription={t("createJobToStart")} - hasFilter={!!searchFilter.trim()} - onClearFilter={() => setSearchFilter("")} - ItemComponent={createExtractionJobListItem(extractionViewMode)} - /> - - {/* Pagination */} - {totalPages > 1 && ( - - )} -
- - ); -} diff --git a/components/extraction/extraction-plan-gate.tsx b/components/extraction/extraction-plan-gate.tsx deleted file mode 100644 index 2e686ae3b..000000000 --- a/components/extraction/extraction-plan-gate.tsx +++ /dev/null @@ -1,165 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { useTranslations } from "next-intl"; -import { motion } from "motion/react"; -import type { ComponentType, SVGProps } from "react"; -import { - ArrowRight, - BarChart3, - CheckCircle2, - FileSearch, - Sparkles, - Users, -} from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { Badge } from "@/components/ui/badge"; -import { useFeatureFlag } from "@/lib/feature-flags/hook"; - -type Step = { - title: string; - description: string; -}; - -type ValueCard = { - title: string; - description: string; - icon: ComponentType>; -}; - -export function ExtractionPlanGate() { - const t = useTranslations("extraction"); - const subscriptionsEnabled = useFeatureFlag("subscriptions.enabled"); - - const steps: Step[] = [ - { - title: t("planGateStep1Title"), - description: t("planGateStep1Description"), - }, - { - title: t("planGateStep2Title"), - description: t("planGateStep2Description"), - }, - { - title: t("planGateStep3Title"), - description: t("planGateStep3Description"), - }, - ]; - - const cards: ValueCard[] = [ - { - title: t("planGateCardOutcomesTitle"), - description: t("planGateCardOutcomesDescription"), - icon: BarChart3, - }, - { - title: t("planGateCardMethodsTitle"), - description: t("planGateCardMethodsDescription"), - icon: FileSearch, - }, - { - title: t("planGateCardPopulationTitle"), - description: t("planGateCardPopulationDescription"), - icon: Users, - }, - ]; - - return ( -
- -
-
- - - {t("planGateBadge")} - -

- {t("planGateTitle")} -

-

- {t("planGateDescription")} -

- {subscriptionsEnabled && ( -
- -
- )} -
- - - -

- {t("planGateHowItWorksTitle")} -

-

- {t("planGateHowItWorksDescription")} -

-
- {steps.map((step, index) => ( -
-
- {index + 1} -
-

{step.title}

-

- {step.description} -

-
- ))} -
-
- - -

- {t("planGateWhatYouCanExtractTitle")} -

-

- {t("planGateWhatYouCanExtractDescription")} -

-
- {cards.map(({ title, description, icon: Icon }) => ( -
-
- -
-

{title}

-

- {description} -

-
- ))} -
-
- -
- - {t("planGateProNote")} -
-
- ); -} diff --git a/components/extraction/extraction-results-shell.tsx b/components/extraction/extraction-results-shell.tsx deleted file mode 100644 index e38412186..000000000 --- a/components/extraction/extraction-results-shell.tsx +++ /dev/null @@ -1,111 +0,0 @@ -"use client"; - -import type { ReactNode } from "react"; -import { FileText } from "lucide-react"; -import { motion, AnimatePresence } from "motion/react"; -import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; -import { useIsMobile } from "@/lib/hooks"; -import { PdfCitationPanel } from "@/components/extraction/pdf-citation-panel"; -import type { CitationPanelPayload } from "@/lib/extraction/citation-panel"; -import { subtleSpring } from "@/lib/animation-config"; -import { useTranslations } from "next-intl"; - -type Direction = 1 | -1; - -const slideVariants = { - enter: (direction: Direction) => ({ - x: direction > 0 ? 40 : -40, - opacity: 0, - }), - center: { - x: 0, - opacity: 1, - }, - exit: (direction: Direction) => ({ - x: direction > 0 ? -40 : 40, - opacity: 0, - }), -}; - -type ExtractionResultsShellProps = { - panelPayload: CitationPanelPayload | null; - mobilePane: "results" | "citation"; - onMobilePaneChange: (pane: "results" | "citation") => void; - primaryLabel?: string; - children: ReactNode; -}; - -export function ExtractionResultsShell({ - panelPayload, - mobilePane, - onMobilePaneChange, - primaryLabel, - children, -}: ExtractionResultsShellProps) { - const t = useTranslations("extractionView"); - const isMobile = useIsMobile(); - const label = primaryLabel ?? t("results"); - const hasActiveCitationPanel = panelPayload !== null; - // results → citation = going right (1), citation → results = going left (-1) - const direction: Direction = mobilePane === "citation" ? 1 : -1; - - if (isMobile) { - if (!hasActiveCitationPanel) { - return
{children}
; - } - - return ( -
- onMobilePaneChange(value as "results" | "citation")} - className="flex min-w-0 flex-col gap-0" - > - - - - {label} - - {t("citation")} - - -
- - {mobilePane === "results" ? ( - - {children} - - ) : ( - -
- -
-
- )} -
-
-
-
- ); - } - - return
{children}
; -} diff --git a/components/extraction/grouped-answer-row.tsx b/components/extraction/grouped-answer-row.tsx deleted file mode 100644 index c44dc402a..000000000 --- a/components/extraction/grouped-answer-row.tsx +++ /dev/null @@ -1,78 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { useTranslations } from "next-intl"; -import { ChevronDown, ChevronRight } from "lucide-react"; - -interface GroupedAnswerVariant { - display: string; - normalized: string; - count: number; - citationStatusMix: { - grounded: number; - best_effort: number; - insufficient_evidence: number; - extraction_error: number; - }; -} - -interface GroupedAnswer { - groupRepresentative: string; - groupNormalized: string; - count: number; - citationStatusMix: { - grounded: number; - best_effort: number; - insufficient_evidence: number; - extraction_error: number; - }; - variants: GroupedAnswerVariant[]; -} - -export interface GroupedAnswerRowProps { - group: GroupedAnswer; -} - -export function GroupedAnswerRow({ group }: GroupedAnswerRowProps) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const t: any = useTranslations("extraction"); - const [isExpanded, setIsExpanded] = useState(false); - - const hasVariants = group.variants.length > 1; - - return ( -
-
- {group.groupRepresentative} - {hasVariants && ( - - )} -
- - {isExpanded && hasVariants && ( -
- {group.variants.map((variant, idx) => ( -
- {variant.display} - - {variant.count} - -
- ))} -
- )} -
- ); -} diff --git a/components/extraction/history-selector.tsx b/components/extraction/history-selector.tsx deleted file mode 100644 index 7cbdef8fd..000000000 --- a/components/extraction/history-selector.tsx +++ /dev/null @@ -1,106 +0,0 @@ -"use client"; - -import { motion } from "motion/react"; -import { useExtractionStore } from "@/lib/store/extraction"; -import { useSearchHistoryStore } from "@/lib/store"; -import { cn } from "@/lib/utils"; -import { Search, Calendar, FileText } from "lucide-react"; -import { Checkbox } from "@/components/ui/checkbox"; -import { useLocale, useTranslations, useFormatter, useNow } from "next-intl"; - -export function HistorySelector() { - const locale = useLocale(); - const format = useFormatter(); - const now = useNow(); - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - const { draftJob, toggleHistorySelection } = useExtractionStore(); - const searchHistory = useSearchHistoryStore((state) => state.searchHistory); - - if (searchHistory.length === 0) { - return ( - - -

- {t("noSearchHistoryFound")} -

-

- {t("performSearchesFirst")} -

-
- ); - } - - return ( -
- {searchHistory.map((entry, index) => { - const isSelected = draftJob.selectedHistoryIds.includes(entry.id); - - return ( - toggleHistorySelection(entry.id)} - className={cn( - "cursor-pointer transition-all duration-200 p-4", - index % 2 === 0 ? "bg-background" : "bg-muted/30", - isSelected - ? "bg-primary/5 border-l-4 border-l-primary" - : "hover:bg-muted/50 border-l-4 border-l-transparent" - )} - > -
- {/* Selection Indicator */} -
- -
- - {/* Content */} -
-
- - - {entry.query} - -
- -
-
- - {format.relativeTime(new Date(entry.createdAt), now)} -
- - - -
- - {format.number(entry.count ?? 0)} {tc("results").toLowerCase()} -
- - {entry.screeningQuestions?.length > 0 && ( - <> - - - {t("screeningQuestionsLabel", { count: entry.screeningQuestions.length })} - - - )} -
-
-
-
- ); - })} -
- ); -} diff --git a/components/extraction/insights-overview.tsx b/components/extraction/insights-overview.tsx deleted file mode 100644 index c46428498..000000000 --- a/components/extraction/insights-overview.tsx +++ /dev/null @@ -1,138 +0,0 @@ -"use client"; - -import { api } from "@/convex/_generated/api"; -import type { Id } from "@/convex/_generated/dataModel"; -import { Button } from "@/components/ui/button"; -import { Loader2, AlertCircle } from "lucide-react"; -import { motion } from "motion/react"; -import { useProtectedQuery } from "@/lib/auth/use-auth-query"; -import { useTranslations } from "next-intl"; -import { SummaryCards } from "./summary-cards"; -import { QuestionListItem } from "./question-list-item"; -import { useFeatureFlag } from "@/lib/feature-flags/hook"; -import { cardEntrance, cardEntranceTransition } from "@/lib/animation-config"; - -interface InsightsOverviewProps { - jobId: Id<"extractionJobs">; - selectedQuestionKey?: string; - onSelectQuestion: (questionKey: string) => void; - onRerun?: () => void; - enabled?: boolean; -} - -export function InsightsOverview({ - jobId, - selectedQuestionKey, - onSelectQuestion, - onRerun, - enabled = true, -}: InsightsOverviewProps) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const t: any = useTranslations("extraction"); - const pdfEnabled = useFeatureFlag("extraction.pdf"); - const insightsQuery = useProtectedQuery( - api.extraction.queries.getJobInsights, - enabled ? { jobId } : "skip", - ); - const insights = insightsQuery.data; - - if (!enabled) return null; - - if (insightsQuery.isDeferred || insights === undefined) { - return ( -
- -
- ); - } - - if (!insights || insights.status !== "ok") { - const message = - insights?.status === "unauthenticated" - ? t("signInToViewInsights") - : insights?.status === "no_access" - ? t("noAccessInsights") - : t("insightsUnavailable"); - return ( -
- {message} -
- ); - } - - const { summary, questions, diagnostics } = insights; - - return ( -
- 0 ? questions[0].total : summary.noContentCount + summary.abstractOnlyCount} - /> - - {pdfEnabled && ( - -
-
-

{t("noContentDiagnostics")}

-

{t("noContentDiagnosticsDescription")}{summary.noContentCount}

-
- {onRerun ? ( - - ) : null} -
- {diagnostics?.noContentPapers?.length > 0 ? ( -
- {diagnostics.noContentPapers.slice(0, 3).map((paper) => ( -
-
{paper.title}
-
- - {paper.reason} -
-
- ))} -
- ) : null} -
- )} - - -
-

{t("questionLevelInsights")}

-
-
- {questions.map((question, idx) => ( - - onSelectQuestion(question.key)} - /> - - ))} -
-
-
- ); -} diff --git a/components/extraction/insights-question-panel.tsx b/components/extraction/insights-question-panel.tsx deleted file mode 100644 index 64fc25ca0..000000000 --- a/components/extraction/insights-question-panel.tsx +++ /dev/null @@ -1,249 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { motion } from "motion/react"; -import { api } from "@/convex/_generated/api"; -import type { Id } from "@/convex/_generated/dataModel"; -import { Badge } from "@/components/ui/badge"; -import { Loader2, BarChart3, MessageSquareWarning } from "lucide-react"; -import { DisagreementList } from "@/components/extraction/disagreement-list"; -import { useProtectedQuery } from "@/lib/auth/use-auth-query"; -import { useTranslations } from "next-intl"; -import { BarVisualization } from "@/components/extraction/bar-visualization"; -import { buildSynonymMap, groupAnswersBySynonym, mergeDisagreementClusters } from "@/lib/extraction/answer-grouping"; -import { useFeatureFlag } from "@/lib/feature-flags/hook"; -import { - pct, - CONFIDENCE_BAR_COLORS, - CITATION_BAR_COLORS, -} from "@/lib/extraction/card-thresholds"; -import { cardEntrance, cardEntranceTransition } from "@/lib/animation-config"; - -interface InsightsQuestionPanelProps { - jobId: Id<"extractionJobs">; - questionKey?: string; - onJumpToPaper?: (paperId: string) => void; - enabled?: boolean; -} - -function MiniBar({ value, color, label }: { value: number; color?: string; label: string }) { - const pctValue = Math.max(2, Math.round(value * 100)); - return ( -
-
-
- ); -} - -export function InsightsQuestionPanel({ - jobId, - questionKey, - onJumpToPaper, - enabled = true, -}: InsightsQuestionPanelProps) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const t: any = useTranslations("extraction"); - const tc = useTranslations("common"); - const pdfEnabled = useFeatureFlag("extraction.pdf"); - const questionInsightsQuery = useProtectedQuery( - api.extraction.queries.getQuestionInsights, - enabled && questionKey ? { jobId, questionKey } : "skip", - ); - const disagreementQuery = useProtectedQuery( - api.extraction.queries.getQuestionDisagreements, - enabled && questionKey ? { jobId, questionKey } : "skip", - ); - const questionInsights = questionInsightsQuery.data; - const disagreementData = disagreementQuery.data; - const [arrayView, setArrayView] = useState<"entities" | "raw">("entities"); - - if (!enabled) return null; - - if (!questionKey) { - return ( -
-

{t("selectQuestionToInspect")}

-
- ); - } - - if (questionInsightsQuery.isDeferred || disagreementQuery.isDeferred || questionInsights === undefined || disagreementData === undefined) { - return ( -
- -
- ); - } - - if (!questionInsights || questionInsights.status !== "ok") { - const message = - questionInsights?.status === "not_found" ? t("questionInsightsUnavailable") - : questionInsights?.status === "unauthenticated" ? t("signInToViewQuestionInsights") - : questionInsights?.status === "no_access" ? t("noAccessQuestionInsights") - : t("questionInsightsGenericUnavailable"); - return ( -
{message}
- ); - } - - const total = Math.max(questionInsights.total, 1); - const rawAnswerDistribution = questionInsights.rawAnswerDistribution || questionInsights.topAnswers || []; - const entityDistribution = questionInsights.entityDistribution || []; - const isArrayMode = questionInsights.insightMode === "array"; - const effectiveArrayView = isArrayMode ? arrayView : "raw"; - const synonymMap = buildSynonymMap(); - const disagreementTitle = disagreementData?.status === "ok" && disagreementData.viewMode === "answer_profiles" ? t("answerProfiles") : t("disagreementFinder"); - - // Pre-compute answer distribution data (avoid IIFEs in JSX) - const entityBarData = entityDistribution.map((entity) => { - const groundedCount = Math.round(entity.count * (entity.groundedRate || 0)); - return { - answer: entity.entity + (entity.generic ? ` ${t("genericSuffix")}` : ""), - count: entity.count, - citationStatusMix: { grounded: groundedCount, best_effort: entity.count - groundedCount, insufficient_evidence: 0, extraction_error: 0 }, - }; - }); - const entityMaxCount = Math.max(...entityDistribution.map((e) => e.count), 1); - - const groupedAnswers = groupAnswersBySynonym(rawAnswerDistribution, synonymMap); - const rawDisplayAnswers = groupedAnswers.map((group) => ({ - answer: group.groupRepresentative, - count: group.count, - citationStatusMix: group.citationStatusMix, - })); - const rawMaxCount = Math.max(...rawDisplayAnswers.map((a) => a.count), 1); - - const rawClusters = disagreementData?.status === "ok" ? disagreementData.clusters || [] : []; - const mergedClusters = mergeDisagreementClusters(rawClusters, synonymMap); - - return ( -
- {/* Question Info Card */} - -
-

{questionInsights.question.question}

-

{questionInsights.question.type} {t("questionSuffix")}

-
- -
- {pct(questionInsights.answered / total)} {tc("answered").toLowerCase()} - {pdfEnabled && ( - {pct(questionInsights.grounded / total)} {tc("grounded").toLowerCase()} - )} - - {Math.round((questionInsights.avgEffectiveConfidence ?? questionInsights.avgConfidence) * 100)}% {t("effectiveConf")} - -
- - {/* Confidence & Citation Distribution */} -
-
-

{t("confidenceDistribution")}

-
- {(["high", "medium", "low", "unknown"] as const).map((bucket) => { - const count = questionInsights.confidenceBuckets[bucket]; - const bucketLabels: Record = { high: tc("high"), medium: tc("medium"), low: tc("low"), unknown: tc("unknown") }; - return ( -
-
- {bucketLabels[bucket]} - {count} -
- -
- ); - })} -
-
- {pdfEnabled && ( -
-

{t("citationStatusMix")}

-
- {(["grounded", "best_effort", "insufficient_evidence", "extraction_error"] as const).map((status) => { - const count = questionInsights.citationStatusMix[status]; - const citationLabels: Record = { grounded: tc("grounded"), best_effort: (tc as any)("bestEffort"), insufficient_evidence: (tc as any)("insufficientEvidence"), extraction_error: (tc as any)("extractionError") }; - return ( -
-
- {citationLabels[status]} - {count} -
- -
- ); - })} -
-
- )} -
-
- - {/* Answer Distribution */} - -
-
- -

{isArrayMode && effectiveArrayView === "entities" ? t("topEntities") : t("answerDistribution")}

-
- {isArrayMode ? ( -
- - -
- ) : null} -
-
- {isArrayMode && effectiveArrayView === "entities" ? ( - entityDistribution.length === 0 - ?
{t("noEntityValues")}
- : - ) : rawAnswerDistribution.length === 0 - ?
{t("noAnswerValues")}
- : - } -
-
- - {/* Disagreement / Answer Profiles */} - -
- -

{disagreementTitle}

-
-
- onJumpToPaper?.(paperId)} - /> -
-
-
- ); -} diff --git a/components/extraction/job-creator.tsx b/components/extraction/job-creator.tsx deleted file mode 100644 index 3ef8c029b..000000000 --- a/components/extraction/job-creator.tsx +++ /dev/null @@ -1,426 +0,0 @@ -"use client"; -"use no memo"; // try/finally in handlers - -import { useState, useMemo } from "react"; -import { motion, AnimatePresence } from "motion/react"; -import { useMutation } from "convex/react"; -import { useRouter } from "next/navigation"; -import { parseAsInteger, useQueryState } from "nuqs"; -import { useTranslations } from "next-intl"; -import { api } from "@/convex/_generated/api"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { - ArrowLeft, - ArrowRight, - Check, - Loader2, - Layers, - FileText, - Zap, -} from "lucide-react"; -import { useExtractionStore } from "@/lib/store/extraction"; -import { Id } from "@/convex/_generated/dataModel"; -import { useSearchHistoryStore } from "@/lib/store"; -import type { SearchResult } from "@/lib/types"; -import { QuestionBuilder } from "./question-builder"; -import { SourceSelector } from "./source-selector"; -import { SourceSummary } from "./source-summary"; -import { useAppToast } from "@/lib/toast"; -import { cn } from "@/lib/utils"; - -const stepVariants = { - enter: (direction: number) => ({ - x: direction > 0 ? 50 : -50, - opacity: 0, - scale: 0.95, - }), - center: { - x: 0, - opacity: 1, - scale: 1, - }, - exit: (direction: number) => ({ - x: direction < 0 ? 50 : -50, - opacity: 0, - scale: 0.95, - }), -}; - -export function JobCreator() { - const router = useRouter(); - const toast = useAppToast(); - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - const [stepRaw, setStepRaw] = useQueryState( - "step", - parseAsInteger.withDefault(1).withOptions({ history: "push" }), - ); - const [direction, setDirection] = useState(0); - const [isSubmitting, setIsSubmitting] = useState(false); - - const validStep = Math.min(3, Math.max(1, stepRaw)) as 1 | 2 | 3; - - const { draftJob, setDraftJobName, clearDraftJob } = useExtractionStore(); - const startExtraction = useMutation(api.extraction.mutations.startExtraction); - const searchHistory = useSearchHistoryStore((state) => state.searchHistory); - - const steps = useMemo(() => [ - { id: 1, title: t("jobDetails"), icon: Layers, description: t("nameYourJob") }, - { id: 2, title: t("selectPapers"), icon: FileText, description: t("chooseFromHistory") }, - { id: 3, title: t("defineQuestions"), icon: Zap, description: t("whatToExtract") }, - ], [t]); - - const handleNext = (e?: React.FormEvent) => { - e?.preventDefault(); - if (validStep < 3 && canProceed()) { - setDirection(1); - setStepRaw((prev) => Math.min(prev + 1, 3)); - } - }; - - const handleBack = () => { - if (validStep > 1) { - setDirection(-1); - setStepRaw((prev) => Math.max(prev - 1, 1)); - } else { - router.push("/extraction"); - } - }; - - const handleSubmit = async () => { - const hasHistory = draftJob.selectedHistoryIds.length > 0; - const hasZotero = (draftJob.zoteroSelection?.items || []).length > 0; - const hasManual = draftJob.manualItems.length > 0; - if (!hasHistory && !hasZotero && !hasManual) { - toast.validation.failed(t("pleaseSelectSource")); - return; - } - - if (draftJob.questions.length === 0) { - toast.validation.failed(t("pleaseCompleteSteps")); - return; - } - - const historyEntries = draftJob.selectedHistoryIds - .map((id) => searchHistory.find((h) => h.id === id)) - .filter((entry): entry is SearchResult => Boolean(entry)); - - if (hasHistory && historyEntries.length === 0) { - toast.validation.failed(t("selectedHistoryNotFound")); - return; - } - - setIsSubmitting(true); - - try { - const sourceHistoryEntries = historyEntries.map((entry) => ({ - historyId: entry.id, - searchFilters: { - query: entry.query, - field: entry.field, - yearRange: entry.yearRange, - dateRange: entry.dateRange - ? { from: entry.dateRange.from?.toISOString(), to: entry.dateRange.to?.toISOString() } - : undefined, - filterType: entry.filterType, - isYearRangeEnabled: entry.isYearRangeEnabled, - sortBy: entry.sortBy, - selectedRegions: entry.selectedRegions, - selectedCountryFocus: entry.selectedCountryFocus, - ratingRange: entry.ratingRange, - onlyRatedPapers: entry.onlyRatedPapers, - citesItemId: entry.citesItemId, - citedByItemId: entry.citedByItemId, - relatedToItemId: entry.relatedToItemId, - reviewFilter: entry.reviewFilter, - language: entry.language, - searchField: entry.field, - }, - })); - - const result = await startExtraction({ - name: draftJob.name || t("untitledJob"), - sourceType: hasHistory && !hasZotero && !hasManual - ? "history" - : hasZotero && !hasHistory && !hasManual - ? "zotero" - : hasManual && !hasHistory && !hasZotero - ? "manual" - : "mixed", - sourceHistoryEntries: sourceHistoryEntries.length > 0 ? sourceHistoryEntries : undefined, - sourceZoteroSelection: hasZotero ? draftJob.zoteroSelection || undefined : undefined, - sourceManualItems: hasManual - ? draftJob.manualItems.map((item) => ({ - ...item, - storageId: item.storageId as Id<"_storage"> | undefined, - })) - : undefined, - questions: draftJob.questions.map((q, i) => ({ - key: q.key || `q_${i}`, - question: q.question, - type: q.type, - description: q.description, - })), - }); - - clearDraftJob(); - router.push(`/extraction/${result.jobId}`); - } catch (error) { - toast.job.createFailed(error); - } finally { - setIsSubmitting(false); - } - }; - - const canProceed = () => { - switch (validStep) { - case 1: - return draftJob.name.trim().length > 0; - case 2: - return ( - (draftJob.selectedHistoryIds ?? []).length > 0 || - (draftJob.zoteroSelection?.items ?? []).length > 0 || - (draftJob.manualItems ?? []).length > 0 - ); - case 3: - return draftJob.questions.length > 0; - default: - return false; - } - }; - - return ( -
- {/* Header with Cancel */} - - - -
- {t("stepOfThree", { step: validStep, total: 3 })} -
-
- - {/* Step Progress - Horizontal Timeline */} - -
- {/* Progress Line */} -
- -
- - {/* Step Indicators */} - {steps.map((s, i) => { - const isActive = validStep >= s.id; - const isCurrent = validStep === s.id; - - return ( - - - {isActive && validStep > s.id ? ( - - ) : ( - - )} - -
-

- {s.title} -

-

- {s.description} -

-
-
- ); - })} -
-
- - {/* Content Area with Spring Physics */} -
- - - {validStep === 1 && ( -
- -

- {t("nameYourJob")} -

-

- {t("nameYourJobDescription")} -

-
- - -
- - setDraftJobName(e.target.value)} - className="h-14 text-lg" - autoFocus - /> -
-
-
- )} - - {validStep === 2 && ( -
- -

- {t("selectPapers")} -

-

- {t("combineSources")} -

- -
- - -
- )} - - {validStep === 3 && ( -
- -

- {t("defineQuestions")} -

-

- {t("whatDataPoints")} -

-
- - -
- )} -
-
-
- - {/* Footer Actions */} - - - - - -
- ); -} diff --git a/components/extraction/job-list-item.tsx b/components/extraction/job-list-item.tsx deleted file mode 100644 index a3c47ac2a..000000000 --- a/components/extraction/job-list-item.tsx +++ /dev/null @@ -1,249 +0,0 @@ -"use client"; - -import { useMemo } from "react"; -import { motion } from "motion/react"; -import type { Doc } from "@/convex/_generated/dataModel"; -import { useTranslations, useLocale, useFormatter, useNow } from "next-intl"; -import { cn } from "@/lib/utils"; -import { FileText, Clock } from "lucide-react"; -import Link from "next/link"; -import type { ViewMode } from "@/lib/types"; -import { subtleSpring } from "@/lib/animation-config"; - -type ExtractionJob = Doc<"extractionJobs">; - -interface JobListItemProps { - job: ExtractionJob; - viewMode: ViewMode; - index: number; -} - -const STATUS_DOT_COLORS: Record = { - completed: "bg-emerald-500", - failed: "bg-destructive", - cancelled: "bg-muted-foreground", -}; - -const STATUS_BAR_COLORS: Record = { - completed: "bg-emerald-500", - failed: "bg-destructive", - cancelled: "bg-muted-foreground", -}; - -const STATUS_STRIPE_COLORS: Record = { - completed: "bg-emerald-500", - failed: "bg-destructive", - cancelled: "bg-muted-foreground", -}; - -function getStatusDotColor(status: string) { - return STATUS_DOT_COLORS[status] ?? "bg-primary animate-pulse"; -} - -function getStatusBarColor(status: string) { - return STATUS_BAR_COLORS[status] ?? "bg-primary"; -} - -function getStatusStripeColor(status: string) { - return STATUS_STRIPE_COLORS[status] ?? "bg-primary"; -} - -export function JobListItem({ job, viewMode, index }: JobListItemProps) { - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - const locale = useLocale(); - const format = useFormatter(); - const now = useNow(); - - const statusLabelMap: Record = useMemo(() => ({ - completed: tc("completed"), - failed: tc("failed"), - cancelled: tc("cancelled"), - }), [tc]); - - const getStatusLabel = (status: string) => - statusLabelMap[status] ?? status.replace(/_/g, " "); - const progressPercentage = - job.totalPapers > 0 - ? Math.round((job.processedPapers / job.totalPapers) * 100) - : 0; - - // list-simple: Single compact row - if (viewMode === "list-simple") { - return ( - - - {/* Status dot */} - - - {/* Job name */} - - {job.name} - - - {/* Papers count */} - - {t("paperProgress", { processed: job.processedPapers, total: job.totalPapers })} - - - {/* Time ago */} - - {format.relativeTime(new Date(job.createdAt), now)} - - - - ); - } - - // list-detail: Detailed row - if (viewMode === "list-detail") { - return ( - - -
-
- {/* Status dot */} - - -
- {/* Job name */} -

- {job.name} -

- - {/* Description */} - {job.description && ( -

- {job.description} -

- )} - - {/* Progress bar */} -
- -
- - {/* Metadata row */} -
- - {getStatusLabel(job.status)} - - - - -
- - {t("paperProgress", { processed: job.processedPapers, total: job.totalPapers })} -
- - - -
- - {format.relativeTime(new Date(job.createdAt), now)} -
-
-
-
-
-
- - ); - } - - // grid-2 / grid-3: Card layout - const isCompact = viewMode === "grid-3"; - - return ( - - - {/* Colored top stripe */} -
- - {/* Content */} -
- {/* Job name */} -

- {job.name} -

- - {/* Description */} - {job.description && ( -

- {job.description} -

- )} - - {/* Progress bar */} -
- -
- - {/* Metadata */} -
-
- - {t("paperProgress", { processed: job.processedPapers, total: job.totalPapers })} -
- - {format.relativeTime(new Date(job.createdAt), now)} - -
-
- - - ); -} diff --git a/components/extraction/manual-items.tsx b/components/extraction/manual-items.tsx deleted file mode 100644 index cc48b474a..000000000 --- a/components/extraction/manual-items.tsx +++ /dev/null @@ -1,172 +0,0 @@ -"use client"; -"use no memo"; // try/finally in handlers - -import { useState } from "react"; -import { useTranslations } from "next-intl"; -import { useMutation } from "convex/react"; -import { api } from "@/convex/_generated/api"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Textarea } from "@/components/ui/textarea"; -import { useExtractionStore } from "@/lib/store/extraction"; -import { cn } from "@/lib/utils"; -import { useAppToast } from "@/lib/toast"; -import { useFeatureFlag } from "@/lib/feature-flags/hook"; -import { FileUp, Plus, Trash2 } from "lucide-react"; - -const ACCEPTED_TYPES = ["application/pdf"]; -const MAX_FILE_MB = 25; - -export function ManualItems() { - const toast = useAppToast(); - const t = useTranslations("extraction"); - const tc = useTranslations("common"); - const tToast = useTranslations("toast"); - const { draftJob, addManualItem, updateManualItem, removeManualItem } = useExtractionStore(); - const generateUploadUrl = useMutation(api.extraction.uploads.generateUploadUrl); - const [uploadingIds, setUploadingIds] = useState([]); - const pdfEnabled = useFeatureFlag("extraction.pdf"); - - const handleFileUpload = async (id: string, file: File) => { - if (!ACCEPTED_TYPES.includes(file.type)) { - toast.validation.fileType(tToast("entityPdf")); - return; - } - if (file.size > MAX_FILE_MB * 1024 * 1024) { - toast.validation.fileSize(MAX_FILE_MB); - return; - } - - setUploadingIds((prev) => [...prev, id]); - try { - const uploadUrl = await generateUploadUrl({}); - const result = await fetch(uploadUrl, { - method: "POST", - headers: { "Content-Type": file.type }, - body: file, - }); - if (!result.ok) { - toast.io.uploadFailed(tToast("entityPdf")); - return; - } - const { storageId } = await result.json(); - updateManualItem(id, { storageId, pdfUrl: undefined }); - } catch (error) { - toast.io.uploadFailed(tToast("entityPdf")); - } finally { - setUploadingIds((prev) => prev.filter((itemId) => itemId !== id)); - } - }; - - return ( -
-
-
- {t("addPapersDescription")} -
- -
- - {draftJob.manualItems.length === 0 && ( -
- {t("noManualItems")} -
- )} - -
- {draftJob.manualItems.map((item, index) => { - const isUploading = uploadingIds.includes(item.id); - return ( -
-
-
- updateManualItem(item.id, { title: e.target.value })} - /> -