From 5c18185d6f22ae8b31c9757d1cd1969b6d7a8207 Mon Sep 17 00:00:00 2001 From: rjgtav Date: Wed, 18 Nov 2026 13:41:28 +0000 Subject: [PATCH 1/6] feat(framework): expose the agent sandbox to tool scorers Lets a scorer run the files the agent produced in the sandbox it worked in. --- apps/framework/harness/run-eval.ts | 1 + packages/core/src/index.ts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/apps/framework/harness/run-eval.ts b/apps/framework/harness/run-eval.ts index e1a86de4..19a9432f 100644 --- a/apps/framework/harness/run-eval.ts +++ b/apps/framework/harness/run-eval.ts @@ -573,6 +573,7 @@ async function runOne( transcript: run.transcript, agentReport: run.agentReport, judge: judges.judge, + sandbox: cliSandbox?.sandbox, }); const scoringEndedAt = Date.now(); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2d40130f..4331507f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -315,6 +315,11 @@ export interface ToolEvalContext extends ToolScoringContext { agentReport?: string; /** Ask an LLM judge whether `input` meets `rubric`. Each call shows up in the run's trace. */ judge: (args: JudgeInput) => Promise; + /** + * The sandbox the agent worked in, when it ran in one (a CLI agent). Lets a + * scorer run the files the agent produced; absent for in-process agents. + */ + sandbox?: AgentSandbox; } /** From bfa08895c9fdb9f317e01c11c95fbb8f43aa4058 Mon Sep 17 00:00:00 2001 From: rjgtav Date: Wed, 18 Nov 2026 13:41:28 +0000 Subject: [PATCH 2/6] refactor(spark): share scorer helpers and make getClient publishable getClient now returns a publishable-key client, like the local stack, while client keeps the secret key for reading ground truth. Add stubSandbox for the Spark eval tests and checkNoRawSql, which also rejects the SQL endpoint. --- experiments/spark/lib/runtime-stub.ts | 58 ++++++++++++++++++++++++++- experiments/spark/lib/runtime.test.ts | 26 +++++++++++- experiments/spark/lib/runtime.ts | 16 +++++--- experiments/spark/lib/scoring.test.ts | 31 +++++++++++++- experiments/spark/lib/scoring.ts | 24 ++++++++++- 5 files changed, 144 insertions(+), 11 deletions(-) diff --git a/experiments/spark/lib/runtime-stub.ts b/experiments/spark/lib/runtime-stub.ts index 8f68a530..98fe2dd9 100644 --- a/experiments/spark/lib/runtime-stub.ts +++ b/experiments/spark/lib/runtime-stub.ts @@ -1,5 +1,13 @@ -import type { ToolEvalContext, ToolScorer } from '@supabase-evals/core'; -import { vi } from 'vitest'; +import { execFile } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import type { + AgentSandbox, + ToolEvalContext, + ToolScorer, +} from '@supabase-evals/core'; +import { onTestFinished, vi } from 'vitest'; import { sparkRuntime } from './runtime.js'; export const SPARK_TEST_KEYS = { @@ -76,3 +84,49 @@ export const bashCalls = (commands: string[]) => /** Names of the checks that failed. */ export const failedChecks = (result: Awaited>) => (result.checks ?? []).filter((check) => !check.passed).map((c) => c.name); + +/** + * A sandbox over a real temp workspace holding `files` (paths relative to the + * workspace), run with the real shell and node. `npm install` is a no-op and + * `@supabase/supabase-js` resolves to a stub package, so no network is needed. + * Call it inside a test: the workspace is removed when that test finishes. + */ +export function stubSandbox(files: Record): AgentSandbox { + const workspace = mkdtempSync(join(tmpdir(), 'spark-stub-')); + onTestFinished(() => rmSync(workspace, { recursive: true, force: true })); + const sdk = 'app/node_modules/@supabase/supabase-js'; + for (const [path, content] of Object.entries({ + 'app/package.json': '{"type":"module"}', + [`${sdk}/package.json`]: + '{"name":"@supabase/supabase-js","main":"index.js"}', + [`${sdk}/index.js`]: 'exports.createClient = () => ({});', + ...files, + })) { + mkdirSync(dirname(join(workspace, path)), { recursive: true }); + writeFileSync(join(workspace, path), content); + } + return { + workspace, + exec: (command, options) => + new Promise((resolve) => + execFile( + 'bash', + ['-c', command.replace('npm install', 'true')], + { + cwd: workspace, + env: { ...process.env, ...options?.env }, + timeout: options?.timeoutMs, + }, + (error, stdout, stderr) => + resolve({ + ok: !error, + exitCode: error ? Number(error.code ?? 1) : 0, + stdout, + stderr, + }) + ) + ), + readFile: async () => '', + copyToHost: async () => {}, + }; +} diff --git a/experiments/spark/lib/runtime.test.ts b/experiments/spark/lib/runtime.test.ts index 0d368365..7481830f 100644 --- a/experiments/spark/lib/runtime.test.ts +++ b/experiments/spark/lib/runtime.test.ts @@ -2,7 +2,8 @@ import { mkdtemp, readFile, stat, writeFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, expect, it, vi } from 'vitest'; -import { sparkRuntime } from './runtime.js'; +import { type SparkScoringContext, sparkRuntime } from './runtime.js'; +import { SPARK_TEST_KEYS, sparkScorer } from './runtime-stub.js'; afterEach(() => vi.unstubAllGlobals()); @@ -77,6 +78,29 @@ it('creates fresh projects, seeds before execution and reads scoring state', asy } }); +it('getClient uses the publishable key, client the secret key', async () => { + const seen: Record = {}; + await sparkScorer( + async (ctx) => { + const { getClient, client } = ctx as unknown as SparkScoringContext; + const first = getClient(); + expect(getClient()).not.toBe(first); + await first.from('publishable_table').select('id'); + await client.from('secret_table').select('id'); + return { checks: [] }; + }, + (url, init, request) => { + const headers = new Headers(request ? request.headers : init?.headers); + seen[url.pathname.split('/').pop() ?? ''] = headers.get('apikey'); + return Response.json([]); + } + ); + expect(seen).toEqual({ + publishable_table: SPARK_TEST_KEYS.publishable, + secret_table: SPARK_TEST_KEYS.secret, + }); +}); + it('rejects configuration and unsupported fixtures before provisioning', async () => { const fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); diff --git a/experiments/spark/lib/runtime.ts b/experiments/spark/lib/runtime.ts index ff9713fd..7150b658 100644 --- a/experiments/spark/lib/runtime.ts +++ b/experiments/spark/lib/runtime.ts @@ -21,7 +21,12 @@ export type SparkProjectStatus = { secretKey: string; }; -/** Scoring context plus the project's URL and keys, for scorers that act as an end user or look for leaked keys. */ +/** + * Scoring context plus the project's URL and keys, for scorers that act as an + * end user or look for leaked keys. `client` uses the secret key (service_role, + * bypasses RLS); `getClient()` returns a fresh publishable-key client with no + * session (anon role), matching the local stack. + */ export type SparkScoringContext = ToolScoringContext & { project: SparkProjectStatus; }; @@ -100,10 +105,11 @@ export function sparkRuntime( ); } + const authOptions = { + auth: { persistSession: false, autoRefreshToken: false }, + }; const getClient = () => - createClient(project.url, secret, { - auth: { persistSession: false, autoRefreshToken: false }, - }); + createClient(project.url, publishable, authOptions); return { // WARP credentials live on the VM. mountDockerSocket: false, @@ -129,7 +135,7 @@ export function sparkRuntime( ref: project.ref, // Required by ToolScoringContext, but Spark's Management API is incomplete. mgmt: createManagementApiClient(apiUrl, secret), - client: getClient(), + client: createClient(project.url, secret, authOptions), getClient, async query(sql) { const response = await fetch( diff --git a/experiments/spark/lib/scoring.test.ts b/experiments/spark/lib/scoring.test.ts index e82ea12b..f5aaa324 100644 --- a/experiments/spark/lib/scoring.test.ts +++ b/experiments/spark/lib/scoring.test.ts @@ -1,5 +1,6 @@ -import { describe, expect, it } from 'vitest'; -import { findLeakedCredentials } from './scoring.js'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { stubSandbox } from './runtime-stub.js'; +import { checkNoRawSql, findLeakedCredentials } from './scoring.js'; const project = { projectUrl: 'https://project.example', @@ -55,3 +56,29 @@ describe('findLeakedCredentials', () => { ).toEqual([]); }); }); + +describe('checkNoRawSql', () => { + const scan = (source: string) => + checkNoRawSql(stubSandbox({ 'app/report.mjs': source }), 'app'); + + it('passes a Data API app and flags psql, raw drivers and the SQL endpoint', async () => { + expect( + await scan(`import { createClient } from '@supabase/supabase-js';`) + ).toMatchObject({ + name: 'report queries via the Data API, not raw SQL', + passed: true, + notes: 'no psql / raw Postgres driver / SQL endpoint usage found', + }); + for (const source of [ + `const driver = 'pg';`, + `const driver = "postgres";`, + `const driver = 'pg-promise';`, + `const command = 'psql -c "select 1"';`, + `const path = '/database/query';`, + ]) + expect(await scan(source)).toMatchObject({ + passed: false, + notes: 'app/report.mjs', + }); + }); +}); diff --git a/experiments/spark/lib/scoring.ts b/experiments/spark/lib/scoring.ts index f2dbf2c8..810c6ae6 100644 --- a/experiments/spark/lib/scoring.ts +++ b/experiments/spark/lib/scoring.ts @@ -1,4 +1,4 @@ -import type { ToolEvalContext } from '@supabase-evals/core'; +import type { CheckResult, ToolEvalContext } from '@supabase-evals/core'; import type { SparkProjectStatus } from './runtime.js'; const JWT = /eyJ[\w-]+\.[\w-]+\.[\w-]+/; @@ -36,3 +36,25 @@ export function findLeakedCredentials( JWT.test(visible) ? 'JWT-shaped token' : undefined, ].filter((leak) => leak !== undefined); } + +/** + * The app must query through the Data API: no psql, no raw Postgres driver + * (pg / postgres / pg-promise) and no Spark SQL endpoint (`/database/query`) + * anywhere in `appDir`. + */ +export async function checkNoRawSql( + sandbox: NonNullable, + appDir: string +): Promise { + const scan = await sandbox.exec( + `grep -rlE --exclude-dir=node_modules --include='*.mjs' --include='*.js' --include='*.cjs' --include='*.ts' ` + + `"psql|['\\"](pg|postgres|pg-promise)['\\"]|/database/query" ${appDir} || true` + ); + return { + name: 'report queries via the Data API, not raw SQL', + passed: scan.stdout.trim() === '', + notes: + scan.stdout.trim().replace(/\s+/g, ', ') || + 'no psql / raw Postgres driver / SQL endpoint usage found', + }; +} From 358ad5bfed76f7dd51280b10757dfd22f7560873 Mon Sep 17 00:00:00 2001 From: rjgtav Date: Wed, 18 Nov 2026 13:41:28 +0000 Subject: [PATCH 3/6] feat(spark): port dataapi-001 relational report to the original shape Same app stub, schema with RLS and scorer checks as the benchmark eval, run through supabase-js against a Spark project. --- .../EVAL.test.ts | 218 ++++++----- .../EVAL.ts | 356 +++++++++--------- .../PROMPT.md | 18 +- .../local/app/package.json | 5 + .../local/app/report.mjs | 22 ++ .../remote/project.sql | 92 +++-- 6 files changed, 391 insertions(+), 320 deletions(-) create mode 100644 evals/spark/build-dataapi-001-relational-report-spark/local/app/package.json create mode 100644 evals/spark/build-dataapi-001-relational-report-spark/local/app/report.mjs diff --git a/evals/spark/build-dataapi-001-relational-report-spark/EVAL.test.ts b/evals/spark/build-dataapi-001-relational-report-spark/EVAL.test.ts index 72b6cf6b..e242abae 100644 --- a/evals/spark/build-dataapi-001-relational-report-spark/EVAL.test.ts +++ b/evals/spark/build-dataapi-001-relational-report-spark/EVAL.test.ts @@ -1,42 +1,33 @@ import { describe, expect, it } from 'vitest'; import { - bashCalls, + SPARK_TEST_KEYS, failedChecks, sparkScorer, + stubSandbox, } from '../../../experiments/spark/lib/runtime-stub.js'; import scorer from './EVAL.js'; -const tables: Record = { - customers: [ - { id: 1, name: 'Ada Lovelace' }, - { id: 2, name: 'Grace Hopper' }, - { id: 3, name: 'Linus Pauling' }, - { id: 4, name: 'Alan Turing' }, - ], - products: [ - { id: 1, name: 'Keyboard', price_cents: 4500 }, - { id: 2, name: 'Mouse', price_cents: 2500 }, - { id: 3, name: 'Monitor', price_cents: 32000 }, - { id: 4, name: 'Cable', price_cents: 900 }, - ], - orders: [ - { id: 1, customer_id: 1 }, - { id: 2, customer_id: 1 }, - { id: 3, customer_id: 2 }, - { id: 4, customer_id: 2 }, - { id: 5, customer_id: 3 }, - ], - order_items: [ - { order_id: 1, product_id: 1, quantity: 2 }, - { order_id: 1, product_id: 4, quantity: 1 }, - { order_id: 2, product_id: 3, quantity: 1 }, - { order_id: 3, product_id: 2, quantity: 3 }, - { order_id: 4, product_id: 1, quantity: 1 }, - { order_id: 4, product_id: 4, quantity: 4 }, - { order_id: 5, product_id: 3, quantity: 2 }, - { order_id: 5, product_id: 2, quantity: 1 }, - ], -}; +// What the SQL endpoint returns for the scorer's expected-report query. +const expectedRows = [ + { + customer: 'Ada Lovelace', + order_count: 2, + total_cents: 41900, + top_product: 'Keyboard', + }, + { + customer: 'Grace Hopper', + order_count: 2, + total_cents: 15600, + top_product: 'Cable', + }, + { + customer: 'Linus Pauling', + order_count: 1, + total_cents: 66500, + top_product: 'Monitor', + }, +]; const report = [ { @@ -59,106 +50,127 @@ const report = [ }, ]; -async function score(options: { - reply: string; - data?: Record; - commands?: string[]; -}) { +/** A report script that uses the SDK client (the stub) and prints `value`. */ +const sdkScript = (value: unknown = report) => `// Nightly sales report +import { createClient } from '@supabase/supabase-js'; +if (!process.env.SPARK_PROJECT_URL || !process.env.SPARK_SECRET_KEY) process.exit(2); +createClient(process.env.SPARK_PROJECT_URL, process.env.SPARK_SECRET_KEY); +console.log(JSON.stringify(${JSON.stringify(value)}, null, 2)); +`; + +async function score( + options: { + script?: string; + publishable?: 'denied' | 'empty' | 'rows'; + } = {} +) { + const { publishable = 'denied' } = options; return failedChecks( await sparkScorer( scorer, - (url) => - Response.json( - (options.data ?? tables)[url.pathname.replace('/rest/v1/', '')] - ), + (url, init, request) => { + if (url.pathname === '/database/query') + return Response.json(expectedRows); + const apikey = new Headers(init?.headers ?? request?.headers).get( + 'apikey' + ); + if (apikey !== SPARK_TEST_KEYS.publishable) return Response.json([]); + if (publishable === 'denied') + return Response.json( + { message: 'permission denied: read on table customers' }, + { status: 403 } + ); + return Response.json( + publishable === 'empty' ? [] : [{ id: 1 }, { id: 2 }] + ); + }, { - transcript: bashCalls( - options.commands ?? [ - 'curl "$SPARK_PROJECT_URL/rest/v1/customers?select=*,orders(*)"', - ] - ), - agentReport: options.reply, + sandbox: stubSandbox({ + 'app/report.mjs': options.script ?? sdkScript(), + }), } ) ); } -const fenced = (value: unknown) => - `Here you go:\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``; - describe('relational report scorer', () => { - it('accepts the correct report, fenced or bare', async () => { - expect(await score({ reply: fenced(report) })).toEqual([]); - expect(await score({ reply: JSON.stringify(report) })).toEqual([]); + it('passes every check for an SDK report with the right output and a locked-down project', async () => { + // The script exits 2 without the project URL and secret key, so this also + // proves the scorer sets them. + expect(await score()).toEqual([]); }); - it('rejects wrong numbers, wrong order and tie-break mistakes', async () => { - const name = 'Report numbers match the database (per customer, sorted)'; + it('rejects wrong output, and a report that is not implemented or prints no JSON array', async () => { + const name = 'report numbers match the database (per customer, sorted)'; for (const wrong of [ report.map((row, i) => (i === 0 ? { ...row, totalCents: 1 } : row)), report.map((row, i) => (i === 1 ? { ...row, orderCount: 3 } : row)), report.map((row, i) => (i === 2 ? { ...row, topProduct: 'Mouse' } : row)), [...report].reverse(), + [ + ...report, + { + customer: 'Alan Turing', + orderCount: 0, + totalCents: 0, + topProduct: null, + }, + ], ]) - expect(await score({ reply: fenced(wrong) })).toEqual([name]); - }); + expect(await score({ script: sdkScript(wrong) })).toEqual([name]); - it('rejects a customer without orders', async () => { - const withAlan = [ - ...report, - { customer: 'Alan Turing', orderCount: 0, totalCents: 0, topProduct: '' }, + const failing = [ + 'report runs and prints JSON', + 'report numbers match the database (per customer, sorted)', ]; - expect(await score({ reply: fenced(withAlan) })).toEqual([ - 'Report numbers match the database (per customer, sorted)', - 'Customers without orders are left out', - ]); - }); - - it('rejects a reply without a JSON array', async () => { - expect(await score({ reply: 'Ada ordered the most.' })).toEqual([ - 'Reply contains the report as a JSON array', - 'Report numbers match the database (per customer, sorted)', - 'Customers without orders are left out', - ]); - }); - - it('detects changed seed data', async () => { expect( await score({ - reply: fenced(report), - data: { ...tables, order_items: tables.order_items.slice(1) }, + script: `import { createClient } from '@supabase/supabase-js';\nconsole.error('not implemented');\nprocess.exit(1);\n`, + }) + ).toEqual(failing); + expect( + await score({ + script: `import { createClient } from '@supabase/supabase-js';\nconsole.log('Ada ordered the most.');\n`, }) - ).toContain('Seed data left unchanged'); + ).toEqual(failing); }); - it('detects edited seed rows that keep the row counts', async () => { - const products = tables.products.map((p, i) => - i === 0 ? { ...p, price_cents: 1 } : p - ); - expect( - await score({ reply: fenced(report), data: { ...tables, products } }) - ).toContain('Seed data left unchanged'); + it('fails the lock-down check when a publishable key reads rows, passes on error or empty data', async () => { + expect(await score({ publishable: 'rows' })).toEqual([ + 'tables stay locked down (publishable key reads nothing)', + ]); + expect(await score({ publishable: 'denied' })).toEqual([]); + expect(await score({ publishable: 'empty' })).toEqual([]); }); - it('requires the Data API and rejects the SQL endpoint', async () => { - const name = 'Report is built from the Data API, not the SQL endpoint'; - expect( - await score({ - reply: fenced(report), - commands: ['curl "$SPARK_PROJECT_URL/database/query" -d {}'], - }) - ).toEqual([name]); + it('requires a real @supabase/supabase-js import', async () => { + const name = 'implementation uses @supabase/supabase-js'; + const printing = `console.log(JSON.stringify(${JSON.stringify(report)}));`; + for (const script of [ + // Plain fetch against the REST API. + `const res = await fetch(process.env.SPARK_PROJECT_URL + '/rest/v1/customers');\n${printing}\n`, + // Commented out, or a different package with the same prefix. + `// import { createClient } from '@supabase/supabase-js';\n${printing}\n`, + `import { createClient } from '@supabase/supabase-js-not-real';\n${printing}\n`, + ]) + expect(await score({ script })).toContain(name); expect( await score({ - reply: fenced(report), - commands: [ - 'curl "$SPARK_PROJECT_URL/rest/v1/orders?select=id,customers(name)"', - 'curl "$SPARK_PROJECT_URL/database/query" -d {}', - ], + script: `const { createClient } = await import('@supabase/supabase-js');\n${printing}\n`, }) - ).toEqual([name]); - expect(await score({ reply: fenced(report), commands: [] })).toEqual([ - name, - ]); + ).not.toContain(name); + }); + + it('rejects psql, raw Postgres drivers and the SQL endpoint', async () => { + const name = 'report queries via the Data API, not raw SQL'; + for (const extra of [ + `const driver = 'pg';`, + `const driver = "postgres";`, + `const command = 'psql -c "select 1"';`, + `const path = '/database/query';`, + ]) + expect(await score({ script: `${sdkScript()}${extra}\n` })).toEqual([ + name, + ]); }); }); diff --git a/evals/spark/build-dataapi-001-relational-report-spark/EVAL.ts b/evals/spark/build-dataapi-001-relational-report-spark/EVAL.ts index e0bb2303..b002e985 100644 --- a/evals/spark/build-dataapi-001-relational-report-spark/EVAL.ts +++ b/evals/spark/build-dataapi-001-relational-report-spark/EVAL.ts @@ -1,197 +1,209 @@ -import type { CheckResult, ToolScorer } from '@supabase-evals/core'; -import { z } from 'zod'; - -// Spark port of the benchmark build-dataapi-001 scenario. The agent produces -// the report itself, reading through the Data API, and replies with the JSON array. Expected numbers are -// computed at scoring time from the project's own rows (read over the Data -// API), so the seed stays the single source of truth. The original's -// backend-only access control (RLS) is not scored: Spark has no RLS yet. - -const tablesSchema = { - customers: z.array(z.object({ id: z.number(), name: z.string() })), - products: z.array( - z.object({ id: z.number(), name: z.string(), price_cents: z.number() }) - ), - orders: z.array(z.object({ id: z.number(), customer_id: z.number() })), - order_items: z.array( - z.object({ - order_id: z.number(), - product_id: z.number(), - quantity: z.number(), - }) - ), -}; +import type { + CheckResult, + ToolEvalContext, + ToolScorer, +} from '@supabase-evals/core'; +import type { SparkScoringContext } from '../../../experiments/spark/lib/runtime.js'; +import { checkNoRawSql } from '../../../experiments/spark/lib/scoring.js'; + +// Spark port of the benchmark build-dataapi-001 scenario: the prompt asks the +// agent to finish a backend reporting script (`app/report.mjs`) over a seeded +// relational schema (customers → orders → order_items → products) and never +// names supabase-js — the "uses @supabase/supabase-js" check is GATING, and +// shelling out to psql / a raw Postgres driver instead fails. Expected numbers +// are computed from the project's own rows at scoring time, so the seed stays +// the single source of truth. + +const APP_DIR = 'app'; +const REPORT = 'report.mjs'; -// Row counts in the seed, to detect an agent that changed the data. -const SEED_COUNTS = { customers: 4, products: 4, orders: 5, order_items: 8 }; - -// The report the seed produces. Expected rows are derived from live data, so -// this catches an agent that edited rows without changing their count. -const SEED_REPORT = [ - { - customer: 'Ada Lovelace', - orderCount: 2, - totalCents: 41900, - topProduct: 'Keyboard', - }, - { - customer: 'Grace Hopper', - orderCount: 2, - totalCents: 15600, - topProduct: 'Cable', - }, - { - customer: 'Linus Pauling', - orderCount: 1, - totalCents: 66500, - topProduct: 'Monitor', - }, -]; - -type ReportRow = { +interface ReportRow { customer: unknown; orderCount: unknown; totalCents: unknown; topProduct: unknown; -}; +} -const normalize = (rows: ReportRow[]) => - rows.map((row) => ({ - customer: row.customer, - orderCount: row.orderCount, - totalCents: row.totalCents, - topProduct: row.topProduct, - })); +const EXPECTED_SQL = ` +with per_product as ( + select c.name as customer, p.name as product, + sum(oi.quantity)::int as units + from public.customers c + join public.orders o on o.customer_id = c.id + join public.order_items oi on oi.order_id = o.id + join public.products p on p.id = oi.product_id + group by c.name, p.name +), totals as ( + select c.name as customer, + count(distinct o.id)::int as order_count, + sum(oi.quantity * p.price_cents)::int as total_cents + from public.customers c + join public.orders o on o.customer_id = c.id + join public.order_items oi on oi.order_id = o.id + join public.products p on p.id = oi.product_id + group by c.name +) +select t.customer, + t.order_count, + t.total_cents, + (select pp.product + from per_product pp + where pp.customer = t.customer + order by pp.units desc, pp.product asc + limit 1) as top_product + from totals t + order by t.customer asc +`; const scorer: ToolScorer = async (ctx) => { const checks: CheckResult[] = []; - const read = async (table: T) => { - const { data, error } = await ctx.client.from(table).select('*'); - if (error) throw new Error(`${table}: ${error.message}`); - return tablesSchema[table].parse(data) as z.infer<(typeof tablesSchema)[T]>; - }; - - let expected: ReturnType | undefined; try { - const [customers, products, orders, items] = await Promise.all([ - read('customers'), - read('products'), - read('orders'), - read('order_items'), - ]); - expected = expectedReport(customers, products, orders, items); + const { sandbox } = ctx; + if (!sandbox) + return fail( + 'agent sandbox available', + 'the scorer runs the report in the agent sandbox, but this run had none' + ); + const { project } = ctx as unknown as SparkScoringContext; + + // Be generous about a missing install step; the eval is about the report, + // not npm. A no-op when the agent already installed dependencies. + const install = await sandbox.exec( + `cd ${APP_DIR} && npm install --no-audit --no-fund --silent`, + { timeoutMs: 180_000 } + ); + if (!install.ok) { + return fail( + 'installed app dependencies', + install.stderr.trim() || install.stdout.trim() + ); + } + + const run = await sandbox.exec(`cd ${APP_DIR} && node ${REPORT}`, { + timeoutMs: 60_000, + env: { + SPARK_PROJECT_URL: project.projectUrl, + SPARK_SECRET_KEY: project.secretKey, + }, + }); + const actual = parseReport(run.stdout); + checks.push({ + name: 'report runs and prints JSON', + passed: run.ok && actual !== undefined, + notes: + actual !== undefined + ? `exit ${run.exitCode}` + : `no JSON array in output — ${preview(run.stderr || run.stdout)}`, + }); + + // Ground truth straight from the seeded database. + const { rows } = await ctx.query(EXPECTED_SQL); + const expected = rows.map((row) => ({ + customer: row.customer, + orderCount: row.order_count, + totalCents: row.total_cents, + topProduct: row.top_product, + })); + const normalized = (actual ?? []).map((row) => ({ + customer: row.customer, + orderCount: row.orderCount, + totalCents: row.totalCents, + topProduct: row.topProduct, + })); + checks.push({ + name: 'report numbers match the database (per customer, sorted)', + passed: JSON.stringify(normalized) === JSON.stringify(expected), + notes: `expected ${JSON.stringify(expected)}, got ${JSON.stringify(normalized)}`, + }); + + // The tables are backend-only: the right fix is the secret key in the + // worker, not opening them up to client keys. + // Spark reports the denied read as an error rather than empty data. + const probe = await ctx.getClient().from('customers').select('id'); checks.push({ - name: 'Seed data left unchanged', - passed: - JSON.stringify(expected) === JSON.stringify(SEED_REPORT) && - customers.length === SEED_COUNTS.customers && - products.length === SEED_COUNTS.products && - orders.length === SEED_COUNTS.orders && - items.length === SEED_COUNTS.order_items, - notes: `customers ${customers.length}, products ${products.length}, orders ${orders.length}, order_items ${items.length}`, + name: 'tables stay locked down (publishable key reads nothing)', + passed: !!probe.error || (probe.data ?? []).length === 0, + notes: probe.error + ? `publishable read errored: ${probe.error.message}` + : `publishable read returned ${(probe.data ?? []).length} rows`, }); + + // GATING: the report must be built on supabase-js, even though the prompt + // never names it… + checks.push(await sdkUsageCheck(sandbox)); + + // …and must actually query through the Data API, not shell out to psql, a + // raw Postgres driver or Spark's SQL endpoint. + checks.push(await checkNoRawSql(sandbox, APP_DIR)); + + return { passed: checks.every((c) => c.passed), checks }; } catch (error) { + const msg = error instanceof Error ? error.message : String(error); checks.push({ - name: 'Seed data left unchanged', + name: 'scorer completed without errors', passed: false, - notes: error instanceof Error ? error.message : String(error), + notes: msg, }); + return { passed: false, checks }; } - - const actual = parseReport(ctx.agentReport ?? ''); - checks.push({ - name: 'Reply contains the report as a JSON array', - passed: actual !== undefined, - notes: actual - ? undefined - : (ctx.agentReport ?? '').replace(/\s+/g, ' ').slice(0, 160), - }); - checks.push({ - name: 'Report numbers match the database (per customer, sorted)', - passed: - !!expected && - !!actual && - JSON.stringify(normalize(actual)) === JSON.stringify(expected), - notes: `expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual && normalize(actual))}`, - }); - checks.push({ - name: 'Customers without orders are left out', - passed: - !!expected && - !!actual && - actual.length === expected.length && - !actual.some((row) => row.customer === 'Alan Turing'), - }); - - const commands = ctx.transcript - .filter((part) => part.type === 'tool_call') - .map((part) => JSON.stringify(part.input)); - checks.push({ - name: 'Report is built from the Data API, not the SQL endpoint', - passed: - commands.some((command) => command.includes('/rest/v1/')) && - !commands.some((command) => command.includes('/database/query')), - notes: `${commands.filter((c) => c.includes('/rest/v1/')).length} Data API call(s), ${commands.filter((c) => c.includes('/database/query')).length} SQL endpoint call(s)`, - }); - - return { passed: checks.every((check) => check.passed), checks }; }; export default scorer; -function expectedReport( - customers: z.infer<(typeof tablesSchema)['customers']>, - products: z.infer<(typeof tablesSchema)['products']>, - orders: z.infer<(typeof tablesSchema)['orders']>, - items: z.infer<(typeof tablesSchema)['order_items']> -) { - const productById = new Map(products.map((p) => [p.id, p])); - const orderCustomer = new Map(orders.map((o) => [o.id, o.customer_id])); - const report = customers.flatMap((customer) => { - const customerOrders = orders.filter((o) => o.customer_id === customer.id); - if (customerOrders.length === 0) return []; - const units = new Map(); - let totalCents = 0; - for (const item of items) { - if (orderCustomer.get(item.order_id) !== customer.id) continue; - const product = productById.get(item.product_id); - if (!product) continue; - totalCents += item.quantity * product.price_cents; - units.set(product.name, (units.get(product.name) ?? 0) + item.quantity); - } - const [topProduct] = [...units].sort( - ([nameA, unitsA], [nameB, unitsB]) => - unitsB - unitsA || (nameA < nameB ? -1 : nameA > nameB ? 1 : 0) - )[0] ?? [null]; - return [ - { - customer: customer.name, - orderCount: customerOrders.length, - totalCents, - topProduct, - }, - ]; - }); - return normalize( - report.sort((a, b) => (a.customer < b.customer ? -1 : 1)) as ReportRow[] - ); +function parseReport(stdout: string): ReportRow[] | undefined { + const start = stdout.indexOf('['); + const end = stdout.lastIndexOf(']'); + if (start === -1 || end <= start) return undefined; + try { + const parsed = JSON.parse(stdout.slice(start, end + 1)); + return Array.isArray(parsed) ? (parsed as ReportRow[]) : undefined; + } catch { + return undefined; + } } -/** The report array from the agent's reply: a fenced block first, else the outermost brackets. */ -function parseReport(reply: string): ReportRow[] | undefined { - const candidates = [ - ...[...reply.matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1]), - reply.slice(reply.indexOf('['), reply.lastIndexOf(']') + 1), +/** + * GATING: some app code file must genuinely import @supabase/supabase-js — + * the specifier must be closed by a matching quote (so `-not-real` doesn't + * match) and sit on a `from`/`require(`/`import(` line that isn't commented + * out. Multi-line named imports still match: the closing `} from '…'` line + * always carries `from` alongside the specifier. + */ +async function sdkUsageCheck( + sandbox: NonNullable +): Promise { + const NAME = 'implementation uses @supabase/supabase-js'; + const scan = await sandbox.exec( + `grep -rnE --exclude-dir=node_modules --include='*.mjs' --include='*.js' --include='*.cjs' --include='*.ts' ` + + `"(from|require\\(|import\\()\\s*['\\"](npm:)?@supabase/supabase-js['\\"]" ${APP_DIR} ` + + `| grep -vE ':[0-9]+:\\s*(//|\\*)' || true` + ); + const files = [ + ...new Set( + scan.stdout + .trim() + .split('\n') + .filter(Boolean) + .map((line) => line.slice(0, line.indexOf(':'))) + ), ]; - for (const candidate of candidates) { - try { - const parsed: unknown = JSON.parse(candidate); - if ( - Array.isArray(parsed) && - parsed.every((row) => typeof row === 'object' && row !== null) - ) - return parsed as ReportRow[]; - } catch {} - } - return undefined; + return { + name: NAME, + passed: files.length > 0, + notes: + files.length > 0 + ? `imports found in: ${files.join(', ')}` + : 'no @supabase/supabase-js import found — this eval requires the SDK', + }; +} + +function preview(body: string): string { + return body.replace(/\s+/g, ' ').slice(0, 160); +} + +function fail( + name: string, + notes: string +): { passed: false; checks: CheckResult[] } { + return { passed: false, checks: [{ name, passed: false, notes }] }; } diff --git a/evals/spark/build-dataapi-001-relational-report-spark/PROMPT.md b/evals/spark/build-dataapi-001-relational-report-spark/PROMPT.md index 72bab3b9..dbc88c99 100644 --- a/evals/spark/build-dataapi-001-relational-report-spark/PROMPT.md +++ b/evals/spark/build-dataapi-001-relational-report-spark/PROMPT.md @@ -5,11 +5,17 @@ product: - data-api - database topic: - - sql -motivation: Spark port of the benchmark build-dataapi-001 scenario. The report is produced by the agent directly, and access control is not scored until Spark supports RLS. + - sdk +motivation: >- + Spark port of the benchmark build-dataapi-001 scenario. Relationship embedding + is the query-builder surface users trip on most (supabase/postgrest-js#609, + supabase/postgrest-js#611, supabase/supabase-js#1639), and the most-used + supabase-js surface had no dedicated eval coverage. --- -We need the nightly sales report from the provided Spark project's order history. -Read the data through the Data API and reply with a JSON array of `{customer, orderCount, totalCents, topProduct}` for each customer with at least one order, sorted by name. -`totalCents` is what they spent in cents, and `topProduct` is the product they bought the most units of (alphabetically first on a tie). -Don't change the data. +We need the nightly sales report working. `app/report.mjs` has the spec in a +comment — it runs in our Node backend worker and prints a JSON summary of what +each customer has ordered. + +The data lives in the provided Spark project (already running). Finish the +script and make sure it prints the right numbers. diff --git a/evals/spark/build-dataapi-001-relational-report-spark/local/app/package.json b/evals/spark/build-dataapi-001-relational-report-spark/local/app/package.json new file mode 100644 index 00000000..81652eb0 --- /dev/null +++ b/evals/spark/build-dataapi-001-relational-report-spark/local/app/package.json @@ -0,0 +1,5 @@ +{ + "name": "reporting-worker", + "private": true, + "type": "module" +} diff --git a/evals/spark/build-dataapi-001-relational-report-spark/local/app/report.mjs b/evals/spark/build-dataapi-001-relational-report-spark/local/app/report.mjs new file mode 100644 index 00000000..e2cba815 --- /dev/null +++ b/evals/spark/build-dataapi-001-relational-report-spark/local/app/report.mjs @@ -0,0 +1,22 @@ +// Nightly sales report, run inside our Node backend worker: +// +// node report.mjs +// +// Connection settings come from the environment: SPARK_PROJECT_URL and +// SPARK_SECRET_KEY (this is trusted backend code). +// +// Print to stdout a JSON array with one entry per customer who has placed at +// least one order, sorted by customer name: +// +// { +// "customer": string, // customer name +// "orderCount": number, // how many orders they placed +// "totalCents": number, // total spent across all their orders +// "topProduct": string // product they bought the most units of +// } +// +// If two products tie on units, topProduct is the alphabetically first one. +// +// TODO: implement +console.error('not implemented'); +process.exit(1); diff --git a/evals/spark/build-dataapi-001-relational-report-spark/remote/project.sql b/evals/spark/build-dataapi-001-relational-report-spark/remote/project.sql index b3bb0ceb..29f889c1 100644 --- a/evals/spark/build-dataapi-001-relational-report-spark/remote/project.sql +++ b/evals/spark/build-dataapi-001-relational-report-spark/remote/project.sql @@ -1,55 +1,69 @@ --- Order history for the sales report. Alan has no orders and must not appear --- in the report. +-- Order history for the reporting worker. These tables are backend-only: +-- RLS is enabled with no policies, so client-side (publishable) keys read +-- nothing. Trusted backend code authenticates with the secret key, which +-- bypasses RLS. create table public.customers ( - id integer primary key, + id bigint generated always as identity primary key, name text not null, email text not null unique ); create table public.products ( - id integer primary key, + id bigint generated always as identity primary key, name text not null, - price_cents integer not null + price_cents int not null ); create table public.orders ( - id integer primary key, - customer_id integer not null references public.customers (id), + id bigint generated always as identity primary key, + customer_id bigint not null references public.customers (id), ordered_at timestamptz not null default now() ); create table public.order_items ( - id integer primary key, - order_id integer not null references public.orders (id), - product_id integer not null references public.products (id), - quantity integer not null check (quantity > 0) + id bigint generated always as identity primary key, + order_id bigint not null references public.orders (id), + product_id bigint not null references public.products (id), + quantity int not null check (quantity > 0) ); -insert into public.customers (id, name, email) values - (1, 'Ada Lovelace', 'ada@example.com'), - (2, 'Grace Hopper', 'grace@example.com'), - (3, 'Linus Pauling', 'linus@example.com'), - (4, 'Alan Turing', 'alan@example.com'); - -insert into public.products (id, name, price_cents) values - (1, 'Keyboard', 4500), - (2, 'Mouse', 2500), - (3, 'Monitor', 32000), - (4, 'Cable', 900); - -insert into public.orders (id, customer_id, ordered_at) values - (1, 1, '2026-06-01T10:00:00Z'), - (2, 1, '2026-06-14T09:30:00Z'), - (3, 2, '2026-06-03T16:20:00Z'), - (4, 2, '2026-06-20T11:05:00Z'), - (5, 3, '2026-06-08T14:45:00Z'); - -insert into public.order_items (id, order_id, product_id, quantity) values - (1, 1, 1, 2), -- Ada: 2x Keyboard - (2, 1, 4, 1), -- Ada: 1x Cable - (3, 2, 3, 1), -- Ada: 1x Monitor - (4, 3, 2, 3), -- Grace: 3x Mouse - (5, 4, 1, 1), -- Grace: 1x Keyboard - (6, 4, 4, 4), -- Grace: 4x Cable - (7, 5, 3, 2), -- Linus: 2x Monitor - (8, 5, 2, 1); -- Linus: 1x Mouse +alter table public.customers enable row level security; +alter table public.products enable row level security; +alter table public.orders enable row level security; +alter table public.order_items enable row level security; + +-- Newer Supabase CLIs no longer auto-grant privileges on migration-created +-- tables. The trusted backend (secret key → service_role) needs the SELECT +-- privilege; client-side roles get nothing, so these tables stay backend-only. +grant select on public.customers, public.products, public.orders, + public.order_items to service_role; + +-- Seed data. Alan has no orders and must not appear in the report. +insert into public.customers (name, email) values + ('Ada Lovelace', 'ada@example.com'), + ('Grace Hopper', 'grace@example.com'), + ('Linus Pauling', 'linus@example.com'), + ('Alan Turing', 'alan@example.com'); + +insert into public.products (name, price_cents) values + ('Keyboard', 4500), + ('Mouse', 2500), + ('Monitor', 32000), + ('Cable', 900); + +insert into public.orders (customer_id, ordered_at) values + (1, '2026-06-01T10:00:00Z'), + (1, '2026-06-14T09:30:00Z'), + (2, '2026-06-03T16:20:00Z'), + (2, '2026-06-20T11:05:00Z'), + (3, '2026-06-08T14:45:00Z'); + +insert into public.order_items (order_id, product_id, quantity) values + (1, 1, 2), -- Ada: 2x Keyboard + (1, 4, 1), -- Ada: 1x Cable + (2, 3, 1), -- Ada: 1x Monitor + (3, 2, 3), -- Grace: 3x Mouse + (4, 1, 1), -- Grace: 1x Keyboard + (4, 4, 4), -- Grace: 4x Cable + (5, 3, 2), -- Linus: 2x Monitor + (5, 2, 1); -- Linus: 1x Mouse From 0b03b75c1b02af9ad42477d64d37afd8395303df Mon Sep 17 00:00:00 2001 From: rjgtav Date: Wed, 18 Nov 2026 13:41:28 +0000 Subject: [PATCH 4/6] feat(spark): port dataapi-002 restock alert report to the original shape --- .../EVAL.test.ts | 241 ++++++------ .../EVAL.ts | 356 +++++++++--------- .../PROMPT.md | 21 +- .../local/app/package.json | 5 + .../local/app/restock.mjs | 24 ++ .../remote/project.sql | 86 +++-- 6 files changed, 399 insertions(+), 334 deletions(-) create mode 100644 evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/package.json create mode 100644 evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/restock.mjs diff --git a/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.test.ts b/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.test.ts index d357faab..787ab9b6 100644 --- a/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.test.ts +++ b/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.test.ts @@ -1,39 +1,45 @@ import { describe, expect, it } from 'vitest'; import { - bashCalls, + SPARK_TEST_KEYS, failedChecks, sparkScorer, + stubSandbox, } from '../../../experiments/spark/lib/runtime-stub.js'; import scorer from './EVAL.js'; -const tables: Record = { - warehouses: [ - { id: 1, name: 'North DC' }, - { id: 2, name: 'South DC' }, - { id: 3, name: 'West DC' }, - ], - suppliers: [ - { id: 1, name: 'Acme Supplies', email: 'acme@example.com' }, - { id: 2, name: 'Global Parts', email: 'parts@example.com' }, - ], - products: [ - { id: 1, name: 'Widget', supplier_id: 1, reorder_threshold: 20 }, - { id: 2, name: 'Gadget', supplier_id: 2, reorder_threshold: 15 }, - { id: 3, name: 'Gizmo', supplier_id: 1, reorder_threshold: 10 }, - ], - inventory: [ - { id: 1, warehouse_id: 1, product_id: 1, quantity: 5 }, - { id: 2, warehouse_id: 1, product_id: 2, quantity: 30 }, - { id: 3, warehouse_id: 1, product_id: 3, quantity: 3 }, - { id: 4, warehouse_id: 2, product_id: 1, quantity: 25 }, - { id: 5, warehouse_id: 2, product_id: 2, quantity: 2 }, - { id: 6, warehouse_id: 2, product_id: 3, quantity: 12 }, - { id: 7, warehouse_id: 3, product_id: 1, quantity: 20 }, - { id: 8, warehouse_id: 3, product_id: 2, quantity: 0 }, - ], -}; +// What the SQL endpoint returns for the scorer's expected-alerts query. +const expectedRows = [ + { + warehouse: 'North DC', + product: 'Gizmo', + quantity: 3, + reorder_threshold: 10, + supplier_email: 'acme@example.com', + }, + { + warehouse: 'North DC', + product: 'Widget', + quantity: 5, + reorder_threshold: 20, + supplier_email: 'acme@example.com', + }, + { + warehouse: 'South DC', + product: 'Gadget', + quantity: 2, + reorder_threshold: 15, + supplier_email: 'parts@example.com', + }, + { + warehouse: 'West DC', + product: 'Gadget', + quantity: 0, + reorder_threshold: 15, + supplier_email: 'parts@example.com', + }, +]; -const alerts = [ +const report = [ { warehouse: 'North DC', product: 'Gizmo', @@ -64,112 +70,129 @@ const alerts = [ }, ]; -async function score(options: { - reply: string; - data?: Record; - commands?: string[]; -}) { +/** A report script that uses the SDK client (the stub) and prints `value`. */ +const sdkScript = (value: unknown = report) => `// Restock alert worker +import { createClient } from '@supabase/supabase-js'; +if (!process.env.SPARK_PROJECT_URL || !process.env.SPARK_SECRET_KEY) process.exit(2); +createClient(process.env.SPARK_PROJECT_URL, process.env.SPARK_SECRET_KEY); +console.log(JSON.stringify(${JSON.stringify(value)}, null, 2)); +`; + +async function score( + options: { + script?: string; + publishable?: 'denied' | 'empty' | 'rows'; + } = {} +) { + const { publishable = 'denied' } = options; return failedChecks( await sparkScorer( scorer, - (url) => - Response.json( - (options.data ?? tables)[url.pathname.replace('/rest/v1/', '')] - ), + (url, init, request) => { + if (url.pathname === '/database/query') + return Response.json(expectedRows); + const apikey = new Headers(init?.headers ?? request?.headers).get( + 'apikey' + ); + if (apikey !== SPARK_TEST_KEYS.publishable) return Response.json([]); + if (publishable === 'denied') + return Response.json( + { message: 'permission denied: read on table inventory' }, + { status: 403 } + ); + return Response.json( + publishable === 'empty' ? [] : [{ id: 1 }, { id: 2 }] + ); + }, { - transcript: bashCalls( - options.commands ?? ['curl "$SPARK_PROJECT_URL/rest/v1/inventory"'] - ), - agentReport: options.reply, + sandbox: stubSandbox({ + 'app/restock.mjs': options.script ?? sdkScript(), + }), } ) ); } -const fenced = (value: unknown) => - `Here you go:\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``; -const matchName = 'Alerts match the database (below threshold, sorted)'; - describe('restock alert scorer', () => { - it('accepts the correct alerts, fenced or bare', async () => { - expect(await score({ reply: fenced(alerts) })).toEqual([]); - expect(await score({ reply: JSON.stringify(alerts) })).toEqual([]); + it('passes every check for an SDK report with the right output and a locked-down project', async () => { + // The script exits 2 without the project URL and secret key, so this also + // proves the scorer sets them. + expect(await score()).toEqual([]); }); - it('rejects wrong values and wrong order', async () => { + it('rejects wrong output, and a report that is not implemented or prints no JSON array', async () => { + const name = 'alerts match the database (below threshold, sorted)'; for (const wrong of [ - alerts.map((row, i) => (i === 0 ? { ...row, quantity: 4 } : row)), - alerts.map((row, i) => - i === 2 ? { ...row, supplierEmail: 'acme@example.com' } : row - ), - alerts.slice(1), - [...alerts].reverse(), + report.map((row, i) => (i === 0 ? { ...row, quantity: 4 } : row)), + report.map((row, i) => (i === 1 ? { ...row, supplierEmail: 'x' } : row)), + [...report].reverse(), + // West DC's Widget sits exactly at its threshold: not strictly below. + [ + ...report, + { + warehouse: 'West DC', + product: 'Widget', + quantity: 20, + reorderThreshold: 20, + supplierEmail: 'acme@example.com', + }, + ], + report.slice(1), ]) - expect(await score({ reply: fenced(wrong) })).toEqual([matchName]); - }); + expect(await score({ script: sdkScript(wrong) })).toEqual([name]); - it('rejects an alert for a row exactly at its threshold', async () => { - const withBoundary = [ - ...alerts, - { - warehouse: 'West DC', - product: 'Widget', - quantity: 20, - reorderThreshold: 20, - supplierEmail: 'acme@example.com', - }, + const failing = [ + 'report runs and prints JSON', + 'alerts match the database (below threshold, sorted)', ]; - expect(await score({ reply: fenced(withBoundary) })).toEqual([ - matchName, - 'Rows at the threshold are not alerted', - ]); - }); - - it('rejects a reply without a JSON array', async () => { - expect(await score({ reply: 'Widgets are low.' })).toEqual([ - 'Reply contains the alerts as a JSON array', - matchName, - 'Rows at the threshold are not alerted', - ]); - }); - - it('detects changed seed data', async () => { expect( await score({ - reply: fenced(alerts), - data: { ...tables, inventory: tables.inventory.slice(1) }, + script: `import { createClient } from '@supabase/supabase-js';\nconsole.error('not implemented');\nprocess.exit(1);\n`, }) - ).toContain('Seed data left unchanged'); + ).toEqual(failing); + expect( + await score({ + script: `import { createClient } from '@supabase/supabase-js';\nconsole.log('Ada ordered the most.');\n`, + }) + ).toEqual(failing); }); - it('detects edited seed rows that keep the row counts', async () => { - const inventory = tables.inventory.map((r, i) => - i === 0 ? { ...r, quantity: 6 } : r - ); - expect( - await score({ reply: fenced(alerts), data: { ...tables, inventory } }) - ).toContain('Seed data left unchanged'); + it('fails the lock-down check when a publishable key reads rows, passes on error or empty data', async () => { + expect(await score({ publishable: 'rows' })).toEqual([ + 'tables stay locked down (publishable key reads nothing)', + ]); + expect(await score({ publishable: 'denied' })).toEqual([]); + expect(await score({ publishable: 'empty' })).toEqual([]); }); - it('requires the Data API and rejects the SQL endpoint', async () => { - const name = 'Alerts are built from the Data API, not the SQL endpoint'; - expect( - await score({ - reply: fenced(alerts), - commands: ['curl "$SPARK_PROJECT_URL/database/query" -d {}'], - }) - ).toEqual([name]); + it('requires a real @supabase/supabase-js import', async () => { + const name = 'implementation uses @supabase/supabase-js'; + const printing = `console.log(JSON.stringify(${JSON.stringify(report)}));`; + for (const script of [ + // Plain fetch against the REST API. + `const res = await fetch(process.env.SPARK_PROJECT_URL + '/rest/v1/inventory');\n${printing}\n`, + // Commented out, or a different package with the same prefix. + `// import { createClient } from '@supabase/supabase-js';\n${printing}\n`, + `import { createClient } from '@supabase/supabase-js-not-real';\n${printing}\n`, + ]) + expect(await score({ script })).toContain(name); expect( await score({ - reply: fenced(alerts), - commands: [ - 'curl "$SPARK_PROJECT_URL/rest/v1/inventory"', - 'curl "$SPARK_PROJECT_URL/database/query" -d {}', - ], + script: `const { createClient } = await import('@supabase/supabase-js');\n${printing}\n`, }) - ).toEqual([name]); - expect(await score({ reply: fenced(alerts), commands: [] })).toEqual([ - name, - ]); + ).not.toContain(name); + }); + + it('rejects psql, raw Postgres drivers and the SQL endpoint', async () => { + const name = 'report queries via the Data API, not raw SQL'; + for (const extra of [ + `const driver = 'pg';`, + `const driver = "postgres";`, + `const command = 'psql -c "select 1"';`, + `const path = '/database/query';`, + ]) + expect(await score({ script: `${sdkScript()}${extra}\n` })).toEqual([ + name, + ]); }); }); diff --git a/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.ts b/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.ts index 381a1932..8c878642 100644 --- a/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.ts +++ b/evals/spark/build-dataapi-002-restock-alert-report-spark/EVAL.ts @@ -1,211 +1,197 @@ -import type { CheckResult, ToolScorer } from '@supabase-evals/core'; -import { z } from 'zod'; - -// Spark port of the benchmark build-dataapi-002 scenario. The agent produces -// the alert list itself, reading through the Data API, and replies with the -// JSON array. Expected alerts are computed at scoring time from the project's -// own rows, so the seed stays the single source of truth. The original's -// backend-only access control (RLS) is not scored: Spark has no RLS yet. - -const tablesSchema = { - warehouses: z.array(z.object({ id: z.number(), name: z.string() })), - suppliers: z.array(z.object({ id: z.number(), email: z.string() })), - products: z.array( - z.object({ - id: z.number(), - name: z.string(), - supplier_id: z.number(), - reorder_threshold: z.number(), - }) - ), - inventory: z.array( - z.object({ - warehouse_id: z.number(), - product_id: z.number(), - quantity: z.number(), - }) - ), -}; +import type { + CheckResult, + ToolEvalContext, + ToolScorer, +} from '@supabase-evals/core'; +import type { SparkScoringContext } from '../../../experiments/spark/lib/runtime.js'; +import { checkNoRawSql } from '../../../experiments/spark/lib/scoring.js'; + +// Spark port of the benchmark build-dataapi-002 scenario, the companion to +// build-dataapi-001: same "unnamed SDK, empty package.json, backend worker +// script" shape, different schema (warehouses → inventory → products → +// suppliers) and aggregation (below-threshold restock alert, not a sales +// rollup). Checks whether the SDK adoption seen in 001 generalizes. The +// "uses @supabase/supabase-js" check is GATING, and shelling out to psql / a +// raw Postgres driver / Spark's SQL endpoint instead fails. Expected alerts +// are computed from the project's own rows at scoring time, so the seed stays +// the single source of truth. -// Row counts in the seed, to detect an agent that changed the data. -const SEED_COUNTS = { warehouses: 3, suppliers: 2, products: 3, inventory: 8 }; - -// The alerts the seed produces. Expected rows are derived from live data, so -// this catches an agent that edited rows without changing their count. -const SEED_ALERTS = [ - { - warehouse: 'North DC', - product: 'Gizmo', - quantity: 3, - reorderThreshold: 10, - supplierEmail: 'acme@example.com', - }, - { - warehouse: 'North DC', - product: 'Widget', - quantity: 5, - reorderThreshold: 20, - supplierEmail: 'acme@example.com', - }, - { - warehouse: 'South DC', - product: 'Gadget', - quantity: 2, - reorderThreshold: 15, - supplierEmail: 'parts@example.com', - }, - { - warehouse: 'West DC', - product: 'Gadget', - quantity: 0, - reorderThreshold: 15, - supplierEmail: 'parts@example.com', - }, -]; - -type AlertRow = { +const APP_DIR = 'app'; +const REPORT = 'restock.mjs'; + +interface AlertRow { warehouse: unknown; product: unknown; quantity: unknown; reorderThreshold: unknown; supplierEmail: unknown; -}; +} -const normalize = (rows: AlertRow[]) => - rows.map((row) => ({ - warehouse: row.warehouse, - product: row.product, - quantity: row.quantity, - reorderThreshold: row.reorderThreshold, - supplierEmail: row.supplierEmail, - })); +const EXPECTED_SQL = ` +select w.name as warehouse, + p.name as product, + i.quantity, + p.reorder_threshold, + s.email as supplier_email + from public.inventory i + join public.warehouses w on w.id = i.warehouse_id + join public.products p on p.id = i.product_id + join public.suppliers s on s.id = p.supplier_id + where i.quantity < p.reorder_threshold + order by w.name asc, p.name asc +`; const scorer: ToolScorer = async (ctx) => { const checks: CheckResult[] = []; - const read = async (table: T) => { - const { data, error } = await ctx.client.from(table).select('*'); - if (error) throw new Error(`${table}: ${error.message}`); - return tablesSchema[table].parse(data) as z.infer<(typeof tablesSchema)[T]>; - }; - - let expected: ReturnType | undefined; try { - const [warehouses, suppliers, products, inventory] = await Promise.all([ - read('warehouses'), - read('suppliers'), - read('products'), - read('inventory'), - ]); - expected = expectedAlerts(warehouses, suppliers, products, inventory); + const { sandbox } = ctx; + if (!sandbox) + return fail( + 'agent sandbox available', + 'the scorer runs the report in the agent sandbox, but this run had none' + ); + const { project } = ctx as unknown as SparkScoringContext; + + // Be generous about a missing install step; the eval is about the report, + // not npm. A no-op when the agent already installed dependencies. + const install = await sandbox.exec( + `cd ${APP_DIR} && npm install --no-audit --no-fund --silent`, + { timeoutMs: 180_000 } + ); + if (!install.ok) { + return fail( + 'installed app dependencies', + install.stderr.trim() || install.stdout.trim() + ); + } + + const run = await sandbox.exec(`cd ${APP_DIR} && node ${REPORT}`, { + timeoutMs: 60_000, + env: { + SPARK_PROJECT_URL: project.projectUrl, + SPARK_SECRET_KEY: project.secretKey, + }, + }); + const actual = parseReport(run.stdout); + checks.push({ + name: 'report runs and prints JSON', + passed: run.ok && actual !== undefined, + notes: + actual !== undefined + ? `exit ${run.exitCode}` + : `no JSON array in output — ${preview(run.stderr || run.stdout)}`, + }); + + // Ground truth straight from the seeded database. + const { rows } = await ctx.query(EXPECTED_SQL); + const expected = rows.map((row) => ({ + warehouse: row.warehouse, + product: row.product, + quantity: row.quantity, + reorderThreshold: row.reorder_threshold, + supplierEmail: row.supplier_email, + })); + const normalized = (actual ?? []).map((row) => ({ + warehouse: row.warehouse, + product: row.product, + quantity: row.quantity, + reorderThreshold: row.reorderThreshold, + supplierEmail: row.supplierEmail, + })); + checks.push({ + name: 'alerts match the database (below threshold, sorted)', + passed: JSON.stringify(normalized) === JSON.stringify(expected), + notes: `expected ${JSON.stringify(expected)}, got ${JSON.stringify(normalized)}`, + }); + + // The tables are backend-only: the right fix is the secret key in the + // worker, not opening them up to client keys. + // Spark reports the denied read as an error rather than empty data. + const probe = await ctx.getClient().from('inventory').select('id'); checks.push({ - name: 'Seed data left unchanged', - passed: - JSON.stringify(expected) === JSON.stringify(SEED_ALERTS) && - warehouses.length === SEED_COUNTS.warehouses && - suppliers.length === SEED_COUNTS.suppliers && - products.length === SEED_COUNTS.products && - inventory.length === SEED_COUNTS.inventory, - notes: `warehouses ${warehouses.length}, suppliers ${suppliers.length}, products ${products.length}, inventory ${inventory.length}`, + name: 'tables stay locked down (publishable key reads nothing)', + passed: !!probe.error || (probe.data ?? []).length === 0, + notes: probe.error + ? `publishable read errored: ${probe.error.message}` + : `publishable read returned ${(probe.data ?? []).length} rows`, }); + + // GATING: the report must be built on supabase-js, even though the prompt + // never names it… + checks.push(await sdkUsageCheck(sandbox)); + + // …and must actually query through the Data API, not shell out to psql, a + // raw Postgres driver or Spark's SQL endpoint. + checks.push(await checkNoRawSql(sandbox, APP_DIR)); + + return { passed: checks.every((c) => c.passed), checks }; } catch (error) { + const msg = error instanceof Error ? error.message : String(error); checks.push({ - name: 'Seed data left unchanged', + name: 'scorer completed without errors', passed: false, - notes: error instanceof Error ? error.message : String(error), + notes: msg, }); + return { passed: false, checks }; } - - const actual = parseAlerts(ctx.agentReport ?? ''); - checks.push({ - name: 'Reply contains the alerts as a JSON array', - passed: actual !== undefined, - notes: actual - ? undefined - : (ctx.agentReport ?? '').replace(/\s+/g, ' ').slice(0, 160), - }); - checks.push({ - name: 'Alerts match the database (below threshold, sorted)', - passed: - !!expected && - !!actual && - JSON.stringify(normalize(actual)) === JSON.stringify(expected), - notes: `expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual && normalize(actual))}`, - }); - checks.push({ - name: 'Rows at the threshold are not alerted', - passed: - !!actual && - !actual.some( - (row) => row.warehouse === 'West DC' && row.product === 'Widget' - ), - }); - - const commands = ctx.transcript - .filter((part) => part.type === 'tool_call') - .map((part) => JSON.stringify(part.input)); - checks.push({ - name: 'Alerts are built from the Data API, not the SQL endpoint', - passed: - commands.some((command) => command.includes('/rest/v1/')) && - !commands.some((command) => command.includes('/database/query')), - notes: `${commands.filter((c) => c.includes('/rest/v1/')).length} Data API call(s), ${commands.filter((c) => c.includes('/database/query')).length} SQL endpoint call(s)`, - }); - - return { passed: checks.every((check) => check.passed), checks }; }; export default scorer; -function expectedAlerts( - warehouses: z.infer<(typeof tablesSchema)['warehouses']>, - suppliers: z.infer<(typeof tablesSchema)['suppliers']>, - products: z.infer<(typeof tablesSchema)['products']>, - inventory: z.infer<(typeof tablesSchema)['inventory']> -) { - const warehouseById = new Map(warehouses.map((w) => [w.id, w])); - const supplierById = new Map(suppliers.map((s) => [s.id, s])); - const productById = new Map(products.map((p) => [p.id, p])); - const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); - return normalize( - inventory - .flatMap((row) => { - const product = productById.get(row.product_id); - const warehouse = warehouseById.get(row.warehouse_id); - const supplier = product && supplierById.get(product.supplier_id); - if (!product || !warehouse || !supplier) return []; - if (row.quantity >= product.reorder_threshold) return []; - return [ - { - warehouse: warehouse.name, - product: product.name, - quantity: row.quantity, - reorderThreshold: product.reorder_threshold, - supplierEmail: supplier.email, - }, - ]; - }) - .sort( - (a, b) => - compare(a.warehouse, b.warehouse) || compare(a.product, b.product) - ) - ); +function parseReport(stdout: string): AlertRow[] | undefined { + const start = stdout.indexOf('['); + const end = stdout.lastIndexOf(']'); + if (start === -1 || end <= start) return undefined; + try { + const parsed = JSON.parse(stdout.slice(start, end + 1)); + return Array.isArray(parsed) ? (parsed as AlertRow[]) : undefined; + } catch { + return undefined; + } } -/** The alert array from the agent's reply: a fenced block first, else the outermost brackets. */ -function parseAlerts(reply: string): AlertRow[] | undefined { - const candidates = [ - ...[...reply.matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1]), - reply.slice(reply.indexOf('['), reply.lastIndexOf(']') + 1), +/** + * GATING: some app code file must genuinely import @supabase/supabase-js — + * the specifier must be closed by a matching quote (so `-not-real` doesn't + * match) and sit on a `from`/`require(`/`import(` line that isn't commented + * out. Multi-line named imports still match: the closing `} from '…'` line + * always carries `from` alongside the specifier. + */ +async function sdkUsageCheck( + sandbox: NonNullable +): Promise { + const NAME = 'implementation uses @supabase/supabase-js'; + const scan = await sandbox.exec( + `grep -rnE --exclude-dir=node_modules --include='*.mjs' --include='*.js' --include='*.cjs' --include='*.ts' ` + + `"(from|require\\(|import\\()\\s*['\\"](npm:)?@supabase/supabase-js['\\"]" ${APP_DIR} ` + + `| grep -vE ':[0-9]+:\\s*(//|\\*)' || true` + ); + const files = [ + ...new Set( + scan.stdout + .trim() + .split('\n') + .filter(Boolean) + .map((line) => line.slice(0, line.indexOf(':'))) + ), ]; - for (const candidate of candidates) { - try { - const parsed: unknown = JSON.parse(candidate); - if ( - Array.isArray(parsed) && - parsed.every((row) => typeof row === 'object' && row !== null) - ) - return parsed as AlertRow[]; - } catch {} - } - return undefined; + return { + name: NAME, + passed: files.length > 0, + notes: + files.length > 0 + ? `imports found in: ${files.join(', ')}` + : 'no @supabase/supabase-js import found — this eval requires the SDK', + }; +} + +function preview(body: string): string { + return body.replace(/\s+/g, ' ').slice(0, 160); +} + +function fail( + name: string, + notes: string +): { passed: false; checks: CheckResult[] } { + return { passed: false, checks: [{ name, passed: false, notes }] }; } diff --git a/evals/spark/build-dataapi-002-restock-alert-report-spark/PROMPT.md b/evals/spark/build-dataapi-002-restock-alert-report-spark/PROMPT.md index 7a081de1..9ec0c25a 100644 --- a/evals/spark/build-dataapi-002-restock-alert-report-spark/PROMPT.md +++ b/evals/spark/build-dataapi-002-restock-alert-report-spark/PROMPT.md @@ -5,11 +5,20 @@ product: - data-api - database topic: - - sql -motivation: Spark port of the benchmark build-dataapi-002 scenario. The agent produces the alert list itself, and access control is not scored until Spark supports RLS. + - sdk +motivation: >- + Spark port of the benchmark build-dataapi-002 scenario, the companion to + build-dataapi-001: same "unnamed SDK, empty package.json, backend worker + script" shape with an unrelated schema and aggregation (inventory restock + alerts vs. sales report), to check whether agents' SDK adoption for a bare + backend Data API script generalizes. Agents defaulting to the wrong + data-access path on a backend task is a real, documented failure + (supabase/agent-skills#173). --- -Purchasing needs a restock alert from the provided Spark project's inventory. -Read the data through the Data API and reply with a JSON array of `{warehouse, product, quantity, reorderThreshold, supplierEmail}` for every warehouse and product combination whose quantity is strictly below the product's reorder threshold, sorted by warehouse name and then product name. -`supplierEmail` is who to email about it. -Don't change the data. +Purchasing needs a restock alert. `app/restock.mjs` has the spec in a +comment — it runs in our Node backend worker and prints a JSON list of what +needs reordering, with who to email about it. + +The data lives in the provided Spark project (already running). Finish the +script and make sure it prints the right alerts. diff --git a/evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/package.json b/evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/package.json new file mode 100644 index 00000000..4f4a0bce --- /dev/null +++ b/evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/package.json @@ -0,0 +1,5 @@ +{ + "name": "restock-alert-worker", + "private": true, + "type": "module" +} diff --git a/evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/restock.mjs b/evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/restock.mjs new file mode 100644 index 00000000..99a26e09 --- /dev/null +++ b/evals/spark/build-dataapi-002-restock-alert-report-spark/local/app/restock.mjs @@ -0,0 +1,24 @@ +// Restock alert worker, run inside our Node backend worker: +// +// node restock.mjs +// +// Connection settings come from the environment: SPARK_PROJECT_URL and +// SPARK_SECRET_KEY (this is trusted backend code). +// +// Print to stdout a JSON array with one entry per warehouse/product +// combination that's below its reorder threshold, sorted by warehouse name +// then product name: +// +// { +// "warehouse": string, // warehouse name +// "product": string, // product name +// "quantity": number, // current quantity on hand +// "reorderThreshold": number, // reorder threshold for this product +// "supplierEmail": string // email of the product's supplier +// } +// +// Only include rows where quantity is strictly below the reorder threshold. +// +// TODO: implement +console.error('not implemented'); +process.exit(1); diff --git a/evals/spark/build-dataapi-002-restock-alert-report-spark/remote/project.sql b/evals/spark/build-dataapi-002-restock-alert-report-spark/remote/project.sql index 2cc48ea9..0dfdff73 100644 --- a/evals/spark/build-dataapi-002-restock-alert-report-spark/remote/project.sql +++ b/evals/spark/build-dataapi-002-restock-alert-report-spark/remote/project.sql @@ -1,50 +1,68 @@ --- Inventory for the restock alert. West DC's Widget sits exactly at its --- threshold and must not alert, and West DC has no Gizmo row at all. +-- Inventory for the restock-alert worker. These tables are backend-only: +-- RLS is enabled with no policies, so client-side (publishable) keys read +-- nothing. Trusted backend code authenticates with the secret key, which +-- bypasses RLS. create table public.warehouses ( - id integer primary key, + id bigint generated always as identity primary key, name text not null ); create table public.suppliers ( - id integer primary key, + id bigint generated always as identity primary key, name text not null, email text not null unique ); create table public.products ( - id integer primary key, + id bigint generated always as identity primary key, name text not null, - supplier_id integer not null references public.suppliers (id), - reorder_threshold integer not null + supplier_id bigint not null references public.suppliers (id), + reorder_threshold int not null ); create table public.inventory ( - id integer primary key, - warehouse_id integer not null references public.warehouses (id), - product_id integer not null references public.products (id), - quantity integer not null check (quantity >= 0) + id bigint generated always as identity primary key, + warehouse_id bigint not null references public.warehouses (id), + product_id bigint not null references public.products (id), + quantity int not null check (quantity >= 0) ); -insert into public.warehouses (id, name) values - (1, 'North DC'), - (2, 'South DC'), - (3, 'West DC'); - -insert into public.suppliers (id, name, email) values - (1, 'Acme Supplies', 'acme@example.com'), - (2, 'Global Parts', 'parts@example.com'); - -insert into public.products (id, name, supplier_id, reorder_threshold) values - (1, 'Widget', 1, 20), - (2, 'Gadget', 2, 15), - (3, 'Gizmo', 1, 10); - -insert into public.inventory (id, warehouse_id, product_id, quantity) values - (1, 1, 1, 5), -- North DC / Widget: 5 < 20, alert - (2, 1, 2, 30), -- North DC / Gadget: ok - (3, 1, 3, 3), -- North DC / Gizmo: 3 < 10, alert - (4, 2, 1, 25), -- South DC / Widget: ok - (5, 2, 2, 2), -- South DC / Gadget: 2 < 15, alert - (6, 2, 3, 12), -- South DC / Gizmo: ok - (7, 3, 1, 20), -- West DC / Widget: exactly at threshold, no alert - (8, 3, 2, 0); -- West DC / Gadget: 0 < 15, alert +alter table public.warehouses enable row level security; +alter table public.suppliers enable row level security; +alter table public.products enable row level security; +alter table public.inventory enable row level security; + +-- Newer Supabase CLIs no longer auto-grant privileges on migration-created +-- tables. The trusted backend (secret key → service_role) needs the SELECT +-- privilege; client-side roles get nothing, so these tables stay backend-only. +grant select on public.warehouses, public.suppliers, public.products, + public.inventory to service_role; + +-- Seed data. +insert into public.warehouses (name) values + ('North DC'), + ('South DC'), + ('West DC'); + +insert into public.suppliers (name, email) values + ('Acme Supplies', 'acme@example.com'), + ('Global Parts', 'parts@example.com'); + +insert into public.products (name, supplier_id, reorder_threshold) values + ('Widget', 1, 20), + ('Gadget', 2, 15), + ('Gizmo', 1, 10); + +-- warehouse_id, product_id, quantity. Below-threshold rows are the alerts; +-- West DC's Widget sits exactly at threshold and must NOT alert (strict +-- less-than), and West DC has no Gizmo row at all (untracked combos are +-- simply absent, not a zero-quantity alert). +insert into public.inventory (warehouse_id, product_id, quantity) values + (1, 1, 5), -- North DC / Widget: 5 < 20 -> alert + (1, 2, 30), -- North DC / Gadget: 30 >= 15 -> ok + (1, 3, 3), -- North DC / Gizmo: 3 < 10 -> alert + (2, 1, 25), -- South DC / Widget: 25 >= 20 -> ok + (2, 2, 2), -- South DC / Gadget: 2 < 15 -> alert + (2, 3, 12), -- South DC / Gizmo: 12 >= 10 -> ok + (3, 1, 20), -- West DC / Widget: 20 >= 20 -> ok (boundary, not strictly below) + (3, 2, 0); -- West DC / Gadget: 0 < 15 -> alert From e62da1b5f3337738dc684a60e53b6376c49e1e0b Mon Sep 17 00:00:00 2001 From: rjgtav Date: Wed, 18 Nov 2026 13:41:28 +0000 Subject: [PATCH 5/6] feat(spark): port auth-001 email password flow to the original shape Spark has no triggers on auth.users, so the app creates the profile row itself after signup; the schema gains an insert policy for that. --- .../EVAL.test.ts | 218 +++++++----- .../EVAL.ts | 317 ++++++++++++++---- .../PROMPT.md | 20 +- .../local/app/package.json | 5 + .../local/app/src/auth.mjs | 36 ++ .../remote/project.sql | 35 +- 6 files changed, 463 insertions(+), 168 deletions(-) create mode 100644 evals/spark/build-auth-001-email-password-flow-spark/local/app/package.json create mode 100644 evals/spark/build-auth-001-email-password-flow-spark/local/app/src/auth.mjs diff --git a/evals/spark/build-auth-001-email-password-flow-spark/EVAL.test.ts b/evals/spark/build-auth-001-email-password-flow-spark/EVAL.test.ts index 86e02719..66804996 100644 --- a/evals/spark/build-auth-001-email-password-flow-spark/EVAL.test.ts +++ b/evals/spark/build-auth-001-email-password-flow-spark/EVAL.test.ts @@ -1,121 +1,155 @@ -import { describe, expect, it, vi } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { - SPARK_TEST_KEYS, failedChecks, sparkScorer, + stubSandbox, } from '../../../experiments/spark/lib/runtime-stub.js'; import scorer from './EVAL.js'; const USER_ID = '11111111-1111-4111-8111-111111111111'; -const profile = { - id: USER_ID, - display_name: 'Alex Doe', - plan: 'free', - created_at: '2026-11-06 12:00:00', -}; +// What the SQL endpoint returns for the scorer's ground-truth query: the new +// auth user joined to its profile. +const dbRow = { id: USER_ID, display_name: 'Alex Doe', plan: 'free' }; -function score( - options: { - accountExists?: boolean; - acceptsAnyPassword?: boolean; - profiles?: unknown[]; - agentReport?: string; - transcript?: Parameters[0]['transcript']; - reportPasses?: boolean; - } = {} +interface AuthModule { + /** The import line; defaults to a real supabase-js import. */ + sdkImport?: string; + /** Extra top-level source, e.g. a comment mentioning a key. */ + extra?: string; + /** Replacement bodies for the exported functions. */ + signUp?: string; + signInWrong?: string; + getMyProfile?: string; +} + +/** + * An auth module that uses the SDK client (the stub). It exits early without + * the project URL and publishable key, or when it is handed a secret key, so + * a passing run also proves the scorer sets exactly those. + */ +const authModule = (options: AuthModule = {}) => `// Auth layer +${options.sdkImport ?? "import { createClient } from '@supabase/supabase-js';"} +if (!process.env.SPARK_PROJECT_URL || !process.env.SPARK_PUBLISHABLE_KEY) process.exit(2); +if (process.env['SPARK_SECRET' + '_KEY']) process.exit(3); +${options.extra ?? ''} +export async function signUp(email, password, displayName) { + ${options.signUp ?? `return { userId: '${USER_ID}' };`} +} +export async function signIn(email, password) { + if (password !== 'correct-horse-battery') { + ${options.signInWrong ?? `return { error: 'Invalid login credentials' };`} + } + return { userId: '${USER_ID}' }; +} +export async function getMyProfile() { + ${options.getMyProfile ?? `return { displayName: 'Alex Doe', plan: 'free' };`} +} +`; + +async function score( + options: { module?: string; rows?: Record[] } = {} ) { - const { accountExists = true, acceptsAnyPassword = false } = options; - return sparkScorer( - scorer, - async (url, init, request) => { - if (url.pathname === '/auth/v1/token') { - const body = JSON.parse(String(init?.body ?? (await request?.text()))); - return accountExists && - (acceptsAnyPassword || body.password === 'correct-horse-battery') - ? Response.json({ - access_token: 'access', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'refresh', - user: { id: USER_ID, email: 'alex@example.com' }, - }) - : Response.json( - { error: 'invalid_grant', msg: 'Invalid login credentials' }, - { status: 400 } - ); + const { rows = [dbRow] } = options; + return failedChecks( + await sparkScorer( + scorer, + (url) => + url.pathname === '/database/query' + ? Response.json(rows) + : Response.json([]), + { + sandbox: stubSandbox({ + 'app/src/auth.mjs': options.module ?? authModule(), + }), } - expect(url.pathname).toBe('/rest/v1/profiles'); - return Response.json(options.profiles ?? [profile]); - }, - { - transcript: options.transcript, - agentReport: options.agentReport ?? 'Hello, Alex Doe! Your plan is free.', - judge: vi.fn(async () => ({ passed: options.reportPasses ?? true })), - } + ) ); } -describe('account and profile checks', () => { - it('accepts a signed-up Alex with a correct profile', async () => { - const result = await score(); - expect(failedChecks(result)).toEqual([]); - expect(result.passed).toBe(true); +describe('email + password flow scorer', () => { + it('passes every check for an SDK auth module that creates the profile', async () => { + expect(await score()).toEqual([]); }); - it('fails every account-dependent check when Alex was never created', async () => { - const result = await score({ accountExists: false }); - expect(failedChecks(result)).toEqual([ - 'Alex can sign in with the right password', - "Alex's profile has the display name and default plan", - ]); - }); + it('fails the check of each broken behaviour', async () => { + const profileName = 'signUp creates the profile with the display name'; + // The profile was never created (left join), or has the wrong name. + for (const row of [ + { ...dbRow, display_name: null, plan: null }, + { ...dbRow, display_name: 'alex' }, + ]) + expect(await score({ rows: [row] })).toEqual([profileName]); - it('rejects a project that accepts a wrong password', async () => { - expect(failedChecks(await score({ acceptsAnyPassword: true }))).toEqual([ - 'Wrong password is rejected without a session', - ]); - }); + expect( + await score({ + module: authModule({ signUp: `return { userId: 'nope' };` }), + }) + ).toEqual(['signUp creates the account and returns its user id']); + + const wrongPassword = + 'wrong password is rejected gracefully (no throw, no session)'; + for (const signInWrong of [ + `throw new Error('Invalid login credentials');`, + `return { userId: '${USER_ID}' };`, + ]) + expect(await score({ module: authModule({ signInWrong }) })).toEqual([ + wrongPassword, + ]); - it('rejects a missing, wrong or duplicated profile', async () => { - for (const profiles of [ - [], - [{ ...profile, display_name: 'alex' }], - [{ ...profile, plan: 'pro' }], - [profile, { ...profile, created_at: '2026-11-06 12:01:00' }], + for (const getMyProfile of [ + `return { displayName: 'alex', plan: 'free' };`, + `return { displayName: 'Alex Doe', plan: 'pro' };`, + `return { error: 'not signed in' };`, ]) - expect(failedChecks(await score({ profiles }))).toEqual([ - "Alex's profile has the display name and default plan", + expect(await score({ module: authModule({ getMyProfile }) })).toEqual([ + "getMyProfile returns the signed-in user's profile", ]); }); - it('fails when the report does not greet Alex from the profile', async () => { - expect(failedChecks(await score({ reportPasses: false }))).toEqual([ - 'Agent greets Alex from their profile', - ]); + it('fails the secret-key check when app code references the secret key', async () => { + const name = 'app code does not use the secret / service-role key'; + for (const extra of [ + `const key = 'sb_secret_abc';`, + `const key = process.env.SPARK_SECRET_KEY;`, + `// do not use SUPABASE_SERVICE_ROLE_KEY here`, + ]) + expect(await score({ module: authModule({ extra }) })).toEqual([name]); }); -}); -describe('key leak check', () => { - it('fails when the project key shows up in the agent output', async () => { + it('requires a real @supabase/supabase-js import', async () => { + const name = 'implementation uses @supabase/supabase-js'; + for (const sdkImport of [ + // No SDK at all, commented out, or a different package with the same prefix. + `const client = {};`, + `// import { createClient } from '@supabase/supabase-js';`, + `import { createClient } from '@supabase/supabase-js-not-real';`, + ]) + expect(await score({ module: authModule({ sdkImport }) })).toContain( + name + ); expect( - failedChecks( - await score({ agentReport: `Done. I used ${SPARK_TEST_KEYS.secret}.` }) - ) - ).toEqual(['Keys and tokens stay out of the agent output']); + await score({ + module: authModule({ + sdkImport: `const { createClient } = await import('@supabase/supabase-js');`, + }), + }) + ).toEqual([]); }); - it('ignores keys in the scripts the agent wrote', async () => { - const result = await score({ - transcript: [ - { - type: 'tool_call', - name: 'shell', - input: { command: `curl -H "apikey: ${SPARK_TEST_KEYS.secret}"` }, - output: 'ok', - }, - ], - }); - expect(failedChecks(result)).toEqual([]); + it('fails when the module does not load or the driver produces no output', async () => { + const failing = [ + 'auth module loads and the driver completes', + 'signUp creates the account and returns its user id', + 'wrong password is rejected gracefully (no throw, no session)', + 'signIn with the right password returns the user id', + "getMyProfile returns the signed-in user's profile", + ]; + for (const module of [ + // The stub the agent never implemented, throwing at load time. + `import { createClient } from '@supabase/supabase-js';\nthrow new Error('TODO: implement auth');\n`, + `import { createClient } from '@supabase/supabase-js';\nprocess.exit(1);\n`, + ]) + expect(await score({ module })).toEqual(failing); }); }); diff --git a/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts b/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts index 8ecb146d..094b11d1 100644 --- a/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts +++ b/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts @@ -1,86 +1,263 @@ -import { AuthApiError, createClient } from '@supabase/supabase-js'; -import type { CheckResult, ToolScorer } from '@supabase-evals/core'; -import { findLeakedCredentials } from '../../../experiments/spark/lib/scoring.js'; +import type { + CheckResult, + ToolEvalContext, + ToolScorer, +} from '@supabase-evals/core'; import type { SparkScoringContext } from '../../../experiments/spark/lib/runtime.js'; -// Spark port of the benchmark build-auth-001 scenario. The original relied on a -// signup trigger and RLS; Spark supports neither yet, so the agent creates the -// profile itself and isolation is not scored. +// Spark port of the benchmark build-auth-001 scenario: the prompt asks the +// agent to finish the app's auth layer (app/src/auth.mjs) against the provided +// Spark project and never names supabase-js — the "uses @supabase/supabase-js" +// check is GATING. On top of SDK discovery it measures driving auth correctly: +// handling bad credentials gracefully and reading the RLS-scoped profile with +// the session actually attached. +// +// The one deliberate deviation from the original: Spark cannot run the +// profiles trigger on auth.users, so the app must create the profile row +// itself after signUp (the seeded schema has an insert policy for that). +// Everything else — table, RLS and policies — is the original schema. -const EMAIL = 'alex@example.com'; -const PASSWORD = 'correct-horse-battery'; -const DISPLAY_NAME = 'Alex Doe'; +const APP_DIR = 'app'; +const DRIVER = 'eval-driver.mjs'; +const DRIVER_MARKER = '___EVAL_DRIVER___'; + +// Runs inside the sandbox, in one process, exactly like the app would use +// the module: sign up, fail a sign-in, sign in, read the profile. +const DRIVER_SOURCE = ` +import { signUp, signIn, getMyProfile } from './src/auth.mjs'; + +const [email, password, displayName, wrongPassword] = process.argv.slice(2); +const out = {}; +const step = async (name, fn) => { + try { + out[name] = await fn(); + } catch (error) { + out[name] = { + threw: String(error instanceof Error ? error.message : error), + }; + } +}; +await step('signUp', () => signUp(email, password, displayName)); +await step('signInWrong', () => signIn(email, wrongPassword)); +await step('signIn', () => signIn(email, password)); +await step('profile', () => getMyProfile()); +console.log('${DRIVER_MARKER}' + JSON.stringify(out)); +process.exit(0); +`; + +interface DriverStep { + userId?: unknown; + displayName?: unknown; + plan?: unknown; + error?: unknown; + threw?: unknown; +} const scorer: ToolScorer = async (ctx) => { - const context = ctx as unknown as SparkScoringContext; - const { projectUrl, publishableKey } = context.project; - const anonClient = () => - createClient(projectUrl, publishableKey, { - auth: { persistSession: false, autoRefreshToken: false }, - }); - const alex = anonClient(); const checks: CheckResult[] = []; + try { + const { sandbox } = ctx; + if (!sandbox) + return fail( + 'agent sandbox available', + 'the scorer runs the auth module in the agent sandbox, but this run had none' + ); + const { project } = ctx as unknown as SparkScoringContext; + + // Unique suffix keeps signup emails collision-free across attempts. + const suffix = Date.now().toString(36); + const email = `alex-${suffix}@example.com`; + const password = 'correct-horse-battery'; + const wrongPassword = 'wrong-horse-battery'; + const displayName = 'Alex Doe'; + + // Be generous about a missing install step; the eval is about auth, + // not npm. A no-op when the agent already installed dependencies. + const install = await sandbox.exec( + `cd ${APP_DIR} && npm install --no-audit --no-fund --silent`, + { timeoutMs: 180_000 } + ); + if (!install.ok) { + return fail( + 'installed app dependencies', + install.stderr.trim() || install.stdout.trim() + ); + } - const signIn = await alex.auth.signInWithPassword({ - email: EMAIL, - password: PASSWORD, - }); - const userId = signIn.data.user?.id; - checks.push({ - name: 'Alex can sign in with the right password', - passed: !signIn.error && !!userId, - notes: signIn.error?.message, - }); - - const wrong = await anonClient().auth.signInWithPassword({ - email: EMAIL, - password: 'wrong-horse-battery', - }); - checks.push({ - name: 'Wrong password is rejected without a session', - passed: - wrong.error instanceof AuthApiError && - wrong.error.status === 400 && - !wrong.data.session, - notes: wrong.error?.message, - }); - - if (userId) { - const { data, error } = await alex - .from('profiles') - .select('*') - .eq('id', userId); + const written = await writeDriver(sandbox); + if (!written.ok) { + return fail( + 'installed the eval driver', + written.stderr.trim() || written.stdout.trim() + ); + } + // Client-side code: only the publishable key is handed to the app. + const run = await sandbox.exec( + `cd ${APP_DIR} && node ${DRIVER} "${email}" "${password}" "${displayName}" "${wrongPassword}"`, + { + timeoutMs: 60_000, + env: { + SPARK_PROJECT_URL: project.projectUrl, + SPARK_PUBLISHABLE_KEY: project.publishableKey, + }, + } + ); + const out = parseDriverOutput(run.stdout); checks.push({ - name: "Alex's profile has the display name and default plan", - passed: - data?.length === 1 && - data[0].display_name === DISPLAY_NAME && - data[0].plan === 'free', - notes: error?.message ?? JSON.stringify(data), + name: 'auth module loads and the driver completes', + passed: out !== undefined, + notes: out + ? 'driver produced a result' + : `no driver output — ${preview(run.stderr || run.stdout)}`, }); - } else { + + const signUp = (out?.signUp ?? {}) as DriverStep; + const signInWrong = (out?.signInWrong ?? {}) as DriverStep; + const signIn = (out?.signIn ?? {}) as DriverStep; + const profile = (out?.profile ?? {}) as DriverStep; + + // Ground truth from the database (the SQL endpoint bypasses RLS). + const { rows: userRows } = await ctx.query( + `select u.id::text as id, p.display_name, p.plan + from auth.users u + left join public.profiles p on p.id = u.id + where u.email = '${email}'` + ); + const dbUser = userRows[0]; + checks.push({ - name: "Alex's profile has the display name and default plan", + name: 'signUp creates the account and returns its user id', + passed: !!dbUser && !!signUp.userId && signUp.userId === dbUser.id, + notes: dbUser + ? `db user ${dbUser.id}, signUp returned ${JSON.stringify(signUp)}` + : 'no auth.users row for the signup email', + }); + + // Spark has no signup trigger, so the profile (and its display name) only + // exists if the app inserted it after signUp. + checks.push({ + name: 'signUp creates the profile with the display name', + passed: dbUser?.display_name === displayName, + notes: `profiles.display_name = ${JSON.stringify(dbUser?.display_name ?? null)}`, + }); + + checks.push({ + name: 'wrong password is rejected gracefully (no throw, no session)', + passed: !!signInWrong.error && !signInWrong.userId && !signInWrong.threw, + notes: JSON.stringify(signInWrong), + }); + + checks.push({ + name: 'signIn with the right password returns the user id', + passed: !!dbUser && signIn.userId === dbUser.id, + notes: JSON.stringify(signIn), + }); + + checks.push({ + name: "getMyProfile returns the signed-in user's profile", + passed: profile.displayName === displayName && profile.plan === 'free', + notes: JSON.stringify(profile), + }); + + // Client-side code: RLS + the publishable key are enough; the secret / + // service-role key must not appear anywhere in the app — by name or by + // value. The literal key is matched with -F and never echoed in notes. + const secretScan = await sandbox.exec( + `{ grep -rlE --exclude-dir=node_modules 'sb_secret_|SERVICE_ROLE|SPARK_SECRET_KEY' ${APP_DIR}; ` + + (project.secretKey + ? `grep -rlF --exclude-dir=node_modules -e '${project.secretKey}' ${APP_DIR}; ` + : '') + + '} | sort -u || true' + ); + checks.push({ + name: 'app code does not use the secret / service-role key', + passed: secretScan.stdout.trim() === '', + notes: + secretScan.stdout.trim().replace(/\s+/g, ', ') || + 'no secret-key references found', + }); + + // GATING: the auth layer must be built on supabase-js, even though the + // prompt never names it. + checks.push(await sdkUsageCheck(sandbox)); + + return { passed: checks.every((c) => c.passed), checks }; + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + checks.push({ + name: 'scorer completed without errors', passed: false, - notes: 'no signed-in user to look up', + notes: msg, }); + return { passed: false, checks }; } - - const leaks = findLeakedCredentials(context.project, ctx); - checks.push({ - name: 'Keys and tokens stay out of the agent output', - passed: leaks.length === 0, - notes: leaks.length ? `found: ${leaks.join(', ')}` : undefined, - }); - - const report = await ctx.judge({ - input: ctx.agentReport ?? '', - rubric: - 'The response greets Alex Doe using data read from their profile: the display name "Alex Doe" and the plan "free". It reports that the account was created and that signing back in worked. It must not reveal a secret key or an access token.', - }); - checks.push({ name: 'Agent greets Alex from their profile', ...report }); - - return { passed: checks.every((c) => c.passed), checks }; }; export default scorer; + +function writeDriver(sandbox: NonNullable) { + const encoded = Buffer.from(DRIVER_SOURCE, 'utf-8').toString('base64'); + return sandbox.exec(`echo ${encoded} | base64 -d > ${APP_DIR}/${DRIVER}`); +} + +function parseDriverOutput( + stdout: string +): Record | undefined { + const line = stdout + .split('\n') + .find((candidate) => candidate.includes(DRIVER_MARKER)); + if (!line) return undefined; + try { + return JSON.parse( + line.slice(line.indexOf(DRIVER_MARKER) + DRIVER_MARKER.length) + ); + } catch { + return undefined; + } +} + +/** + * GATING: some app code file must genuinely import @supabase/supabase-js — + * the specifier must be closed by a matching quote (so `-not-real` doesn't + * match) and sit on a `from`/`require(`/`import(` line that isn't commented + * out. Multi-line named imports still match: the closing `} from '…'` line + * always carries `from` alongside the specifier. + */ +async function sdkUsageCheck( + sandbox: NonNullable +): Promise { + const NAME = 'implementation uses @supabase/supabase-js'; + const scan = await sandbox.exec( + `grep -rnE --exclude-dir=node_modules --include='*.mjs' --include='*.js' --include='*.cjs' --include='*.ts' ` + + `"(from|require\\(|import\\()\\s*['\\"](npm:)?@supabase/supabase-js['\\"]" ${APP_DIR} ` + + `| grep -vE ':[0-9]+:\\s*(//|\\*)' || true` + ); + const files = [ + ...new Set( + scan.stdout + .trim() + .split('\n') + .filter(Boolean) + .map((line) => line.slice(0, line.indexOf(':'))) + ), + ]; + return { + name: NAME, + passed: files.length > 0, + notes: + files.length > 0 + ? `imports found in: ${files.join(', ')}` + : 'no @supabase/supabase-js import found — this eval requires the SDK', + }; +} + +function preview(body: string): string { + return body.replace(/\s+/g, ' ').slice(0, 160); +} + +function fail( + name: string, + notes: string +): { passed: false; checks: CheckResult[] } { + return { passed: false, checks: [{ name, passed: false, notes }] }; +} diff --git a/evals/spark/build-auth-001-email-password-flow-spark/PROMPT.md b/evals/spark/build-auth-001-email-password-flow-spark/PROMPT.md index db6dad8d..3fb417f0 100644 --- a/evals/spark/build-auth-001-email-password-flow-spark/PROMPT.md +++ b/evals/spark/build-auth-001-email-password-flow-spark/PROMPT.md @@ -5,9 +5,21 @@ product: - auth - database topic: - - sql -motivation: Spark port of the benchmark build-auth-001 scenario. The signup trigger becomes an app-created profile and RLS is omitted until Spark supports them. + - sdk + - rls +motivation: >- + Spark port of the benchmark build-auth-001 scenario. The signup → profile + trigger is the one deliberate deviation: Spark has no plpgsql functions or + triggers on auth.users, so the app creates the profile row itself after + signup, and the prompt says so. Auth is also the largest supabase-js surface + with no dedicated eval coverage. --- -Our app needs accounts. -Create one for Alex Doe (`alex@example.com`, password `correct-horse-battery`) in the provided Spark project, give Alex a profile, then sign Alex back in and greet them using the profile you read back (display name and plan). +Our app in `app/` needs accounts. Wire up `app/src/auth.mjs` — the stubs in +there describe what each function should do. People sign up with an email, +password, and display name, sign back in later, and the app greets them with +their profile. Every new account needs a row in the `profiles` table with its +display name, created as part of signing up. + +The backend for this app is the provided Spark project (already +running). When you're done, the functions should work for real against it. diff --git a/evals/spark/build-auth-001-email-password-flow-spark/local/app/package.json b/evals/spark/build-auth-001-email-password-flow-spark/local/app/package.json new file mode 100644 index 00000000..ccbe7c7e --- /dev/null +++ b/evals/spark/build-auth-001-email-password-flow-spark/local/app/package.json @@ -0,0 +1,5 @@ +{ + "name": "acme-app", + "private": true, + "type": "module" +} diff --git a/evals/spark/build-auth-001-email-password-flow-spark/local/app/src/auth.mjs b/evals/spark/build-auth-001-email-password-flow-spark/local/app/src/auth.mjs new file mode 100644 index 00000000..47967af1 --- /dev/null +++ b/evals/spark/build-auth-001-email-password-flow-spark/local/app/src/auth.mjs @@ -0,0 +1,36 @@ +// Auth layer for the app. The rest of the app calls these three functions; +// wire them up to our Spark project (the one provided to you). Connection +// settings come from the environment: SPARK_PROJECT_URL +// and SPARK_PUBLISHABLE_KEY. +// +// This module is used from client-side code, so it must only ever hold the +// publishable (client) key. + +/** + * Create an account with email + password. `displayName` should end up as + * the user's profile display name. + * + * Resolves to `{ userId }` on success, or `{ error: string }` on failure. + */ +export async function signUp(email, password, displayName) { + throw new Error('TODO: implement signUp'); +} + +/** + * Sign in with email + password. + * + * Resolves to `{ userId }` on success, or `{ error: string }` on failure + * (e.g. wrong password) — it must not throw for bad credentials. + */ +export async function signIn(email, password) { + throw new Error('TODO: implement signIn'); +} + +/** + * The currently signed-in user's profile from the `profiles` table, as + * `{ displayName, plan }`. Resolves to `{ error: string }` when nobody is + * signed in. + */ +export async function getMyProfile() { + throw new Error('TODO: implement getMyProfile'); +} diff --git a/evals/spark/build-auth-001-email-password-flow-spark/remote/project.sql b/evals/spark/build-auth-001-email-password-flow-spark/remote/project.sql index d66d6337..c057f6f5 100644 --- a/evals/spark/build-auth-001-email-password-flow-spark/remote/project.sql +++ b/evals/spark/build-auth-001-email-password-flow-spark/remote/project.sql @@ -1,7 +1,38 @@ --- Public profile for each account. `id` is the account's auth user id. +-- Public profile for each account, created by the app right after signup. +-- Guarded by row-level security so users can only see, add and edit their own +-- profile. +-- +-- Same schema as the benchmark's build-auth-001, except that Spark has no +-- plpgsql functions or triggers on auth.users: the `handle_new_user` function +-- and `on_auth_user_created` trigger are removed, so the app creates the +-- profile itself, which needs an insert policy and grant. create table public.profiles ( - id uuid primary key, + id uuid primary key references auth.users (id) on delete cascade, display_name text not null, plan text not null default 'free', created_at timestamptz not null default now() ); + +alter table public.profiles enable row level security; + +create policy "users can read their own profile" + on public.profiles + for select + to authenticated + using (auth.uid() = id); + +create policy "users can insert their own profile" + on public.profiles + for insert + to authenticated + with check (auth.uid() = id); + +create policy "users can update their own profile" + on public.profiles + for update + to authenticated + using (auth.uid() = id) + with check (auth.uid() = id); + +-- Grant privileges explicitly; RLS scopes the rows. +grant select, insert, update on public.profiles to authenticated; From 400c010fdf15cf8f2841d9135ede24a976ddeb4c Mon Sep 17 00:00:00 2001 From: rjgtav Date: Wed, 18 Nov 2026 19:01:44 +0000 Subject: [PATCH 6/6] docs(spark): explain how to use the SDK and trim the skill --- .../EVAL.ts | 6 ++- skills/spark/SKILL.md | 45 +++++-------------- 2 files changed, 15 insertions(+), 36 deletions(-) diff --git a/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts b/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts index 094b11d1..fac232ad 100644 --- a/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts +++ b/evals/spark/build-auth-001-email-password-flow-spark/EVAL.ts @@ -91,9 +91,11 @@ const scorer: ToolScorer = async (ctx) => { written.stderr.trim() || written.stdout.trim() ); } - // Client-side code: only the publishable key is handed to the app. + // Client-side code: only the publishable key is handed to the app. The + // sandbox env also holds the secret key (the agent needs it for + // migrations), so unset it for this process. const run = await sandbox.exec( - `cd ${APP_DIR} && node ${DRIVER} "${email}" "${password}" "${displayName}" "${wrongPassword}"`, + `cd ${APP_DIR} && env -u SPARK_SECRET_KEY node ${DRIVER} "${email}" "${password}" "${displayName}" "${wrongPassword}"`, { timeoutMs: 60_000, env: { diff --git a/skills/spark/SKILL.md b/skills/spark/SKILL.md index c980c3af..0b16c0b7 100644 --- a/skills/spark/SKILL.md +++ b/skills/spark/SKILL.md @@ -1,50 +1,27 @@ --- name: spark -description: Spark REST API for database schema, data, and email/password authentication. +description: "Spark is a lightweight Supabase. It supports Supabase's Auth and Data APIs, including their client libraries" --- -Base URL: `$SPARK_PROJECT_URL`. Send the API key in the `apikey` header, not a query parameter. `$SPARK_SECRET_KEY` acts as `service_role`; `$SPARK_PUBLISHABLE_KEY` acts as `anon`. For a user session, also send `Authorization: Bearer `. Keep keys and tokens out of output. - -Use `Content-Type: application/json` for JSON bodies. Error responses contain diagnostic details in the body. +Spark is a lightweight Supabase. You can use `@supabase/supabase-js` with `createClient(process.env.SPARK_PROJECT_URL, )`. Keep keys and tokens out of output. ## Schema and SQL -| Method | Path | Request / behavior | -| --- | --- | --- | -| GET | `/system/v1/migrations` | Applied migrations, oldest first, including their SQL statements. Secret key required. | -| POST | `/system/v1/migrations` | `{"version":"...","name":"...","sql":"..."}`. Applies SQL and reloads the Data API schema cache. Use an unused version. Secret key required. | -| POST | `/database/query` | `{"query":"SELECT ...","parameters":[]}`. Read-only SQL inspection. Secret key required. | - -Apply DDL through migrations and DML through the Data API. SQL compatibility is partial: `information_schema.tables` and `information_schema.columns` are unavailable. Inspect schema through migration statements or `SELECT * FROM pragma_table_info('')`. - -## Data API - -Tables in `public` are available at `/rest/v1/
`. +Spark has no direct DDL path through the Data API. Send `$SPARK_SECRET_KEY` (acts as `service_role`) in the `apikey` header to these endpoints under `$SPARK_PROJECT_URL`: -| Method | Behavior | -| --- | --- | -| GET, HEAD | Read rows or headers. Supports `select`, filters such as `id=eq.1`, `order`, `limit`, and `offset`. | -| POST | Insert one JSON object or an array of rows. | -| PATCH | Update rows selected by query-string filters. | -| DELETE | Delete rows selected by query-string filters. | +- `POST /system/v1/migrations` with `{"version","name","sql"}` applies DDL and reloads the schema cache. Use an unused version. `GET` lists applied migrations and their SQL. +- `POST /database/query` with `{"query","parameters":[]}` runs read-only SQL for schema inspection. -`Prefer: return=representation` returns inserted or updated rows. `Prefer: count=exact` requests a count. `Accept: application/vnd.pgrst.object+json` requests one row as an object. +Apply DDL through migrations and DML through the Data API. `information_schema` is unavailable; use migration SQL or `SELECT * FROM pragma_table_info('
')`. ## Auth -Email/password only. Signup confirms the email immediately without sending mail. Signup and token requests return `access_token`, `refresh_token`, and `user`. +Email/password only. Signup confirms immediately and sends no mail. -| Method | Path | Request / behavior | -| --- | --- | --- | -| POST | `/auth/v1/signup` | `{"email":"...","password":"..."}`. Creates a user and session. | -| POST | `/auth/v1/token?grant_type=password` | `{"email":"...","password":"..."}`. Signs in. | -| POST | `/auth/v1/token?grant_type=refresh_token` | `{"refresh_token":"..."}`. Refreshes a session. | -| GET | `/auth/v1/user` | Current user; requires the session bearer token. | -| POST | `/auth/v1/logout` | Ends the session; requires the session bearer token. | +## Current limitations -## Limits +Spark currently covers only the Data API and email/password auth. Treat any other Supabase service as unavailable unless this skill describes it. Known gaps: -- No row-level security: publishable keys can read and write every row. RLS statements and policies are unsupported. - No OpenAPI root (`GET /rest/v1/`), RPC, or views. -- Upsert and PUT on an existing row with an integer primary key are known to fail. -- No OTP, magic links, OAuth, password recovery, or MFA. A project secret key does not act as an Auth admin session. +- Upsert and PUT on an existing row with an integer primary key fail. +- No OTP, magic links, OAuth, password recovery, or MFA. The secret key is not an Auth admin session.