llm-bench

"""Task ts_next: a NexTask-shape Next.js App Router app with Prisma (SQLite), a Zod-validated API
route and a server-rendered page.

Gates: install (`npm install`); typecheck (`npx tsc --noEmit`); test (`npm test`; `vitest run`
exits non-zero when no test runs); serves (dev server: GET / 200, POST /api/items valid -> 201,
invalid -> 400, GET /api/items lists the new item). Every npm/npx call of the item (tools AND
gates) runs with npm_config_before=NPM_BEFORE, so "latest" and ^ranges resolve to the same
versions on every run. REFERENCE pins the newest release inside each major the PLAN asks for,
not the overall latest: Prisma 7+ drops `url` in the datasource block the PLAN specifies.
"""
import json
import os
import time
import urllib.error
import urllib.request

from bench.core import tools

CATEGORY = "ts"
GATES = ("install", "typecheck", "test", "serves")
PORT_TOKEN = None
TOOLSET = tools.TS_TOOLSET
NPM_BEFORE = "2026-10-01T00:00:00.000Z"
ENV = {"npm_config_before": NPM_BEFORE}

TASK_NAME = "ts_next"

PLAN = """\
# Task — Build a Next.js app with Prisma + API route + Zod validation

## Goal
`npm install` succeeds, `npx tsc --noEmit` passes (typecheck), `npm test`
passes (a Vitest unit test of the Zod schema), and the dev server responds:
`GET /` returns the HTML page, `POST /api/items` with valid JSON creates an
item (201), `POST /api/items` with invalid JSON returns 400, `GET /api/items`
returns the list. Mirrors the NexTask shape: Next.js App Router + Prisma +
Zod-validated API routes + server-rendered page.

## Prerequisites
Starter scaffold in the work dir:
  - `package.json` (name: "items-app", no deps yet)
  - `tsconfig.json` (basic strict config)
  - `next.config.ts` (minimal)

## Spec — the app to build
A Next.js 15+ App Router app with a Prisma-backed CRUD API for "items" (a
simple name + description entity). One page (`/`) that server-renders the
item list + a create form. One API route (`POST /api/items` + `GET /api/items`)
with Zod input validation on POST. Prisma with SQLite (file-based, no external
DB needed).

### Prisma schema (prisma/schema.prisma)
  generator client { provider = "prisma-client-js" }
  datasource db { provider = "sqlite"; url = "file:./dev.db" }
  model Item {
    id          String   @id @default(cuid())
    name        String
    description String
    createdAt   DateTime @default(now())
  }

### Files to produce
  package.json              deps: next (15+), react, react-dom; devDeps: typescript, @types/react, @types/node, prisma, @prisma/client, zod, vitest, @vitejs/plugin-react, jsdom. Scripts: dev, build, test, typecheck (tsc --noEmit).
  tsconfig.json             strict, target ES2022, moduleResolution bundler, jsx preserve, lib [dom, dom.iterable, esnext], paths for ~/* -> src/*.
  next.config.ts            minimal (no special config needed).
  prisma/schema.prisma      the schema above.
  src/lib/prisma.ts         export a singleton PrismaClient instance.
  src/lib/validation.ts     export `createItemSchema = z.object({ name: z.string().min(1).max(100), description: z.string().min(1).max(500) })` and `type CreateItemInput = z.infer<typeof createItemSchema>`.
  src/lib/validation.test.ts a Vitest test: valid input parses, empty name fails, name > 100 chars fails, empty description fails.
  src/app/layout.tsx        root layout (html + body, minimal).
  src/app/page.tsx          server component: fetches items via prisma, renders a list + a client-side create form (the form POSTs to /api/items as JSON; on success, refresh the page — a simple form with onSubmit that fetch + router.refresh() is fine, or even simpler: a plain HTML form that posts to /api/items and redirects back).
  src/app/api/items/route.ts POST: parse JSON body, validate with createItemSchema, on failure return 400 + errors; on success prisma.item.create + return 201 + the created item. GET: prisma.item.findMany + return 200 + the list.

### Constraints
  - Use Prisma with the **sqlite** provider (file-based `dev.db` — no external Postgres needed for this bench).
  - Use `zod` for API input validation — this is the security boundary (same pattern as NexTask).
  - The API route must return **400** with the Zod errors on invalid input, **201** + the created item on success.
  - The page (`/`) must server-render the item list (read from Prisma in the server component).
  - Use Next.js App Router (`src/app/` layout). NOT the pages router.
  - Run `npx prisma generate` + `npx prisma db push` after writing the schema so the client is generated + the DB is created.

## Steps
1. Write package.json + tsconfig.json + next.config.ts.
2. `npm install` (this pulls next, react, prisma, zod, vitest — takes a minute).
3. Write prisma/schema.prisma. Run `npx prisma generate && npx prisma db push`.
4. Write src/lib/{prisma.ts, validation.ts, validation.test.ts}.
5. Write src/app/{layout.tsx, page.tsx, api/items/route.ts}.
6. `npm run typecheck` (tsc --noEmit) — fix type errors.
7. `npm test` (vitest) — the validation test must pass.
8. Optionally start the dev server briefly to confirm it responds.

## Acceptance (harness-verified)
1. `npm install` exits 0.
2. `npx tsc --noEmit` exits 0 (typecheck clean).
3. `npm test` exits 0 (vitest passes).
4. Dev server starts; `GET /` returns 200 + HTML containing an item list or a form; `POST /api/items` with valid JSON (`{"name":"Test","description":"desc"}`) returns 201; `POST /api/items` with invalid JSON (`{"name":"","description":""}`) returns 400; `GET /api/items` returns 200 + a JSON array.

## Out of scope
Auth/Auth.js, sessions, CSRF, Postgres, Docker, Tailwind, RBAC, middleware, themes. This is the smallest real NexTask-shape — a working CRUD app with Zod-validated API + server-rendered page.

## Commit
You do not commit; the harness owns the work dir.
"""

