Rebasely Beta: data may be purged

justintsus-experiment Public

JavaScript · 212 lines · 11.7 KiB · at 8e57616

// Shared fixture for the hidden tests of the search query language (BRIEF.md, "The module interface").// The worktree under test is SEARCH_WORKTREE; its apps/web/src/search/api.ts is imported as is.// Expectations come from the brief's spec, not from any implementation.import assert from "node:assert/strict";import { existsSync } from "node:fs";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { pathToFileURL } from "node:url";const W = process.env.SEARCH_WORKTREE;if (!W) throw new Error("set SEARCH_WORKTREE to the worktree under test (run.sh does)");const API = join(W, "apps/web/src/search/api.ts");if (!existsSync(API)) throw new Error(`${API} does not exist`);export const api = await import(pathToFileURL(API).href);export const DAY = 86_400_000;export const HOUR = 3_600_000;export const NOW = Date.UTC(2026, 9, 16, 12, 0, 0, 0); // 2026-10-16T12:00:00.000Zexport const d = (s) => Date.parse(`${s}T00:00:00.000Z`);export const ORG = "org-1";export const ORG2 = "org-2";export const REPO = "repo-1";export const REPO_B = "repo-2"; // same orgexport const REPO_C = "repo-3"; // other orgexport const ME = "11111111-1111-4111-8111-111111111111";export const ALICE = "22222222-2222-4222-8222-222222222222";export const BOB = "33333333-3333-4333-8333-333333333333";export const FIXER = "44444444-4444-4444-8444-444444444444"; // agent "fixer" in org-1, owner MEexport const FIXER2 = "55555555-5555-4555-8555-555555555555"; // agent "fixer" in org-2, owner BOBexport const CTX = { repoId: REPO, orgId: ORG, viewerId: ME, now: NOW };export const ANON = { ...CTX, viewerId: null };export const ERROR_CODES = new Set([  "too_long", "too_many_terms", "unterminated_quote", "unexpected_quote", "unknown_qualifier", "unsupported_qualifier",  "empty_value", "negation_not_allowed", "bad_value", "bad_date", "conflict",]);const SCHEMA = `CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL, email_lower TEXT NOT NULL UNIQUE, name TEXT, kind TEXT NOT NULL DEFAULT 'human',  created_at INTEGER NOT NULL, suspended_at INTEGER, deleted_at INTEGER);CREATE TABLE agents (user_id TEXT PRIMARY KEY, org_id TEXT NOT NULL, slug TEXT NOT NULL, owner_user_id TEXT NOT NULL, description TEXT,  created_at INTEGER NOT NULL, created_by TEXT NOT NULL, disabled_at INTEGER, UNIQUE (org_id, slug));CREATE TABLE memberships (org_id TEXT, user_id TEXT, role TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (org_id, user_id));CREATE TABLE issues (repo_id TEXT NOT NULL, number INTEGER NOT NULL, org_id TEXT NOT NULL, author_id TEXT NOT NULL, title TEXT NOT NULL,  body TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT 'open', labels TEXT NOT NULL DEFAULT '[]', comments INTEGER NOT NULL DEFAULT 0,  created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, closed_at INTEGER, closed_by TEXT, ip_key TEXT, notified INTEGER NOT NULL DEFAULT 0,  PRIMARY KEY (repo_id, number));CREATE TABLE pull_index (repo_id TEXT NOT NULL, number INTEGER NOT NULL, org_id TEXT NOT NULL, author_id TEXT NOT NULL, owner_id TEXT,  state TEXT NOT NULL, draft INTEGER NOT NULL DEFAULT 0, title TEXT NOT NULL, base_ref TEXT NOT NULL, head_ref TEXT NOT NULL,  created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, merged_at INTEGER, closed_at INTEGER, PRIMARY KEY (repo_id, number));CREATE TABLE pull_review_requests (repo_id TEXT NOT NULL, number INTEGER NOT NULL, user_id TEXT NOT NULL, requested_at INTEGER NOT NULL,  PRIMARY KEY (repo_id, number, user_id));`;// [number, author, state, labels, title, body, comments, created_at, updated_at]export const ISSUES = [  [1, ME, "open", ["bug"], "Crash on startup", "stack trace attached", 3, d("2026-09-30") + DAY - 1, NOW - 7 * DAY],  [2, ALICE, "open", ["bug", "needs review"], "Login fails with 100% CPU", "", 10, d("2026-10-01"), NOW - 7 * DAY + 1],  [3, ALICE, "closed", ["wontfix", "bug"], "Typo in docs", "the word teh", 0, d("2026-10-01") + DAY - 1, NOW - 7 * DAY - 1],  [4, BOB, "open", [], "Ünïcode title 🐛 works", "body with a_c and 1000", 1, d("2026-10-02"), NOW - HOUR],  [5, FIXER, "open", ["enhancement"], "Add search syntax", 'say "hi" OR 1=1', 5, d("2026-10-10"), NOW - 2 * DAY],  [6, FIXER2, "closed", [], "Path a\\b backslash", "abc", 2, d("2024-02-29"), d("2024-03-01")],  [7, BOB, "open", ["docs"], "Needs review of the docs", "phrase test: login fails", 0, d("2026-10-15") + 12 * HOUR, NOW - 60_000],  [8, ME, "closed", ["bug"], "100 percent", "", 7, d("2026-08-01"), d("2026-08-02")],];// [number, author, owner, state, draft, title, created_at, updated_at]export const PULLS = [  [1, ME, null, "open", 0, "Add parser", d("2026-10-01"), NOW - HOUR],  [2, FIXER, ME, "open", 1, "Draft: tokenizer", d("2026-10-03"), NOW - 2 * DAY],  [3, ALICE, null, "merged", 0, "Fix 100% bug", d("2026-09-20"), NOW - 8 * DAY],  [4, BOB, null, "closed", 0, "Refactor a_b", d("2026-09-25"), NOW - 10 * DAY],  [5, ALICE, null, "closed", 1, "Old draft axb", d("2026-08-01"), d("2026-08-05")],  [6, FIXER2, BOB, "open", 0, "Cross org agent", d("2026-10-05"), NOW - 3 * DAY],];// Rows that no query against repo-1 / org-1 may ever return: they match almost everything.const LEAK_ISSUES = [  [REPO_B, ORG, 1, "Crash on startup leak"], [REPO_B, ORG, 9, "Crash on startup leak"],  [REPO_C, ORG2, 1, "Crash on startup leak"], [REPO, ORG2, 50, "Crash on startup orgleak"],];const LEAK_PULLS = [[REPO_B, ORG, 1], [REPO_B, ORG, 2], [REPO_C, ORG2, 7], [REPO, ORG2, 60]];export function fixture({ repoId = REPO, orgId = ORG } = {}) {  const db = new DatabaseSync(":memory:");  db.exec(SCHEMA);  const u = db.prepare("INSERT INTO users (id, email, email_lower, name, created_at) VALUES (?, ?, ?, ?, 0)");  for (const [id, e] of [[ME, "me@example.com"], [ALICE, "alice@example.com"], [BOB, "bob@example.com"], [FIXER, "fixer1@agents"], [FIXER2, "fixer2@agents"]]) u.run(id, e, e, e.split("@")[0]);  const a = db.prepare("INSERT INTO agents (user_id, org_id, slug, owner_user_id, created_at, created_by) VALUES (?, ?, ?, ?, 0, ?)");  a.run(FIXER, orgId, "fixer", ME, ME);  a.run(FIXER2, ORG2 === orgId ? "org-x" : ORG2, "fixer", BOB, BOB);  const m = db.prepare("INSERT INTO memberships (org_id, user_id, role, created_at) VALUES (?, ?, ?, 0)");  for (const id of [ME, ALICE, BOB, FIXER]) m.run(orgId, id, "writer");  const i = db.prepare(`INSERT INTO issues (repo_id, number, org_id, author_id, title, body, state, labels, comments, created_at, updated_at)    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);  for (const [n, au, st, lb, ti, bo, co, ca, ua] of ISSUES) i.run(repoId, n, orgId, au, ti, bo, st, JSON.stringify(lb), co, ca, ua);  for (const [r, o, n, ti] of LEAK_ISSUES) i.run(r === REPO ? repoId : r, n, o === ORG ? orgId : o, ME, ti, "Crash 100% a_c login fails", "open", '["bug","needs review"]', 99, d("2026-10-05"), NOW - 1000);  const p = db.prepare(`INSERT INTO pull_index (repo_id, number, org_id, author_id, owner_id, state, draft, title, base_ref, head_ref, created_at, updated_at)    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'main', 'feature', ?, ?)`);  for (const [n, au, ow, st, dr, ti, ca, ua] of PULLS) p.run(repoId, n, orgId, au, ow, st, dr, ti, ca, ua);  for (const [r, o, n] of LEAK_PULLS) p.run(r === REPO ? repoId : r, n, o === ORG ? orgId : o, ME, ME, "open", 1, "Add parser leak 100% a_b", d("2026-10-05"), NOW - 1000);  const rr = db.prepare("INSERT INTO pull_review_requests (repo_id, number, user_id, requested_at) VALUES (?, ?, ?, 0)");  rr.run(repoId, 1, ME);  rr.run(repoId, 3, ALICE);  rr.run(repoId, 4, ME);  rr.run(REPO_B, 1, ME);  rr.run(REPO_B, 2, ME); // repo-1 has a #2 too: a subquery that forgets repo_id would pick it up  return db;}export const tableOf = (target) => (target === "issues" ? "issues" : "pull_index");// parseQuery that must succeed.export function parsed(input, target = "issues") {  const r = api.parseQuery(input, target);  assert.equal(r.ok, true, `expected ${JSON.stringify(input)} (${target}) to parse, got ${JSON.stringify(r.errors)}`);  return r.query;}// parseQuery that must fail; returns the errors.export function failed(input, target = "issues") {  const r = api.parseQuery(input, target);  assert.equal(r.ok, false, `expected ${JSON.stringify(input)} (${target}) to fail to parse`);  assert.ok(Array.isArray(r.errors) && r.errors.length > 0, "errors is a non-empty array");  for (const e of r.errors) {    assert.ok(ERROR_CODES.has(e.code), `unknown error code ${e.code}`);    assert.equal(typeof e.message, "string");    assert.ok(e.message.trim().length > 0, "message is not empty");    assert.ok(Number.isInteger(e.start) && Number.isInteger(e.end) && e.start >= 0 && e.end <= input.length && e.start <= e.end, `bad span ${e.start}..${e.end}`);  }  return r.errors;}export const codes = (input, target = "issues") => failed(input, target).map((e) => e.code);export const canon = (input, target = "issues") => api.serializeQuery(parsed(input, target));// Counts placeholders outside string literals and quoted identifiers. Numbered ?NNN placeholders// count as their highest index.export function placeholders(sql) {  let anon = 0;  let maxNum = 0;  let numbered = 0;  for (let i = 0; i < sql.length; i++) {    const c = sql[i];    if (c === "'" || c === '"' || c === "`") {      const q = c;      i++;      while (i < sql.length) {        if (sql[i] === q && sql[i + 1] === q) i += 2;        else if (sql[i] === q) break;        else i++;      }      continue;    }    if (c === "?") {      const m = /^[0-9]+/.exec(sql.slice(i + 1));      if (m) {        numbered++;        maxNum = Math.max(maxNum, Number(m[0]));        i += m[0].length;      } else anon++;    }  }  assert.ok(!(anon && numbered), "mixes ? and ?NNN placeholders");  return numbered ? maxNum : anon;}const ORDER_BY = /^\s*(?:(?:issues|pull_index)\.)?(created_at|updated_at|comments)\s+(ASC|DESC)\s*,\s*(?:(?:issues|pull_index)\.)?number\s+(ASC|DESC)\s*$/i;// toSql with the contract's structural checks.export function sqlOf(query, ctx = CTX) {  const s = api.toSql(query, ctx);  assert.equal(typeof s.where, "string");  assert.equal(typeof s.orderBy, "string");  assert.ok(Array.isArray(s.params));  for (const p of s.params) assert.ok(p === null || typeof p === "string" || (typeof p === "number" && Number.isFinite(p)), `param ${String(p)} is a string, a finite number or null`);  assert.equal(placeholders(s.where), s.params.length, "placeholder count equals params.length");  assert.ok(!/\?/.test(s.orderBy), "orderBy binds nothing");  const m = ORDER_BY.exec(s.orderBy);  assert.ok(m, `orderBy ${JSON.stringify(s.orderBy)} is "<column> <dir>, number <dir>"`);  assert.equal(m[2].toUpperCase(), m[3].toUpperCase(), "the number tie-break goes the same direction");  return s;}// Runs a query and returns the rows (numbers, with repo_id and org_id), checking scope on the way.export function rowsOf(db, input, target = "issues", ctx = CTX) {  const s = sqlOf(parsed(input, target), ctx);  const sql = `SELECT number, repo_id, org_id FROM ${tableOf(target)} WHERE ${s.where} AND number > 0 ORDER BY ${s.orderBy}`;  const rows = db.prepare(sql).all(...s.params);  for (const r of rows) {    assert.equal(r.repo_id, ctx.repoId, `row #${r.number} of ${r.repo_id} leaked into ${ctx.repoId}`);    assert.equal(r.org_id, ctx.orgId, `row #${r.number} of org ${r.org_id} leaked into ${ctx.orgId}`);  }  return rows;}export const numbers = (db, input, target = "issues", ctx = CTX) => rowsOf(db, input, target, ctx).map((r) => r.number);// A deterministic PRNG for the generated inputs.export function prng(seed) {  let s = seed >>> 0;  return () => {    s = (s + 0x6d2b79f5) >>> 0;    let t = s;    t = Math.imul(t ^ (t >>> 15), t | 1);    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;  };}