Skip to content
Merged
30 changes: 30 additions & 0 deletions .claude/context/chores.xml
Original file line number Diff line number Diff line change
Expand Up @@ -566,5 +566,35 @@ WHAT IS OUT OF SCOPE
- Do NOT touch plans.xml, splits.xml, sequence.xml, chores.xml (lead owns those).
- Do NOT edit package.json, bun.lock, tsconfig.json, drizzle.config.ts (foundation §6.1 froze the dep set).</synopsis>
</chore>

<!--
Post-audit gap chores opened 2026-05-29 (followup PR off main after the
33-commit audit-hardening sweep merged at d544ea7). Both close the
8 unchanged pre-existing test failures called out in the audit PR.
-->

<chore id="pdf-test-fakectx-pdfviews-fixture"
status="closed"
fulfillment="24309eb"
blast-radius="src/server/tools/pdf.test.ts"
blocks-plans="">
<synopsis>Post-S1 §13 v1.1 amendment introduced `ctx.pdfViews: Map&lt;paper_id, viewUUID&gt;` as the viewUUID resolution surface (refreshExtraction at src/server/tools/pdf.ts:141 calls `ctx.pdfViews.get(args.paper_id)`). The `fakeCtx` helper in src/server/tools/pdf.test.ts:63-92 was never updated to populate this map, so the 5 refresh-extraction tests fail at TypeError "undefined is not an object (evaluating 'ctx.pdfViews.get')". Production path is fine — real `scholar.pdf.open` populates the map — but the tests give zero green-suite assertion that refresh-extraction works end-to-end.

Fix: extend `fakeCtx` to accept an optional `pdfViews` arg (default `new Map()`), then have each test that calls refreshExtraction with paper_id "pN" pre-populate the map with a synthetic viewUUID. Cleanest pattern: synthesize viewUUID as `view-${paper_id}` and let each test do `fakeCtx(sqlite, { pdfViews: new Map([["p1", "view-p1"]]) })`. Tier: mechanical (haiku → sonnet depending on whether all 5 tests can use a shared helper). Acceptance: 5 refresh-extraction tests go green; the rest of the suite stays at 289 pass; typecheck clean. Single commit: `test(pdf): seed ctx.pdfViews fixture so refresh-extraction tests pass`.</synopsis>
</chore>

<chore id="fix-build-ui-script-cwd-paths"
status="closed"
fulfillment="609749d"
blast-radius="package.json scripts/build-ui.ts scripts/measure-bundle.ts"
blocks-plans="">
<synopsis>`bun run build:ui` fails with `FileNotFound: failed to open root directory: src/ui` because package.json declares `bun --cwd=scripts build-ui`, which sets cwd to `scripts/` before invoking `bun build-ui` (resolves to `scripts/build-ui.ts`). The script then passes `"src/ui/index.html"` as entrypoint and `"build/ui"` as outdir — both relative to the cwd, so they resolve to `scripts/src/ui/index.html` and `scripts/build/ui` (neither exists). The same failure mode hits `bun run measure-bundle` (`bun --cwd=scripts measure-bundle`). Consequently `src/ui/bundle.test.ts` beforeAll silently swallows the build error, and the 3 bundle-budget tests fail on missing `build/ui/app.html` and `build/ui/bundle-budget.json`.

Fix options (pick A unless reason to keep --cwd=scripts):
(A) Drop --cwd: change package.json to `"build:ui": "bun scripts/build-ui.ts"` and `"measure-bundle": "bun scripts/measure-bundle.ts"`. Both scripts already use repo-root-relative paths internally.
(B) Anchor scripts to import.meta.dir: refactor build-ui.ts and measure-bundle.ts to resolve `src/ui/index.html` and `build/ui` via `path.join(import.meta.dir, "..", ...)` so cwd doesn't matter.

Acceptance: `bun run build:ui` succeeds and produces `build/ui/app.html`; `bun run measure-bundle` produces `build/ui/bundle-budget.json` matching the shape `bundle.test.ts` asserts (total_kb / threshold_kb / over_budget / per_dep[]); the 3 bundle.test.ts tests go green; full suite reaches 297 pass / 8 skip / 0 fail; typecheck clean. Tier: mechanical-with-interpretation (sonnet) — picking A vs B is a 30-second judgment, the edit itself is ≤5 LOC. Single commit: `fix(build): resolve build:ui + measure-bundle without --cwd=scripts`.</synopsis>
</chore>
</chores>
</reference>
32 changes: 16 additions & 16 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: ci