STARTER = {
    "package.json": json.dumps({
        "name": "items-app",
        "version": "0.1.0",
        "private": True,
        "scripts": {"dev": "next dev", "build": "next build", "test": "vitest run", "typecheck": "tsc --noEmit"},
        "dependencies": {},
        "devDependencies": {}
    }, indent=2),
    "tsconfig.json": json.dumps({
        "compilerOptions": {
            "target": "ES2022", "lib": ["dom", "dom.iterable", "esnext"],
            "allowJs": True, "skipLibCheck": True, "strict": True,
            "noEmit": True, "esModuleInterop": True, "module": "esnext",
            "moduleResolution": "bundler", "resolveJsonModule": True,
            "isolatedModules": True, "jsx": "preserve", "incremental": True,
            "plugins": [{"name": "next"}],
            "paths": {"~/*": ["./src/*"]}
        },
        "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
        "exclude": ["node_modules"]
    }, indent=2),
    "next.config.ts": "import type { NextConfig } from 'next'\n\nconst config: NextConfig = {}\n\nexport default config\n",
}

# The reference is minimal but complete. Prisma + sqlite is the trickiest part
# to get self-contained — we use the prisma sqlite provider with a file-based db.
REFERENCE = {
    "package.json": json.dumps({
        "name": "items-app",
        "version": "0.1.0",
        "private": True,
        "scripts": {"dev": "next dev", "build": "next build", "start": "next start", "test": "vitest run", "typecheck": "tsc --noEmit"},
        "dependencies": {
            "next": "15.5.27",
            "react": "19.3.0",
            "react-dom": "19.3.0",
            "@prisma/client": "6.19.3",
            "zod": "3.25.76",
        },
        "devDependencies": {
            "typescript": "5.9.3",
            "@types/react": "19.3.0",
            "@types/node": "22.20.4",
            "prisma": "6.19.3",
            "vitest": "2.1.9",
            "@vitejs/plugin-react": "4.7.0",
            "jsdom": "25.0.1",
        }
    }, indent=2),
    "tsconfig.json": STARTER["tsconfig.json"],
    "next.config.ts": STARTER["next.config.ts"],
    "vitest.config.ts": '''import { defineConfig } from 'vitest/config'
export default defineConfig({
  test: { environment: 'node', include: ['src/**/*.test.ts'] },
})
''',
    "prisma/schema.prisma": '''generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

model Item {
  id          String   @id @default(cuid())
  name        String
  description String
  createdAt   DateTime @default(now())
}
''',
    "src/lib/prisma.ts": '''import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined }
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
''',
    "src/lib/validation.ts": '''import { z } from 'zod'

export const createItemSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().min(1).max(500),
})

export type CreateItemInput = z.infer<typeof createItemSchema>
''',
    "src/lib/validation.test.ts": '''import { describe, it, expect } from 'vitest'
import { createItemSchema } from './validation'

describe('createItemSchema', () => {
  it('accepts valid input', () => {
    const result = createItemSchema.safeParse({ name: 'Test', description: 'desc' })
    expect(result.success).toBe(true)
  })
  it('rejects empty name', () => {
    const result = createItemSchema.safeParse({ name: '', description: 'desc' })
    expect(result.success).toBe(false)
  })
  it('rejects name > 100 chars', () => {
    const result = createItemSchema.safeParse({ name: 'x'.repeat(101), description: 'desc' })
    expect(result.success).toBe(false)
  })
  it('rejects empty description', () => {
    const result = createItemSchema.safeParse({ name: 'Test', description: '' })
    expect(result.success).toBe(false)
  })
})
''',
    "src/app/layout.tsx": '''import type { ReactNode } from 'react'

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
''',
    "src/app/page.tsx": '''import { prisma } from '~/lib/prisma'

export default async function Home() {
  const items = await prisma.item.findMany({ orderBy: { createdAt: 'desc' } })
  return (
    <main>
      <h1>Items</h1>
      <form action="/api/items" method="POST" id="createForm">
        <input name="name" placeholder="Name" required />
        <input name="description" placeholder="Description" required />
        <button type="submit">Add</button>
      </form>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.name}: {item.description}</li>
        ))}
      </ul>
    </main>
  )
}
''',
    "src/app/api/items/route.ts": '''import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '~/lib/prisma'
import { createItemSchema } from '~/lib/validation'

export async function GET() {
  const items = await prisma.item.findMany({ orderBy: { createdAt: 'desc' } })
  return NextResponse.json(items)
}

export async function POST(request: NextRequest) {
  let body: unknown
  try {
    body = await request.json()
  } catch {
    return NextResponse.json({ error: 'invalid JSON' }, { status: 400 })
  }
  const parsed = createItemSchema.safeParse(body)
  if (!parsed.success) {
    return NextResponse.json({ error: 'validation failed', issues: parsed.error.issues }, { status: 400 })
  }
  const item = await prisma.item.create({ data: parsed.data })
  return NextResponse.json(item, { status: 201 })
}
''',
    "next-env.d.ts": '/// <reference types="next" />\n/// <reference types="next/image-types/global" />\n',
    ".gitignore": "node_modules\ndev.db*\n.next\n",
}