on:
push:
branches: [main, "ingest/**"]
branches: [main *]
pull_request:
branches: [main]

Expand All @@ -17,28 +17,28 @@ jobs:
with:
bun-version: 1.3.11 # match scholar.bundledBunVersion

- name: Install dependencies (frozen)
- name: install
run: bun install --frozen-lockfile

- name: Typecheck
- name: typecheck
run: bunx tsc --noEmit

- name: Test
run: bun test
- name: compile
run: bun run build:vec

- name: Smoke — vec0 compile-from-source + ABI probe
# Mirrors build-plugin.ts:compileVec0FromSource (§14.1 step 5 fallback).
# Catches regressions in vendored sqlite3.h vs Bun's bundled SQLite ABI.
- name: test
run: bun test --bail --only-failures

- name: smoke
run: |
gcc -O2 -fPIC -shared -I src/vendor/sqlite-vec \
src/vendor/sqlite-vec/sqlite-vec.c \
-o /tmp/vec0-smoke.so
bun -e '
import { Database } from "bun:sqlite";
const db = new Database(":memory:");
db.loadExtension("/tmp/vec0-smoke.so", "sqlite3_vec_init");
const v = db.query("SELECT vec_version() AS v").get();
console.log("vec_version:", v);
db.run("CREATE VIRTUAL TABLE v USING vec0(emb float[4])");
console.log("CREATE vec0 VTAB OK");
const so = "runtime/vendor/sqlite-vec/vec0.so"
const q = "SELECT vec_version() as v"
const r = "CREATE VIRTUAL TABLE v USING vec0(emb float[4])"
db.loadExtension(so, "sqlite3_vec_init");
console.log("version:", db.query(q).get());
db.run(r);
console.log("CREATE VTAB vec0: ok");
'
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
"test": "bun test",
"db:generate": "drizzle-kit generate",
"build:server": "tsc --noEmit && bun build src/server/index.ts --compile --target=bun-windows-x64 --outfile build/scholar.exe",
"build:ui": "bun --cwd=scripts build-ui",
"build:ui": "bun scripts/build-ui.ts",
"build:ui:dev": "UI_MINIFY=false bun -q build:ui",
"build:pdf": "bun --cwd=scripts vendor-pdf-server",
"build:vec": "bun --cwd=scripts build-vec0",
"build:plugin": "bun --cwd=scripts build-plugin",
"measure-bundle": "bun --cwd=scripts measure-bundle",
"measure-bundle": "bun scripts/measure-bundle.ts",
"serve": "bun --cwd=scripts start-server.ts"
},
"dependencies": {
Expand Down
10 changes: 8 additions & 2 deletions scripts/build-vec0.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { $ } from "bun"
import { Database } from "bun:sqlite"
import { join, basename } from "node:path"
import { join, basename, dirname } from "node:path"
import { copyFileSync, existsSync, mkdirSync } from "node:fs"
import { getVec0Extension } from "../src/server/db/sqlite-vec.ts"
import util, { ROOT } from "./util"
import env from "./util/env"

Expand Down Expand Up @@ -119,6 +120,9 @@ export async function compileVec0FromSource(destPath: string): Promise<void> {
const { bin, args: prefixArgs } = compiler
console.log(`Compiling vec0 from source using ${bin}...`)

// Ensure the output directory exists — ld errors on missing parent dir.
mkdirSync(dirname(destPath), { recursive: true })

// Use Bun.spawn (not $`...`) so multi-word CC commands (bin + prefixArgs)
// are passed as a proper argv array — $`${cc} -flag` treats the whole
// interpolated string as a single argument (no shell word-splitting).
Expand Down Expand Up @@ -152,7 +156,9 @@ export async function compileVec0FromSource(destPath: string): Promise<void> {
}

if (import.meta.main)
compileVec0FromSource(util.subpath("build/vendor/sqlite-vec")).catch((e) => {
compileVec0FromSource(
util.subpath("build/vendor/sqlite-vec", `vec0.${getVec0Extension()}`),
).catch((e) => {
const error =
e instanceof Error ? `Unhandled compile error: ${e.message}\n` : String(e)
process.stderr.write(error)
Expand Down
28 changes: 22 additions & 6 deletions src/server/tools/ingest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Uses buildServer + dispatch pattern (established in corpus.test.ts).
// Mocks allPdfRoots/defaultPdfRoot so tests don't need real pdf_roots config rows.
// ctx.db is set directly after buildServer() to inject an in-memory corpus DB.
import { test, expect, describe, mock, beforeEach, afterEach } from "bun:test";
import { test, expect, describe, mock, beforeAll, afterAll, beforeEach, afterEach } from "bun:test";
import Database from "bun:sqlite";
import { drizzle } from "drizzle-orm/bun-sqlite";
import { mkdtempSync, rmSync, mkdirSync } from "node:fs";
Expand All @@ -14,14 +14,30 @@ import { openWithPragmas, applyMigrations } from "../db/migrations.ts";
import type { PdfChild } from "./registry.ts";
import { papers, citations } from "../db/schema.ts";
import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite";
import * as defaultPdfRootMod from "../db/default-pdf-root.ts";

// F1 test-isolation: mock the foundation helper so tests never hit the config DB pdf_roots table.
// Use /tmp as the test root — it always exists, so realpathSync inside resolveUnderRoot won't throw ENOENT.
mock.module("../db/default-pdf-root.ts", () => ({
allPdfRoots: (_tx: unknown, _corpusId: string) => ["/tmp"],
defaultPdfRoot: (_tx: unknown, _corpusId: string) => "/tmp",
ConfigurationIncompleteError: class extends Error { override name = "ConfigurationIncompleteError"; },
}));
//
// bun:test mock.module() is process-global; if we don't restore on teardown,
// later test files that import the same module receive the mock instead of
// the real exports (bun 1.3.11 surfaced this clearly; later bun versions
// happen to isolate it). Snapshot the real exports and re-mock with them in
// afterAll so subsequent files (roots.test.ts, etc.) get the real DB-backed
// allPdfRoots / defaultPdfRoot.
const _realDefaultPdfRoot = { ...defaultPdfRootMod };

beforeAll(() => {
mock.module("../db/default-pdf-root.ts", () => ({
allPdfRoots: (_tx: unknown, _corpusId: string) => ["/tmp"],
defaultPdfRoot: (_tx: unknown, _corpusId: string) => "/tmp",
ConfigurationIncompleteError: class extends Error { override name = "ConfigurationIncompleteError"; },
}));
});

afterAll(() => {
mock.module("../db/default-pdf-root.ts", () => _realDefaultPdfRoot);
});

const mockPdf: PdfChild = {
interact: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); },
Expand Down
49 changes: 32 additions & 17 deletions src/server/tools/pdf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,19 @@ const noopLog = {
}

type FakePdfText = string | ((viewUUID: string) => Promise<string>)
function fakeCtx(sqlite: Database, opts?: { text?: FakePdfText }) {
// `paperId` opt seeds ctx.pdfViews with `<paperId> -> view-<paperId>` so
// refreshExtraction's viewUUID lookup (pdf.ts:141, `ctx.pdfViews.get(...)`)
// resolves. The S1 §13 v1.1 amendment introduced that map as the viewUUID
// resolution surface; tests must simulate the scholar.pdf.open call that
// populates it in production.
function fakeCtx(
sqlite: Database,
opts?: { text?: FakePdfText; paperId?: string },
) {
const db = drizzle(sqlite)
const textFactory = opts?.text ?? "Hello scholar. " + "word ".repeat(500)
const pdfViews = new Map<string, string>()
if (opts?.paperId) pdfViews.set(opts.paperId, `view-${opts.paperId}`)
return {
db,
configDb: db,
Expand All @@ -76,6 +86,7 @@ function fakeCtx(sqlite: Database, opts?: { text?: FakePdfText }) {
setRoots: async () => {},
isHealthy: () => ({ alive: true, lastOkAt: Date.now(), stdioOpen: true }),
},
pdfViews,
config: {
get: <T,>(_key: string): T | undefined => undefined,
set: (_k: string, _v: unknown) => {},
Expand All @@ -101,7 +112,7 @@ test("refresh-extraction: writes paper_chunks AND chunk_vec rows for a fixture p
sqlite.run(`INSERT INTO papers(id,key,title,imported_at)
VALUES ('p1','fake2026','Fake paper','2026-05-22T00:00:00.000Z')`)

await refreshExtraction(fakeCtx(sqlite), { paper_id: "p1" })
await refreshExtraction(fakeCtx(sqlite, { paperId: "p1" }), { paper_id: "p1" })

const n = (
sqlite
Expand Down Expand Up @@ -151,7 +162,7 @@ test("refresh-extraction: lazily materializes chunk_vec when deferred (via _test
sqlite.run(`INSERT INTO papers(id,key,title,imported_at)
VALUES ('p2','lazy','Lazy paper','2026-05-22T00:00:00.000Z')`)

await refreshExtraction(fakeCtx(sqlite), {
await refreshExtraction(fakeCtx(sqlite, { paperId: "p2" }), {
paper_id: "p2",
_testProbeDim: async () => ({
dim: 768,
Expand Down Expand Up @@ -180,7 +191,7 @@ test("refresh-extraction: idempotent — re-run yields equal counts (Ruling B co
sqlite.run(`INSERT INTO papers(id,key,title,imported_at)
VALUES ('p3','idem','Idem paper','2026-05-22T00:00:00.000Z')`)

await refreshExtraction(fakeCtx(sqlite), { paper_id: "p3" })
await refreshExtraction(fakeCtx(sqlite, { paperId: "p3" }), { paper_id: "p3" })
const n1 = (
sqlite
.query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='p3'")
Expand All @@ -195,7 +206,7 @@ test("refresh-extraction: idempotent — re-run yields equal counts (Ruling B co
.get() as { n: number }
).n

await refreshExtraction(fakeCtx(sqlite), { paper_id: "p3" })
await refreshExtraction(fakeCtx(sqlite, { paperId: "p3" }), { paper_id: "p3" })
const n2 = (
sqlite
.query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='p3'")
Expand Down Expand Up @@ -226,9 +237,10 @@ test("refresh-extraction: ordinal shrinkage — fewer chunks on re-run trims sta
VALUES ('p4','shrink','Shrinking paper','2026-05-22T00:00:00.000Z')`)

// First run: long text → many chunks.
await refreshExtraction(fakeCtx(sqlite, { text: "word ".repeat(1000) }), {
paper_id: "p4",
})
await refreshExtraction(
fakeCtx(sqlite, { text: "word ".repeat(1000), paperId: "p4" }),
{ paper_id: "p4" },
)
const longCount = (
sqlite
.query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='p4'")
Expand All @@ -237,9 +249,10 @@ test("refresh-extraction: ordinal shrinkage — fewer chunks on re-run trims sta
expect(longCount).toBeGreaterThan(1)

// Second run: tiny text → 1 chunk.
await refreshExtraction(fakeCtx(sqlite, { text: "Tiny." }), {
paper_id: "p4",
})
await refreshExtraction(
fakeCtx(sqlite, { text: "Tiny.", paperId: "p4" }),
{ paper_id: "p4" },
)
const shortCount = (
sqlite
.query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='p4'")
Expand Down Expand Up @@ -267,19 +280,21 @@ test("refresh-extraction: ordinal growth — more chunks on re-run leaves contig
sqlite.run(`INSERT INTO papers(id,key,title,imported_at)
VALUES ('p5','grow','Growing paper','2026-05-22T00:00:00.000Z')`)

await refreshExtraction(fakeCtx(sqlite, { text: "Tiny." }), {
paper_id: "p5",
})
await refreshExtraction(
fakeCtx(sqlite, { text: "Tiny.", paperId: "p5" }),
{ paper_id: "p5" },
)
const tiny = (
sqlite
.query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='p5'")
.get() as { n: number }
).n
expect(tiny).toBe(1)

await refreshExtraction(fakeCtx(sqlite, { text: "word ".repeat(1000) }), {
paper_id: "p5",
})
await refreshExtraction(
fakeCtx(sqlite, { text: "word ".repeat(1000), paperId: "p5" }),
{ paper_id: "p5" },
)
const long = (
sqlite
.query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='p5'")
Expand Down
Loading