def _has_real_app(work_dir):
    if not os.path.isfile(os.path.join(work_dir, "src", "app", "page.tsx")): return False
    if not os.path.isfile(os.path.join(work_dir, "src", "app", "api", "items", "route.ts")): return False
    if not os.path.isfile(os.path.join(work_dir, "prisma", "schema.prisma")): return False
    return True


def gates(ws, port=None):
    """Return ({gate_name: bool}, detail)."""
    g = {k: False for k in GATES}
    d = {}
    if not _has_real_app(ws.dir):
        d["reason"] = "no real app present (page.tsx / api/items/route.ts / schema.prisma missing)"
        return g, d
    # install
    inst = ws.run("npm install", 300)
    g["install"] = inst.ok
    if not g["install"]:
        d["install_tail"] = inst.text()[-400:]
        return g, d
    # prisma generate + db push
    d["prisma_generate_ok"] = ws.run("npx prisma generate", 120).ok
    d["prisma_db_push_ok"] = ws.run("npx prisma db push", 120).ok
    # typecheck
    tc = ws.run("npx tsc --noEmit", 120)
    g["typecheck"] = tc.ok
    if not tc.ok:
        d["typecheck_tail"] = tc.text()[-400:]
    # test
    te = ws.run("npm test", 120)
    g["test"] = te.ok
    if not te.ok:
        d["test_tail"] = te.text()[-400:]
    # serves: start dev server, test the API + page
    if port is None or not tools.port_is_free(port):
        port = ws.allocate_port()
    d["port"] = port
    try:
        proc = ws.popen(["npx", "next", "dev", "-p", str(port)], env={"PORT": str(port)})
    except Exception as e:
        d["serves"] = f"failed to start dev server: {e!r}"
        return g, d
    try:
        # wait for the dev server to be ready (can take 10-30s on first compile)
        for _ in range(60):
            try:
                with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=2) as r:
                    if r.status == 200:
                        page_html = r.read().decode(errors="replace")
                        break
            except Exception:
                time.sleep(1)
        else:
            d["serves"] = "dev server never returned 200 on / : " + ws.proc_output(proc, 400)
            return g, d
        page_ok = "<h1>Items</h1>" in page_html or "Items" in page_html
        # POST valid
        base = f"http://127.0.0.1:{port}"
        valid_data = json.dumps({"name": "BenchItem", "description": "from harness"}).encode()
        req = urllib.request.Request(f"{base}/api/items", data=valid_data,
                                     headers={"Content-Type": "application/json"}, method="POST")
        post_ok = False
        try:
            with urllib.request.urlopen(req, timeout=15) as r:
                post_ok = r.status == 201
        except Exception:
            post_ok = False
        # POST invalid (should 400)
        invalid_data = json.dumps({"name": "", "description": ""}).encode()
        req2 = urllib.request.Request(f"{base}/api/items", data=invalid_data,
                                      headers={"Content-Type": "application/json"}, method="POST")
        reject_ok = False
        try:
            with urllib.request.urlopen(req2, timeout=15) as r:
                reject_ok = False  # should have been 400
        except urllib.error.HTTPError as e:
            reject_ok = e.code == 400
        except Exception:
            reject_ok = False
        # GET list
        get_ok = False
        try:
            with urllib.request.urlopen(f"{base}/api/items", timeout=15) as r:
                items = json.loads(r.read().decode())
                get_ok = isinstance(items, list) and any(isinstance(i, dict) and i.get("name") == "BenchItem" for i in items)
        except Exception:
            pass
        g["serves"] = page_ok and post_ok and reject_ok and get_ok
        if not g["serves"]:
            d["serves_detail"] = f"page={page_ok} post={post_ok} reject400={reject_ok} get={get_ok}"
    finally:
        ws.stop(proc, grace=10)
    return g, d