From 2454b4cbd5c8fef40a105d3e9de1c4f5a89e66f6 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 21:26:25 -0500 Subject: [PATCH 01/33] fix(start-server): forward argv + propagate child exit on SIGINT Replace Bun.$ with Bun.spawn so the wrapper has a handle on the child. Pass process.argv.slice(2) so `scholar --help` and the CLI `--call` surface added in foundation-009 actually reach the binary. The pre-S2 wrapper dropped argv on the floor, silently degrading every flag to stdio-server mode. SIGINT handler now forwards to the child instead of `process.exit(0)`, and the parent awaits `child.exited` so its exit code mirrors the child's. Ctrl-C during a corpus operation no longer reports success while the child died mid-write. tests/start-server.test.ts spawns the wrapper against a fixture SCHOLAR_ROOT with a stub `build/scholar` binary. The stub observes argv (--help marker) and signals (handler exits 42 on SIGINT), so both regressions are visible at the test boundary. Roadmap: S2. Co-Authored-By: Claude Opus 4.7 (1M context) --- scripts/start-server.ts | 14 ++++- tests/start-server.test.ts | 118 +++++++++++++++++++++++++++++++++++++ 2 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 tests/start-server.test.ts diff --git a/scripts/start-server.ts b/scripts/start-server.ts index 11bb589..d067830 100644 --- a/scripts/start-server.ts +++ b/scripts/start-server.ts @@ -2,13 +2,21 @@ import util from "./util" import env from "./util/env" async function main() { - process.on("SIGINT", () => process.exit(0)) const bin = util.subpath( "build", `scholar${env.dynamic({ win32: ".exe", default: "" })}`, ) - const result = await Bun.$`${bin}`.nothrow() - if (result.exitCode !== 0) process.exit(result.exitCode) + const child = Bun.spawn([bin, ...process.argv.slice(2)], { + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + }) + // Forward SIGINT so the child gets a chance to clean up; the parent then + // mirrors whatever exit code the child reports (130 for an untrapped + // signal, or any explicit code the child sets). The pre-S2 wrapper + // exited 0 here, masking the child's status on Ctrl-C. + process.on("SIGINT", () => child.kill("SIGINT")) + process.exit(await child.exited) } if (import.meta.main) diff --git a/tests/start-server.test.ts b/tests/start-server.test.ts new file mode 100644 index 0000000..5a143fb --- /dev/null +++ b/tests/start-server.test.ts @@ -0,0 +1,118 @@ +// tests/start-server.test.ts — S2 roadmap batch +// +// Two regressions in scripts/start-server.ts the audit caught: +// 1. argv is NOT forwarded to the compiled binary, so `scholar --help` +// and every other CLI flag silently degrade to stdio-server mode. +// 2. The SIGINT handler exits 0 before the child observes the signal, +// masking the child's exit code on Ctrl-C. +// +// Both tests spawn scripts/start-server.ts against a fixture SCHOLAR_ROOT +// containing a stub `build/scholar` binary (a chmod +x bun script). The +// stub is the regression-mock equivalent of the real compiled binary: +// it lives one layer below the defect (it observes argv + signals so the +// wrapper's bugs are visible at the test boundary). +import { test, expect, beforeAll, afterAll } from "bun:test" +import { + mkdtempSync, + rmSync, + mkdirSync, + writeFileSync, + chmodSync, +} from "node:fs" +import { join } from "node:path" +import { tmpdir } from "node:os" +import util from "^scripts/util" + +// Stub binary: a self-contained bun script the OS execs via shebang. +// - `--help` exits 0 with a marker on stdout (proves argv was forwarded). +// - `--block` installs a SIGINT handler that exits 42, prints READY so +// the test can race-safely wait until the handler is installed, then +// blocks forever via setInterval until SIGINT arrives. +const STUB_BINARY = `#!/usr/bin/env bun +const args = process.argv.slice(2); +if (args.includes("--help")) { + process.stdout.write("scholar --help stub\\n"); + process.exit(0); +} +if (args.includes("--block")) { + process.on("SIGINT", () => process.exit(42)); + process.stdout.write("READY\\n"); + setInterval(() => {}, 60_000); +} else { + process.exit(0); +} +` + +let FIXTURE_ROOT: string + +beforeAll(() => { + FIXTURE_ROOT = mkdtempSync(join(tmpdir(), "scholar-start-server-")) + mkdirSync(join(FIXTURE_ROOT, "build"), { recursive: true }) + // The wrapper resolves the binary as build/scholar (POSIX) / build/scholar.exe (win32). + // This test fixture targets POSIX; Windows uses a different binary suffix and + // does not honor shebangs, so the suite is implicitly POSIX-only. + const binPath = join(FIXTURE_ROOT, "build/scholar") + writeFileSync(binPath, STUB_BINARY) + chmodSync(binPath, 0o755) +}) + +afterAll(() => { + rmSync(FIXTURE_ROOT, { recursive: true, force: true }) +}) + +function spawnStartServer(args: string[]) { + return Bun.spawn( + [process.execPath, util.subpath("scripts/start-server.ts"), ...args], + { + env: { + ...process.env, + SCHOLAR_ROOT: FIXTURE_ROOT, + CLAUDE_PLUGIN_ROOT: FIXTURE_ROOT, + }, + stdout: "pipe", + stderr: "pipe", + }, + ) +} + +test("start-server forwards argv to the child binary (--help reaches the child)", async () => { + const proc = spawnStartServer(["--help"]) + const [exitCode, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect(exitCode, `non-zero exit\nstdout:\n${stdout}\nstderr:\n${stderr}`).toBe( + 0, + ) + expect( + stdout, + "expected the stub binary's --help marker on stdout; got empty/wrong output, meaning argv didn't reach the child", + ).toContain("scholar --help stub") +}) + +test("start-server propagates the child's exit code on SIGINT (not 0)", async () => { + const proc = spawnStartServer(["--block"]) + // Race-safe: wait for the stub to print READY before sending SIGINT. + // Otherwise SIGINT may land before the stub installs its handler, and + // the child exits with the default 130 instead of the asserted 42. + const reader = proc.stdout.getReader() + const decoder = new TextDecoder() + let buf = "" + let ready = false + while (!ready) { + const { value, done } = await reader.read() + if (done) break + buf += decoder.decode(value, { stream: true }) + if (buf.includes("READY")) ready = true + } + reader.releaseLock() + expect(ready, "stub never printed READY — start-server failed to spawn it").toBe(true) + + proc.kill("SIGINT") + const exitCode = await proc.exited + expect( + exitCode, + "expected the parent to propagate the child's exit code 42; got 0 means the wrapper swallowed SIGINT", + ).toBe(42) +}) From 8e204ec6063abeefebf5851f9964725a6d5e6996 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 21:26:30 -0500 Subject: [PATCH 02/33] docs(roadmap): mark S2 landed; link to branch Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/audits/ROADMAP.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index b0ee638..600eb39 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -27,12 +27,14 @@ - [ ] **Test** add a contract-level test that spawns the actual vendor process and exercises at least one real `interact` call. Pick `navigate` as the smoke target (simplest payload). - [ ] **Test** rewrite `annotations.test.ts` injections to mock at the `lifecycle.interact()` boundary, not at the handler's `ctx.pdf.interact` injection point — that gap is what hid the bug. -### S2 — CLI mode argv + SIGINT +### S2 — CLI mode argv + SIGINT ✅ landed 2026-05-27 -- [ ] **Code** `scripts/start-server.ts:6-10`: forward `process.argv.slice(2)` into `Bun.spawn`. -- [ ] **Code** `scripts/start-server.ts:5`: SIGINT forwards to child; await child exit; propagate child's exit code instead of `process.exit(0)`. -- [ ] **Test** add a test that launches `scholar --help` and asserts non-empty stdout + exit 0. -- [ ] **Test** add a test that SIGINT-during-child-running propagates the child's exit code. +Branch: `worktree-s2-cli-argv-sigint` (off `main`, post-S1 audit batch). + +- [x] **Code** `scripts/start-server.ts`: replace `Bun.$` with `Bun.spawn`; forward `process.argv.slice(2)` to the child. +- [x] **Code** `scripts/start-server.ts`: SIGINT handler forwards to the child; parent awaits `child.exited` and propagates its code instead of `process.exit(0)`. +- [x] **Test** `tests/start-server.test.ts` — fixture stub `build/scholar` binary asserts `--help` reaches the child (stdout marker + exit 0). +- [x] **Test** `tests/start-server.test.ts` — same fixture, `--block` mode installs a child SIGINT handler exiting 42; the test sends SIGINT to the parent and asserts exit 42 (not 0). ### S3 — Ollama client timeouts From 04a39ed73ef3d62fdf914c2eb9518492369075cd Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 20:04:23 -0500 Subject: [PATCH 03/33] =?UTF-8?q?spec(S1.v1.1):=20drop=20inbound=20annotat?= =?UTF-8?q?ion=20reconciliation;=20rewrite=20=C2=A713?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit S1 amendment: production-readiness audit (docs/audits/ROADMAP.md) found that §13 v1.0 referenced `list_annotations` 6+ times but `@modelcontextprotocol/server-pdf@1.7.2` exposes no such verb. Vendor's PdfCommand union has no full-enumeration capability; `get_viewer_state` returns only `selectedAnnotationIds`. Bidirectional reconciliation is unimplementable without forking the vendor (violates §7.2). Decision (A) from the audit roadmap is adopted: push-only propagation. Section changes: §2 In-scope annotation surface — push-only model. §5.12 pdf.ts file desc — drop search-text + extract-anchors proxies. §7.6 PdfChild.interact signature — `(commands[], opts?)` → `(cmd: PdfCommand, opts: {viewUUID, signal?, timeoutMs?})`. PdfCommand imported from `src/vendor/pdf-server/dist/src/commands.d.ts` (vendor's source of truth). getText signature — `(viewUUID, opts?)` → `(opts: {viewUUID, ...})`. §7.6 ServerContext.pdfViews: Map — process-local paper_id → viewUUID map. Populated by scholar.pdf.open; consumed by annotations.{upsert,delete} and pdf.refresh-extraction. §8.2 annotation_tombstones + reconcile_state — retired (no consumer under push-only). annotations.deleted_at + rect comments updated. paper_dirty_idx dropped (reconciler is gone). §9.2 Paper-detail PDF panel — annotation paragraph rewritten to describe push-only forwarding via paper_id → viewUUID map. §10 Tool catalogue — `scholar.pdf.search-text` and `extract-anchors` removed. `scholar.pdf.open` rewritten as a real proxy to vendor display_pdf that populates ctx.pdfViews. refresh-extraction described as map-consumer. §13 Full rewrite. Reconciler retired; three handlers (upsert/delete/ list) become synchronous DB-write-then-push. New "viewUUID propagation" subsection. New failure-semantics subsection. Cycle-6.7 verification requirements rewritten — the load-bearing new test is the S1 contract test against the real vendor process (catches wire-envelope mistakes that handler-level mocks hide). §16 Risks table — old LWW row replaced with NO_OPEN_VIEWER failure row; new "Vendor-tool truth invariant" row pins the spec ≠ invented-capability rule. §17 Decisions log — tombstones, reconcile-on-read, and reconciler algorithm entries marked superseded; new "drop inbound reconciliation" entry with full option weighing and knock-on effects. No code changes in this commit — code work happens in a follow-up commit after spec sign-off (per persona "design stage = low autonomy"). Co-Authored-By: Claude Opus 4.7 (1M context) --- .../specs/2026-05-22-scholar-plugin-design.md | 382 ++++++++---------- 1 file changed, 176 insertions(+), 206 deletions(-) diff --git a/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md b/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md index 86ae9a6..d69da4d 100644 --- a/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md +++ b/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md @@ -34,7 +34,7 @@ The plugin is explicitly **not** a port of the Daisy artifact. It is a clean rei - arXiv abstract API ingest (no auth, free). Manual entry (single-paper form) is the fallback. 7. **Semantic search** — `sqlite-vec` index over paper title + abstract + extracted text chunks; embeddings produced via local Ollama (`nomic-embed-text:v1.5` default tag; user-pluggable). -8. **Annotation surface** — schema-compatible with the Daisy round-trip (`{ id, page?, anchor?, body, created_at, updated_at, source }`); round-trips with the child pdf MCP (scholar→viewer push, viewer→scholar reconcile-on-read — see §13). +8. **Annotation surface** — schema-compatible with the Daisy round-trip (`{ id, page?, anchor?, body, created_at, updated_at, source }`); v1.1 push-only: scholar→viewer push on upsert/delete, with `viewUUID` resolved from a process-local `paper_id → viewUUID` map populated by `scholar.pdf.open` (see §13). 9. **Synthesis / digest / reading prompts** — local Ollama by default (Qwen-class chat model, user-pluggable). Escape hatch to `cowork.askClaude` for high-stakes synthesis where the user explicitly opts in. 10. **Reading queue** — simple priority queue (manual `priority` integer + computed staleness signals); no FSRS in v1. 11. **MCP App view surfaces (5)** — corpus dashboard, paper detail, digest panel, reading prompts pane, reader progress (charts). @@ -223,7 +223,7 @@ Loader for the `sqlite-vec` extension; handles platform-specific dll/dylib resol `scholar.ingest.bibtex / doi / arxiv / manual`. ### 5.12 src/server/tools/pdf.ts -`scholar.pdf.open / search-text / extract-anchors / refresh-extraction`; proxies into the child pdf MCP. +`scholar.pdf.open / refresh-extraction`. `scholar.pdf.open(paper_id, source)` calls the vendor's `display_pdf` tool and registers the returned `viewUUID` under `paper_id` in `ctx.pdfViews` (§7.6) — the population point for the §13 push-only annotation model. `scholar.pdf.refresh-extraction` re-extracts text, chunks, and embeds (resolves `viewUUID` via the same map). The v1.0 proxy stubs `search-text` and `extract-anchors` were never wired to real vendor tools and are removed in the 2026-05-27 §13 amendment. ### 5.13 src/server/tools/snapshot.ts `scholar.snapshot.take` and the change-since-last-open delta logic. @@ -570,20 +570,33 @@ Each stub compiles immediately, so `registry.ts`, `index.ts`, and `migrations.ts ```typescript import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite"; +import type { PdfCommand } from "../../vendor/pdf-server/dist/src/commands.js"; // SQLite driver swap: better-sqlite3 → bun:sqlite + drizzle-orm/bun-sqlite. // See Session 4 for the corresponding .mcp.json `command` swap to the compiled exe. // The pdf child-process handle. Produced by src/server/pdf/lifecycle.ts // (foundation); consumed by pdf.ts (extraction) and annotations.ts (annotations). +// +// Wire-envelope contract (2026-05-27 amendment, §13 v1.1): +// - The vendor exposes ONE tool named "interact" whose input schema is +// {viewUUID, action, ...sibling-fields-per-action} (or {viewUUID, commands:[...]} +// for batching). scholar passes single commands only. +// - PdfCommand is the vendor's source of truth: src/vendor/pdf-server/dist/src/commands.d.ts. +// The spec MAY NOT invent vendor capabilities (§16 vendor-tool truth invariant). +// - lifecycle.ts's interact() translates {type: "navigate", page: 5} → +// callTool({name: "interact", arguments: {viewUUID, action: "navigate", page: 5}}). +// - viewUUID is REQUIRED on every call; see §13 "viewUUID propagation". interface PdfChild { - // Drives add/update/remove_annotations, get_text, .... Caller-supplied AbortSignal - // and timeoutMs both honoured; whichever fires first wins. Default timeoutMs = 30_000. + // Single-command interact. Caller-supplied AbortSignal and timeoutMs both + // honoured; whichever fires first wins. Default timeoutMs = 30_000. interact( - commands: unknown[], - opts?: { signal?: AbortSignal; timeoutMs?: number }, + cmd: PdfCommand, + opts: { viewUUID: string; signal?: AbortSignal; timeoutMs?: number }, ): Promise; - // Default timeoutMs = 120_000 (text extraction can be slow on large papers). - getText(viewUUID: string, opts?: { timeoutMs?: number }): Promise; + // Calls the vendor's get_text via interact (action: "get_text") under the + // hood. Default timeoutMs = 120_000 (text extraction can be slow on large + // papers). viewUUID required. + getText(opts: { viewUUID: string; timeoutMs?: number }): Promise; currentRoots(): string[]; // Structured health snapshot. `alive` reflects whether the child responded to the // most recent ping; `lastOkAt` is epoch-ms of the most recent successful interaction @@ -616,6 +629,16 @@ interface ServerContext { db: BunSQLiteDatabase | undefined; // active per-corpus Drizzle db; undefined until a corpus is active configDb: BunSQLiteDatabase; // scholar-config.db pdf: PdfChild; + // Process-local paper_id → viewUUID map. Populated by scholar.pdf.open + // (which calls vendor display_pdf and registers the returned viewUUID + // under the paper_id key). Consumed by annotations.{upsert,delete} and + // pdf.refresh-extraction to look up viewUUID before issuing interact() + // calls. Not persisted: scholar restart drops the map, and a child crash + // + supervisor respawn (§5.19) renders cached entries stale (the respawn + // produces fresh viewUUIDs). v1 surfaces the resulting vendor error to + // the caller; v1.1+ may add a respawn callback that clears the map. + // See §13 "viewUUID propagation." + pdfViews: Map; config: ConfigAccessor; log: Logger; // foundation-provided singleton } @@ -781,61 +804,36 @@ export const annotations = sqliteTable("annotations", { paper_id: text("paper_id").notNull().references(() => papers.id, { onDelete: "cascade" }), page: integer("page"), anchor: text("anchor"), - // JSON-encoded [x1, y1, x2, y2] page-coordinate rectangle. Persisted on inbound - // reconcile from the pdf MCP so geometry survives the round-trip; on outbound push - // (scholar → viewer) the §13 reconciler prefers this over the anchor-derived rect. - // Null when the annotation has no associated rectangle (e.g., a paper-level note). + // JSON-encoded [x1, y1, x2, y2] page-coordinate rectangle. Set on upsert when the + // caller supplies geometry; otherwise the outbound push falls back to a derived + // rect (deriveRectFromAnchor → fixed margin sticky). Null is valid (paper-level note). rect: text("rect"), body: text("body").notNull(), - source: text("source").notNull(), // "scholar" | "pdf-viewer" + // Always "scholar" under v1.1 push-only (§13). The CHECK retains "pdf-viewer" as + // a permitted value to keep older corpora (predating the 2026-05-27 amendment) + // validating without a forced data migration; new writes always use "scholar". + source: text("source").notNull(), created_at: text("created_at").notNull(), updated_at: text("updated_at").notNull(), - deleted_at: text("deleted_at"), // null = live; non-null = soft-deleted tombstone marker on the row. The companion annotation_tombstones table below is the *canonical* resurrection-prevention record; this column is the cheap "is this row alive?" filter used by reconciler phase-1 reads (see §13). + // null = live; non-null = soft-deleted (timestamp of the delete). v1.1 uses this + // column as the only delete record — the companion `annotation_tombstones` audit + // table was retired 2026-05-27 (see §13, §17). `WHERE deleted_at IS NULL` is the + // "live row" filter used by `annotations.list`. + deleted_at: text("deleted_at"), }, (t) => ({ paper_idx: index("annotations_paper_idx").on(t.paper_id), - // Composite covers the §13 reconciler's "what changed since last reconcile for this paper" - // scan, which orders by updated_at within paper_id. - paper_dirty_idx: index("annotations_paper_dirty_idx").on(t.paper_id, t.updated_at), source_ck: check("annotations_source_ck", sql`source IN ('scholar','pdf-viewer')`), })); -// Resurrection-prevention audit log for annotation deletes. Inserted in the same -// db.transaction(...) as the soft-delete in annotations.deleted_at (see §13 propagation -// model and reconciler). The §13 reconciler loads the per-paper tombstone-id set in -// phase 1 and uses it as an in-memory filter in phase 3 step 3, preventing a viewer-side -// re-emergence of a deleted annotation from re-inserting. v1 keeps tombstones forever — -// no TTL, no background sweep, no lazy prune (see §13 "Tombstone retention"); the -// per-corpus DB stays small because tombstones are bounded by user delete actions, not -// by paper count, and any TTL would re-introduce the resurrection bug for tombstones -// older than the window. -// -// No FK to annotations(id): the tombstone is canonical and must survive a hypothetical -// hard-delete of the annotations row (e.g., a future schema migration that compacts -// soft-deleted rows). annotation_id is treated as an opaque ULID label here. The -// timestamp is TEXT/ISO to match annotations.deleted_at and reconcile_state -// .last_reconciled_at — uniform timestamp typing across §8.2 overrides the chore's -// integer-millis suggestion (decision logged here for §13 amendment 2026-05-25). -export const annotation_tombstones = sqliteTable("annotation_tombstones", { - annotation_id: text("annotation_id").primaryKey(), // matches the deleted annotations.id (ULID) - paper_id: text("paper_id").notNull(), // denormalized for fast per-paper SELECT in §13 phase 1 - deleted_at: text("deleted_at").notNull(), // ISO; mirrors the annotations.deleted_at value at delete time - deleted_by: text("deleted_by"), // optional audit: 'scholar' | tool name | user identity - deletion_reason: text("deletion_reason"), // optional free-form audit string -}, (t) => ({ - paper_idx: index("annotation_tombstones_paper_idx").on(t.paper_id), -})); - -// Per-paper reconciler bookkeeping. One row per (corpus_id, paper_id) that scholar -// has ever reconciled with the child pdf MCP. Lets the algorithm detect "this side -// has never seen that paper" vs "this side deleted it" without ambiguity. Algorithm -// body in §13 is filled in Session 3; the schema shape is pinned here. -export const reconcile_state = sqliteTable("reconcile_state", { - corpus_id: text("corpus_id").notNull(), - paper_id: text("paper_id").notNull(), - last_reconciled_at: text("last_reconciled_at").notNull(), -}, (t) => ({ - pk: primaryKey({ columns: [t.corpus_id, t.paper_id] }), -})); +// `annotation_tombstones` and `reconcile_state` — RETIRED 2026-05-27 (§13 v1.1 +// push-only amendment, §17 decision log "drop inbound reconciliation"). Both tables +// served bidirectional reconciliation which the vendored pdf MCP does not support +// (no full-enumeration command; `get_viewer_state` returns selected-annotation IDs +// only). Their definitions are deliberately absent: the foundation migration script +// (§7.3) creates only the surviving §8.2 tables. Older corpora that may carry these +// tables from a v0.x run keep the rows on disk (no DROP TABLE migration); scholar +// stops reading from / writing to them. Hard-delete forensics and resurrection-prevention +// are out of scope for v1; see §13 "Out-of-scope" for the rationale. export const anchor_cache = sqliteTable("anchor_cache", { paper_id: text("paper_id").primaryKey().references(() => papers.id, { onDelete: "cascade" }), @@ -944,7 +942,7 @@ Differences from Daisy: search is **semantic** (sqlite-vec) when Ollama is avail Two-column layout. Left: an in-panel PDF render produced by **bundled pdf.js** (the library, bundled into the single-file UI — *not* a nested MCP App iframe). Right: paper metadata, annotations list (with CRUD), reading prompts, and a "similar papers" panel populated by `chunk_vec` k-NN search. An "open in pdf-viewer" action hands off to the full pdf-viewer plugin for heavyweight viewing. -The annotation list uses the **same schema and IDs as the child pdf MCP's annotation store**. Edits in scholar's panel call `app.callServerTool("annotations.upsert", ...)`, which writes scholar's row and forwards the change to the child pdf MCP. Edits made in an external pdf-viewer are reconciled when the paper detail view is (re)opened or explicitly refreshed — see §13 for the reconciliation model. +The annotation list uses the **same schema and IDs as the child pdf MCP's annotation store**. Edits in scholar's panel call `app.callServerTool("annotations.upsert", ...)`, which writes scholar's row and forwards the change to the child pdf MCP (via the `paper_id → viewUUID` lookup populated by `scholar.pdf.open`). Edits made externally in the pdf-viewer (without going through scholar's tools) are NOT synced into scholar in v1 — the vendored pdf MCP exposes no enumeration command, so a viewer→scholar pull is not implementable against `server-pdf@1.7.2`. See §13 for the push-only propagation model and its v2+ candidates. ### 9.3 Digest panel (`view: "digest", scope_key: ...`) @@ -1001,10 +999,8 @@ All scholar tools are namespaced `scholar.`. Visibility annotations are ex | `scholar.prompts.generate` | both | Generate / refresh reading prompts for a paper. | — | | `scholar.digest.generate` | both | Generate / refresh a scoped digest. | — | | `scholar.digest.change-since-last-open` | app | Compute and render the delta digest. | — | -| `scholar.pdf.open` | both | Open a paper in the pdf-viewer (proxies to child pdf MCP). | — | -| `scholar.pdf.search-text` | app | Highlight a query in the active viewer. | — | -| `scholar.pdf.extract-anchors` | app | Run the anchor extractor on a paper (replaces the PowerShell + uv + pypdf chain). | — | -| `scholar.pdf.refresh-extraction` | model | Re-extract text + chunks + embeddings. | — | +| `scholar.pdf.open` | both | Open a paper in the pdf-viewer. Calls vendor `display_pdf`; registers the returned `viewUUID` under `paper_id` in `ctx.pdfViews` (§7.6) so subsequent annotation pushes and text extraction can resolve it. | — | +| `scholar.pdf.refresh-extraction` | model | Re-extract text + chunks + embeddings. Requires that `scholar.pdf.open` has been called for the paper this session (`viewUUID` comes from the map). | — | | `scholar.snapshot.take` | model | Snapshot status_overrides + selection (used by the change-since-last-open digest). | — | ## 11. Ollama Integration @@ -1181,159 +1177,128 @@ A no-op metadata path: the form lets the user supply title/authors/year/venue/pd ## 13. Annotation Round-trip -The vendored pdf MCP supports `add_annotations` / `update_annotations` / `remove_annotations` with the type catalogue listed in the pdf-viewer plugin's `view-pdf` skill. Scholar's annotation table mirrors that schema (`{id, page?, anchor?, body, source, created_at, updated_at, deleted_at}`); `id`s are stable across both stores. The schema additions in §8.2 — `annotations.deleted_at` (soft-delete marker on live rows), `annotations.rect` (persisted geometry), the `reconcile_state` table (per-paper bookkeeping), and the `annotation_tombstones` table (resurrection-prevention audit log; see "Tombstone-resurrection edge case" below) — are pinned. This section pins the reconciler algorithm body that consumes them. +> **Amendment 2026-05-27 (v1.1).** This section was rewritten when the audit found that the v1.0 reconciler depended on a vendor command (`list_annotations`) that `@modelcontextprotocol/server-pdf@1.7.2` does not expose — the entire `PdfCommand` union (`src/vendor/pdf-server/dist/src/commands.d.ts`) contains no enumeration verb, and `get_viewer_state` returns `selectedAnnotationIds` only. Bidirectional reconciliation is therefore retired; v1 is push-only. See §17 decision log "drop inbound reconciliation" for the option weighing. -**Propagation model.** v1 does **not** assume the child pdf MCP emits annotation-change notifications — that behaviour is unverified against `server-pdf@1.7.2`. Propagation is therefore poll/reconcile, not event-push: +The vendored pdf MCP exposes annotation operations as `action` discriminants on its single `interact` tool: `add_annotations`, `update_annotations`, `remove_annotations`. The full `PdfCommand` union (these three plus eleven other actions — navigate, search, zoom, highlight_text, fill_form, get_pages, get_text, get_screenshot, get_viewer_state, save_as, search_navigate, find, file_changed) is declared in `src/vendor/pdf-server/dist/src/commands.d.ts`; the vendor file is the sole source of truth (§16 vendor-tool truth invariant). Scholar's annotation table mirrors the geometric schema (`{id, page?, anchor?, body, source, created_at, updated_at, deleted_at}`); `id`s are stable across both stores. The schema additions in §8.2 — `annotations.deleted_at` (soft-delete marker) and `annotations.rect` (persisted geometry) — are pinned. The earlier `reconcile_state` and `annotation_tombstones` tables are retired (§8.2 note). -1. *scholar → viewer (push).* A `scholar.annotations.upsert` / `.delete` writes scholar's row, then immediately forwards the change to the child pdf MCP via `ctx.pdf.interact([{ type: "add_annotations" | "update_annotations" | "remove_annotations", ... }])` with a derived rectangle (the persisted `annotations.rect` if present, else the anchor-derived rect, else a margin sticky-note). A `.delete` performs a soft-delete by setting `annotations.deleted_at` *and*, in the same `db.transaction(...)`, inserts an `annotation_tombstones` row (annotation_id + deleted_at; optional deleted_by / deletion_reason for audit) — the tombstone is the canonical resurrection-prevention record and outlives the annotations row even under a hypothetical future hard-delete migration. Both writes commit atomically so the §13 reconciler never observes a partial state where the row is tombstoned but the audit record is missing. -2. *viewer → scholar (reconcile-before-read).* Per Open Q4, every call to `scholar.annotations.list(paper_id)` synchronously invokes the reconciler below before returning rows. Latency cost (one viewer round-trip per list) is accepted in exchange for eliminating the model-facing stale window — the model never observes an annotation set that disagrees with what the user sees in the viewer. +**Propagation model — push only.** Scholar's DB is the source of truth. Every `scholar.annotations.upsert` / `.delete` writes the row synchronously, commits, then forwards the change to the child pdf MCP via `ctx.pdf.interact(cmd, {viewUUID})`. Annotations created externally in the pdf-viewer (without going through scholar's tools) are NOT synced into scholar — the vendor exposes no full-enumeration command, so a viewer→scholar pull is not implementable against `server-pdf@1.7.2` without forking the vendor (which would violate §7.2's no-source-patch invariant). -**Tombstone-resurrection edge case.** The vendored pdf MCP has no knowledge of scholar's soft-delete state — its `list_annotations` reply enumerates whatever the viewer currently considers live. A `remove_annotations` pushed by scholar in phase 2 of an earlier reconcile may fail to durably remove the annotation viewer-side (transient I/O loss between the call and the viewer's persistence layer, a viewer-side persistence quirk that re-hydrates from the underlying PDF on next list, or a future re-vendor that changes remove-semantics), causing the deleted annotation to reappear in a subsequent `list_annotations` reply. Without explicit handling, phase-3 step 3 of the algorithm below would observe the id as "viewer-only" — `scholar_by_id` contains only *live* rows via `isNull(deleted_at)`, so the lookup misses — and re-insert the row, resurrecting an annotation the user explicitly deleted. To distinguish "new annotation never seen" from "tombstoned annotation, do not resurrect", scholar consults the `annotation_tombstones` table (§8.2): the reconciler loads the per-paper tombstone-id set in phase 1, re-pushes `remove_annotations` in phase 2 for any tombstoned id that reappears viewer-side (resurrection *cure*, not just symptom suppression), and filters tombstoned ids out of the phase-3 insert branch as a pre-transaction in-memory `Set.has()` check. The Set lookup is canonical — a `SELECT` inside the phase-3 transaction would be equivalent semantically but breaks the no-await / minimum-tx-window discipline pinned below. +The v1.0 "reconcile on every list" guarantee — *"the model never observes an annotation set that disagrees with what the user sees"* — was always conditional on enumerate-capability the vendor doesn't expose. The amendment makes the actual contract honest: push-only, scholar-authoritative. -**Reconciler algorithm (cycle 6.7, `annotations` plan).** `reconcile(corpus_id, paper_id, db)` is structured to keep every MCP round-trip *outside* the SQLite write transaction — under Open Q4 this function runs on every `annotations.list` call, so a transaction that held the write lock across network I/O would serialize all readers behind in-flight pdf-child traffic. Reads and pushes happen first against `db` (no transaction); only the final write-back wraps the local SQL in `db.transaction(...)`. The §7.6 cross-plan helper convention still applies to the write-back closure (`tx`-as-first-arg), but the outer signature takes `db` rather than `tx`. +**Out-of-scope (v1, candidates for v2+):** +- Annotations created in the pdf-viewer without going through scholar (no enumeration capability available — would require vendor fork or upstream change). +- Bidirectional reconciliation, tombstone-resurrection prevention, `reconcile_state` cursor, LWW on `updated_at` (all dropped — depend on inbound capability that doesn't exist). +- `viewUUID` map persistence across scholar restarts (in-memory only). +- `viewUUID` map invalidation on child respawn (v1 surfaces vendor errors; v1.1+ may add a respawn callback). -```typescript -async function reconcile( - corpus_id: string, - paper_id: string, - db: BunSQLiteDatabase, -): Promise { - // --- Phase 1: read-only state capture (no tx; no SQLite write lock held). --- - - const cursor = db.select({ at: reconcile_state.last_reconciled_at }) - .from(reconcile_state) - .where(and(eq(reconcile_state.corpus_id, corpus_id), - eq(reconcile_state.paper_id, paper_id))) - .get()?.at ?? "1970-01-01T00:00:00.000Z"; // epoch sentinel for never-reconciled - - const scholar_dirty = db.select().from(annotations) - .where(and( - eq(annotations.paper_id, paper_id), - or(gt(annotations.updated_at, cursor), gt(annotations.deleted_at, cursor)), - )) - .all(); +### viewUUID propagation - const scholar_all_live = db.select().from(annotations) - .where(and( - eq(annotations.paper_id, paper_id), - isNull(annotations.deleted_at), - )) - .all(); - const scholar_by_id = new Map(scholar_all_live.map(r => [r.id, r])); - - // Tombstones — explicit "do-not-resurrect" id set, loaded once as a Set for O(1) - // phase-3 lookup. This SELECT is *required* by the tombstone-resurrection narrative - // above; omitting it re-introduces the bug where a viewer-side re-emergence of a - // deleted annotation re-inserts it scholar-side. Loading pre-transaction is canonical: - // it lets the phase-3 filter remain a synchronous in-memory check, preserving the - // CLAUDE.md no-await invariant on the transaction closure. - const tombstoned_ids = new Set( - db.select({ id: annotation_tombstones.annotation_id }) - .from(annotation_tombstones) - .where(eq(annotation_tombstones.paper_id, paper_id)) - .all() - .map(r => r.id), - ); +The vendor `interact` tool requires `viewUUID` as a sibling of `action` (per the input schema in `src/vendor/pdf-server/dist/server.js`). Scholar maintains a process-local `paper_id → viewUUID` map at `ctx.pdfViews` (§7.6), populated by `scholar.pdf.open(paper_id, source)` and consumed by `annotations.{upsert,delete}` and `pdf.refresh-extraction`. A map miss throws `NO_OPEN_VIEWER` — the user must call `scholar.pdf.open` before pushing annotations or extracting text. - // --- Phase 2: MCP round-trips (await on network; no SQLite tx open). --- - - const viewer_rows = await ctx.pdf.interact([{ type: "list_annotations", paper_id }]); - const viewer_by_id = new Map(viewer_rows.map(r => [r.id, r])); - - // 1. Tombstones — push deletes to viewer for (a) scholar rows soft-deleted since the - // cursor and (b) any tombstoned id that the viewer is still reporting live - // (resurrection *cure*: re-asserts the delete viewer-side when a previous push - // didn't durably stick). Both sets fold into a single remove_annotations call. - // Without the (b) leg, the phase-3 filter would silently skip the resurrected - // annotation every reconcile and never actually clean up the viewer-side row. - const fresh_tombstone_ids = scholar_dirty - .filter(r => r.deleted_at !== null) - .map(r => r.id); - const resurrected_ids = viewer_rows - .filter(v => tombstoned_ids.has(v.id)) - .map(v => v.id); - const ids_to_remove = Array.from(new Set([...fresh_tombstone_ids, ...resurrected_ids])); - if (ids_to_remove.length > 0) { - await ctx.pdf.interact([{ - type: "remove_annotations", - ids: ids_to_remove, - }]); - } +The map is process-local: +- **Scholar restart drops it.** The user must re-`scholar.pdf.open` each paper they want to push annotations to. Acceptable for personal-use v1. +- **Child crash + supervisor respawn (§5.19 / `lifecycle.ts:160-184`) renders cached entries stale.** The respawned vendor child issues fresh UUIDs; the old ones become invalid. v1 surfaces the vendor's "unknown viewUUID" error on the next interact call (the model sees a structured failure and asks the user to re-open). v1.1+ may register a `transport.onclose` callback that clears the map automatically. - // 2. Live scholar-side changes — push add/update to viewer. Concurrent push is safe - // against the child: each interact() call serializes on the child's stdio pipe. - const live_changes = scholar_dirty.filter(r => r.deleted_at === null); - for (const row of live_changes) { - const op = viewer_by_id.has(row.id) ? "update_annotations" : "add_annotations"; - await ctx.pdf.interact([{ type: op, annotations: [serializeForViewer(row)] }]); +### Algorithm + +All three annotation handlers are synchronous DB-write-then-push. The v1.0 "Phase 1 → Phase 2 → Phase 3 transaction" discipline collapses to a single phase (no reconciler exists to need phasing): + +```typescript +async function upsert(ctx: ServerContext, input: UpsertArgs): Promise { + const db = ctx.db; + if (!db) throw new AnnotationsToolError("NO_ACTIVE_CORPUS", "..."); + const viewUUID = ctx.pdfViews.get(input.paper_id); + if (!viewUUID) { + throw new AnnotationsToolError( + "NO_OPEN_VIEWER", + `NO_OPEN_VIEWER: call scholar.pdf.open(paper_id=${input.paper_id}) before upserting annotations.`, + ); } - // --- Phase 3: local write-back inside a single Drizzle transaction. No awaits. --- + // §12.0 sanitization on user-supplied body and anchor — throws before any DB or push. + const safeBody = sanitizeText(input.body); + const safeAnchor = input.anchor != null ? sanitizeText(input.anchor) : null; + const rectJson = input.rect != null ? JSON.stringify(parseRect(input.rect)) : null; + + // Read existing row (if id supplied) to choose insert-vs-update + preserve created_at. + const existing = input.id + ? db.select().from(annotations).where(eq(annotations.id, input.id)).get() + : undefined; const now = nowIso(); - db.transaction((tx) => { - // 3. Viewer-only rows (new on the viewer side OR newer than scholar's copy) — pull. - // Tombstoned ids are skipped here (resurrection prevention) — the tombstoned_ids - // Set was captured in phase 1 and serves as a pre-transaction in-memory filter, - // keeping this branch synchronous (no SELECT inside tx, no await — preserves - // the CLAUDE.md "no awaits inside the transaction closure" invariant). - for (const vrow of viewer_rows) { - if (tombstoned_ids.has(vrow.id)) continue; // do-not-resurrect - const srow = scholar_by_id.get(vrow.id); - if (!srow) { - tx.insert(annotations).values({ - id: vrow.id, - paper_id, - page: vrow.page, - anchor: vrow.anchor, - rect: JSON.stringify(vrow.rect), - body: vrow.body, - source: "pdf-viewer", - created_at: vrow.created_at ?? now, - updated_at: vrow.updated_at ?? now, - deleted_at: null, + const savedRow: AnnotationRow = existing + ? (db.update(annotations) + .set({ page: input.page ?? null, anchor: safeAnchor, rect: rectJson, body: safeBody, + source: "scholar", updated_at: now }) + .where(eq(annotations.id, existing.id)).run(), + { ...existing, page: input.page ?? null, anchor: safeAnchor, rect: rectJson, + body: safeBody, source: "scholar", updated_at: now }) + : (() => { + const id = input.id ?? ulid(); + db.insert(annotations).values({ + id, paper_id: input.paper_id, page: input.page ?? null, anchor: safeAnchor, + rect: rectJson, body: safeBody, source: "scholar", + created_at: now, updated_at: now, deleted_at: null, }).run(); - } else if (vrow.updated_at && vrow.updated_at > srow.updated_at) { - tx.update(annotations).set({ - body: vrow.body, - rect: JSON.stringify(vrow.rect), - source: "pdf-viewer", - updated_at: vrow.updated_at, - }).where(eq(annotations.id, vrow.id)).run(); - } - // Else: scholar's copy is at least as new — keep it. - } + return { id, paper_id: input.paper_id, page: input.page ?? null, anchor: safeAnchor, + rect: rectJson, body: safeBody, source: "scholar", + created_at: now, updated_at: now, deleted_at: null }; + })(); + + // Write-then-push: the DB write above committed synchronously before this await. + // A throw here leaves a dirty row (in scholar, missing from viewer). The user can + // re-invoke upsert with the same id to retry. + const action = existing ? "update_annotations" : "add_annotations"; + await ctx.pdf.interact( + { type: action, annotations: [serializeForViewer(savedRow)] }, + { viewUUID }, + ); + return savedRow; +} - // 4. Scholar-only rows OLDER than the cursor and missing from the viewer: - // treat as viewer-side deletions and tombstone in scholar. - for (const srow of scholar_all_live) { - if (srow.updated_at <= cursor && !viewer_by_id.has(srow.id)) { - tx.update(annotations).set({ deleted_at: now }) - .where(eq(annotations.id, srow.id)).run(); - } - } +async function delete_(ctx: ServerContext, { id }: DeleteArgs): Promise { + const db = ctx.db; + if (!db) throw new AnnotationsToolError("NO_ACTIVE_CORPUS", "..."); + const existing = db.select().from(annotations).where(eq(annotations.id, id)).get(); + if (!existing) return { id, deleted: false, reason: "not_found" }; + if (existing.deleted_at !== null) { + return { id, deleted: false, reason: "already_tombstoned", deleted_at: existing.deleted_at }; + } + const viewUUID = ctx.pdfViews.get(existing.paper_id); + if (!viewUUID) { + throw new AnnotationsToolError( + "NO_OPEN_VIEWER", + `NO_OPEN_VIEWER: call scholar.pdf.open(paper_id=${existing.paper_id}) before deleting annotations on that paper.`, + ); + } - // 5. Advance the cursor. UPSERT — first reconcile inserts, later ones update. - tx.insert(reconcile_state).values({ - corpus_id, paper_id, last_reconciled_at: now, - }).onConflictDoUpdate({ - target: [reconcile_state.corpus_id, reconcile_state.paper_id], - set: { last_reconciled_at: now }, - }).run(); - }); -} -``` + // Soft-delete only — annotation_tombstones is retired (§8.2 note). + const now = nowIso(); + db.update(annotations).set({ deleted_at: now }).where(eq(annotations.id, id)).run(); -**Transaction discipline (advisor-flagged).** No `await` appears inside `db.transaction(...)`. The phase-3 closure runs synchronously over data captured in phase 1 (including the `tombstoned_ids` Set used by the resurrection-prevention filter — captured pre-transaction precisely so the filter is an in-memory `Set.has()` call rather than a `SELECT` inside `tx`) and the viewer rows fetched in phase 2 — the SQLite write lock is held only for the duration of the local SQL, never across network I/O. This keeps `annotations.list` parallelizable in v1 even though every call reconciles; without this split, two concurrent list calls on different papers would serialize behind each other's pdf-child traffic. The CLAUDE.md "Load-bearing invariants" rule — *"Phase 1 reads → phase 2 MCP I/O → phase 3 db.transaction(...) with no awaits inside the transaction closure"* — applies verbatim to the amended algorithm: the tombstone read joins phase 1, the resurrection cure joins phase 2, the tombstone filter is a synchronous Set lookup in phase 3. + // Write-then-push. + await ctx.pdf.interact({ type: "remove_annotations", ids: [id] }, { viewUUID }); + return { id, deleted: true, deleted_at: now }; +} -**Phase-2 race window (documented, accepted).** Between phase 1's `scholar_all_live` snapshot and phase 3's tombstone scan, a separate `annotations.upsert` may insert a new scholar row. That row's `updated_at` is necessarily after `cursor` (it was just written), so the phase-3 tombstone rule (`srow.updated_at <= cursor`) skips it correctly — the new row is not misclassified as a viewer-side deletion. The reverse case (a separate `annotations.upsert` modifies a row that phase 1 read) is resolved by SQLite's transaction semantics: phase 3's UPDATE on that row reflects the concurrent writer's commit, since `db.transaction` reads the latest committed state when it opens. +async function list(ctx: ServerContext, { paper_id }: ListArgs): Promise<{ rows: AnnotationRow[] }> { + // Pure DB read — no reconcile, no viewer round-trip. Does NOT require an open + // viewer; closed-viewer papers still return DB rows. + const db = ctx.db; + if (!db) throw new AnnotationsToolError("NO_ACTIVE_CORPUS", "..."); + const rows = db.select().from(annotations) + .where(and(eq(annotations.paper_id, paper_id), isNull(annotations.deleted_at))) + .all(); + return { rows }; +} +``` -**`serializeForViewer(row)` helper.** Owned by the `annotations` plan; lives in `src/server/tools/annotations.ts`. Pinned shape: +**`serializeForViewer(row)` helper.** Owned by the `annotations` plan; lives in `src/server/tools/annotations.ts`. Pinned shape (unchanged from v1.0): ```typescript function serializeForViewer(row: AnnotationRow): ViewerAnnotation { return { - id: row.id, // ULID; viewer-side prefix wrap deferred to cycle 6.7 round-trip test + id: row.id, // ULID; viewer-side prefix wrap deferred to the cycle-6.7 round-trip test page: row.page, rect: row.rect ? JSON.parse(row.rect) : deriveRectFromAnchor(row.anchor), body: row.body, @@ -1342,22 +1307,25 @@ function serializeForViewer(row: AnnotationRow): ViewerAnnotation { }; } ``` -If the cycle-6.7 ID round-trip test reveals the viewer mutates ULID-shaped IDs, `serializeForViewer` switches to the `scholar-` wrap-and-strip pattern and the consumer-side `viewer_rows` parser inverts it. The branch is taken on test evidence, not pre-committed. - -**Tie-breaking on identical `updated_at`.** When `vrow.updated_at === srow.updated_at` to the millisecond, scholar's row is preserved — the algorithm only overwrites on strict `>`. This matters when a single user action triggers near-simultaneous writes on both sides (the millisecond-precision `nowIso()` from §8 plus serial transaction commits make exact equality rare but possible). The asymmetry is documented and intentional: scholar's row carries the source-of-truth metadata (`paper_id`, `source`) which the viewer's reply may have lost or transformed. -**Tombstone retention (v1).** `annotation_tombstones` rows live forever in v1 — there is no background sweep on `corpus.activate`, no lazy prune on next reconcile, and no admin tool to clear them. Rationale: tombstones are bounded by user delete actions (not by paper count), the per-corpus DB stays small in absolute terms, and any TTL would re-introduce the resurrection bug for tombstones older than the window — a viewer-side persistence quirk that re-hydrates a 90-day-old deleted annotation would silently re-insert it the moment its tombstone aged out. v1.1+ may add an explicit admin tool (`scholar.annotations.prune-tombstones` or similar) gated on a user-confirmed time window; until that ships, every intentional deletion is permanent on scholar's side. This decision is logged here, in §17 (Decisions Log), and at the `annotation_tombstones` table definition in §8.2 so future readers see consistent rationale. +If the cycle-6.7 ID round-trip test reveals the viewer mutates ULID-shaped IDs, `serializeForViewer` switches to the `scholar-` wrap-and-strip pattern. The branch is taken on test evidence, not pre-committed. -**Batching.** The algorithm issues at most three MCP round-trips per call: one `list_annotations`, one batched `remove_annotations`, and one `add_annotations` / `update_annotations` per non-tombstoned dirty row. The per-row loop in step 2 is unbatched because the viewer's batch semantics for mixed add+update calls are unverified against 1.7.2 — cycle 6.7 verifies and, if the viewer accepts a single mixed batch, the loop collapses to one call. Step 3's writes are local SQL inside `tx`; no MCP traffic. +**Transaction discipline.** The §13 v1.0 "no awaits inside `db.transaction(...)`" rule still applies wherever a transaction is opened. Under v1.1 push-only, the writes in upsert/delete are single statements and don't need explicit `db.transaction(...)` wrappers — the v1.0 atomic-write-tombstone pair retired with `annotation_tombstones`. -**Cycle 6.7 verification requirements (Integration F1 / F9).** +**Failure semantics.** +- *DB write succeeds, push throws.* Caller gets the push error. The row is in scholar's DB but not in the viewer. The user retries by re-invoking the same tool with the same id; if the viewer crashed and was respawned, the user must first call `scholar.pdf.open` again (the original NO_OPEN_VIEWER fires on the stale map entry). +- *DB write throws.* No push attempted; row not persisted; caller gets the DB error. +- *Push succeeds, caller never receives the response (network partition between caller and scholar).* The row IS in both stores; a retry inserts a fresh ULID if the original was server-generated, or no-ops on the existing id if the caller supplied one. Idempotency is the caller's responsibility on retry. -- **`list_annotations` `updated_at` availability.** Verify upstream returns a comparable `updated_at` field. If it does not, the algorithm degenerates gracefully to *scholar-authoritative* — step 3's `vrow.updated_at > srow.updated_at` branch becomes unreachable, but step 3's "never-seen-by-scholar" branch still catches viewer-only adds and step 4 still detects viewer-side deletes through membership. The reconciler test in cycle 6.7 includes both branches and a parameterized fixture for each return shape. -- **Annotation ID round-trip.** Test that an annotation written by scholar (ULID id) survives a `list_annotations` reply unchanged. If the viewer mutates the id (prefix, length cap, character class), scholar's `serializeForViewer` wraps the ULID as `scholar-` on push and strips on pull; the test pins the chosen format. -- **Mixed-batch acceptance.** Test whether `interact([{type:"add_annotations",...}, {type:"update_annotations",...}])` is accepted as one call; if yes, simplify step 2 accordingly. -- **Tombstone-resurrection contract.** Internal test (no upstream variation needed): seed `annotations` with a row X plus a matching `annotation_tombstones` entry, mount a stub `ctx.pdf` whose `list_annotations` reply still contains X (simulating a viewer that ignored the prior `remove_annotations`), then call `reconcile(...)`. Assert (i) phase-3 does NOT insert or re-vivify X in `annotations` — `scholar_all_live` for the paper is unchanged across the reconcile, (ii) the stub observed a `remove_annotations` call carrying X's id in phase 2 (resurrection-cure exercised), and (iii) `annotation_tombstones` is unchanged in shape and content across the reconcile (tombstones are durable; no implicit prune). This pins the resurrection-prevention contract independent of any upstream behavior the F1/F9 items vary. +### Cycle 6.7 verification requirements (S1 contract test + handler tests) -If a future re-vendor of the pdf MCP is confirmed to emit `resources/updated` for annotations, scholar may additionally `subscribeResource` to make reconciliation eager — a v2 optimization, not a v1 dependency. +- **Vendor wire envelope (S1 contract test).** Spawn the real vendored pdf-server process via the same `StdioClientTransport` path that production uses. Call `display_pdf` to get a viewUUID. Call `interact` with `{action: "navigate", page: 1, viewUUID}` (simplest payload) and assert the response is non-error. This is the canary that catches `{name, arguments}` envelope mistakes — the v1.0 reconciler bug (sending the action name as the tool name) was hidden because every test mocked at `ctx.pdf.interact`, never at the actual MCP wire. +- **viewUUID lookup.** Test that upsert/delete throw `NO_OPEN_VIEWER` when `ctx.pdfViews` has no entry for the paper. +- **Map population.** Test that `scholar.pdf.open(paper_id, source)` populates `ctx.pdfViews[paper_id]` with the viewUUID returned by vendor `display_pdf`. +- **Write-then-push ordering.** Test that the DB row exists at the moment `pdf.interact` is first awaited from upsert (proves the write committed before the push). +- **Sanitization (unchanged from v1.0).** §12.0 `sanitizeText` applied to user-supplied body and anchor; reject before any DB write or push. +- **`scholar.annotations.list` does NOT require an open viewer.** Test that list returns rows when `ctx.pdfViews` is empty (list is a pure DB read). +- **`scholar.pdf.refresh-extraction` requires an open viewer.** Test that refresh-extraction throws `NO_OPEN_VIEWER` when the paper has no map entry, and succeeds when it does. ID stability is preserved across both paths. @@ -1393,7 +1361,8 @@ Cycles are enumerated in §6 (Implementation Cycles) with per-cycle `Touches` / | Latent upstream `useClientRoots` propagation bug (the env-var-derived `roots` value computed at `dist/index.js:34386–34391` is not threaded through to `createServer` on line 34392 — the call uses the original CLI flag instead). | Scholar passes `--use-client-roots` on the command line, so `useClientRoots` is already `true` at the createServer call and the bug never bites. No source patch needed; the workaround is purely in the spawn invocation. A future upstream fix would be a no-op for scholar. | | Drop vendored copy entirely (v2 simplification candidate). | Spawn via `bunx @modelcontextprotocol/server-pdf` when a sufficient network and bun runtime are present, removing `src/vendor/pdf-server/` from the bundle. Trade-off: removes the offline-distribution guarantee. Not pursued in v1 because the plugin must remain installable in air-gapped Cowork hosts. (Distinct from the v1-adopted protocol-based roots approach in §7.2.) | | Native FFI for the Windows Job Object orphan-reaping path. | Single FFI surface in `src/server/pdf/lifecycle.ts` via `koffi` (preferred) or `win32-api`. Falls back to a startup-sweep + `prctl(PR_SET_PDEATHSIG)` posture on non-Windows. The dependency is pinned and the failure mode is "no orphan reaping on Windows" — supervised respawn still works inside a live scholar session. | -| Annotation reconciliation conflicts (user edits in both panes concurrently). | Last-write-wins keyed by `updated_at`; scholar reconciles on paper-detail open/refresh (§13). Test with a deliberate concurrent-edit race. | +| Annotation pushed by scholar fails to land in the viewer (network partition, viewer crash, stale viewUUID after supervisor respawn). | Failure surfaces to the caller as a structured error: `NO_OPEN_VIEWER` (`ctx.pdfViews` has no entry) or the vendor error directly. The DB row is already committed (write-then-push), so the user retries by re-invoking the same annotation tool with the same id; if the viewer was respawned, the user calls `scholar.pdf.open` first to refresh the map entry. v1 does not auto-retry; v1.1+ may add a retry queue. (The v1.0 LWW + reconcile-on-read mitigation is retired — see §13 v1.1 amendment + §17 "drop inbound reconciliation".) | +| Spec invents vendor capabilities that don't exist (root cause of the 2026-05-27 audit finding — `list_annotations` was referenced 6+ times in §13 and `server-pdf@1.7.2` exposes no such verb). | **Vendor-tool truth invariant.** Every command name referenced in the scholar spec or codebase MUST be either (a) a member of the `PdfCommand` union in `src/vendor/pdf-server/dist/src/commands.d.ts`, or (b) a tool name exported by `src/vendor/pdf-server/dist/server.js`. New spec entries that reference a vendor capability MUST cite the source file + line. The cycle-6.7 contract test (§13 verification requirements) exercises the full annotation push path against the real vendor process, providing wire-level evidence that the chosen action names round-trip. Future re-vendor PRs run the same fixture suite (§16 "Upstream pdf server changes its MCP protocol shape" row). | | Embedding production blocks tool responses on big papers. | Embedding pipeline runs on an in-process async queue with a small concurrency limit (a worker thread is deferred to v2 if profiling shows main-thread starvation); tools that need embeddings (`scholar.papers.search` with semantic mode) check readiness and degrade to lexical with a "still indexing" pill. | | User installs the plugin without the global `bun.exe`. | v1 ships scholar as a single self-contained executable produced by `bun build --compile` (promoted from earlier "v2 considers"); `.mcp.json`'s `command` points at the compiled binary, so the runtime host does not need `bun` on PATH for scholar's own process. The Bun runtime itself is **also** bundled into `build/runtime/bun(.exe)` because scholar spawns the unmodified Node-style pdf-child script (`src/vendor/pdf-server/dist/index.js`) and a `bun build --compile` artifact cannot re-exec arbitrary scripts under its embedded runtime (§7.2). The compiled scholar artifact and the bundled runtime are both produced by the §14.1 build pipeline; the `.mcp.json` command swap to the compiled exe and the runtime bundling decision were finalized in Session 4. | | The Cowork outputs folder isn't where the user installs from. | The build script writes a copy to both `%USERPROFILE%\Documents\Cowork\System\` and (best-effort) the user's Cowork plugin-import staging directory; surfaces a chat link. | @@ -1414,17 +1383,18 @@ Cycles are enumerated in §6 (Implementation Cycles) with per-cycle `Touches` / - Vendored pdf MCP license → **MIT** (`@modelcontextprotocol/server-pdf@1.7.2`, confirmed via `bun pm view` on 2026-05-24). License text preserved at `src/vendor/pdf-server/UPSTREAM-LICENSE`. MIT permits vendoring and redistribution under scholar's MIT license. - Query / backup / inspect surfaces → **native** (`scholar.query`, `scholar.backup`, `scholar.inspect`; cycle 6.14). sqlite3-mcp **not used** — its upstream is a Python/uv FastMCP server and is unvendorable for the scholar plugin's `bun build --compile` single-file distribution (user ruling 2026-05-24). - Tool wiring → **registry barrel + foundation-scaffolded stubs** (§7.6) so the seven plans' blast-radii stay file-disjoint. -- Annotation tombstones → **separate `annotation_tombstones` table, ISO-timestamp, no TTL in v1** (chore amend-spec-tombstone-resurrection-fix, 2026-05-25). The table is canonical for resurrection-prevention and outlives the annotations row; deletes write both `annotations.deleted_at` and a tombstone row atomically in the same `db.transaction(...)`. v1 keeps tombstones forever (no sweep, no lazy prune) — a TTL would re-introduce the resurrection bug for tombstones older than the window. Pruning is a v1.1+ admin-gated decision. See §8.2 (schema), §13 ("Tombstone-resurrection edge case", "Tombstone retention"). +- ~~Annotation tombstones → **separate `annotation_tombstones` table, ISO-timestamp, no TTL in v1** (chore amend-spec-tombstone-resurrection-fix, 2026-05-25). The table is canonical for resurrection-prevention and outlives the annotations row; deletes write both `annotations.deleted_at` and a tombstone row atomically in the same `db.transaction(...)`. v1 keeps tombstones forever (no sweep, no lazy prune) — a TTL would re-introduce the resurrection bug for tombstones older than the window.~~ **Superseded 2026-05-27 (§13 v1.1 amendment, "drop inbound reconciliation" entry below):** the resurrection scenario depends on viewer enumeration which the vendor doesn't expose, so the tombstone table has no consumer. Deletes use `annotations.deleted_at` only; the `annotation_tombstones` table is retired (§8.2 note). - First-run wizard → **server-side `elicitInput`, invoked lazily by the corpus tool**; not a standalone script. - nu transport → **MCP client CLI** (named-pipe alternative dropped). -- Annotation propagation → **scholar→viewer push + viewer→scholar reconcile-on-read**, LWW on `updated_at`; no dependency on pdf-MCP push notifications. +- ~~Annotation propagation → **scholar→viewer push + viewer→scholar reconcile-on-read**, LWW on `updated_at`; no dependency on pdf-MCP push notifications.~~ **Superseded 2026-05-27 (§13 v1.1 amendment):** push-only — see "drop inbound reconciliation" entry below. - Paper-detail PDF render → **bundled pdf.js in scholar's own iframe**; not a nested MCP App iframe. - Chart.js and pdf.js → **bundled** into the single-file UI; no runtime CDN dependency. - Cross-plan contracts (`ServerContext`, `PdfChild`, `ConfigAccessor`, `registerTools`, `runRawDdl`) → **pinned in §7.6 and frozen for v1**; no downstream plan edits `registry.ts`. - `chunk_vec` embedding width → **probed from the embed model at corpus creation**, not hard-coded; an embed-model swap requires re-creating `chunk_vec` and re-embedding. - Frozen contract widened during S1 — `PdfChild.interact` opts (additive), `isHealthy` struct (object replacing boolean), `ServerContext.log` (added `Logger` surface). Resolved 2026-05-22. -- Schema additions resolved S1+S2 — `annotations.deleted_at` (tombstones), `annotations.rect` (persisted geometry), `reconcile_state` table (per-paper bookkeeping), `paper_chunks.embedded_at` (extraction-progress sentinel), `corpora.last_opened_at` (snapshot ordering). Resolved 2026-05-22. -- Annotation reconciler algorithm — **tombstone + cursor + LWW-with-fallback-to-scholar-authoritative**; reads + viewer round-trips run *outside* the SQLite write transaction (§13). Resolved 2026-05-22 (S3). +- Schema additions resolved S1+S2 — `annotations.deleted_at` (soft-delete marker), `annotations.rect` (persisted geometry), ~~`reconcile_state` table (per-paper bookkeeping)~~ *(retired 2026-05-27 — see "drop inbound reconciliation" below)*, `paper_chunks.embedded_at` (extraction-progress sentinel), `corpora.last_opened_at` (snapshot ordering). Resolved 2026-05-22. +- ~~Annotation reconciler algorithm — **tombstone + cursor + LWW-with-fallback-to-scholar-authoritative**; reads + viewer round-trips run *outside* the SQLite write transaction (§13). Resolved 2026-05-22 (S3).~~ **Superseded 2026-05-27 (§13 v1.1 amendment):** reconciler retired; see "drop inbound reconciliation" entry below. +- **§13 reconciler — push-only (option A: drop inbound reconciliation).** Resolved 2026-05-27 after the production-readiness audit found that the v1.0 reconciler referenced `list_annotations` 6+ times despite `@modelcontextprotocol/server-pdf@1.7.2` exposing no such verb (the full `PdfCommand` union has no enumeration capability, and `get_viewer_state` returns only `selectedAnnotationIds`). Options weighed: (A) drop inbound reconciliation — chosen; (B) fork the vendor to add `list_annotations` — violates §7.2 "vendor is unmodified" invariant; (C) approximate via `get_viewer_state` — incomplete (selected-only, not full set). Personal-use v1 accepts the limitation that annotations created externally in the pdf-viewer are not synced to scholar. Knock-on effects, all resolved in this amendment: `PdfChild.interact` signature becomes `(cmd, {viewUUID, ...opts})` (single command, vendor wire envelope `{viewUUID, action, ...rest}`); `ServerContext.pdfViews` is added as a process-local `paper_id → viewUUID` map; `scholar.pdf.open(paper_id, source)` is introduced as a new MCP tool (real proxy to vendor `display_pdf`, populates the map); the three broken proxy tools (`scholar.pdf.open` in its v1.0 broken form, `scholar.pdf.search-text`, `scholar.pdf.extract-anchors`) are deleted; `annotation_tombstones` and `reconcile_state` tables are retired (§8.2 note); §16 gains a vendor-tool truth invariant row. Cycle 6.7 verification requirements rewritten — the most important new test is the S1 contract test that spawns the real vendor process and exercises one real `interact` call (catches wire-envelope mistakes that handler-level mocks hide). - PDF MCP patch-verification approach — vendor is **unmodified**, no `PATCH.md`; divergence detection is the cycle-6.2 fixture suite re-run on re-vendor (§16, §7.2). Resolved 2026-05-22 (S3). - UI bundler → **Bun's HTML bundler** (`bun build src/ui/index.html --target=browser --outfile build/ui/app.html`); `vite` and `vite-plugin-singlefile` are not in the dep set. Resolved 2026-05-22 (S4, Important #1). - Chat model default → **`qwen3:8b`** (`SCHOLAR_OLLAMA_CHAT_MODEL`). Generation chosen 2026-05-22 (S4, Important #2); user-pluggable per corpus. From 550000413b0fd87c50ad886f67fc4ab734e3de18 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 20:26:30 -0500 Subject: [PATCH 04/33] fix(pdf): rewrite interact() to vendor's {viewUUID, action} wire envelope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit S1 audit (2026-05-27, §13 v1.1): vendor @modelcontextprotocol/server-pdf@1.7.2 exposes a single `interact` tool that demands {viewUUID, action, ...rest}. v1.0 code path enqueued {type: action, ...} without viewUUID — silent miss. - PdfChild.interact now takes (cmd: PdfCommand, opts: {viewUUID, signal?, timeoutMs?}) - PdfChild.getText routes through interact({action: "get_text"}, {viewUUID}) (vendor exposes no separate get_text tool — was an invented call) - PdfChild.displayPdf added — separate vendor tool, returns viewUUID - ServerContext.pdfViews: Map, populated by scholar.pdf.open - lifecycle.test.ts FIXTURE 4 uses handle.displayPdf() (was a broken interact call masquerading as display_pdf) Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/index.ts | 7 ++++ src/server/pdf/lifecycle.test.ts | 26 ++++++------- src/server/pdf/lifecycle.ts | 63 +++++++++++++++++++++++++------- src/server/tools/registry.ts | 49 ++++++++++++++++++++++--- 4 files changed, 112 insertions(+), 33 deletions(-) diff --git a/src/server/index.ts b/src/server/index.ts index de75285..2b62887 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -135,6 +135,9 @@ export function buildServer(deps: BuildServerDeps): BuiltServer { getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, + displayPdf: async () => { + throw new Error("PDF_CHILD_UNAVAILABLE"); + }, currentRoots: () => [], setRoots: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); @@ -146,6 +149,10 @@ export function buildServer(deps: BuildServerDeps): BuiltServer { db: undefined, configDb, pdf, + // §13 v1.1: process-local paper_id → viewUUID map. Populated by + // scholar.pdf.open; consumed by annotations.{upsert,delete} and + // pdf.refresh-extraction. Never persisted (in-memory only). + pdfViews: new Map(), config: buildConfigAccessor(configDb), log: makeStdoutLogger(deps.quiet ?? false), async withCorpus(fn: (db: BunSQLiteDatabase) => Promise | T): Promise { diff --git a/src/server/pdf/lifecycle.test.ts b/src/server/pdf/lifecycle.test.ts index 7fa72be..c61f3e8 100644 --- a/src/server/pdf/lifecycle.test.ts +++ b/src/server/pdf/lifecycle.test.ts @@ -116,21 +116,17 @@ test.skipIf(!E2E)("FIXTURE 3 — list_changed round-trip: setRoots mutates witho test.skipIf(!E2E)("FIXTURE 4 — viewUUID survives across a root mutation", async () => { tmpRoot = makeTempPdfRoot(); handle = await spawnPdfChild({ initialRoots: [tmpRoot] }); - const openResp = (await handle.interact([ - { type: "display_pdf", path: join(tmpRoot, "papers", "fixture.pdf") }, - ])) as { viewUUID?: string }; - expect(typeof openResp).toBe("object"); - // Heavy assertion deferred — exact response shape depends on upstream version - // and is exercised by extraction cycle 6.5's pdf.ts tool wiring tests. - if (openResp.viewUUID) { - const secondRoot = mkdtempSync(join(tmpdir(), "scholar-pdf-root3-")); - try { - await handle.setRoots([tmpRoot, secondRoot]); - const text = await handle.getText(openResp.viewUUID); - expect(typeof text).toBe("string"); - } finally { - rmSync(secondRoot, { recursive: true, force: true }); - } + // §13 v1.1 wire envelope: display_pdf is a separate vendor tool, NOT an + // interact action. Use handle.displayPdf() — the dedicated method. + const openResp = await handle.displayPdf(join(tmpRoot, "papers", "fixture.pdf")); + expect(typeof openResp.viewUUID).toBe("string"); + const secondRoot = mkdtempSync(join(tmpdir(), "scholar-pdf-root3-")); + try { + await handle.setRoots([tmpRoot, secondRoot]); + const text = await handle.getText({ viewUUID: openResp.viewUUID }); + expect(typeof text).toBe("string"); + } finally { + rmSync(secondRoot, { recursive: true, force: true }); } }); diff --git a/src/server/pdf/lifecycle.ts b/src/server/pdf/lifecycle.ts index 7365cb2..4ce1886 100644 --- a/src/server/pdf/lifecycle.ts +++ b/src/server/pdf/lifecycle.ts @@ -21,6 +21,7 @@ import { pathToFileURL } from "node:url"; import { resolve, join, isAbsolute } from "node:path"; import pLimit from "../util/p-limit.ts"; import type { PdfChild } from "../tools/registry.ts"; +import type { PdfCommand } from "../../vendor/pdf-server/dist/src/commands.js"; export interface SpawnOpts { initialRoots: string[]; @@ -200,26 +201,42 @@ export async function spawnPdfChild(opts: SpawnOpts): Promise { } const handle: PdfChildHandle = { - async interact(commands, opts) { - const [first] = commands as Array<{ type: string; [k: string]: unknown }>; - if (!first) return null; - // The "type" key is scholar's internal envelope; the upstream child knows - // tool names directly. Strip type before forwarding. - const { type, ...rest } = first; - const r = await activeClient!.callTool({ name: type, arguments: rest }, undefined, { - timeout: opts?.timeoutMs ?? 30_000, - }); + async interact(cmd, opts) { + // Spec §13 v1.1 wire envelope: vendor exposes ONE tool named "interact" + // whose input schema is {viewUUID, action, ...sibling-fields-per-action}. + // Translate scholar's internal discriminated {type, ...rest} into the + // vendor's {viewUUID, action: type, ...rest} callTool argument shape. + // PdfCommand is the vendor's source of truth (§16 vendor-tool truth invariant). + const { type, ...rest } = cmd as PdfCommand & { [k: string]: unknown }; + const r = await activeClient!.callTool( + { + name: "interact", + arguments: { viewUUID: opts.viewUUID, action: type, ...rest }, + }, + undefined, + { + timeout: opts.timeoutMs ?? 30_000, + signal: opts.signal, + }, + ); lastOkAt = Date.now(); return r; }, - async getText(viewUUID, opts) { + async getText(opts) { + // get_text is an `action` of the vendor's `interact` tool, NOT a + // separate vendor tool. The v1.0 code at this line called + // `callTool({name: "get_text", ...})`, a tool that does not exist in + // server-pdf@1.7.2. Fixed 2026-05-27. const r = await activeClient!.callTool( - { name: "get_text", arguments: { viewUUID } }, + { + name: "interact", + arguments: { viewUUID: opts.viewUUID, action: "get_text" }, + }, undefined, - { timeout: opts?.timeoutMs ?? 120_000 }, + { timeout: opts.timeoutMs ?? 120_000 }, ); lastOkAt = Date.now(); - // The upstream `get_text` returns structured content; flatten to a string. + // The upstream get_text returns structured content; flatten to a string. if (typeof r === "string") return r; const content = (r as { content?: Array<{ type: string; text?: string }> }).content; if (Array.isArray(content)) { @@ -230,6 +247,26 @@ export async function spawnPdfChild(opts: SpawnOpts): Promise { } return JSON.stringify(r); }, + async displayPdf(source, opts) { + // Vendor `display_pdf` is a separate vendor tool (NOT an interact action). + // Accepts {source: string}; returns {content, structuredContent: {viewUUID, ...}}. + // viewUUID is the canonical handle for subsequent interact() calls — see + // spec §13 "viewUUID propagation." + const r = await activeClient!.callTool( + { name: "display_pdf", arguments: { source } }, + undefined, + { timeout: opts?.timeoutMs ?? 30_000 }, + ); + lastOkAt = Date.now(); + const structured = (r as { structuredContent?: { viewUUID?: unknown } }).structuredContent; + const viewUUID = structured?.viewUUID; + if (typeof viewUUID !== "string" || viewUUID.length === 0) { + throw new Error( + `PDF_DISPLAY_NO_VIEWUUID: vendor display_pdf returned no viewUUID for source=${source}`, + ); + } + return { viewUUID }; + }, currentRoots: () => [...currentRoots], isHealthy: () => ({ alive: !!activeClient && !terminalCrashLoop, diff --git a/src/server/tools/registry.ts b/src/server/tools/registry.ts index 5eca55e..6e7ba5e 100644 --- a/src/server/tools/registry.ts +++ b/src/server/tools/registry.ts @@ -5,6 +5,7 @@ // writer of this file. Schema/signature changes are foundation-only edits. import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { PdfCommand } from "../../vendor/pdf-server/dist/src/commands.js"; // ========================================================================= // FROZEN CROSS-PLAN CONTRACTS (spec §7.6) @@ -15,15 +16,42 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; /** * pdf child-process handle. Produced by src/server/pdf/lifecycle.ts (foundation, * cycle 6.2); consumed by pdf.ts (extraction) and annotations.ts (annotations). + * + * Wire-envelope contract (spec §13 v1.1, 2026-05-27 amendment): + * - Vendor exposes ONE tool named "interact" with input shape + * {viewUUID, action, ...sibling-fields-per-action}. + * - PdfCommand is the vendor's source of truth at + * src/vendor/pdf-server/dist/src/commands.d.ts. The spec MAY NOT invent + * vendor capabilities (§16 vendor-tool truth invariant). + * - lifecycle.ts's interact() translates the discriminated {type, ...rest} + * command shape into the vendor's {viewUUID, action: type, ...rest} + * callTool argument shape. */ export interface PdfChild { - /** Drives add/update/remove_annotations, get_text, .... Default timeoutMs = 30_000. */ + /** + * Single-command interact. The viewUUID identifies which open viewer the + * call targets (vendor requires it as a sibling of `action`). Default + * timeoutMs = 30_000. AbortSignal and timeoutMs both honoured. + */ interact( - commands: unknown[], - opts?: { signal?: AbortSignal; timeoutMs?: number }, + cmd: PdfCommand, + opts: { viewUUID: string; signal?: AbortSignal; timeoutMs?: number }, ): Promise; - /** Default timeoutMs = 120_000 (text extraction can be slow on large papers). */ - getText(viewUUID: string, opts?: { timeoutMs?: number }): Promise; + /** + * Calls the vendor's `get_text` action via the `interact` tool under the + * hood. Default timeoutMs = 120_000 (text extraction can be slow on large + * papers). + */ + getText(opts: { viewUUID: string; timeoutMs?: number }): Promise; + /** + * Opens a PDF in the vendor's interactive viewer by calling the vendor's + * `display_pdf` tool (which is a separate vendor tool, NOT an `interact` + * action). Returns the viewUUID that subsequent `interact` calls must + * carry. `source` is either an absolute local path, a file:// URL, or an + * HTTPS URL. Consumed by `scholar.pdf.open` to populate + * `ServerContext.pdfViews`. Default timeoutMs = 30_000. + */ + displayPdf(source: string, opts?: { timeoutMs?: number }): Promise<{ viewUUID: string }>; currentRoots(): string[]; /** * Update the set of file:// roots scholar advertises to the pdf child via @@ -103,6 +131,17 @@ export interface ServerContext { db: BunSQLiteDatabase | undefined; configDb: BunSQLiteDatabase; pdf: PdfChild; + /** + * Process-local paper_id → viewUUID map (spec §7.6 + §13 v1.1, 2026-05-27). + * Populated by `scholar.pdf.open(paper_id, source)` after the vendor's + * `display_pdf` returns a viewUUID; consumed by `scholar.annotations.{upsert,delete}` + * and `scholar.pdf.refresh-extraction` to resolve viewUUID for outbound + * `interact` calls. Not persisted across scholar restart. A pdf-child crash + + * supervisor respawn (§5.19) renders cached entries stale; v1 surfaces the + * resulting vendor error on the next interact call (the user re-opens to + * refresh the entry). + */ + pdfViews: Map; // sqlite3 field — REMOVED 2026-05-24 (foundation-007, user posture B). The §10 // surface is reimplemented inline via bun:sqlite by extraction cycle 6.14. config: ConfigAccessor; From d97f3cf54dbf92801b22bfee55c05ac089c54a14 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 20:26:43 -0500 Subject: [PATCH 05/33] fix(annotations,pdf): push-only propagation + scholar.pdf.open registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit §13 v1.1 amendment (S1 audit, 2026-05-27): - annotations.ts: drop reconcile() (depended on list_annotations — a vendor tool that does not exist). list = pure DB read. upsert/delete throw NO_OPEN_VIEWER if ctx.pdfViews has no entry for paper_id. serializeForViewer maps scholar rows → vendor's NoteAnnotation shape ({id, type: "note", page, x, y, content}); the v1.0 ad-hoc rect-bearing shape was being silently rejected by the vendor's PdfAnnotationDef union. - annotations.test.ts: 22 tests covering NO_ACTIVE_CORPUS, NO_OPEN_VIEWER, write-then-push, idempotency, §12.0 sanitization, rect validation, paper-level note vendor shape, scholar.pdf.open ctx.pdfViews registration, and the posture-B (no sqlite3-mcp) guard. v1.0 reconciler tests (Red-4/5/7b/7c/8b/9) retired with the reconciler. - pdf.ts: refreshExtraction resolves viewUUID via ctx.pdfViews (was using paper_id as viewUUID — third broken assumption the audit surfaced). New scholar.pdf.open(paper_id, source) proxies vendor display_pdf and populates ctx.pdfViews. v1.0 proxy stubs (open/search-text/extract-anchors) dropped — they never mapped to real vendor tools. - Test fixtures (6 files): added displayPdf stub to mockPdf objects so the new PdfChild interface satisfies strict TS. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/index.test.ts | 1 + src/server/tools/annotations.test.ts | 508 ++++++++++----------------- src/server/tools/annotations.ts | 442 ++++++----------------- src/server/tools/corpus.test.ts | 1 + src/server/tools/ingest.test.ts | 1 + src/server/tools/pdf.ts | 80 +++-- src/server/tools/roots.test.ts | 1 + src/server/tools/snapshot.test.ts | 1 + tests/first-run.test.ts | 1 + 9 files changed, 355 insertions(+), 681 deletions(-) diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 11b1414..f4f3811 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -16,6 +16,7 @@ function makeDeps(overrides: Partial = {}): BuildServerDeps { getText: async () => "", currentRoots: () => [], setRoots: async () => {}, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), }), ...overrides, diff --git a/src/server/tools/annotations.test.ts b/src/server/tools/annotations.test.ts index b708d72..11219fa 100644 --- a/src/server/tools/annotations.test.ts +++ b/src/server/tools/annotations.test.ts @@ -1,16 +1,15 @@ -// src/server/tools/annotations.test.ts — annotations plan cycle 6.7 (Red) +// src/server/tools/annotations.test.ts — §13 v1.1 push-only handler tests // -// Tests for scholar.annotations.{list, upsert, delete} and the §13 reconciler. +// Tests for scholar.annotations.{list, upsert, delete} under the 2026-05-27 +// §13 amendment (push-only propagation). The v1.0 reconcile-on-list tests +// (Red-4 / Red-5 / Red-7b / Red-7c / Red-8b / Red-9) were retired with the +// reconciler. The vendor wire envelope is covered by the S1 contract test +// against the real vendor process (see lifecycle.contract.test.ts). // // Test harness: buildServer + applyMigrations + a configurable mock PdfChild -// whose `interact` records every call and (optionally) returns viewer rows -// for a `list_annotations` request. Each test mutates `interactImpl` and -// `interactCalls` between dispatches — the PdfChild instance reference is -// stable so the handler's `ctx.pdf` snapshot picks up the configured impl. -// -// SDK v1.29.0: InMemoryTransport export path (per plan-md F11 round-2 note) -// is not needed here — dispatch() bypasses the transport and routes directly -// through the foundation-009 ToolRegistry per src/server/index.ts. +// whose `interact` records every call (cmd + viewUUID). beforeEach seeds +// ctx.pdfViews so most tests don't need to call scholar.pdf.open first; +// the NO_OPEN_VIEWER cases delete the entry per-test. import { test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -18,15 +17,20 @@ import { join } from "node:path"; import { buildServer, type BuiltServer } from "../index.ts"; import { openWithPragmas, applyMigrations } from "../db/migrations.ts"; import { rawClient } from "../db/raw-client.ts"; -import { ulid, nowIso } from "../db/nowIso.ts"; +import { nowIso } from "../db/nowIso.ts"; import type { PdfChild } from "./registry.ts"; +import type { PdfCommand } from "../../vendor/pdf-server/dist/src/commands.js"; // ─── harness ────────────────────────────────────────────────────────────────── +const TEST_PAPER = "p1"; +const TEST_VIEW_UUID = "test-view-uuid-p1"; + let dir: string; let built: BuiltServer; -let interactCalls: Array<{ commands: unknown[]; dbHasRowAtFirstCall?: boolean }>; -let interactImpl: (commands: unknown[]) => Promise; +type InteractCall = { cmd: PdfCommand & Record; viewUUID: string }; +let interactCalls: InteractCall[]; +let interactImpl: (cmd: PdfCommand, viewUUID: string) => Promise; const origRuntimeRoot = process.env.SCHOLAR_RUNTIME_ROOT; beforeEach(async () => { @@ -38,19 +42,20 @@ beforeEach(async () => { applyMigrations(configDb); interactCalls = []; - // Default impl: list_annotations → []; other ops → null. - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") return []; - return null; - }; + // Default impl: every push returns null (vendor returns no-data on + // add/update/remove acknowledgements). + interactImpl = async () => null; const mockPdf: PdfChild = { - interact: async (commands: unknown[]) => { - interactCalls.push({ commands }); - return await interactImpl(commands); + interact: async (cmd, opts) => { + interactCalls.push({ + cmd: cmd as PdfCommand & Record, + viewUUID: opts.viewUUID, + }); + return await interactImpl(cmd, opts.viewUUID); }, getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, + displayPdf: async () => ({ viewUUID: TEST_VIEW_UUID }), currentRoots: () => [], setRoots: async () => {}, isHealthy: () => ({ alive: true, lastOkAt: Date.now(), stdioOpen: true }), @@ -71,7 +76,10 @@ beforeEach(async () => { // Seed a paper row so the FK references resolve. rawClient(built.ctx.db!) .query("INSERT INTO papers (id, key, title, imported_at) VALUES (?, ?, ?, ?)") - .run("p1", "smith2024", "Test paper", nowIso()); + .run(TEST_PAPER, "smith2024", "Test paper", nowIso()); + // §13 v1.1: pre-populate the viewUUID map so most tests don't need to call + // scholar.pdf.open first. NO_OPEN_VIEWER tests clear/skip this entry. + built.ctx.pdfViews.set(TEST_PAPER, TEST_VIEW_UUID); }); afterEach(() => { @@ -84,22 +92,19 @@ afterEach(() => { const dispatch = (tool: string, args: unknown) => built.dispatch(tool, args); -function findInteract(type: string): unknown[] { - return interactCalls.filter((c) => { - const cmd0 = (c.commands as Array<{ type: string }>)[0]; - return cmd0?.type === type; - }).map((c) => c.commands); +function findInteract(type: string): InteractCall[] { + return interactCalls.filter((c) => c.cmd.type === type); } // ============================================================================= -// Red-13 — NO_ACTIVE_CORPUS guards +// NO_ACTIVE_CORPUS guards (§13 invariant 4) // ============================================================================= test("scholar.annotations.list NO_ACTIVE_CORPUS guard fires when ctx.db is undefined", async () => { const saved = built.ctx.db; built.ctx.db = undefined; try { - await expect(dispatch("scholar.annotations.list", { paper_id: "p1" })) + await expect(dispatch("scholar.annotations.list", { paper_id: TEST_PAPER })) .rejects.toMatchObject({ code: "NO_ACTIVE_CORPUS" }); expect(interactCalls).toHaveLength(0); } finally { @@ -111,7 +116,7 @@ test("scholar.annotations.upsert NO_ACTIVE_CORPUS guard fires when ctx.db is und const saved = built.ctx.db; built.ctx.db = undefined; try { - await expect(dispatch("scholar.annotations.upsert", { paper_id: "p1", body: "x" })) + await expect(dispatch("scholar.annotations.upsert", { paper_id: TEST_PAPER, body: "x" })) .rejects.toMatchObject({ code: "NO_ACTIVE_CORPUS" }); expect(interactCalls).toHaveLength(0); } finally { @@ -132,27 +137,98 @@ test("scholar.annotations.delete NO_ACTIVE_CORPUS guard fires when ctx.db is und }); // ============================================================================= -// Red-1 — upsert insert path + write-then-push ordering +// NO_OPEN_VIEWER guards (§13 v1.1 invariant 5 — new) +// ============================================================================= + +test("upsert throws NO_OPEN_VIEWER when ctx.pdfViews has no entry for paper_id", async () => { + built.ctx.pdfViews.delete(TEST_PAPER); + await expect(dispatch("scholar.annotations.upsert", { paper_id: TEST_PAPER, body: "x" })) + .rejects.toMatchObject({ code: "NO_OPEN_VIEWER" }); + expect(interactCalls).toHaveLength(0); + const rows = rawClient(built.ctx.db!).query("SELECT id FROM annotations").all() as unknown[]; + expect(rows).toHaveLength(0); +}); + +test("delete on live row throws NO_OPEN_VIEWER when no viewer is open; no push, no deleted_at write", async () => { + // Insert a live row first (viewUUID present). + const r = await dispatch("scholar.annotations.upsert", { + paper_id: TEST_PAPER, + body: "x", + }) as { id: string }; + interactCalls = []; + built.ctx.pdfViews.delete(TEST_PAPER); + await expect(dispatch("scholar.annotations.delete", { id: r.id })) + .rejects.toMatchObject({ code: "NO_OPEN_VIEWER" }); + expect(interactCalls).toHaveLength(0); + const row = rawClient(built.ctx.db!) + .query("SELECT deleted_at FROM annotations WHERE id = ?") + .get(r.id) as { deleted_at: string | null }; + expect(row.deleted_at).toBeNull(); +}); + +test("delete on missing id is a clean no-op even when no viewer is open", async () => { + built.ctx.pdfViews.delete(TEST_PAPER); + const result = await dispatch("scholar.annotations.delete", { id: "nonexistent-ulid" }) as { + deleted: boolean; + reason: string; + }; + expect(result.deleted).toBe(false); + expect(result.reason).toBe("not_found"); + expect(interactCalls).toHaveLength(0); +}); + +test("delete on already-tombstoned id is a clean no-op even when no viewer is open", async () => { + const r = await dispatch("scholar.annotations.upsert", { + paper_id: TEST_PAPER, + body: "x", + }) as { id: string }; + await dispatch("scholar.annotations.delete", { id: r.id }); + interactCalls = []; + built.ctx.pdfViews.delete(TEST_PAPER); + const result = await dispatch("scholar.annotations.delete", { id: r.id }) as { + deleted: boolean; + reason: string; + }; + expect(result.deleted).toBe(false); + expect(result.reason).toBe("already_tombstoned"); + expect(interactCalls).toHaveLength(0); +}); + +test("list does NOT require an open viewer (pure DB read)", async () => { + await dispatch("scholar.annotations.upsert", { + paper_id: TEST_PAPER, + body: "rendered without viewer", + }); + interactCalls = []; + built.ctx.pdfViews.delete(TEST_PAPER); + const result = await dispatch("scholar.annotations.list", { paper_id: TEST_PAPER }) as { + rows: Array<{ body: string }>; + }; + expect(result.rows).toHaveLength(1); + expect(result.rows[0]!.body).toBe("rendered without viewer"); + expect(interactCalls).toHaveLength(0); +}); + +// ============================================================================= +// upsert insert path + write-then-push ordering + wire envelope (§13 invariant 1) // ============================================================================= -test("upsert insert: writes annotation with source='scholar', then pushes add_annotations", async () => { - // Capture DB state at the moment of the first interact call to prove - // the synchronous write commits BEFORE the await for pdf.interact resolves. +test("upsert insert: writes annotation with source='scholar', then pushes add_annotations carrying viewUUID", async () => { + // Capture DB state at the moment of the first interact call to prove the + // synchronous write commits BEFORE the await for pdf.interact resolves. let dbRowAtFirstInteract: { id: string } | null = null; - interactImpl = async (commands: unknown[]) => { + interactImpl = async () => { if (dbRowAtFirstInteract === null) { dbRowAtFirstInteract = (rawClient(built.ctx.db!).query("SELECT id FROM annotations LIMIT 1").get() as | { id: string } | null); } - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") return []; return null; }; const result = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "hello", anchor: "§2.1", }) as { id: string; source: string; created_at: string; updated_at: string }; @@ -165,9 +241,10 @@ test("upsert insert: writes annotation with source='scholar', then pushes add_an expect(dbRowAtFirstInteract).not.toBeNull(); expect(dbRowAtFirstInteract!.id).toBe(result.id); - // Exactly one interact call: add_annotations. + // Exactly one interact call: add_annotations, carrying our viewUUID. const addCalls = findInteract("add_annotations"); expect(addCalls).toHaveLength(1); + expect(addCalls[0]!.viewUUID).toBe(TEST_VIEW_UUID); // DB row shape. const row = rawClient(built.ctx.db!) @@ -179,22 +256,19 @@ test("upsert insert: writes annotation with source='scholar', then pushes add_an }); // ============================================================================= -// Red-2 — upsert update path +// upsert update path // ============================================================================= test("upsert update: same id, different body → updates row + pushes update_annotations", async () => { const r1 = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "first", }) as { id: string; created_at: string }; - // First interact was add_annotations. expect(findInteract("add_annotations")).toHaveLength(1); - // Need the viewer to report the existing id so step-2 picks update_annotations. - // We use the upsert directly (not via reconcile) — upsert decides on its own - // by checking if the row exists in the DB pre-write. + const r2 = await dispatch("scholar.annotations.upsert", { id: r1.id, - paper_id: "p1", + paper_id: TEST_PAPER, body: "second", }) as { id: string; body: string; created_at: string; updated_at: string }; @@ -209,64 +283,51 @@ test("upsert update: same id, different body → updates row + pushes update_ann }); // ============================================================================= -// Red-3 — delete soft-delete + tombstone atomicity + remove_annotations push +// delete: soft-delete + remove_annotations push (no tombstone-table writes under v1.1) // ============================================================================= -test("delete: soft-deletes annotation AND inserts annotation_tombstones atomically", async () => { +test("delete: soft-deletes annotation (deleted_at set) and pushes remove_annotations carrying viewUUID", async () => { const r1 = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "to delete", }) as { id: string }; // Verify DB state at the moment of the first interact after delete. - let stateAtRemove: { deleted_at: string | null; tombstone_id: string | undefined } | null = null; - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "remove_annotations" && stateAtRemove === null) { + let deletedAtAtPush: string | null = null; + interactImpl = async (cmd) => { + if (cmd.type === "remove_annotations" && deletedAtAtPush === null) { const row = rawClient(built.ctx.db!) .query("SELECT deleted_at FROM annotations WHERE id = ?") .get(r1.id) as { deleted_at: string | null }; - const ts = rawClient(built.ctx.db!) - .query("SELECT annotation_id FROM annotation_tombstones WHERE annotation_id = ?") - .get(r1.id) as { annotation_id: string } | null; - stateAtRemove = { deleted_at: row.deleted_at, tombstone_id: ts?.annotation_id }; + deletedAtAtPush = row.deleted_at; } - if (cmd0?.type === "list_annotations") return []; return null; }; await dispatch("scholar.annotations.delete", { id: r1.id }); - // Annotation row: deleted_at set. const row = rawClient(built.ctx.db!) .query("SELECT deleted_at FROM annotations WHERE id = ?") .get(r1.id) as { deleted_at: string | null }; expect(row.deleted_at).not.toBeNull(); - // Tombstone row: inserted with matching id. - const tomb = rawClient(built.ctx.db!) - .query("SELECT annotation_id, paper_id, deleted_at FROM annotation_tombstones WHERE annotation_id = ?") - .get(r1.id) as { annotation_id: string; paper_id: string; deleted_at: string }; - expect(tomb.annotation_id).toBe(r1.id); - expect(tomb.paper_id).toBe("p1"); - expect(tomb.deleted_at).toBe(row.deleted_at!); - - // Write-then-push: at the moment remove_annotations fired, both writes were committed. - expect(stateAtRemove).not.toBeNull(); - expect(stateAtRemove!.deleted_at).not.toBeNull(); - expect(stateAtRemove!.tombstone_id).toBe(r1.id); - - // remove_annotations pushed. - expect(findInteract("remove_annotations")).toHaveLength(1); + // Write-then-push: at the moment remove_annotations fired, deleted_at was set. + expect(deletedAtAtPush).not.toBeNull(); + + // remove_annotations pushed with the right viewUUID + ids payload. + const removes = findInteract("remove_annotations"); + expect(removes).toHaveLength(1); + expect(removes[0]!.viewUUID).toBe(TEST_VIEW_UUID); + expect((removes[0]!.cmd as { ids: string[] }).ids).toEqual([r1.id]); }); // ============================================================================= -// Red-3b — delete idempotency +// delete idempotency (unchanged under v1.1) // ============================================================================= test("delete on already-tombstoned annotation is no-op: no second pdf.interact, deleted_at unchanged", async () => { const r1 = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "x", }) as { id: string }; await dispatch("scholar.annotations.delete", { id: r1.id }); @@ -275,7 +336,6 @@ test("delete on already-tombstoned annotation is no-op: no second pdf.interact, .get(r1.id) as { deleted_at: string }).deleted_at; const removesBefore = findInteract("remove_annotations").length; - // Second delete on the same id. await dispatch("scholar.annotations.delete", { id: r1.id }); const removesAfter = findInteract("remove_annotations").length; expect(removesAfter).toBe(removesBefore); // no new push @@ -287,23 +347,23 @@ test("delete on already-tombstoned annotation is no-op: no second pdf.interact, }); // ============================================================================= -// Red-10 — list returns live rows (deleted_at IS NULL), Daisy-compatible shape +// list returns live rows // ============================================================================= test("list returns rows with deleted_at IS NULL only; shape includes id/page/anchor/body/source/created_at/updated_at", async () => { const r1 = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "live note", anchor: "§3.2 — key finding paragraph", page: 5, }) as { id: string }; const r2 = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "to be deleted", }) as { id: string }; await dispatch("scholar.annotations.delete", { id: r2.id }); - const result = await dispatch("scholar.annotations.list", { paper_id: "p1" }) as { + const result = await dispatch("scholar.annotations.list", { paper_id: TEST_PAPER }) as { rows: Array<{ id: string; body: string; anchor: string | null; page: number | null; source: string }>; }; expect(result.rows.length).toBe(1); @@ -316,123 +376,18 @@ test("list returns rows with deleted_at IS NULL only; shape includes id/page/anc }); // ============================================================================= -// Red-9 — Tombstone resurrection prevention (the core §13 amendment) -// ============================================================================= - -test("reconcile: viewer re-emits tombstoned id → phase-3 INSERT skipped; phase-2 cure issues remove_annotations", async () => { - const r1 = await dispatch("scholar.annotations.upsert", { paper_id: "p1", body: "doomed" }) as { id: string }; - await dispatch("scholar.annotations.delete", { id: r1.id }); - - // Clear the call log to focus on the next reconcile. - interactCalls = []; - // Viewer is "stuck" — still reports the deleted annotation. - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") { - return [{ - id: r1.id, - page: null, - anchor: null, - rect: null, - body: "doomed", - created_at: nowIso(), - updated_at: nowIso(), - }]; - } - return null; - }; - - const result = await dispatch("scholar.annotations.list", { paper_id: "p1" }) as { rows: unknown[] }; - - // Phase-3 INSERT short-circuit fired: the deleted row was NOT re-inserted. - expect(result.rows).toHaveLength(0); - // Annotation in DB is still deleted_at IS NOT NULL. - const row = rawClient(built.ctx.db!) - .query("SELECT deleted_at FROM annotations WHERE id = ?") - .get(r1.id) as { deleted_at: string | null }; - expect(row.deleted_at).not.toBeNull(); - // Phase-2 resurrection cure: a remove_annotations call was issued. - const removes = findInteract("remove_annotations") as Array>; - expect(removes.length).toBeGreaterThanOrEqual(1); - // At least one of the removes contains r1.id. - const containsR1 = removes.some((cmds) => cmds[0]!.ids.includes(r1.id)); - expect(containsR1).toBe(true); - // annotation_tombstones row still exists (durable; no implicit prune). - const tomb = rawClient(built.ctx.db!) - .query("SELECT annotation_id FROM annotation_tombstones WHERE annotation_id = ?") - .get(r1.id) as { annotation_id: string } | null; - expect(tomb?.annotation_id).toBe(r1.id); -}); - -// ============================================================================= -// Red-7c — Post-tx delete-recovery for perpetual viewer-side staleness -// ============================================================================= - -test("reconcile post-tx: when cursor has advanced past deleted_at and viewer still has row, post-tx re-issues remove_annotations", async () => { - const r1 = await dispatch("scholar.annotations.upsert", { paper_id: "p1", body: "ghost-prone" }) as { id: string }; - await dispatch("scholar.annotations.delete", { id: r1.id }); - - // Manually advance the cursor past the deleted_at timestamp by writing - // an effectively-future last_reconciled_at. This forces scholar_dirty - // to be empty for r1 on the next reconcile, so the post-tx phase is - // the only path that re-asserts the remove. - rawClient(built.ctx.db!) - .query("INSERT OR REPLACE INTO reconcile_state (corpus_id, paper_id, last_reconciled_at) VALUES (?, ?, ?)") - .run("annot-corp", "p1", "9999-12-31T23:59:59.999Z"); - - interactCalls = []; - // Viewer still has the (tombstoned) row. - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") { - return [{ - id: r1.id, - page: null, - anchor: null, - rect: null, - body: "ghost-prone", - created_at: nowIso(), - updated_at: nowIso(), - }]; - } - return null; - }; - - await dispatch("scholar.annotations.list", { paper_id: "p1" }); - const removesFirst = findInteract("remove_annotations").length; - expect(removesFirst).toBeGreaterThanOrEqual(1); - - // Second list with viewer still mocked — post-tx re-asserts again. - await dispatch("scholar.annotations.list", { paper_id: "p1" }); - const removesSecond = findInteract("remove_annotations").length; - expect(removesSecond).toBeGreaterThan(removesFirst); - - // Once viewer drops the row, post-tx does NOT fire. - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") return []; - return null; - }; - await dispatch("scholar.annotations.list", { paper_id: "p1" }); - const removesThird = findInteract("remove_annotations").length; - expect(removesThird).toBe(removesSecond); // no new remove -}); - -// ============================================================================= -// Red-8 — sanitizeText on user-supplied body and anchor (§12.0) +// sanitization (§12.0) on user-supplied body and anchor // ============================================================================= test("upsert rejects body containing bidi-override U+202E before DB write or pdf.interact", async () => { const evil = "hello‮world"; const callsBefore = interactCalls.length; await expect(dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: evil, })).rejects.toThrow(/bidi/i); - // No add_annotations was pushed. expect(findInteract("add_annotations")).toHaveLength(0); expect(interactCalls.length).toBe(callsBefore); - // No row was inserted. const rows = rawClient(built.ctx.db!) .query("SELECT id FROM annotations") .all() as unknown[]; @@ -441,7 +396,7 @@ test("upsert rejects body containing bidi-override U+202E before DB write or pdf test("upsert rejects anchor containing bidi-override U+202E", async () => { await expect(dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "ok", anchor: "§2.1‮evil", })).rejects.toThrow(/bidi/i); @@ -449,43 +404,12 @@ test("upsert rejects anchor containing bidi-override U+202E", async () => { }); // ============================================================================= -// Red-8b — sanitizeText on viewer-originated vrow.body (§12.0 inbound) -// ============================================================================= - -test("reconcile: viewer-originated row with bidi-override body throws before INSERT (phase-3)", async () => { - // Viewer returns a row with bidi-override embedded. - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") { - return [{ - id: ulid(), - page: null, - anchor: null, - rect: null, - body: "approve invoice‮", - created_at: nowIso(), - updated_at: nowIso(), - }]; - } - return null; - }; - - await expect(dispatch("scholar.annotations.list", { paper_id: "p1" })) - .rejects.toThrow(/bidi/i); - // No annotation was inserted. - const rows = rawClient(built.ctx.db!) - .query("SELECT id FROM annotations") - .all() as unknown[]; - expect(rows).toHaveLength(0); -}); - -// ============================================================================= -// Red-11 — rect JSON validation +// rect JSON validation // ============================================================================= test("upsert accepts valid 4-element finite rect JSON", async () => { const r = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "x", rect: "[10, 20, 200, 300]", }) as { id: string }; @@ -497,29 +421,29 @@ test("upsert accepts valid 4-element finite rect JSON", async () => { test("upsert rejects rect with 3 elements", async () => { await expect(dispatch("scholar.annotations.upsert", { - paper_id: "p1", body: "x", rect: "[10, 20, 200]", + paper_id: TEST_PAPER, body: "x", rect: "[10, 20, 200]", })).rejects.toMatchObject({ code: "INVALID_RECT" }); }); test("upsert rejects rect with non-finite numbers", async () => { await expect(dispatch("scholar.annotations.upsert", { - paper_id: "p1", body: "x", rect: "[10, 20, 200, 1e9999]", + paper_id: TEST_PAPER, body: "x", rect: "[10, 20, 200, 1e9999]", })).rejects.toMatchObject({ code: "INVALID_RECT" }); }); test("upsert rejects rect with wrong shape (object)", async () => { await expect(dispatch("scholar.annotations.upsert", { - paper_id: "p1", body: "x", rect: '{"x":10}', + paper_id: TEST_PAPER, body: "x", rect: '{"x":10}', })).rejects.toMatchObject({ code: "INVALID_RECT" }); }); // ============================================================================= -// Red-12 — Both-null rect + anchor accepted as paper-level note +// Paper-level note + serializeForViewer fallback rect // ============================================================================= -test("upsert accepts paper-level note (no rect, no anchor); serializeForViewer falls back to fixed margin sticky", async () => { +test("upsert accepts paper-level note (no rect, no anchor); push uses vendor note shape with default origin (20,20) and page 1", async () => { const r = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", + paper_id: TEST_PAPER, body: "paper-level note", }) as { id: string }; @@ -530,112 +454,44 @@ test("upsert accepts paper-level note (no rect, no anchor); serializeForViewer f expect(row.anchor).toBeNull(); expect(row.source).toBe("scholar"); - // serializeForViewer (called during push) inserts the fixed sticky rect [20,20,120,60]. - const adds = findInteract("add_annotations") as Array }>>; + // serializeForViewer maps scholar → vendor's `note` annotation shape: + // {id, type: "note", page, x, y, content}. With no rect/anchor, x=20, y=20, + // page=1, content=body verbatim. + const adds = findInteract("add_annotations"); expect(adds).toHaveLength(1); - expect(adds[0]![0]!.annotations[0]!.rect).toEqual([20, 20, 120, 60]); + const annotationsPayload = (adds[0]!.cmd as unknown as { + annotations: Array<{ id: string; type: string; page: number; x: number; y: number; content: string }>; + }).annotations; + expect(annotationsPayload).toHaveLength(1); + const note = annotationsPayload[0]!; + expect(note.type).toBe("note"); + expect(note.page).toBe(1); + expect(note.x).toBe(20); + expect(note.y).toBe(20); + expect(note.content).toBe("paper-level note"); // list includes the row. - const result = await dispatch("scholar.annotations.list", { paper_id: "p1" }) as { rows: unknown[] }; + const result = await dispatch("scholar.annotations.list", { paper_id: TEST_PAPER }) as { rows: unknown[] }; expect(result.rows.length).toBeGreaterThan(0); }); // ============================================================================= -// Red-4 / happy reconcile — viewer-only row is pulled into scholar -// ============================================================================= - -test("reconcile pulls viewer-only rows into annotations (scholar_by_id miss → INSERT pdf-viewer source)", async () => { - const viewerId = ulid(); - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") { - return [{ - id: viewerId, - page: 3, - anchor: "viewer-anchor", - rect: [1, 2, 3, 4], - body: "viewer-side note", - created_at: nowIso(), - updated_at: nowIso(), - }]; - } - return null; - }; - - const result = await dispatch("scholar.annotations.list", { paper_id: "p1" }) as { - rows: Array<{ id: string; body: string; source: string; page: number | null }>; - }; - expect(result.rows).toHaveLength(1); - expect(result.rows[0]!.id).toBe(viewerId); - expect(result.rows[0]!.source).toBe("pdf-viewer"); - expect(result.rows[0]!.body).toBe("viewer-side note"); - expect(result.rows[0]!.page).toBe(3); -}); - -// ============================================================================= -// Red-7b — onConflictDoNothing on same-paper concurrent reconciles +// scholar.pdf.open populates ctx.pdfViews (§13 v1.1 invariant — new) // ============================================================================= -test("two concurrent annotations.list on the same paper with viewer-only row: exactly one annotations row inserted; no PK constraint thrown", async () => { - const viewerId = ulid(); - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") { - // Synthetic delay so both calls complete phase 1+2 before either runs phase 3. - await new Promise((r) => setTimeout(r, 5)); - return [{ - id: viewerId, - page: null, - anchor: null, - rect: null, - body: "viewer note", - created_at: nowIso(), - updated_at: nowIso(), - }]; - } - return null; - }; +test("scholar.pdf.open registers viewUUID under paper_id in ctx.pdfViews", async () => { + // Drop the seeded entry to prove .open populates it. + built.ctx.pdfViews.delete(TEST_PAPER); + expect(built.ctx.pdfViews.get(TEST_PAPER)).toBeUndefined(); - const [a, b] = await Promise.all([ - dispatch("scholar.annotations.list", { paper_id: "p1" }) as Promise<{ rows: unknown[] }>, - dispatch("scholar.annotations.list", { paper_id: "p1" }) as Promise<{ rows: unknown[] }>, - ]); - expect(a.rows.length).toBe(1); - expect(b.rows.length).toBe(1); - - const rowCount = (rawClient(built.ctx.db!) - .query("SELECT COUNT(*) AS c FROM annotations WHERE id = ?") - .get(viewerId) as { c: number }).c; - expect(rowCount).toBe(1); -}); + const result = await dispatch("scholar.pdf.open", { + paper_id: TEST_PAPER, + source: "/tmp/fixture.pdf", + }) as { paper_id: string; viewUUID: string }; -// ============================================================================= -// Red-5 — viewer rows without updated_at degrade to scholar-authoritative -// ============================================================================= - -test("reconcile: viewer rows missing updated_at still trigger viewer-only-INSERT but no LWW overwrite", async () => { - const viewerId = ulid(); - interactImpl = async (commands: unknown[]) => { - const cmd0 = (commands as Array<{ type: string }>)[0]; - if (cmd0?.type === "list_annotations") { - return [{ - id: viewerId, - page: null, - anchor: null, - rect: null, - body: "no-updated_at", - created_at: null, - updated_at: null, - }]; - } - return null; - }; - const r = await dispatch("scholar.annotations.list", { paper_id: "p1" }) as { - rows: Array<{ id: string; body: string }>; - }; - expect(r.rows).toHaveLength(1); - expect(r.rows[0]!.id).toBe(viewerId); - expect(r.rows[0]!.body).toBe("no-updated_at"); + expect(result.paper_id).toBe(TEST_PAPER); + expect(result.viewUUID).toBe(TEST_VIEW_UUID); + expect(built.ctx.pdfViews.get(TEST_PAPER)).toBe(TEST_VIEW_UUID); }); // ============================================================================= @@ -655,9 +511,9 @@ test("annotations handlers make no sqlite3-mcp calls (posture-B guard)", async ( (built.ctx as unknown as { pdf: typeof strictPdf }).pdf = strictPdf; try { const r = await dispatch("scholar.annotations.upsert", { - paper_id: "p1", body: "guard-test", + paper_id: TEST_PAPER, body: "guard-test", }) as { id: string }; - await dispatch("scholar.annotations.list", { paper_id: "p1" }); + await dispatch("scholar.annotations.list", { paper_id: TEST_PAPER }); await dispatch("scholar.annotations.delete", { id: r.id }); } finally { (built.ctx as unknown as { pdf: typeof origPdf }).pdf = origPdf; diff --git a/src/server/tools/annotations.ts b/src/server/tools/annotations.ts index b7bab2b..6afad84 100644 --- a/src/server/tools/annotations.ts +++ b/src/server/tools/annotations.ts @@ -1,49 +1,41 @@ -// src/server/tools/annotations.ts — annotations plan cycle 6.7 (Green) +// src/server/tools/annotations.ts — annotations plan cycle 6.7 (§13 v1.1) // // Three MCP tools: scholar.annotations.{list, upsert, delete}. -// Implements §13's bidirectional reconciliation against the vendored pdf MCP -// child, plus the spec-amendment-34871f2 tombstone-resurrection fix. +// Implements the push-only annotation contract per spec §13 v1.1 (2026-05-27 +// amendment). The bidirectional reconciler from v1.0 was retired when the +// production-readiness audit found that it depended on `list_annotations` — +// a vendor command that @modelcontextprotocol/server-pdf@1.7.2 does not expose. // -// LOAD-BEARING INVARIANTS (preserved verbatim from the plan-md): -// 1. §13 phase ordering — phase-1 reads → phase-2 MCP I/O → phase-3 -// db.transaction with NO awaits inside the closure. The transaction -// callback is typed `(tx) => void` so async returns are compile-time -// rejected (constraint #1). -// 2. Write-then-push — handlers commit the synchronous DB write BEFORE -// forwarding to the pdf child. Failure-safe: a viewer crash after DB -// write leaves a dirty row that the next reconcile pushes (constraint #2). -// 3. §12.0 sanitizeText — applied to body and anchor on both outbound -// (user-supplied) and inbound (viewer-originated) paths (constraint #3). -// 4. source hardcoded — upsert input schema excludes source; handler writes -// "scholar"; only phase-3 step-3 writes "pdf-viewer" (constraint #4). -// 5. NO_ACTIVE_CORPUS guard fires before any DB or pdf-child call -// (constraint #5). -// 6. deriveRectFromAnchor returns the fixed [20,20,120,60] sticky — geometry- -// aware anchor resolution is v2 (constraint #6). -// 7. scholar_deleted_ids Set — captured in phase 1 alongside tombstoned_ids; -// filters phase-3 INSERT to prevent resurrection of any soft-deleted id, -// not just the tombstone-audit subset (constraint #7). -// 8. ctx.db snapshot-at-entry; ctx.pdf snapshotted alongside (constraint #8 + #15). -// 9. corpus_id from ctx.config.activeCorpusId(); never from tool input -// (constraint #9). -// 13. Phase-2 step-2 throws propagate — no try/catch in the per-row loop -// (constraint #13). Self-healing depends on phase-3 NOT running after a -// partial push. -// 14. Post-tx delete-recovery — after db.transaction(...) returns and before -// reconcile() resolves, re-assert remove_annotations for any viewer rows -// whose id is in scholar_deleted_ids. Cures perpetual viewer-side staleness -// when the cursor has advanced past deleted_at (constraint #14). -// 16. Phase-3 step-3 INSERT uses .onConflictDoNothing() so concurrent same- -// paper reconciles serialize without throwing PK constraint errors -// (constraint #16). +// LOAD-BEARING INVARIANTS (push-only): +// 1. Write-then-push — handlers commit the synchronous DB write BEFORE +// forwarding to the pdf child. Failure-safe: a viewer crash after the +// write leaves a dirty row that the user can re-push by re-invoking +// upsert with the same id. +// 2. §12.0 sanitizeText — applied to user-supplied body and anchor on the +// outbound (upsert) path. Throws before any DB write or pdf-child call. +// Inbound sanitization is moot — there is no inbound path under v1.1. +// 3. source hardcoded — upsert input schema excludes source; handler always +// writes "scholar". The "pdf-viewer" enum value persists in the §8.2 +// CHECK constraint to keep older v0.x corpora validating; new writes +// never use it. +// 4. NO_ACTIVE_CORPUS guard fires before any DB or pdf-child call. +// 5. NO_OPEN_VIEWER guard fires when ctx.pdfViews has no entry for the +// target paper_id. upsert/delete throw; list does NOT — list is a pure +// DB read and works against closed-viewer papers. +// 6. ctx.db snapshot-at-entry; ctx.pdf snapshotted alongside; ctx.pdfViews +// read at viewUUID-resolution time. +// 7. corpus_id from ctx.config.activeCorpusId(); never from tool input. +// 8. deriveRectFromAnchor returns the fixed [20,20,120,60] sticky — geometry- +// aware anchor resolution is v2. import { z } from "zod"; -import { and, eq, gt, isNull, or, isNotNull } from "drizzle-orm"; +import { and, eq, isNull } from "drizzle-orm"; import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite"; -import { annotations, annotation_tombstones, reconcile_state } from "../db/schema.ts"; +import { annotations } from "../db/schema.ts"; import { sanitizeText } from "../ingest/primitives.ts"; import { ulid, nowIso } from "../db/nowIso.ts"; import type { PdfChild, RegisterTools, ServerContext } from "./registry.ts"; +import type { NoteAnnotation } from "../../vendor/pdf-server/dist/src/pdf-annotations.js"; // ─── error ──────────────────────────────────────────────────────────────────── @@ -60,53 +52,43 @@ class AnnotationsToolError extends Error { export type AnnotationRow = typeof annotations.$inferSelect; -type ViewerRow = { - id: string; - page?: number | null; - anchor?: string | null; - rect?: number[] | null; - body: string; - created_at?: string | null; - updated_at?: string | null; -}; - -type ViewerAnnotation = { - id: string; - page: number | null; - rect: [number, number, number, number]; - body: string; - created_at: string; - updated_at: string; -}; - -// ─── helpers (file-private) ─────────────────────────────────────────────────── +// ─── helpers ────────────────────────────────────────────────────────────────── /** - * v1 fixed margin sticky-note rect. Anchor-geometry-aware resolution is v2 - * (requires PDF geometry from extraction; out-of-scope cross-plan coupling). - * Constraint #6. + * Default sticky-note origin when no rect was supplied. v1 ships a fixed + * top-left margin position; geometry-aware anchor resolution is v2. */ -function deriveRectFromAnchor( - _anchor: string | null | undefined, -): [number, number, number, number] { - return [20, 20, 120, 60]; -} +const DEFAULT_NOTE_ORIGIN: { x: number; y: number } = { x: 20, y: 20 }; /** - * §13 pinned shape. id rides through unchanged (direct ULID — wrap-and-strip - * branch deferred unless a future probe of pdf@1.7.2 reveals viewer-side id - * mutation; constraint #12). + * Map a scholar annotation row to the vendor's `note` annotation shape + * (single source of truth: src/vendor/pdf-server/dist/src/pdf-annotations.d.ts). + * + * Mapping rationale (§13 v1.1 + §16 vendor-truth invariant): + * - scholar's rect [x,y,w,h] is collapsed to vendor's (x, y); vendor's + * `note` doesn't carry width/height — the sticky icon is fixed-size. + * - scholar's anchor metadata (if any) is prefixed onto content so the + * viewer's sticky text box shows it. + * - page defaults to 1 because vendor requires `number` and scholar + * persists `page: number | null` (paper-level notes carry no page). + * + * The discriminator type="note" is hard-coded — scholar v1 only emits + * sticky notes. Highlight/underline/etc. are out of scope until v2. */ -function serializeForViewer(row: AnnotationRow): ViewerAnnotation { +function serializeForViewer(row: AnnotationRow): NoteAnnotation { + const rect = row.rect + ? (JSON.parse(row.rect) as [number, number, number, number]) + : null; + const x = rect ? rect[0] : DEFAULT_NOTE_ORIGIN.x; + const y = rect ? rect[1] : DEFAULT_NOTE_ORIGIN.y; + const content = row.anchor ? `${row.anchor}\n\n${row.body}` : row.body; return { id: row.id, - page: row.page, - rect: row.rect - ? (JSON.parse(row.rect) as [number, number, number, number]) - : deriveRectFromAnchor(row.anchor), - body: row.body, - created_at: row.created_at, - updated_at: row.updated_at, + type: "note", + page: row.page ?? 1, + x, + y, + content, }; } @@ -138,7 +120,7 @@ function parseRect(rectStr: string): [number, number, number, number] { return parsed as [number, number, number, number]; } -/** Require an active corpus; throw structured error otherwise. Constraint #5. */ +/** Require an active corpus; throw structured error otherwise. */ function requireDb(ctx: ServerContext, op: string): BunSQLiteDatabase { if (!ctx.db) { throw new AnnotationsToolError( @@ -149,209 +131,20 @@ function requireDb(ctx: ServerContext, op: string): BunSQLiteDatabase { return ctx.db; } -// ─── §13 reconciler ─────────────────────────────────────────────────────────── - /** - * Bidirectional reconciler. Runs synchronously before every annotations.list - * to eliminate the model-facing stale window. The three-phase structure keeps - * SQLite write-lock holding decoupled from pdf-child network I/O — concurrent - * lists on different papers do NOT serialize behind each other's interact() - * round-trip. - * - * Phase 1 (reads, no tx) → Phase 2 (MCP I/O, no tx) → Phase 3 (write-back, - * sync tx, no awaits) → Post-tx (re-assert removes for ghosts). + * Resolve viewUUID for a paper_id from the in-process map populated by + * scholar.pdf.open. Throws NO_OPEN_VIEWER on miss — the user re-opens the + * viewer to refresh the entry (§13 viewUUID propagation). */ -export async function reconcile( - corpus_id: string, - paper_id: string, - db: BunSQLiteDatabase, - pdf: PdfChild, -): Promise { - // --- Phase 1: read-only state capture (no tx; no SQLite write lock held). --- - - const cursor = db - .select({ at: reconcile_state.last_reconciled_at }) - .from(reconcile_state) - .where( - and( - eq(reconcile_state.corpus_id, corpus_id), - eq(reconcile_state.paper_id, paper_id), - ), - ) - .get()?.at ?? "1970-01-01T00:00:00.000Z"; - - const scholar_dirty = db - .select() - .from(annotations) - .where( - and( - eq(annotations.paper_id, paper_id), - or(gt(annotations.updated_at, cursor), gt(annotations.deleted_at, cursor)), - ), - ) - .all(); - - const scholar_all_live = db - .select() - .from(annotations) - .where( - and( - eq(annotations.paper_id, paper_id), - isNull(annotations.deleted_at), - ), - ) - .all(); - const scholar_by_id = new Map(scholar_all_live.map((r) => [r.id, r])); - - // Constraint #7: every currently soft-deleted id for this paper — stricter - // than tombstoned_ids (which only includes explicit .delete-tool inserts). - // Used in phase-3 step-3 INSERT filter and in the post-tx delete-recovery loop. - const scholar_deleted_ids = new Set( - db - .select({ id: annotations.id }) - .from(annotations) - .where( - and( - eq(annotations.paper_id, paper_id), - isNotNull(annotations.deleted_at), - ), - ) - .all() - .map((r) => r.id), - ); - - // Spec §13 tombstoned_ids — drives the phase-2 resurrection-cure call. - const tombstoned_ids = new Set( - db - .select({ id: annotation_tombstones.annotation_id }) - .from(annotation_tombstones) - .where(eq(annotation_tombstones.paper_id, paper_id)) - .all() - .map((r) => r.id), - ); - - // --- Phase 2: MCP round-trips (await on network; no SQLite tx open). --- - - const viewer_rows = (await pdf.interact([ - { type: "list_annotations", paper_id }, - ])) as ViewerRow[]; - const viewer_by_id = new Map(viewer_rows.map((r) => [r.id, r])); - - // Step 1: tombstone-push + resurrection cure. Folds (a) freshly-deleted - // dirty rows and (b) any tombstoned id the viewer is still reporting live - // into a single remove_annotations call. The (b) leg is the cure for - // amendment 34871f2 — without it, the phase-3 suppression masks the bug - // but never actually cleans up the viewer-side row. - const fresh_tombstone_ids = scholar_dirty - .filter((r) => r.deleted_at !== null) - .map((r) => r.id); - const resurrected_ids = viewer_rows - .filter((v) => tombstoned_ids.has(v.id)) - .map((v) => v.id); - const ids_to_remove = Array.from( - new Set([...fresh_tombstone_ids, ...resurrected_ids]), - ); - if (ids_to_remove.length > 0) { - await pdf.interact([{ type: "remove_annotations", ids: ids_to_remove }]); - } - - // Step 2: per-row push of live add/update. Per spec §13, mixed add+update - // batch semantics are unverified against pdf@1.7.2; we issue one call per - // dirty row. If a probe later confirms mixed batching is supported, this - // loop collapses to one call. - // - // Constraint #13: throws here propagate. Do NOT wrap in try/catch — the - // self-healing property depends on phase-3 NOT running after a partial push. - const live_changes = scholar_dirty.filter((r) => r.deleted_at === null); - for (const row of live_changes) { - const op = viewer_by_id.has(row.id) ? "update_annotations" : "add_annotations"; - await pdf.interact([{ type: op, annotations: [serializeForViewer(row)] }]); - } - - // --- Phase 3: local write-back inside a single Drizzle transaction. No awaits. --- - // - // Callback typed `(tx) => void` so a future maintainer who writes - // `db.transaction(async (tx) => ...)` fails compilation rather than - // silently degrading the §13 invariant. - const now = nowIso(); - db.transaction((tx): void => { - // Step 3: viewer-only rows → pull. Tombstoned/soft-deleted ids skipped - // (resurrection prevention; spec amendment 34871f2 + constraint #7). - // INSERT uses .onConflictDoNothing() so concurrent same-paper reconciles - // serialize without throwing PK constraint errors (constraint #16). - for (const vrow of viewer_rows) { - if (tombstoned_ids.has(vrow.id)) continue; - if (scholar_deleted_ids.has(vrow.id)) continue; - const srow = scholar_by_id.get(vrow.id); - if (!srow) { - // Inbound sanitization: viewer text is untrusted (§12.0 constraint #3). - const safeBody = sanitizeText(vrow.body); - const safeAnchor = vrow.anchor != null ? sanitizeText(vrow.anchor) : null; - tx.insert(annotations) - .values({ - id: vrow.id, - paper_id, - page: vrow.page ?? null, - anchor: safeAnchor, - rect: vrow.rect ? JSON.stringify(vrow.rect) : null, - body: safeBody, - source: "pdf-viewer", - created_at: vrow.created_at ?? now, - updated_at: vrow.updated_at ?? now, - deleted_at: null, - }) - .onConflictDoNothing() - .run(); - } else if (vrow.updated_at && vrow.updated_at > srow.updated_at) { - // LWW with strict-greater tie-break (constraint #11: scholar wins on ==). - const safeBody = sanitizeText(vrow.body); - tx.update(annotations) - .set({ - body: safeBody, - rect: vrow.rect ? JSON.stringify(vrow.rect) : null, - source: "pdf-viewer", - updated_at: vrow.updated_at, - }) - .where(eq(annotations.id, vrow.id)) - .run(); - } - } - - // Step 4: scholar-only rows OLDER than cursor and missing from the viewer - // → treat as viewer-side deletions and tombstone in scholar. - for (const srow of scholar_all_live) { - if (srow.updated_at <= cursor && !viewer_by_id.has(srow.id)) { - tx.update(annotations) - .set({ deleted_at: now }) - .where(eq(annotations.id, srow.id)) - .run(); - } - } - - // Step 5: advance cursor. - tx.insert(reconcile_state) - .values({ corpus_id, paper_id, last_reconciled_at: now }) - .onConflictDoUpdate({ - target: [reconcile_state.corpus_id, reconcile_state.paper_id], - set: { last_reconciled_at: now }, - }) - .run(); - }); - - // --- Post-tx phase: re-assert removes for viewer rows blocked by the F7 filter. --- - // - // Constraint #14: once the cursor has advanced past deleted_at, the - // tombstone no longer appears in scholar_dirty so the phase-2 cure (which - // depends on tombstoned_ids) might still fire for tool-deleted rows, but a - // reconciler-set soft-delete (phase-3 step-4) is NOT in annotation_tombstones - // and would never re-push. This loop fills that gap by issuing remove_annotations - // for ANY soft-deleted id the viewer is still reporting. Throws propagate - // (same reasoning as constraint #13). - for (const vrow of viewer_rows) { - if (scholar_deleted_ids.has(vrow.id)) { - await pdf.interact([{ type: "remove_annotations", ids: [vrow.id] }]); - } +function requireViewUUID(ctx: ServerContext, paper_id: string, op: string): string { + const viewUUID = ctx.pdfViews.get(paper_id); + if (!viewUUID) { + throw new AnnotationsToolError( + "NO_OPEN_VIEWER", + `NO_OPEN_VIEWER: scholar.annotations.${op} requires scholar.pdf.open(paper_id=${paper_id}) to be called first so the viewUUID is registered in ctx.pdfViews.`, + ); } + return viewUUID; } // ─── handlers ───────────────────────────────────────────────────────────────── @@ -369,18 +162,10 @@ type ListArgs = { paper_id: string }; type DeleteArgs = { id: string }; async function handleList(args: unknown, ctx: ServerContext): Promise { + // §13 v1.1: pure DB read. Does NOT require an open viewer — closed-viewer + // papers still return their persisted rows. const db = requireDb(ctx, "list"); - const pdf = ctx.pdf; const { paper_id } = args as ListArgs; - const corpus_id = ctx.config.activeCorpusId(); - if (!corpus_id) { - // Shouldn't happen if ctx.db is set, but guard defensively. - throw new AnnotationsToolError( - "NO_ACTIVE_CORPUS", - "NO_ACTIVE_CORPUS: scholar.annotations.list could not resolve active corpus id.", - ); - } - await reconcile(corpus_id, paper_id, db, pdf); const rows = db .select() .from(annotations) @@ -396,7 +181,7 @@ async function handleList(args: unknown, ctx: ServerContext): Promise { async function handleUpsert(args: unknown, ctx: ServerContext): Promise { const db = requireDb(ctx, "upsert"); - const pdf = ctx.pdf; + const pdf: PdfChild = ctx.pdf; const input = args as UpsertArgs; if (!input || typeof input.body !== "string" || typeof input.paper_id !== "string") { throw new AnnotationsToolError( @@ -404,9 +189,11 @@ async function handleUpsert(args: unknown, ctx: ServerContext): Promise "INVALID_ARGS: paper_id and body are required.", ); } + // viewUUID resolved BEFORE sanitization so a missing-viewer error fires + // before any string parsing — keeps the error ordering predictable. + const viewUUID = requireViewUUID(ctx, input.paper_id, "upsert"); - // Outbound sanitization (§12.0 constraint #3 outbound). Throws SanitizeError - // before any DB write or pdf-child call. + // §12.0 sanitization (constraint #2). Throws SanitizeError before DB or push. const safeBody = sanitizeText(input.body); const safeAnchor = input.anchor != null ? sanitizeText(input.anchor) : null; const rectArr = input.rect != null ? parseRect(input.rect) : null; @@ -476,18 +263,21 @@ async function handleUpsert(args: unknown, ctx: ServerContext): Promise }; } - // Write-then-push (constraint #2): the DB write above committed synchronously - // before this await. A viewer crash here leaves a dirty row that the next - // reconcile will pick up via scholar_dirty (updated_at > cursor). - const op = existing ? "update_annotations" : "add_annotations"; - await pdf.interact([{ type: op, annotations: [serializeForViewer(savedRow)] }]); + // Write-then-push (constraint #1): the DB write above committed synchronously + // before this await. A throw here leaves a dirty row that the user can + // re-push by re-invoking upsert with the same id (idempotent on existing id). + const action = existing ? "update_annotations" : "add_annotations"; + await pdf.interact( + { type: action, annotations: [serializeForViewer(savedRow)] }, + { viewUUID }, + ); return savedRow; } async function handleDelete(args: unknown, ctx: ServerContext): Promise { const db = requireDb(ctx, "delete"); - const pdf = ctx.pdf; + const pdf: PdfChild = ctx.pdf; const { id } = args as DeleteArgs; if (typeof id !== "string") { throw new AnnotationsToolError("INVALID_ARGS", "INVALID_ARGS: id is required."); @@ -498,37 +288,33 @@ async function handleDelete(args: unknown, ctx: ServerContext): Promise .where(eq(annotations.id, id)) .get(); if (!existing) { - // No row to delete — silent success keeps the surface idempotent for stale - // viewer pushes; treat as a no-op (no row to tombstone). + // Idempotent on missing id — keeps the surface resilient to stale viewer + // pushes; treat as a no-op (no row to tombstone, no push to send). return { id, deleted: false, reason: "not_found" }; } - // Constraint #3b: idempotent on already-tombstoned rows. No second - // deleted_at write, no second tombstone insert, no second pdf.interact. + // Idempotent on already-tombstoned rows — no second deleted_at write, no + // second pdf.interact. if (existing.deleted_at !== null) { - return { id, deleted: false, reason: "already_tombstoned", deleted_at: existing.deleted_at }; + return { + id, + deleted: false, + reason: "already_tombstoned", + deleted_at: existing.deleted_at, + }; } + // viewUUID resolved AFTER existence + idempotency checks so a delete on an + // already-tombstoned row is a clean no-op even when no viewer is open. + const viewUUID = requireViewUUID(ctx, existing.paper_id, "delete"); const now = nowIso(); - // Constraint #8 atomicity: deleted_at + annotation_tombstones in a single tx. - db.transaction((tx): void => { - tx.update(annotations) - .set({ deleted_at: now }) - .where(eq(annotations.id, id)) - .run(); - tx.insert(annotation_tombstones) - .values({ - annotation_id: id, - paper_id: existing.paper_id, - deleted_at: now, - deleted_by: "scholar", - deletion_reason: null, - }) - .onConflictDoNothing() - .run(); - }); + // Single-statement update — under v1.1 the atomic tombstones pair retired. + db.update(annotations) + .set({ deleted_at: now }) + .where(eq(annotations.id, id)) + .run(); // Write-then-push. - await pdf.interact([{ type: "remove_annotations", ids: [id] }]); + await pdf.interact({ type: "remove_annotations", ids: [id] }, { viewUUID }); return { id, deleted: true, deleted_at: now }; } @@ -539,9 +325,8 @@ export const registerTools: RegisterTools = (_server, ctx, _register) => { "scholar.annotations.list", { description: - "List live annotations for a paper. Runs §13's bidirectional reconciler " + - "(scholar ↔ vendored pdf MCP child) before returning, so the model never " + - "observes an annotation set that disagrees with the viewer.", + "List live annotations for a paper. Pure DB read under §13 v1.1 push-only; " + + "does NOT require an open viewer.", inputSchema: z.object({ paper_id: z.string().min(1) }), }, handleList, @@ -552,17 +337,15 @@ export const registerTools: RegisterTools = (_server, ctx, _register) => { description: "Create or update an annotation. id is optional on insert (a ULID is " + "generated). On update, created_at is preserved; source is hardcoded " + - "to 'scholar'. Pushes add_annotations/update_annotations to the pdf " + - "child AFTER the DB write commits (write-then-push, §13).", + "to 'scholar'. Pushes add/update_annotations to the pdf child via " + + "ctx.pdfViews[paper_id] AFTER the DB write commits (write-then-push, §13).", inputSchema: z.object({ id: z.string().optional(), paper_id: z.string().min(1), page: z.number().int().nullable().optional(), anchor: z.string().nullable().optional(), - // 4-element JSON string of finite numbers; validated before persist. rect: z.string().nullable().optional(), body: z.string().min(1), - // source intentionally excluded (constraint #4). }), }, handleUpsert, @@ -571,10 +354,9 @@ export const registerTools: RegisterTools = (_server, ctx, _register) => { "scholar.annotations.delete", { description: - "Soft-delete an annotation. Sets annotations.deleted_at AND inserts an " + - "annotation_tombstones row atomically (§13 propagation model), then " + - "pushes remove_annotations to the pdf child. Idempotent on already-" + - "tombstoned ids.", + "Soft-delete an annotation. Sets annotations.deleted_at and pushes " + + "remove_annotations to the pdf child via ctx.pdfViews[paper_id]. " + + "Idempotent on already-tombstoned ids (no-op).", inputSchema: z.object({ id: z.string().min(1) }), }, handleDelete, diff --git a/src/server/tools/corpus.test.ts b/src/server/tools/corpus.test.ts index 91160a9..3199c53 100644 --- a/src/server/tools/corpus.test.ts +++ b/src/server/tools/corpus.test.ts @@ -31,6 +31,7 @@ beforeEach(() => { getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, currentRoots: () => [], setRoots: setRootsMock as unknown as (roots: string[]) => Promise, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), }; diff --git a/src/server/tools/ingest.test.ts b/src/server/tools/ingest.test.ts index 0d4e24f..aef4eee 100644 --- a/src/server/tools/ingest.test.ts +++ b/src/server/tools/ingest.test.ts @@ -28,6 +28,7 @@ const mockPdf: PdfChild = { getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, currentRoots: () => [], setRoots: async () => {}, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), }; diff --git a/src/server/tools/pdf.ts b/src/server/tools/pdf.ts index e614ea8..98f1752 100644 --- a/src/server/tools/pdf.ts +++ b/src/server/tools/pdf.ts @@ -1,11 +1,16 @@ -// src/server/tools/pdf.ts — extraction cycle 6.5 (Green) +// src/server/tools/pdf.ts — extraction cycle 6.5 (Green) + §13 v1.1 amendment // -// Implements scholar.pdf.refresh-extraction per spec §5.12 + §11. Foundation -// scaffolded this module as a no-op stub at cycle 6.1; this cycle fills the -// body for the extraction pipeline. The thin proxy tools (scholar.pdf.open, -// scholar.pdf.search-text, scholar.pdf.extract-anchors) forward into the -// child pdf MCP via ctx.pdf.interact — registered minimally so the -// MCP-side surface advertises them; payload shapes are pdf-child verbatim. +// Implements scholar.pdf.refresh-extraction per spec §5.12 + §11, plus the +// new scholar.pdf.open tool added by the 2026-05-27 §13 amendment. +// +// scholar.pdf.open(paper_id, source) wraps vendor display_pdf and registers +// the returned viewUUID in ctx.pdfViews under the paper_id key. This is the +// population point for the §13 v1.1 push-only annotation propagation model: +// scholar.annotations.{upsert,delete} and scholar.pdf.refresh-extraction +// resolve viewUUID from ctx.pdfViews and throw NO_OPEN_VIEWER on miss. +// +// The v1.0 proxy stubs `scholar.pdf.search-text` and `scholar.pdf.extract-anchors` +// were deleted in the same amendment — they never mapped to real vendor tools. // // §11 contract: // 1. extract via pdf-child get_text @@ -128,8 +133,18 @@ export async function refreshExtraction( ); } - // (1) Extract text via the child pdf MCP. viewUUID === paper_id in v1. - const text = await ctx.pdf.getText(args.paper_id); + // (1) Extract text via the child pdf MCP. viewUUID is resolved from the + // ctx.pdfViews map populated by scholar.pdf.open (§13 v1.1 amendment — + // the v1.0 "viewUUID === paper_id" identity assumption was a bug because + // the vendor issues fresh UUIDs at display_pdf time, not by paper_id). + const viewUUID = ctx.pdfViews.get(args.paper_id); + if (!viewUUID) { + throw new PdfToolError( + "NO_OPEN_VIEWER", + `NO_OPEN_VIEWER: scholar.pdf.refresh-extraction requires scholar.pdf.open(paper_id=${args.paper_id}) to be called first so the viewUUID is registered in ctx.pdfViews.`, + ); + } + const text = await ctx.pdf.getText({ viewUUID }); // (2) Lazy materialization if chunk_vec hasn't been created yet. if (!chunkVecReady(db)) { @@ -231,20 +246,35 @@ export const registerTools: RegisterTools = (_server, ctx, _register) => { }, ); - // Thin proxies into the pdf child MCP — payload shapes are pdf-child verbatim. - // Registered so the MCP surface advertises them; the child handles validation. - const proxy = (toolName: string, description: string) => - _register( - toolName, - { - description, - inputSchema: z.object({}).passthrough(), - }, - async (args) => { - return await ctx.pdf.interact([{ tool: toolName.replace(/^scholar\./, ""), args }]); - }, - ); - proxy("scholar.pdf.open", "Open a PDF in the child pdf MCP and return its viewUUID."); - proxy("scholar.pdf.search-text", "Search the PDF for a string and return matched anchors."); - proxy("scholar.pdf.extract-anchors", "Extract anchor metadata from the PDF for annotation reconciliation."); + // scholar.pdf.open — real proxy to vendor `display_pdf` (§13 v1.1 amendment). + // Calls ctx.pdf.displayPdf, captures the returned viewUUID, and registers it + // under paper_id in ctx.pdfViews so scholar.annotations.{upsert,delete} and + // scholar.pdf.refresh-extraction can resolve viewUUID without the caller + // re-passing it on every tool invocation. + _register( + "scholar.pdf.open", + { + description: + "Open a paper in the child pdf MCP and register its viewUUID under " + + "paper_id in ctx.pdfViews. Required before scholar.annotations.{upsert,delete} " + + "or scholar.pdf.refresh-extraction on the same paper. `source` is an absolute " + + "local path, a file:// URL, or an HTTPS URL — passed through to the vendor.", + inputSchema: z.object({ + paper_id: z.string().min(1).describe("Scholar's paper id (ULID)."), + source: z.string().min(1).describe("Path or URL the vendor display_pdf will open."), + }), + }, + async (args) => { + const parsed = (args ?? {}) as { paper_id?: string; source?: string }; + if (typeof parsed.paper_id !== "string" || typeof parsed.source !== "string") { + throw new PdfToolError( + "INVALID_ARGS", + "INVALID_ARGS: paper_id and source are required.", + ); + } + const { viewUUID } = await ctx.pdf.displayPdf(parsed.source); + ctx.pdfViews.set(parsed.paper_id, viewUUID); + return { paper_id: parsed.paper_id, viewUUID }; + }, + ); }; diff --git a/src/server/tools/roots.test.ts b/src/server/tools/roots.test.ts index 506a8f5..4c0ed81 100644 --- a/src/server/tools/roots.test.ts +++ b/src/server/tools/roots.test.ts @@ -29,6 +29,7 @@ beforeEach(async () => { getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, currentRoots: () => [], setRoots: setRootsMock as unknown as (roots: string[]) => Promise, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), }; diff --git a/src/server/tools/snapshot.test.ts b/src/server/tools/snapshot.test.ts index 718d089..a8e2320 100644 --- a/src/server/tools/snapshot.test.ts +++ b/src/server/tools/snapshot.test.ts @@ -31,6 +31,7 @@ beforeEach(async () => { getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, currentRoots: () => [], setRoots: async () => {}, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), }; diff --git a/tests/first-run.test.ts b/tests/first-run.test.ts index a1c89ae..e9102ff 100644 --- a/tests/first-run.test.ts +++ b/tests/first-run.test.ts @@ -33,6 +33,7 @@ beforeEach(() => { }, currentRoots: () => [], setRoots: async () => {}, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), } From d47298ea4848b4af43f3b24cb404c56c369905b1 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 20:26:51 -0500 Subject: [PATCH 06/33] test(pdf): vendor wire-envelope contract test (S1 drift canary) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New file lifecycle.contract.test.ts — gated by SCHOLAR_PDF_E2E=1 — spawns the real vendored pdf-server and exercises: - C1: navigate via the §13 v1.1 envelope {viewUUID, action: "navigate", page} - C2: add_annotations + remove_annotations with vendor's NoteAnnotation shape ({id, type: "note", page, x, y, content}) If serializeForViewer drifts from the vendor's PdfAnnotationDef union, or if interact()'s envelope translator regresses, these fixtures fail at the wire level rather than at a downstream user-visible bug. Re-vendor reviewers read this file to know what wire shapes scholar relies on (§16 vendor-truth invariant). Notes on what is intentionally NOT covered: - get_text: requires a live viewer process to complete (envelope is already covered indirectly by C1+C2 going through the same translator). - list_annotations: vendor does not expose this command (the entire point of the §13 amendment). Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/pdf/lifecycle.contract.test.ts | 171 ++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 src/server/pdf/lifecycle.contract.test.ts diff --git a/src/server/pdf/lifecycle.contract.test.ts b/src/server/pdf/lifecycle.contract.test.ts new file mode 100644 index 0000000..fd15830 --- /dev/null +++ b/src/server/pdf/lifecycle.contract.test.ts @@ -0,0 +1,171 @@ +// src/server/pdf/lifecycle.contract.test.ts — S1 (2026-05-27) vendor contract test +// +// Exercises the §13 v1.1 wire envelope `{viewUUID, action, ...rest}` against +// the *real* vendored @modelcontextprotocol/server-pdf process. This is the +// drift canary called out by the production-readiness audit (S1 bullet 7): +// scholar's interact() translator + scholar's note-shape mapping land +// together, so if either the translator or the vendor's command schema +// changes in a future re-vendor pass, this test fails at the wire level +// rather than at a downstream user-visible regression. +// +// Why a separate file from lifecycle.test.ts? +// The wire-envelope coverage here is a contract against the vendored binary +// — it's load-bearing for `re-vendor` chore reviewers in particular. Keeping +// it adjacent in its own file (lifecycle.contract.test.ts) is the §16 +// "vendor-truth invariant" — when re-vendoring, the diff-reviewer reads +// exactly this file to know what wire shapes scholar relies on. +// +// Gate: SCHOLAR_PDF_E2E=1 (same flag the FIXTURE 4 + 6 heavyweights use). +// Default `bun test` skips this; CI sets the flag and runs it. +import { test, expect, afterEach } from "bun:test"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnPdfChild, type PdfChildHandle } from "./lifecycle.ts"; +import { ulid } from "../db/nowIso.ts"; + +const E2E = process.env.SCHOLAR_PDF_E2E === "1"; + +let handle: PdfChildHandle | undefined; +let tmpRoot: string | undefined; + +afterEach(async () => { + if (handle) { + await handle.shutdown(); + handle = undefined; + } + if (tmpRoot) { + rmSync(tmpRoot, { recursive: true, force: true }); + tmpRoot = undefined; + } +}); + +/** + * Minimal valid PDF (one empty page, with xref + trailer). Vendor parses this + * via pdf-lib; the synthetic byte-blob FIXTURE 4 uses is not a full PDF and + * vendor may refuse it depending on parser version. This fixture is built + * from a single canonical byte stream tested against pdf-lib 1.17. + */ +function writeMinimalPdf(path: string): void { + // 1-page A4 portrait PDF, no content stream, no fonts — pdf-lib parses this + // and vendor's display_pdf accepts it as openable. Generated offline with + // pdf-lib; bytes are stable. + const bytes = Buffer.from( + [ + "%PDF-1.4", + "1 0 obj<>endobj", + "2 0 obj<>endobj", + "3 0 obj<>>>endobj", + "xref", + "0 4", + "0000000000 65535 f ", + "0000000009 00000 n ", + "0000000054 00000 n ", + "0000000101 00000 n ", + "trailer<>", + "startxref", + "170", + "%%EOF", + "", + ].join("\n"), + "utf-8", + ); + writeFileSync(path, bytes); +} + +function makeFixtureRoot(): { root: string; pdf: string } { + const root = mkdtempSync(join(tmpdir(), "scholar-pdf-contract-")); + mkdirSync(join(root, "papers"), { recursive: true }); + const pdf = join(root, "papers", "fixture.pdf"); + writeMinimalPdf(pdf); + return { root, pdf }; +} + +// ============================================================================= +// FIXTURE C1 — display_pdf returns a viewUUID and `interact` accepts the +// v1.1 envelope `{viewUUID, action: "navigate", page: 1}`. +// +// Why this matters: the v1.0 code path mistakenly sent `{type: "navigate", ...}` +// without viewUUID at all. If the vendor evolves to validate `viewUUID` more +// strictly (or renames `action`), this fixture is the first thing that fails. +// ============================================================================= + +test.skipIf(!E2E)( + "C1 — display_pdf + interact({navigate}) round-trips under the §13 v1.1 envelope", + async () => { + const fix = makeFixtureRoot(); + tmpRoot = fix.root; + handle = await spawnPdfChild({ initialRoots: [fix.root] }); + + const { viewUUID } = await handle.displayPdf(fix.pdf); + expect(typeof viewUUID).toBe("string"); + expect(viewUUID.length).toBeGreaterThan(0); + + // navigate carries no annotations, no rects — pure envelope check. + // If lifecycle.ts.interact ever stops appending viewUUID as a sibling + // of action, the vendor will reject or no-op silently; this fixture + // round-trips a value (vendor returns null on success) and asserts + // no throw. + await expect( + handle.interact({ type: "navigate", page: 1 }, { viewUUID }), + ).resolves.toBeDefined(); + }, +); + +// ============================================================================= +// FIXTURE C2 — add_annotations({note}) round-trips with scholar's serializeForViewer +// shape: {id, type: "note", page, x, y, content}. +// +// Why this matters: serializeForViewer (annotations.ts) maps scholar rows to +// the vendor's NoteAnnotation. If the vendor evolves AnnotationBase or the +// note discriminator, scholar's PUSH path silently fails until users notice +// missing sticky notes. This fixture catches that regression at re-vendor time. +// ============================================================================= + +test.skipIf(!E2E)( + "C2 — add_annotations({type: 'note'}) round-trips under the §13 v1.1 envelope", + async () => { + const fix = makeFixtureRoot(); + tmpRoot = fix.root; + handle = await spawnPdfChild({ initialRoots: [fix.root] }); + const { viewUUID } = await handle.displayPdf(fix.pdf); + + const annotationId = ulid(); + await expect( + handle.interact( + { + type: "add_annotations", + annotations: [ + { + id: annotationId, + type: "note", + page: 1, + x: 20, + y: 20, + content: "contract-test sticky", + }, + ], + }, + { viewUUID }, + ), + ).resolves.toBeDefined(); + + // remove_annotations also exercised — payload is {ids: string[]}; the + // envelope translator strips `type` and pushes ids as a sibling. + await expect( + handle.interact( + { type: "remove_annotations", ids: [annotationId] }, + { viewUUID }, + ), + ).resolves.toBeDefined(); + }, +); + +// Why no C3 for get_text? Vendor's `get_text` action requires a live viewer +// process (browser) connected to the pdf-server to extract text — without one, +// the action enqueues to the poll queue and never gets a response, so a +// vendor-only contract test hangs indefinitely. The wire-envelope translation +// for get_text is *already* covered by C1+C2: both go through the same +// `interact()` translator that getText() uses. If the translator regressed, +// C1/C2 fail before C3 would. Liveness against a real viewer belongs in an +// end-to-end browser fixture, not in the wire-contract suite. From 6dd56cf695aaafe651e49c96030126201716219d Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 20:27:07 -0500 Subject: [PATCH 07/33] =?UTF-8?q?spec(S1.v1.1):=20document=20displayPdf()?= =?UTF-8?q?=20on=20=C2=A77.6=20PdfChild=20contract?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The §13 v1.1 code amendment introduced PdfChild.displayPdf() to wrap the vendor's `display_pdf` tool (separate from interact). The §7.6 contract block missed the corresponding entry — adding it now so the spec and the TypeScript interface match. No behavioral change; spec text follow-up only. Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/superpowers/specs/2026-05-22-scholar-plugin-design.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md b/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md index d69da4d..ddfee84 100644 --- a/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md +++ b/docs/superpowers/specs/2026-05-22-scholar-plugin-design.md @@ -597,6 +597,12 @@ interface PdfChild { // hood. Default timeoutMs = 120_000 (text extraction can be slow on large // papers). viewUUID required. getText(opts: { viewUUID: string; timeoutMs?: number }): Promise; + // Opens a PDF in the vendor's interactive viewer by calling the vendor's + // `display_pdf` tool (a separate vendor tool, NOT an interact action). + // Returns the viewUUID that subsequent interact/getText calls must carry. + // Consumed by scholar.pdf.open to populate ServerContext.pdfViews + // (§13 viewUUID propagation). Default timeoutMs = 30_000. + displayPdf(source: string, opts?: { timeoutMs?: number }): Promise<{ viewUUID: string }>; currentRoots(): string[]; // Structured health snapshot. `alive` reflects whether the child responded to the // most recent ping; `lastOkAt` is epoch-ms of the most recent successful interaction From 0874f3450365e6a12cf77fd6996aba18a8dcf672 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 20:27:54 -0500 Subject: [PATCH 08/33] docs(roadmap): mark S1 landed; link to branch + commits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit S1 (pdf-viewer interop rewrite + §13 amendment) is complete on worktree-s1-pdf-interop-and-13-amendment (a2659b9 → 31d5692). Roadmap checklist updated to reflect what landed; future audits will refer to these commits when triaging regressions in the interop surface. Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/audits/ROADMAP.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index 600eb39..292a89e 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -16,16 +16,18 @@ ## Showstopper batch (S1–S3) — must land first -### S1 — pdf-viewer interop rewrite + §13 spec amendment - -- [ ] **Spec edit** `docs/superpowers/specs/2026-05-22-scholar-plugin-design.md` §13: drop inbound reconciliation phase. Document the one-way push contract. Remove every `list_annotations` reference (6+ sites). -- [ ] **Spec edit** §7.6 `PdfChild` contract: change `interact(commands: PdfCommand[])` → `interact(cmd: PdfCommand)`. Wire envelope translates `{type, ...rest}` → `{action: type, ...rest}` at transport boundary. Cite `src/vendor/pdf-server/dist/src/commands.d.ts` as source of truth for the `PdfCommand` union. -- [ ] **Spec add** §16 vendor-tool truth invariant: every command name in the spec must be exported by `src/vendor/pdf-server/dist/server.js`. The spec MAY NOT invent vendor capabilities. -- [ ] **Code** `src/server/pdf/lifecycle.ts` `interact()`: rewrite to take a single `PdfCommand`, translate `type` → `action`, always call `callTool({ name: "interact", arguments: {...} })`. Drop the per-command tool-name routing at `lifecycle.ts:208`. -- [ ] **Code** `src/server/tools/pdf.ts:244` envelope: route through `lifecycle.interact()`. Delete the `{tool, args}` envelope. -- [ ] **Code** `src/server/tools/annotations.ts`: rewrite reconciler against the chosen §13 path. Drop the `list_annotations` enumeration phase. Treat DB as source of truth; push-only outbound. -- [ ] **Test** add a contract-level test that spawns the actual vendor process and exercises at least one real `interact` call. Pick `navigate` as the smoke target (simplest payload). -- [ ] **Test** rewrite `annotations.test.ts` injections to mock at the `lifecycle.interact()` boundary, not at the handler's `ctx.pdf.interact` injection point — that gap is what hid the bug. +### S1 — pdf-viewer interop rewrite + §13 spec amendment ✅ landed 2026-05-27 + +Branch: `worktree-s1-pdf-interop-and-13-amendment` (5 commits a2659b9 → 31d5692). + +- [x] **Spec edit** §13 v1.1 — inbound reconciliation removed; one-way push contract documented; all 6+ `list_annotations` references purged (commit a2659b9). +- [x] **Spec edit** §7.6 PdfChild contract — `interact(cmd, {viewUUID, ...})`; envelope `{type, ...rest}` → `{viewUUID, action: type, ...rest}` translation pinned. `displayPdf()` added as a sibling vendor tool (commits a2659b9, 31d5692). +- [x] **Spec add** §16 vendor-tool truth invariant — vendor commands.d.ts pinned as source of truth (commit a2659b9). +- [x] **Code** `src/server/pdf/lifecycle.ts` `interact()` rewrite + `getText()` routed through interact + `displayPdf()` added (commit f97007d). +- [x] **Code** `src/server/tools/pdf.ts` `refreshExtraction` viewUUID lookup via `ctx.pdfViews`; new `scholar.pdf.open` tool registers viewUUIDs; broken v1.0 proxies dropped (commit a832876). +- [x] **Code** `src/server/tools/annotations.ts` push-only rewrite + serializeForViewer maps scholar rows → vendor's NoteAnnotation shape (commit a832876). +- [x] **Test** real-vendor contract test `src/server/pdf/lifecycle.contract.test.ts` — navigate + add/remove_annotations envelopes, gated by `SCHOLAR_PDF_E2E=1` (commit 93bfca5; both fixtures pass against the real vendor process). +- [x] **Test** `annotations.test.ts` rewritten — 22 tests covering NO_OPEN_VIEWER, write-then-push, idempotency, vendor note shape; v1.0 reconciler tests (Red-4/5/7b/7c/8b/9) retired with the reconciler (commit a832876). ### S2 — CLI mode argv + SIGINT ✅ landed 2026-05-27 From 99355f92f07acd4b1f769b74d6ca4590e69c7f0e Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 21:43:22 -0500 Subject: [PATCH 09/33] docs(roadmap): retarget S1/S2 branch refs to worktree-pre-v1-roadmap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After consolidating S1 work onto the S2 branch via cherry-pick, the `worktree-s1-pdf-interop-and-13-amendment` branch was deleted and `worktree-s2-cli-argv-sigint` was renamed to `worktree-pre-v1-roadmap` to reflect that this branch now carries both batches and will accumulate remaining roadmap work (S3, H1–H5, optionally M1–M9). Commit SHAs are updated to the live cherry-picked equivalents; the originals are dangling refs reachable only via reflog until GC. Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/audits/ROADMAP.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index 292a89e..b48f8ac 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -18,20 +18,20 @@ ### S1 — pdf-viewer interop rewrite + §13 spec amendment ✅ landed 2026-05-27 -Branch: `worktree-s1-pdf-interop-and-13-amendment` (5 commits a2659b9 → 31d5692). +Branch: `worktree-pre-v1-roadmap` (consolidated showstopper branch; S1 commits 04a39ed → 6dd56cf, cherry-picked from the now-deleted `worktree-s1-pdf-interop-and-13-amendment`). -- [x] **Spec edit** §13 v1.1 — inbound reconciliation removed; one-way push contract documented; all 6+ `list_annotations` references purged (commit a2659b9). -- [x] **Spec edit** §7.6 PdfChild contract — `interact(cmd, {viewUUID, ...})`; envelope `{type, ...rest}` → `{viewUUID, action: type, ...rest}` translation pinned. `displayPdf()` added as a sibling vendor tool (commits a2659b9, 31d5692). -- [x] **Spec add** §16 vendor-tool truth invariant — vendor commands.d.ts pinned as source of truth (commit a2659b9). -- [x] **Code** `src/server/pdf/lifecycle.ts` `interact()` rewrite + `getText()` routed through interact + `displayPdf()` added (commit f97007d). -- [x] **Code** `src/server/tools/pdf.ts` `refreshExtraction` viewUUID lookup via `ctx.pdfViews`; new `scholar.pdf.open` tool registers viewUUIDs; broken v1.0 proxies dropped (commit a832876). -- [x] **Code** `src/server/tools/annotations.ts` push-only rewrite + serializeForViewer maps scholar rows → vendor's NoteAnnotation shape (commit a832876). -- [x] **Test** real-vendor contract test `src/server/pdf/lifecycle.contract.test.ts` — navigate + add/remove_annotations envelopes, gated by `SCHOLAR_PDF_E2E=1` (commit 93bfca5; both fixtures pass against the real vendor process). -- [x] **Test** `annotations.test.ts` rewritten — 22 tests covering NO_OPEN_VIEWER, write-then-push, idempotency, vendor note shape; v1.0 reconciler tests (Red-4/5/7b/7c/8b/9) retired with the reconciler (commit a832876). +- [x] **Spec edit** §13 v1.1 — inbound reconciliation removed; one-way push contract documented; all 6+ `list_annotations` references purged (commit 04a39ed). +- [x] **Spec edit** §7.6 PdfChild contract — `interact(cmd, {viewUUID, ...})`; envelope `{type, ...rest}` → `{viewUUID, action: type, ...rest}` translation pinned. `displayPdf()` added as a sibling vendor tool (commits 04a39ed, 6dd56cf). +- [x] **Spec add** §16 vendor-tool truth invariant — vendor commands.d.ts pinned as source of truth (commit 04a39ed). +- [x] **Code** `src/server/pdf/lifecycle.ts` `interact()` rewrite + `getText()` routed through interact + `displayPdf()` added (commit 5500004). +- [x] **Code** `src/server/tools/pdf.ts` `refreshExtraction` viewUUID lookup via `ctx.pdfViews`; new `scholar.pdf.open` tool registers viewUUIDs; broken v1.0 proxies dropped (commit d97f3cf). +- [x] **Code** `src/server/tools/annotations.ts` push-only rewrite + serializeForViewer maps scholar rows → vendor's NoteAnnotation shape (commit d97f3cf). +- [x] **Test** real-vendor contract test `src/server/pdf/lifecycle.contract.test.ts` — navigate + add/remove_annotations envelopes, gated by `SCHOLAR_PDF_E2E=1` (commit d47298e; both fixtures pass against the real vendor process). +- [x] **Test** `annotations.test.ts` rewritten — 22 tests covering NO_OPEN_VIEWER, write-then-push, idempotency, vendor note shape; v1.0 reconciler tests (Red-4/5/7b/7c/8b/9) retired with the reconciler (commit d97f3cf). ### S2 — CLI mode argv + SIGINT ✅ landed 2026-05-27 -Branch: `worktree-s2-cli-argv-sigint` (off `main`, post-S1 audit batch). +Branch: `worktree-pre-v1-roadmap` (S2 commits 2454b4c → 8e204ec; precedes S1 on the branch since S2 was authored first off `main`, then S1 cherry-picked atop). - [x] **Code** `scripts/start-server.ts`: replace `Bun.$` with `Bun.spawn`; forward `process.argv.slice(2)` to the child. - [x] **Code** `scripts/start-server.ts`: SIGINT handler forwards to the child; parent awaits `child.exited` and propagates its code instead of `process.exit(0)`. From 6dbd990f98ffeb52bb8c0be61a66a0a61857b8de Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 22:30:22 -0500 Subject: [PATCH 10/33] fix(ollama): wrap embed/chat fetches in AbortSignal.timeout (S3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit S3: embed and chat had no timeouts — a hung Ollama process would stall every caller indefinitely. postJson() now takes a timeoutMs arg; embed passes 60s, chat passes 120s (matching the roadmap budgets). The TimeoutError surface stays OllamaUnavailableError so existing catch sites need no changes. Defaults are env-overridable (SCHOLAR_OLLAMA_{EMBED,CHAT}_TIMEOUT_MS) following the baseUrl() pattern, so the regression tests can run in ~0.5s instead of waiting 60s of real time. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/ollama/client.test.ts | 63 +++++++++++++++++++++++++++++++- src/server/ollama/client.ts | 29 ++++++++++++++- 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/src/server/ollama/client.test.ts b/src/server/ollama/client.test.ts index 3bdcf30..eb6bdff 100644 --- a/src/server/ollama/client.test.ts +++ b/src/server/ollama/client.test.ts @@ -4,8 +4,20 @@ // (2026-05-25): deleted the "stubs throw 'unimplemented'" test since the // methods now have real implementations. Retained: singleton surface // assertions (methods exist + default model constants exported correctly). -import { test, expect } from "bun:test"; -import { ollama, DEFAULT_EMBED_MODEL, DEFAULT_CHAT_MODEL, OllamaUnavailableError } from "./client.ts"; +// +// S3 roadmap batch (2026-05-27): timeout regression tests. The audit flagged +// embed/chat with no AbortSignal — a hung Ollama would hang the caller +// forever. The fixture server keeps requests open (handler awaits a +// never-resolving promise) while a short timeout via env-var override keeps +// CI runtime short. Per advisor: 200–500ms keeps the abort firmly in the +// fetch-wait window, out of the body-read race. +import { test, expect, afterEach } from "bun:test"; +import { + ollama, + DEFAULT_EMBED_MODEL, + DEFAULT_CHAT_MODEL, + OllamaUnavailableError, +} from "./client.ts"; test("ollama exposes the foundation-frozen singleton surface", () => { expect(ollama).toBeDefined(); @@ -35,3 +47,50 @@ test("OllamaUnavailableError has correct code and name", () => { expect(err.name).toBe("OllamaUnavailableError"); expect(err instanceof Error).toBe(true); }); + +// ─── S3: timeout coverage ──────────────────────────────────────────────────── + +let hangingServer: ReturnType | null = null; + +afterEach(() => { + hangingServer?.stop(true); + hangingServer = null; + delete process.env.SCHOLAR_OLLAMA_URL; + delete process.env.SCHOLAR_OLLAMA_EMBED_TIMEOUT_MS; + delete process.env.SCHOLAR_OLLAMA_CHAT_TIMEOUT_MS; +}); + +function startHangingServer(): string { + hangingServer = Bun.serve({ + port: 0, + // Handler never resolves: the request stays open until the client aborts + // or the server is force-stopped in afterEach. + fetch: () => new Promise(() => {}), + }); + return `http://127.0.0.1:${hangingServer.port}`; +} + +test("embed throws OllamaUnavailableError when the request exceeds the embed timeout", async () => { + process.env.SCHOLAR_OLLAMA_URL = startHangingServer(); + process.env.SCHOLAR_OLLAMA_EMBED_TIMEOUT_MS = "250"; + + const start = Date.now(); + await expect(ollama.embed("test-model", "hello")).rejects.toBeInstanceOf( + OllamaUnavailableError, + ); + const elapsed = Date.now() - start; + // Should fire close to the 250ms budget — generous upper bound to avoid CI flake. + expect(elapsed, `expected timeout near 250ms, got ${elapsed}ms`).toBeLessThan(5_000); +}); + +test("chat throws OllamaUnavailableError when the request exceeds the chat timeout", async () => { + process.env.SCHOLAR_OLLAMA_URL = startHangingServer(); + process.env.SCHOLAR_OLLAMA_CHAT_TIMEOUT_MS = "250"; + + const start = Date.now(); + await expect( + ollama.chat("test-model", [{ role: "user", content: "hi" }]), + ).rejects.toBeInstanceOf(OllamaUnavailableError); + const elapsed = Date.now() - start; + expect(elapsed, `expected timeout near 250ms, got ${elapsed}ms`).toBeLessThan(5_000); +}); diff --git a/src/server/ollama/client.ts b/src/server/ollama/client.ts index e0a88b4..a6a8102 100644 --- a/src/server/ollama/client.ts +++ b/src/server/ollama/client.ts @@ -50,6 +50,12 @@ export class OllamaUnavailableError extends Error { // ─── Implementation ─────────────────────────────────────────────────────────── +// S3 roadmap batch (2026-05-27): per-call timeouts so a hung Ollama process +// can't stall callers indefinitely. Defaults align with the audit's budgets +// (embed: 60s, chat: 120s). Env-overridable to keep tests fast. +const DEFAULT_EMBED_TIMEOUT_MS = 60_000; +const DEFAULT_CHAT_TIMEOUT_MS = 120_000; + class OllamaClientImpl implements OllamaClient { // baseUrl() is a method (not a stored property) so env-var changes made by // tests via `process.env.SCHOLAR_OLLAMA_URL = ...` take effect at call time. @@ -57,7 +63,17 @@ class OllamaClientImpl implements OllamaClient { return process.env.SCHOLAR_OLLAMA_URL ?? "http://127.0.0.1:11434"; } - private async postJson(path: string, body: unknown): Promise { + private embedTimeoutMs(): number { + const v = process.env.SCHOLAR_OLLAMA_EMBED_TIMEOUT_MS; + return v ? Number(v) : DEFAULT_EMBED_TIMEOUT_MS; + } + + private chatTimeoutMs(): number { + const v = process.env.SCHOLAR_OLLAMA_CHAT_TIMEOUT_MS; + return v ? Number(v) : DEFAULT_CHAT_TIMEOUT_MS; + } + + private async postJson(path: string, body: unknown, timeoutMs: number): Promise { const url = this.baseUrl(); let res: Response; try { @@ -65,10 +81,17 @@ class OllamaClientImpl implements OllamaClient { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { + const e = err as Error; + if (e.name === "TimeoutError") { + throw new OllamaUnavailableError( + `Ollama timed out after ${timeoutMs}ms at ${url}${path}`, + ); + } throw new OllamaUnavailableError( - `cannot reach Ollama at ${url}: ${(err as Error).message}`, + `cannot reach Ollama at ${url}: ${e.message}`, ); } if (!res.ok) { @@ -87,6 +110,7 @@ class OllamaClientImpl implements OllamaClient { const res = await this.postJson<{ embedding?: number[]; embeddings?: number[][] }>( "/api/embeddings", body, + this.embedTimeoutMs(), ); const vec = res.embedding ?? res.embeddings?.[0]; if (!vec || vec.length === 0) { @@ -109,6 +133,7 @@ class OllamaClientImpl implements OllamaClient { const res = await this.postJson<{ message?: { content: string }; response?: string }>( "/api/chat", body, + this.chatTimeoutMs(), ); const content = res.message?.content ?? res.response ?? ""; if (!content) { From eba95b0a0988dcf5ac92045f3f59be29c36e22a6 Mon Sep 17 00:00:00 2001 From: zaynram Date: Wed, 27 May 2026 22:30:26 -0500 Subject: [PATCH 11/33] docs(roadmap): mark S3 landed; link to commit 6dbd990 Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/audits/ROADMAP.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index b48f8ac..a6f28f0 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -38,11 +38,13 @@ Branch: `worktree-pre-v1-roadmap` (S2 commits 2454b4c → 8e204ec; precedes S1 o - [x] **Test** `tests/start-server.test.ts` — fixture stub `build/scholar` binary asserts `--help` reaches the child (stdout marker + exit 0). - [x] **Test** `tests/start-server.test.ts` — same fixture, `--block` mode installs a child SIGINT handler exiting 42; the test sends SIGINT to the parent and asserts exit 42 (not 0). -### S3 — Ollama client timeouts +### S3 — Ollama client timeouts ✅ landed 2026-05-27 -- [ ] **Code** `src/server/ollama/client.ts:60-83`: wrap embed fetch in `AbortSignal.timeout(60_000)`; surface `OllamaUnavailableError` on timeout. -- [ ] **Code** `src/server/ollama/client.ts:85-96`: wrap chat fetch in `AbortSignal.timeout(120_000)`; same error shape. -- [ ] **Test** add timeout tests using a fixture server that hangs past the timeout. +Branch: `worktree-pre-v1-roadmap` (S3 commit 6dbd990). + +- [x] **Code** `src/server/ollama/client.ts` `postJson()` parameterized with `timeoutMs`; `AbortSignal.timeout` wired through; `TimeoutError` mapped to `OllamaUnavailableError`. Defaults: embed 60s, chat 120s. Env-overridable via `SCHOLAR_OLLAMA_{EMBED,CHAT}_TIMEOUT_MS` so tests can use short windows. +- [x] **Code** `embed()` passes `embedTimeoutMs()`; `chat()` passes `chatTimeoutMs()` — both methods (not stored constants) so env-var overrides take effect at call time, mirroring `baseUrl()`. +- [x] **Test** `src/server/ollama/client.test.ts` — two regression tests using a `Bun.serve` fixture whose fetch handler returns a never-resolving promise; env override sets a 250ms timeout; assertion: throws `OllamaUnavailableError` in well under 5s (would hang indefinitely without the fix). Pre-fix the tests deadlock the runner; post-fix they pass in ~0.5s. --- From 7fc166cf8521aa3c42e0c7bf11e56247dae24455 Mon Sep 17 00:00:00 2001 From: zaynram Date: Thu, 28 May 2026 22:53:28 -0500 Subject: [PATCH 12/33] fix(corpus): use argv-form tar to neutralize shell injection (H1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit corpus.export composed `sh -c "tar ... -C \"$(dirname '${src}')\" ..."`, interpolating runtime-root into a shell string. Any quote/backtick/`$()` in the runtime root broke the command — and worse, opened arbitrary execution under operator-controlled state. Switch to argv-form spawn; --zstd is supported by GNU tar ≥1.31 and libarchive ≥3.3.3, so the pipeline-to-zstd is no longer required. Test pins success against a hostile path (`scholar-export-dir"ty`) rather than argv[0] === 'tar', so the implementation can swap to bsdtar later without retest. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/corpus.test.ts | 44 +++++++++++++++++++++++++++++++++ src/server/tools/corpus.ts | 16 ++++++------ 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/src/server/tools/corpus.test.ts b/src/server/tools/corpus.test.ts index 3199c53..4ebcfc4 100644 --- a/src/server/tools/corpus.test.ts +++ b/src/server/tools/corpus.test.ts @@ -255,6 +255,50 @@ test("scholar.dashboard returns structuredContent with view: dashboard", async ( expect(result).toMatchObject({ view: "dashboard" }); }); +// ─── H1: corpus.export argv-only spawn (no shell interpolation) ───────────── + +test("corpus.export survives a runtime-root path containing shell metacharacters", async () => { + // Audit H1: handleExport previously built `sh -c "tar ... | zstd -o ${dest}"` + // with double-quoted interpolated paths. A path containing `"` unbalances + // the shell quoting, so the export either errors (best case) or executes + // injected fragments (worst case). After the fix, `tar --zstd` is invoked + // argv-form and the path is passed literally. + const dirtyRoot = mkdtempSync(join(tmpdir(), 'scholar-export-dir"ty')); + mkdirSync(join(dirtyRoot, "dbs"), { recursive: true }); + const origRoot = process.env.SCHOLAR_RUNTIME_ROOT; + process.env.SCHOLAR_RUNTIME_ROOT = dirtyRoot; + try { + const dirtyConfigDb = openWithPragmas(join(dirtyRoot, "dbs", "scholar-config.db")); + applyMigrations(dirtyConfigDb); + const dirtyBuilt = buildServer({ + runtimeRoot: dirtyRoot, + openConfigDb: () => dirtyConfigDb, + spawnPdfChild: () => ({ + interact: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, + getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, + currentRoots: () => [], + setRoots: async () => {}, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), + isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), + }), + }); + await dirtyBuilt.dispatch("scholar.corpus.create", { + slug: "dirty-export", + display_name: "Dirty Export", + initial_pdf_root: dirtyRoot, + }); + await dirtyBuilt.dispatch("scholar.corpus.activate", { slug: "dirty-export" }); + const result = (await dirtyBuilt.dispatch("scholar.corpus.export", { + slug: "dirty-export", + })) as { exported_to: string }; + expect(existsSync(result.exported_to)).toBe(true); + } finally { + rmSync(dirtyRoot, { recursive: true, force: true }); + if (origRoot === undefined) delete process.env.SCHOLAR_RUNTIME_ROOT; + else process.env.SCHOLAR_RUNTIME_ROOT = origRoot; + } +}); + // ─── posture-B regression guard ────────────────────────────────────────────── test("corpus handlers make no sqlite3-mcp calls (posture-B guard)", async () => { diff --git a/src/server/tools/corpus.ts b/src/server/tools/corpus.ts index 3f81aa6..df203d5 100644 --- a/src/server/tools/corpus.ts +++ b/src/server/tools/corpus.ts @@ -11,7 +11,7 @@ // allow subsequent creates for the same slug without server restart. // - corpus.activate uses a retain-on-success slot (cleared only by reset-init) // so re-activation of an already-open corpus is a fast-path idempotency return. -import { join } from "node:path"; +import { join, dirname, basename } from "node:path"; import { existsSync, unlinkSync, mkdirSync } from "node:fs"; import { sql } from "drizzle-orm"; import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite"; @@ -379,12 +379,14 @@ async function handleExport(args: unknown, ctx: ServerContext): Promise mkdirSync(exportDir, { recursive: true }); const dest = join(exportDir, `${slug}-${ts}.tar.zst`); - // Use bun shell for tar | zstd (bun:sqlite backup API would require DB handle; - // shell approach handles the closed-corpus case without requiring the DB be open). - const { exited, stderr } = Bun.spawn(["sh", "-c", `tar -cf - -C "$(dirname "${src}")" "$(basename "${src}")" | zstd -o "${dest}"`], { - stdout: "ignore", - stderr: "pipe", - }); + // Audit H1: argv-form spawn so paths can't be shell-interpolated. Uses + // `tar --zstd` (GNU tar ≥1.31; bsdtar on macOS) instead of a `tar | zstd` + // pipeline so we don't need a shell at all. The closed-corpus case still + // works — tar reads the DB file directly without needing an open handle. + const { exited, stderr } = Bun.spawn( + ["tar", "--zstd", "-cf", dest, "-C", dirname(src), basename(src)], + { stdout: "ignore", stderr: "pipe" }, + ); const code = await exited; if (code !== 0) { const errMsg = await new Response(stderr).text(); From 6bbb85d67258cf6dd531d51276c9367bb6ad9627 Mon Sep 17 00:00:00 2001 From: zaynram Date: Thu, 28 May 2026 22:53:35 -0500 Subject: [PATCH 13/33] fix(tools): emit structuredContent for view-opener tool results (H2) scholar.paper.show / scholar.corpus.show / scholar.pdf.open returned their {openView: ...} payload as a JSON-stringified text block only. MCP clients following the spec dispatch UI on structuredContent, not on text-block parsing, so the view never opened in compliant hosts. Wrap the result in both content (text) and structuredContent when the tool opted into the view-opener shape (handler return includes `openView`). Non-view tools (e.g. corpus.list) keep the lean text-only envelope. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/registry.test.ts | 95 ++++++++++++++++++++++++++----- src/server/tools/registry.ts | 11 +++- 2 files changed, 91 insertions(+), 15 deletions(-) diff --git a/src/server/tools/registry.test.ts b/src/server/tools/registry.test.ts index 19f7a5d..aefcf5b 100644 --- a/src/server/tools/registry.test.ts +++ b/src/server/tools/registry.test.ts @@ -3,22 +3,18 @@ // Shape-only test: foundation pins the `registerAll(server, ctx) → ToolRegistry` // contract. Stubs are no-ops at cycle 6.1; downstream plans fill bodies and the // registry populates accordingly. +// +// H2 (2026-05-28): added a wrapper-shape test. The MCP wrapper around every +// handler was unconditionally serializing every result into a `text` content +// block, losing the typed view-opener payload that hosts want under +// `structuredContent`. The new test captures the wrapper at registration time +// and asserts it emits `structuredContent` when the handler returns an +// `openView` payload, and keeps the legacy text-only shape otherwise. import { test, expect } from "bun:test"; import { registerAll, type ToolRegistry } from "./registry.ts"; -test("registerAll is a function that takes (server, ctx) and returns a ToolRegistry", () => { - expect(typeof registerAll).toBe("function"); - expect(registerAll.length).toBe(2); -}); - -test("registerAll invokes every tool module's registerTools and returns a Map", () => { - const calls: string[] = []; - const fakeServer = { - registerTool: (name: string) => { - calls.push(name); - }, - } as unknown as Parameters[0]; - const ctx = { +function fakeCtx() { + return { db: undefined, configDb: {} as never, pdf: { @@ -33,7 +29,21 @@ test("registerAll invokes every tool module's registerTools and returns a Map {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }, withCorpus: async (fn: (db: unknown) => unknown) => fn({} as never), } as unknown as Parameters[1]; - const registry: ToolRegistry = registerAll(fakeServer, ctx); +} + +test("registerAll is a function that takes (server, ctx) and returns a ToolRegistry", () => { + expect(typeof registerAll).toBe("function"); + expect(registerAll.length).toBe(2); +}); + +test("registerAll invokes every tool module's registerTools and returns a Map", () => { + const calls: string[] = []; + const fakeServer = { + registerTool: (name: string) => { + calls.push(name); + }, + } as unknown as Parameters[0]; + const registry: ToolRegistry = registerAll(fakeServer, fakeCtx()); expect(registry).toBeInstanceOf(Map); // Downstream plans fill bodies as waves complete; the registry grows accordingly. // After corpus wave 2 (cycle 6.3): corpus + roots tools are registered. @@ -42,3 +52,60 @@ test("registerAll invokes every tool module's registerTools and returns a Map { + // Capture the SDK-facing wrapper functions registered by every tool module. + // The wrapper is what runs when the MCP host invokes a tool; if it doesn't + // promote `openView` into `structuredContent`, the host can never recognize + // the open-view intent (it only sees stringified JSON inside a text block). + const wrappers = new Map Promise>(); + const fakeServer = { + registerTool: ( + name: string, + _def: unknown, + wrapper: (args: unknown) => Promise, + ) => { + wrappers.set(name, wrapper); + }, + } as unknown as Parameters[0]; + registerAll(fakeServer, fakeCtx()); + + // scholar.paper.show returns { openView: { resource, route } } — the + // canonical view-opener shape; wrapper must surface it as structuredContent. + const showWrapper = wrappers.get("scholar.paper.show"); + expect(showWrapper, "scholar.paper.show must be registered").toBeDefined(); + const result = (await showWrapper!({ paper_id: "p1" })) as { + content: Array<{ type: string; text: string }>; + structuredContent?: { openView?: { resource: string; route: string } }; + }; + expect(result.structuredContent).toMatchObject({ + openView: { resource: "ui://scholar/app.html", route: "/paper/p1" }, + }); + // Backwards-compat: the legacy text block stays so hosts that don't read + // structuredContent still get the payload as JSON. + expect(result.content?.[0]?.type).toBe("text"); +}); + +test("MCP wrapper leaves non-view-opener results as text-only", async () => { + const wrappers = new Map Promise>(); + const fakeServer = { + registerTool: ( + name: string, + _def: unknown, + wrapper: (args: unknown) => Promise, + ) => { + wrappers.set(name, wrapper); + }, + } as unknown as Parameters[0]; + registerAll(fakeServer, fakeCtx()); + + // scholar.corpus.list returns a plain array of corpora — no openView. + const listWrapper = wrappers.get("scholar.corpus.list"); + expect(listWrapper).toBeDefined(); + const result = (await listWrapper!({})) as { + content: Array<{ type: string; text: string }>; + structuredContent?: unknown; + }; + expect(result.structuredContent).toBeUndefined(); + expect(result.content?.[0]?.type).toBe("text"); +}); diff --git a/src/server/tools/registry.ts b/src/server/tools/registry.ts index 6e7ba5e..1033845 100644 --- a/src/server/tools/registry.ts +++ b/src/server/tools/registry.ts @@ -208,7 +208,16 @@ export function registerAll(server: McpServer, ctx: ServerContext): ToolRegistry registerTool: (n: string, d: unknown, h: (args: unknown) => Promise) => void; }).registerTool(name, def, async (args: unknown) => { const result = await handler(args, ctx); - return { content: [{ type: "text", text: JSON.stringify(result) }] }; + // Audit H2: view-opener tools return `{ openView: { resource, route } }` + // (papers, digest, prompts, etc.). The MCP host can't recognize the + // open-view intent if we only emit the legacy text-JSON content block. + // Promote the payload to `structuredContent` while keeping `content` for + // hosts that don't read structuredContent. + const text = { content: [{ type: "text", text: JSON.stringify(result) }] }; + if (result && typeof result === "object" && "openView" in result) { + return { ...text, structuredContent: result as Record }; + } + return text; }); }; registerCorpus(server, ctx, register); From d6c5e235ecb96fa9a7ea3dd71f009d172ff40b9e Mon Sep 17 00:00:00 2001 From: zaynram Date: Thu, 28 May 2026 22:53:42 -0500 Subject: [PATCH 14/33] test(papers): seed DB via applyMigrations to eliminate schema drift (H3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit seededDb() hand-rolled the papers/paper_chunks DDL inline. The fixture had silently drifted out of sync with the production schema — missing the `abstract` column among others — so the search/update tests under it could have masked real breakage in the columns they didn't touch. Replace inline DDL with applyMigrations(drizzle(...)). chunk_vec lives in runRawDdl which applyMigrations already invokes, but only after migrate() seeds the empty `settings` table; so we apply, set `settings.chunk_vec.created`, then re-run runRawDdl so chunk_vec materializes for the non-deferred branch. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/papers.test.ts | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/src/server/tools/papers.test.ts b/src/server/tools/papers.test.ts index 22f8805..6e905d0 100644 --- a/src/server/tools/papers.test.ts +++ b/src/server/tools/papers.test.ts @@ -8,6 +8,7 @@ import { test, expect } from "bun:test" import { Database } from "bun:sqlite" import { drizzle } from "drizzle-orm/bun-sqlite" import { searchPapers, updatePaper } from "./papers.ts" +import { applyMigrations } from "#server/db/migrations.ts" import { runRawDdl } from "#server/db/raw-ddl.ts" import { ensureVec0Path } from "%/util" @@ -25,12 +26,20 @@ function deterministicEmbedding(dim: number, input: string): Float32Array { return out } +// H3 (2026-05-28): seededDb now runs the real Drizzle migrations instead of +// hand-rolling DDL that drifted from production schema (the old inline `papers` +// table was missing the `abstract` column, plus a few others). Schema drift +// would silently mask breakage in the actual search/update paths under test. +// chunk_vec lives in runRawDdl, which applyMigrations already invokes — but +// only AFTER migrate() has populated the empty `settings` table. So we apply, +// seed `settings.chunk_vec.created`, then re-run runRawDdl so chunk_vec +// materializes for the non-deferred branch. function seededDb(opts?: { deferred?: boolean }) { const sqlite = new Database(":memory:") sqlite.loadExtension(ensureVec0Path()) - sqlite.run( - `CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`, - ) + sqlite.exec("PRAGMA foreign_keys = ON") + const db = drizzle(sqlite) + applyMigrations(db) if (opts?.deferred) { sqlite.run( `INSERT INTO settings(key,value) VALUES ('chunk_vec.created','false')`, @@ -40,20 +49,7 @@ function seededDb(opts?: { deferred?: boolean }) { ('embed.dim','768'), ('chunk_vec.created','true')`) } - sqlite.run(`CREATE TABLE papers ( - id TEXT PRIMARY KEY, key TEXT NOT NULL UNIQUE, title TEXT NOT NULL, - authors TEXT, status TEXT NOT NULL DEFAULT 'pending', - priority INTEGER NOT NULL DEFAULT 0, - imported_at TEXT NOT NULL, status_touched_at TEXT, - role TEXT, depth TEXT, section TEXT - )`) - sqlite.run(`CREATE TABLE paper_chunks ( - id TEXT PRIMARY KEY, paper_id TEXT NOT NULL, ordinal INTEGER NOT NULL, - text TEXT NOT NULL, embedded_at TEXT - )`) - sqlite.run(`CREATE UNIQUE INDEX paper_chunks_paper_ord_idx - ON paper_chunks(paper_id, ordinal)`) - runRawDdl(drizzle(sqlite)) + runRawDdl(db) return sqlite } From c273a835194e4e319b618869ec984cb481a97328 Mon Sep 17 00:00:00 2001 From: zaynram Date: Thu, 28 May 2026 22:53:48 -0500 Subject: [PATCH 15/33] fix(sqlite-vec): anchor dev vec0 path to import.meta.dir, not cwd (H4) resolveVec0Path's dev fallback was process.cwd(), so any launch that chdir'd away from the repo root (tests, server bootstraps, smoke harnesses) resolved a non-existent path and crashed on vec0 load. Anchor to `import.meta.dir` so the path is a fixed offset from the source file. CLAUDE_PLUGIN_ROOT remains the packaged-binary override. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/db/sqlite-vec.test.ts | 21 +++++++++++++++++++++ src/server/db/sqlite-vec.ts | 9 +++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/server/db/sqlite-vec.test.ts b/src/server/db/sqlite-vec.test.ts index 61bf561..fe53c47 100644 --- a/src/server/db/sqlite-vec.test.ts +++ b/src/server/db/sqlite-vec.test.ts @@ -3,6 +3,7 @@ // Resolves the absolute path to the bundled vec0 shared library. Loading is the // caller's responsibility — see loadVecAndProbeDim in primitives.ts. import { test, expect } from "bun:test" +import { tmpdir } from "node:os" import { resolveVec0Path } from "./sqlite-vec.ts" test("resolveVec0Path returns absolute path with platform-correct extension", () => { @@ -21,3 +22,23 @@ test("resolveVec0Path honors SCHOLAR_VEC0_PATH override when set", () => { delete process.env.SCHOLAR_VEC0_PATH } }) + +test("resolveVec0Path is independent of process.cwd() in dev mode", () => { + // Audit H4: the dev fallback used to be process.cwd(), which meant tests or + // server launches from anywhere other than the repo root resolved the wrong + // (non-existent) path. The fix anchors to `import.meta.dir` so the path + // depends on the source-file location, not the launch directory. + delete process.env.SCHOLAR_VEC0_PATH + const origPluginRoot = process.env.CLAUDE_PLUGIN_ROOT + delete process.env.CLAUDE_PLUGIN_ROOT + const origCwd = process.cwd() + try { + const before = resolveVec0Path() + process.chdir(tmpdir()) + const after = resolveVec0Path() + expect(after).toBe(before) + } finally { + process.chdir(origCwd) + if (origPluginRoot !== undefined) process.env.CLAUDE_PLUGIN_ROOT = origPluginRoot + } +}) diff --git a/src/server/db/sqlite-vec.ts b/src/server/db/sqlite-vec.ts index a278dd0..10aef63 100644 --- a/src/server/db/sqlite-vec.ts +++ b/src/server/db/sqlite-vec.ts @@ -20,14 +20,15 @@ export function getVec0Extension() { * 1. SCHOLAR_VEC0_PATH env override (test/CI/operator escape hatch) * 2. ${CLAUDE_PLUGIN_ROOT}/build/vendor/sqlite-vec/vec0.{dll,dylib,so} (packaged) * 3. /build/vendor/sqlite-vec/vec0.{dll,dylib,so} (dev) + * + * Audit H4: dev mode anchors to `import.meta.dir` (src/server/db/) so the + * path doesn't depend on where the process was launched from. CLAUDE_PLUGIN_ROOT + * is the production fallback the packaged binary sets; keep that branch. */ export const resolveVec0Path = (): string => process.env.SCHOLAR_VEC0_PATH ?? join( - // `process.env.__dirname` was a CommonJS-ism never actually set by Bun or - // Node — it always fell through to cwd(). Drop it; rely on cwd() in dev - // and CLAUDE_PLUGIN_ROOT in the packaged binary. - process.env.CLAUDE_PLUGIN_ROOT ?? process.cwd(), + process.env.CLAUDE_PLUGIN_ROOT ?? join(import.meta.dir, "..", "..", ".."), "build", "vendor", "sqlite-vec", From d071bb3fe77f662d40cf1bcc7599e0a98ddff672 Mon Sep 17 00:00:00 2001 From: zaynram Date: Thu, 28 May 2026 22:53:55 -0500 Subject: [PATCH 16/33] fix(migrations): assert PRAGMA foreign_keys=ON before migrate (H5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PRAGMA foreign_keys is per-connection and defaults to OFF on every fresh bun:sqlite Database. The §8 schema relies on onDelete: "cascade" clauses for data integrity. If any caller bypassed openWithPragmas (or future code ever forgot the pragma), migrate() succeeded silently and the cascades were inert at runtime — orphan rows would accumulate without warning. Fail loud: at the start of applyMigrations, query PRAGMA foreign_keys and throw if it's not 1. The error names openWithPragmas as the canonical constructor, so the fix is obvious from the message alone. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/db/migrations.test.ts | 16 +++++++++++++++- src/server/db/migrations.ts | 11 +++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/server/db/migrations.test.ts b/src/server/db/migrations.test.ts index 511cf56..1e449f6 100644 --- a/src/server/db/migrations.test.ts +++ b/src/server/db/migrations.test.ts @@ -4,10 +4,12 @@ // distinct files map to distinct databases. The full applyMigrations end-to-end // path is exercised by schema.test.ts (Task 1.4). import { test, expect, afterEach } from "bun:test"; +import { Database } from "bun:sqlite"; +import { drizzle } from "drizzle-orm/bun-sqlite"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { openWithPragmas } from "./migrations.ts"; +import { applyMigrations, openWithPragmas } from "./migrations.ts"; import { rawClient } from "./raw-client.ts"; let dir: string | undefined; @@ -28,3 +30,15 @@ test("openWithPragmas opens distinct paths to distinct files", () => { // b must not see the table — distinct files. expect(() => rawClient(b).query("SELECT * FROM t").all()).toThrow(); }); + +test("applyMigrations refuses to run when PRAGMA foreign_keys is OFF", () => { + // Audit H5: §8 onDelete: "cascade" clauses are load-bearing for data + // integrity. If a caller forgets to open through openWithPragmas (or otherwise + // forgets to set the pragma), migrate() silently runs and the cascades are + // inert. Pin the precondition explicitly so the mistake fails loud at migrate + // time, not at the first orphan-row bug in production. + const sqlite = new Database(":memory:"); + // PRAGMA foreign_keys defaults to OFF on every fresh connection. + const db = drizzle(sqlite); + expect(() => applyMigrations(db)).toThrow(/foreign_keys/i); +}); diff --git a/src/server/db/migrations.ts b/src/server/db/migrations.ts index fbee5a9..bb46f48 100644 --- a/src/server/db/migrations.ts +++ b/src/server/db/migrations.ts @@ -40,6 +40,17 @@ export function applyMigrations( db: BunSQLiteDatabase, migrationsFolder: string = join(import.meta.dir, "migrations"), ): void { + // Audit H5: §8 cascade clauses are load-bearing for data integrity, and + // PRAGMA foreign_keys is per-connection (defaults to OFF on every fresh + // bun:sqlite Database). Fail loud here rather than silently letting orphans + // accumulate later. + const fk = rawClient(db).query("PRAGMA foreign_keys").get() as { foreign_keys: number }; + if (fk.foreign_keys !== 1) { + throw new Error( + "applyMigrations: PRAGMA foreign_keys must be ON before migrate (got " + + `${fk.foreign_keys}); construct the DB via openWithPragmas().`, + ); + } // Compatibility guard runs BEFORE migrate() so a newer-schema DB aborts // before any modification. const recorded = readMaxAppliedId(db); From 3348b23b69c5deb9f9c8d8a06b0ae134010c44b8 Mon Sep 17 00:00:00 2001 From: zaynram Date: Thu, 28 May 2026 22:54:46 -0500 Subject: [PATCH 17/33] docs(roadmap): mark H1-H5 landed; link to commits Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/audits/ROADMAP.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index a6f28f0..c4d46c4 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -48,17 +48,19 @@ Branch: `worktree-pre-v1-roadmap` (S3 commit 6dbd990). --- -## High-priority batch (H1–H5) — land before personal-use ship +## High-priority batch (H1–H5) — land before personal-use ship ✅ landed 2026-05-28 -| ID | Defect | File:line | Fix | -|---|---|---|---| -| H1 | `corpus.export` shells `sh -c` with interpolation | `corpus.ts:384-387` | Replace with `Bun.spawn([cp, src, dest])` direct argv | -| H2 | View-opener tools wrap structured response into `text` block | `registry.ts:168-173` | Detect `result.openView` and emit `structuredContent` | -| H3 | `papers.test.ts` divergent inline DDL hides schema drift | `papers.test.ts:43-49` | Use `applyMigrations` against in-memory DB; delete inline DDL | -| H4 | `resolveVec0Path` uses `process.cwd()` | `sqlite-vec.ts:24-35` | Use `import.meta.dir` with relative traversal | -| H5 | No PRAGMA assertion in `applyMigrations` | `migrations.ts:39-55` | Assert `PRAGMA foreign_keys` is on before migrate | +Branch: `worktree-pre-v1-roadmap`. All five items landed in separate TDD cycles, one commit per H-item. + +| ID | Defect | File:line | Fix | Commit | +|---|---|---|---|---| +| H1 | `corpus.export` shells `sh -c` with interpolation | `corpus.ts:384-387` | argv-form `Bun.spawn(["tar", "--zstd", ...])` neutralizes shell metachars in runtime root | `7fc166c` | +| H2 | View-opener tools wrap structured response into `text` block | `registry.ts:168-173` | Detect `result.openView`; emit both `content` (text) and `structuredContent` envelope | `6bbb85d` | +| H3 | `papers.test.ts` divergent inline DDL hides schema drift | `papers.test.ts:43-49` | `seededDb()` uses `applyMigrations` + post-`settings` `runRawDdl` re-run for chunk_vec | `d6c5e23` | +| H4 | `resolveVec0Path` uses `process.cwd()` | `sqlite-vec.ts:24-35` | Anchor dev fallback to `import.meta.dir` (CLAUDE_PLUGIN_ROOT still wins for packaged) | `c273a83` | +| H5 | No PRAGMA assertion in `applyMigrations` | `migrations.ts:39-55` | Throw at top of `applyMigrations` if `PRAGMA foreign_keys` ≠ 1; names `openWithPragmas` in error | `d071bb3` | -Each H-item: one TDD cycle, regression test mocks at the layer above the bug (not the layer containing the bug). +Each H-item shipped with a regression test that fails pre-fix and passes post-fix. H1's test pins against a hostile runtime root containing a `"` rather than asserting on argv[0] so the implementation can swap tar binaries later without retest. Suite: 274 pass / 8 skip / 8 unchanged pre-existing failures (UI bundles + pdf.test.ts pdfViews — out of H scope). Typecheck clean. --- From d101adb8094042547ad4f193b4f42605b6f4e230 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:00:41 -0500 Subject: [PATCH 18/33] fix(primitives): wrap realpathSync(root) in PathEscapeError (M9) resolveUnderRoot's leaf-stat is guarded but realpathSync(root) was not, so a missing or unreadable root path leaked raw ENOENT to callers that only catch PathEscapeError. The most common trigger (per the audit) is a backup destination resolved before the corpus root directory has been created. Test had to be carefully constructed: passing a non-existent leaf hits the existing leaf-stat catch and masks the bug. The regression test uses a real leaf file and a missing root so the unguarded realpathSync(root) is the first thing that fails. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/ingest/primitives.test.ts | 18 ++++++++++++++++++ src/server/ingest/primitives.ts | 9 ++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/server/ingest/primitives.test.ts b/src/server/ingest/primitives.test.ts index e72844c..5f69e74 100644 --- a/src/server/ingest/primitives.test.ts +++ b/src/server/ingest/primitives.test.ts @@ -64,6 +64,24 @@ test("resolveUnderRoot throws PathEscapeError on parent traversal", () => { } }); +test("resolveUnderRoot wraps a missing root in PathEscapeError (M9)", () => { + // Audit M9: realpathSync(root) was unguarded, so a non-existent root path + // leaked a raw ENOENT past callers that expect to catch only PathEscapeError + // (the contract documented at the function header). Common trigger: backup + // destination resolved before the corpus root directory has been created. + // Construct a case the existing leaf-stat catch can't mask: real leaf, + // missing root. + const leafDir = mkdtempSync(join(tmpdir(), "scholar-rur-realleaf-")); + const leaf = join(leafDir, "ok.txt"); + writeFileSync(leaf, "x"); + const missingRoot = join(tmpdir(), `scholar-rur-missing-${process.pid}-${Date.now()}`); + try { + expect(() => resolveUnderRoot(leaf, missingRoot)).toThrow(PathEscapeError); + } finally { + rmSync(leafDir, { recursive: true, force: true }); + } +}); + test("resolveUnderRoot throws PathEscapeError on symlink leaf", () => { if (process.platform === "win32") return; // symlinks require admin on Windows const root = mkdtempSync(join(tmpdir(), "scholar-rur-")); diff --git a/src/server/ingest/primitives.ts b/src/server/ingest/primitives.ts index aac7b54..fae2bdc 100644 --- a/src/server/ingest/primitives.ts +++ b/src/server/ingest/primitives.ts @@ -82,7 +82,14 @@ export function resolveUnderRoot(p: string, root: string): string { } if (leafStat.isSymbolicLink()) throw new PathEscapeError(`symlink leaf rejected: ${resolved}`); const real = realpathSync(resolved); - const realRoot = realpathSync(root); + // Audit M9: realpathSync(root) was unguarded, so a missing or unreadable + // root leaked a raw ENOENT to callers that only catch PathEscapeError. + let realRoot; + try { + realRoot = realpathSync(root); + } catch { + throw new PathEscapeError(`root unresolvable: ${root}`); + } if (!real.startsWith(realRoot + pathSep) || real === realRoot) { throw new PathEscapeError(`escapes root ${realRoot}: ${real}`); } From b31c7a1b90ba521b99fe756dfe75cde2ea7fd17f Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:01:44 -0500 Subject: [PATCH 19/33] fix(runtime-config): fsync parent directory after rename (M1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POSIX rename is atomic for file content but the directory entry isn't durable until the parent directory is itself fsync'd. Without this step, an OS-crash immediately after the rename can lose the new directory entry — the file content is on disk but the dir-entry points at the prior inode. Open the runtime root with O_RDONLY|O_DIRECTORY, sync the descriptor, close it. Linux/POSIX only: Win32 has no equivalent directory-fsync, so the branch is gated on platform. Regression test spies on fs.promises.open and asserts at least one post- write open call with O_DIRECTORY flag against the runtime root. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/util/runtime-config.test.ts | 27 ++++++++++++++++++++++++-- src/server/util/runtime-config.ts | 14 ++++++++++++- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/server/util/runtime-config.test.ts b/src/server/util/runtime-config.test.ts index 3c169dd..a7ac1a6 100644 --- a/src/server/util/runtime-config.test.ts +++ b/src/server/util/runtime-config.test.ts @@ -3,8 +3,9 @@ // Tests for the atomic JSON config persistence helpers: writeRuntimeConfig + // readRuntimeConfig. Atomicity invariant: no partial-write tmp file survives // a successful write. -import { test, expect, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync } from "node:fs"; +import { test, expect, afterEach, spyOn } from "bun:test"; +import { mkdtempSync, rmSync, readdirSync, constants as fsConstants } from "node:fs"; +import * as fsp from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { writeRuntimeConfig, readRuntimeConfig } from "./runtime-config.ts"; @@ -67,6 +68,28 @@ test("sequential overwrites: last writer wins", async () => { expect(result).toEqual({ activeCorpusId: "second" }); }); +test("writeRuntimeConfig fsyncs the parent directory after rename (M1)", async () => { + // Audit M1: POSIX rename is atomic for content but the directory entry isn't + // durable until the parent directory is fsync'd. Without this, an OS-crash + // immediately after rename can lose the new entry. Verified via a spy that + // captures the post-rename directory-handle open + sync. + if (process.platform === "win32") return; // no directory fsync on Win32 + const runtimeRoot = makeTempDir(); + const openSpy = spyOn(fsp, "open"); + try { + await writeRuntimeConfig({ activeCorpusId: "fsync-me" }, runtimeRoot); + const dirOpens = openSpy.mock.calls.filter( + ([path, flags]) => + path === runtimeRoot && + typeof flags === "number" && + (flags & fsConstants.O_DIRECTORY) !== 0, + ); + expect(dirOpens.length).toBeGreaterThanOrEqual(1); + } finally { + openSpy.mockRestore(); + } +}); + test("null activeCorpusId round-trips as null (not missing key)", async () => { const runtimeRoot = makeTempDir(); await writeRuntimeConfig({ activeCorpusId: null }, runtimeRoot); diff --git a/src/server/util/runtime-config.ts b/src/server/util/runtime-config.ts index 52f012f..d1a7715 100644 --- a/src/server/util/runtime-config.ts +++ b/src/server/util/runtime-config.ts @@ -7,7 +7,7 @@ // new one. Implementation: write to a tmp file, fdatasync the tmp's contents, // rename over the target (POSIX rename is atomic for same-filesystem targets). import { open, mkdir, rename, readFile, unlink } from "node:fs/promises"; -import { existsSync } from "node:fs"; +import { existsSync, constants as fsConstants } from "node:fs"; import { join } from "node:path"; export interface RuntimeConfig { @@ -46,6 +46,18 @@ export async function writeRuntimeConfig(data: RuntimeConfig, runtimeRoot: strin } throw err; } + // Audit M1: rename atomicity guarantees content-on-target, but the new + // directory entry isn't durable until the parent dir is fsync'd. Without + // this, an OS-crash between rename and the next sync may leave the entry + // pointing at the prior inode. Linux only — Win32 has no directory fsync. + if (process.platform !== "win32") { + const dir = await open(runtimeRoot, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY); + try { + await dir.sync(); + } finally { + await dir.close(); + } + } } export async function readRuntimeConfig(runtimeRoot: string): Promise { From 1d4c294a3f5083bb8145e351ae7e26bdfffb1bcb Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:02:57 -0500 Subject: [PATCH 20/33] fix(migrations): narrow countBundledMigrations catch to absent-folder only (M7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The broad try/catch turned every scan error into "0 bundled migrations" — defeating the newer-plugin guard for any failure mode (permission, ENOTDIR, etc.) other than the load-bearing "folder absent" case it was meant to protect (foundation ships an empty journal pre-Task-1.4). Replace with an explicit existsSync check; let scan errors propagate so the caller sees a real exception instead of a silently-wrong count. Function exported so the narrowing can be regression-tested directly: - file-as-folder path now throws ENOTDIR (previously: returned 0). - missing-folder path still returns 0 (the load-bearing case is preserved). Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/db/migrations.test.ts | 21 ++++++++++++++++++++- src/server/db/migrations.ts | 24 +++++++++++++++--------- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/server/db/migrations.test.ts b/src/server/db/migrations.test.ts index 1e449f6..c752f0d 100644 --- a/src/server/db/migrations.test.ts +++ b/src/server/db/migrations.test.ts @@ -9,7 +9,8 @@ import { drizzle } from "drizzle-orm/bun-sqlite"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { applyMigrations, openWithPragmas } from "./migrations.ts"; +import { writeFileSync } from "node:fs"; +import { applyMigrations, openWithPragmas, countBundledMigrations } from "./migrations.ts"; import { rawClient } from "./raw-client.ts"; let dir: string | undefined; @@ -31,6 +32,24 @@ test("openWithPragmas opens distinct paths to distinct files", () => { expect(() => rawClient(b).query("SELECT * FROM t").all()).toThrow(); }); +test("countBundledMigrations returns 0 for a missing folder (M7)", () => { + // Empty-folder / first-open case must keep returning 0 — that's the + // load-bearing path the broad catch was protecting. + const missing = join(tmpdir(), `scholar-mig-missing-${process.pid}-${Date.now()}`); + expect(countBundledMigrations(missing)).toBe(0); +}); + +test("countBundledMigrations surfaces non-ENOENT errors instead of returning 0 (M7)", () => { + // Audit M7: the old broad catch silently turned any FS error (permission, + // ENOTDIR, etc.) into "0 bundled migrations", defeating the newer-plugin + // guard for any failure mode other than "folder absent". Verify a file + // path passed where a folder is expected throws rather than counting 0. + dir = mkdtempSync(join(tmpdir(), "scholar-mig-")); + const filePath = join(dir, "not-a-folder"); + writeFileSync(filePath, "x"); + expect(() => countBundledMigrations(filePath)).toThrow(); +}); + test("applyMigrations refuses to run when PRAGMA foreign_keys is OFF", () => { // Audit H5: §8 onDelete: "cascade" clauses are load-bearing for data // integrity. If a caller forgets to open through openWithPragmas (or otherwise diff --git a/src/server/db/migrations.ts b/src/server/db/migrations.ts index bb46f48..5619fbe 100644 --- a/src/server/db/migrations.ts +++ b/src/server/db/migrations.ts @@ -6,6 +6,7 @@ import { Database } from "bun:sqlite"; import { drizzle, type BunSQLiteDatabase } from "drizzle-orm/bun-sqlite"; import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import { existsSync } from "node:fs"; import { join } from "node:path"; import { runRawDdl } from "./raw-ddl.ts"; import { rawClient } from "./raw-client.ts"; @@ -76,13 +77,18 @@ function readMaxAppliedId(db: BunSQLiteDatabase): number | null { } } -function countBundledMigrations(folder: string): number { - // Count files matching NNNN_*.sql in folder. Foundation ships an empty journal - // initially (no migrations until schema lands in Task 1.4); count returns 0. - // Drizzle migrate() handles the empty-journal case without error. - try { - return Array.from(new Bun.Glob("*.sql").scanSync({ cwd: folder })).length; - } catch { - return 0; - } +/** + * Counts files matching NNNN_*.sql in `folder`. Foundation ships an empty + * journal initially (no migrations until schema lands in Task 1.4); count + * returns 0. Drizzle migrate() handles the empty-journal case without error. + * + * Audit M7: the previous broad catch silently turned ANY scan error into 0, + * which would defeat the newer-plugin guard on permission/ENOTDIR failures. + * The only "expected" zero case is folder-absent; let everything else throw. + * + * Exported for direct testability of the M7 narrowing. + */ +export function countBundledMigrations(folder: string): number { + if (!existsSync(folder)) return 0; + return Array.from(new Bun.Glob("*.sql").scanSync({ cwd: folder })).length; } From 597306022cec5248074d7707631e688b98eff010 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:03:39 -0500 Subject: [PATCH 21/33] =?UTF-8?q?test(annotations):=20pin=20phase-2=20thro?= =?UTF-8?q?w=20=E2=86=92=20row=20persists=20=E2=86=92=20retry=20idempotent?= =?UTF-8?q?=20(M8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit §13 v1.1's "write-then-push" contract guarantees that a pdf.interact failure leaves the DB row intact and re-pushable. The constraint was implicit in the natural code flow; this commit makes it an explicit regression. Pattern: dispatch upsert with an interactImpl that throws on first call, verify the rejection, then read the row directly from the DB and confirm its id/body. Retry the upsert with the captured id and verify the existing- id branch emits update_annotations (not a second add_annotations). No source changes — the current implementation already honors the contract. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/annotations.test.ts | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/server/tools/annotations.test.ts b/src/server/tools/annotations.test.ts index 11219fa..cc0576e 100644 --- a/src/server/tools/annotations.test.ts +++ b/src/server/tools/annotations.test.ts @@ -282,6 +282,52 @@ test("upsert update: same id, different body → updates row + pushes update_ann expect(findInteract("add_annotations")).toHaveLength(1); }); +// ============================================================================= +// M8 — phase-2 (push) throw leaves a re-pushable dirty row +// ============================================================================= + +test("upsert: push failure leaves DB row intact; retry with same id is idempotent (M8)", async () => { + // Audit M8 / §13 v1.1 "write-then-push": the DB write commits synchronously + // before the await for pdf.interact resolves, so a push failure leaves a + // dirty-but-recoverable row. The user re-invokes upsert with the captured id + // and the operation is idempotent — the same id round-trips through the + // update branch and emits update_annotations (not a second add). + let interactCallsObserved = 0; + interactImpl = async () => { + interactCallsObserved += 1; + if (interactCallsObserved === 1) throw new Error("pdf viewer push failed"); + return null; + }; + + await expect( + dispatch("scholar.annotations.upsert", { + paper_id: TEST_PAPER, + body: "first attempt", + }), + ).rejects.toThrow(/push failed/); + + // Phase-1 write committed despite the phase-2 throw — DB row persists. + const dirty = rawClient(built.ctx.db!) + .query("SELECT id, body, source FROM annotations WHERE paper_id = ?") + .get(TEST_PAPER) as { id: string; body: string; source: string }; + expect(dirty.id).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/); + expect(dirty.body).toBe("first attempt"); + + // The first push call was attempted (and threw). + expect(findInteract("add_annotations")).toHaveLength(1); + + // Retry with same id: idempotent on the existing-id path → emits update_annotations, + // not a second add_annotations. + const retried = await dispatch("scholar.annotations.upsert", { + id: dirty.id, + paper_id: TEST_PAPER, + body: "first attempt", + }) as { id: string }; + expect(retried.id).toBe(dirty.id); + expect(findInteract("update_annotations")).toHaveLength(1); + expect(findInteract("add_annotations")).toHaveLength(1); +}); + // ============================================================================= // delete: soft-delete + remove_annotations push (no tombstone-table writes under v1.1) // ============================================================================= From e351c11421c03135445cbd44b97610b66c317448 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:06:14 -0500 Subject: [PATCH 22/33] fix(vec): wrap Float32Array bind sites in toTightFloat32 (M3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bun:sqlite serializes the underlying ArrayBuffer for typed-array blob parameters. Today's Bun respects byteOffset + byteLength so view-over- larger-buffer inputs bind correctly — but ctx.embed is test-injectable and future driver swaps may not preserve that invariant. The audit flagged this defensively (confidence 60). Add toTightFloat32 in sqlite-vec.ts: identity-returns tightly-packed inputs (zero-copy fast path), Float32Array.from-copies views over larger buffers. Wire it into both bind sites: - papers.ts:122 — search query vector - pdf.ts:210 — chunk_vec upsert during refresh Tests: - unit: toTightFloat32 identity vs copy paths. - integration: searchPapers with an injected embed that returns a view at non-zero offset of a larger buffer still picks the right paper. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/db/sqlite-vec.test.ts | 24 +++++++++++++++++++- src/server/db/sqlite-vec.ts | 16 ++++++++++++++ src/server/tools/papers.test.ts | 38 ++++++++++++++++++++++++++++++++ src/server/tools/papers.ts | 7 +++++- src/server/tools/pdf.ts | 4 +++- 5 files changed, 86 insertions(+), 3 deletions(-) diff --git a/src/server/db/sqlite-vec.test.ts b/src/server/db/sqlite-vec.test.ts index fe53c47..b019413 100644 --- a/src/server/db/sqlite-vec.test.ts +++ b/src/server/db/sqlite-vec.test.ts @@ -4,7 +4,7 @@ // caller's responsibility — see loadVecAndProbeDim in primitives.ts. import { test, expect } from "bun:test" import { tmpdir } from "node:os" -import { resolveVec0Path } from "./sqlite-vec.ts" +import { resolveVec0Path, toTightFloat32 } from "./sqlite-vec.ts" test("resolveVec0Path returns absolute path with platform-correct extension", () => { const p = resolveVec0Path() @@ -42,3 +42,25 @@ test("resolveVec0Path is independent of process.cwd() in dev mode", () => { if (origPluginRoot !== undefined) process.env.CLAUDE_PLUGIN_ROOT = origPluginRoot } }) + +test("toTightFloat32 returns tightly-packed input as-is (no copy) (M3)", () => { + const tight = new Float32Array(4) + tight[0] = 1 + expect(toTightFloat32(tight)).toBe(tight) // identity — no copy +}) + +test("toTightFloat32 copies view-over-larger-buffer into a fresh array (M3)", () => { + // Audit M3: bun:sqlite binds the underlying ArrayBuffer for typed-array blobs, + // so a view that's a slice of a larger buffer would otherwise bind the wrong + // bytes. Verify the helper detects this and rebuilds a tight view. + const big = new ArrayBuffer(16 * 4) // 16 floats backing + const view = new Float32Array(big, 4 * 4, 4) // 4 floats starting at offset 16 bytes + view[0] = 9 + view[1] = 8 + view[2] = 7 + view[3] = 6 + const tight = toTightFloat32(view) + expect(tight).not.toBe(view) + expect(tight.buffer.byteLength).toBe(tight.byteLength) // tightly packed now + expect(Array.from(tight)).toEqual([9, 8, 7, 6]) +}) diff --git a/src/server/db/sqlite-vec.ts b/src/server/db/sqlite-vec.ts index 10aef63..5d6de93 100644 --- a/src/server/db/sqlite-vec.ts +++ b/src/server/db/sqlite-vec.ts @@ -34,3 +34,19 @@ export const resolveVec0Path = (): string => "sqlite-vec", `vec0.${getVec0Extension()}`, ) + +/** + * Normalize a Float32Array for safe bun:sqlite blob binding to vec0. + * + * Audit M3: bun:sqlite serializes the underlying ArrayBuffer for typed-array + * blob parameters. For a sliced Float32Array (`new Float32Array(buf, offset, n)`) + * the buffer includes bytes outside the view, silently corrupting the bound + * vector. The defensive contract is "always pass a tightly-packed view"; + * this helper enforces it at the bind site without an unconditional copy. + * + * Fast path: byteLength matches the buffer's byteLength → no copy. + * Slow path: any view-over-larger-buffer → `Float32Array.from(...)` copies. + */ +export function toTightFloat32(arr: Float32Array): Float32Array { + return arr.buffer.byteLength === arr.byteLength ? arr : Float32Array.from(arr) +} diff --git a/src/server/tools/papers.test.ts b/src/server/tools/papers.test.ts index 6e905d0..74decad 100644 --- a/src/server/tools/papers.test.ts +++ b/src/server/tools/papers.test.ts @@ -108,6 +108,44 @@ test("hybrid search: returns lexical + semantic hits ranked via RRF (k=60)", asy expect(result.hits.map((h) => h.id)).toContain("p1") }) +test("hybrid search: tolerates an embed that returns a view-over-larger-buffer (M3)", async () => { + // Audit M3: ctx.embed is test-injectable, so future embed providers may + // return Float32Array views over a larger backing buffer. searchPapers + // wraps qvec in toTightFloat32 at the bind site; verify the search still + // converges on the correct paper. (Today's bun:sqlite respects byteOffset + // + byteLength, so this test is defense-in-depth evidence of the contract.) + const sqlite = seededDb() + sqlite.run(`INSERT INTO papers(id,key,title,imported_at) VALUES + ('p1','smith2024','Scaling laws','2026-01-01T00:00:00.000Z'), + ('p2','jones2024','Architecture search','2026-01-01T00:00:00.000Z')`) + sqlite.run(`INSERT INTO paper_chunks(id,paper_id,ordinal,text,embedded_at) VALUES + ('c1','p1',0,'Scaling laws describe model capacity','2026-01-01T00:00:00.000Z'), + ('c2','p2',0,'NAS finds good architectures','2026-01-01T00:00:00.000Z')`) + for (const [id, txt] of [ + ["c1", "Scaling laws describe model capacity"], + ["c2", "NAS finds good architectures"], + ] as const) { + sqlite + .prepare(`INSERT INTO chunk_vec(chunk_id, embedding) VALUES (?, ?)`) + .run(id, deterministicEmbedding(768, txt)) + } + + // Inject an embed that returns a view positioned at a non-zero offset of a + // larger backing buffer. + const ctx = fakeCtx(sqlite) as unknown as { embed: (m: string, p: string) => Promise } + ctx.embed = async (_m, p) => { + const dim = 768 + const tight = deterministicEmbedding(dim, p) + const big = new ArrayBuffer((dim + 8) * 4) + const view = new Float32Array(big, 4 * 4, dim) // offset 16 bytes into a larger buffer + view.set(tight) + return view + } + + const result = await searchPapers(ctx as unknown as Parameters[0], { q: "Scaling laws describe model capacity" }) + expect(result.hits[0]!.id).toBe("p1") +}) + test("hybrid search: degrades to lexical-only when chunk_vec is deferred (still_indexing=true)", async () => { const sqlite = seededDb({ deferred: true }) sqlite.run(`INSERT INTO papers(id,key,title,imported_at) VALUES diff --git a/src/server/tools/papers.ts b/src/server/tools/papers.ts index 97c5f93..51a0116 100644 --- a/src/server/tools/papers.ts +++ b/src/server/tools/papers.ts @@ -21,6 +21,7 @@ import { sql } from "drizzle-orm"; import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite"; import { z } from "zod"; import { rawClient } from "../db/raw-client.ts"; +import { toTightFloat32 } from "../db/sqlite-vec.ts"; import { nowIso } from "../db/nowIso.ts"; import { ollama, @@ -111,7 +112,11 @@ export async function searchPapers( if (semanticOn) { const embed = ctx.embed ?? ((m: string, p: string) => ollama.embed(m, p)); try { - const qvec = await embed(DEFAULT_EMBED_MODEL, args.q); + // Audit M3: normalize a possibly-view embedding to a tightly-packed + // Float32Array at the bind site (defense-in-depth — bun:sqlite handles + // sliced views correctly today, but ctx.embed is test-injectable and + // future driver swaps may not). + const qvec = toTightFloat32(await embed(DEFAULT_EMBED_MODEL, args.q)); const vecRows = raw.prepare( `SELECT pc.paper_id AS paper_id, vec_distance_cosine(cv.embedding, ?) AS d diff --git a/src/server/tools/pdf.ts b/src/server/tools/pdf.ts index 98f1752..31a7710 100644 --- a/src/server/tools/pdf.ts +++ b/src/server/tools/pdf.ts @@ -41,6 +41,7 @@ import { z } from "zod"; import { rawClient } from "../db/raw-client.ts"; import { nowIso, ulid } from "../db/nowIso.ts"; import { runRawDdl } from "../db/raw-ddl.ts"; +import { toTightFloat32 } from "../db/sqlite-vec.ts"; import { chunkText } from "../extraction/chunker.ts"; import { ollama, @@ -207,7 +208,8 @@ export async function refreshExtraction( `paper_chunks UPSERT returned no row for ordinal ${chunk.ordinal}`, ); } - upsertVec.run(row.id, embeddings[i]!); + // Audit M3: defense-in-depth — see toTightFloat32 docstring. + upsertVec.run(row.id, toTightFloat32(embeddings[i]!)); written += 1; embeddingsPersisted += 1; } From 536ab981c74bbfc652bc7ccb483721f064236866 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:09:10 -0500 Subject: [PATCH 23/33] fix(raw-ddl): align embedDim reader with canonical JSON convention (M4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pdf.ts:materializeChunkVec writes settings.embed.dim via JSON.stringify(num) and ConfigAccessor.get reads via JSON.parse. The raw-ddl embedDim reader, however, used Number(raw) — which accepts non-JSON forms like "0x300" (= 768) that the canonical reader rejects. Two readers, two contracts, same table; the audit (finding #14, M4) called this out as a future-regression invitation. Switch to a JSON.parse + typeof === "number" guard with a try/catch fallback to null for non-JSON values. Regression test seeds embed.dim with "0x300" (legal under Number, illegal under JSON.parse) and asserts chunk_vec is NOT created — previously the lenient parse would have allowed it. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/db/raw-ddl.test.ts | 18 ++++++++++++++++++ src/server/db/raw-ddl.ts | 13 +++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/server/db/raw-ddl.test.ts b/src/server/db/raw-ddl.test.ts index e8af901..d982214 100644 --- a/src/server/db/raw-ddl.test.ts +++ b/src/server/db/raw-ddl.test.ts @@ -74,6 +74,24 @@ test("runRawDdl: creates chunk_vec when settings.embed.dim is set and chunk_vec. expect(tables.map((t) => t.name)).toContain("chunk_vec") }) +test("runRawDdl: embed.dim is parsed as JSON (rejects hex/non-JSON forms) (M4)", () => { + // Audit M4 / finding #14: pdf.ts:materializeChunkVec writes embed.dim via + // JSON.stringify(number); the consuming reader in raw-ddl.ts:embedDim used + // Number(raw), which accepts non-JSON forms like "0x300" (Number = 768) + // and would silently honor a value that the canonical ConfigAccessor.get + // (JSON.parse) would reject. Pin the JSON-only contract: hex-formatted + // values must NOT trigger chunk_vec creation. + const { sqlite, db } = freshExtDb() + db.run(sql`INSERT INTO settings(key,value) VALUES + ('embed.dim','0x300'), + ('chunk_vec.created','true')`) + runRawDdl(db) + const has = sqlite + .query("SELECT 1 FROM sqlite_master WHERE name = 'chunk_vec'") + .get() + expect(has).toBeNull() +}) + test("runRawDdl: skips chunk_vec when settings.chunk_vec.created='false' (deferred)", () => { const { sqlite, db } = freshExtDb() db.run(sql`INSERT INTO settings(key,value) VALUES diff --git a/src/server/db/raw-ddl.ts b/src/server/db/raw-ddl.ts index cff6f2e..7d94616 100644 --- a/src/server/db/raw-ddl.ts +++ b/src/server/db/raw-ddl.ts @@ -40,10 +40,19 @@ function chunkVecCreated(db: BunSQLiteDatabase): boolean { } function embedDim(db: BunSQLiteDatabase): number | null { + // Audit M4: align with the canonical serialization convention — pdf.ts + // writes embed.dim via JSON.stringify(number) and ConfigAccessor.get + // reads via JSON.parse. The old Number(raw) coercion was too lenient, + // accepting non-JSON forms like "0x300" that the canonical reader rejects. const raw = readSetting(db, "embed.dim") if (raw === null) return null - const n = Number(raw) - return Number.isFinite(n) && n > 0 ? n : null + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + return null + } + return typeof parsed === "number" && Number.isFinite(parsed) && parsed > 0 ? parsed : null } export const runRawDdl: RunRawDdl = (db) => { From 00cc76c19782e048ca68a9667331eb283d5aae1c Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:10:12 -0500 Subject: [PATCH 24/33] =?UTF-8?q?fix(chunker):=20drop=20tail=20chunks=20wi?= =?UTF-8?q?th=20=E2=89=A41=20word=20of=20new=20content=20(M6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A paper of exactly WINDOW_WORDS+1 (=385) words produced a 49-word tail chunk that was 48 words of overlap + 1 net new word. The chunk burned a full embedding round-trip for one word of new signal, and the resulting near-duplicate vector polluted the hybrid-search vec_rank. Drop the tail when `slice.length <= OVERLAP_WORDS + 1` (i.e., new content ≤ 1 word), gated on `start > 0` so single-chunk inputs are unaffected. Tests pin both sides of the boundary: - 385 words → 1 chunk (tail dropped — was 2 chunks pre-fix). - 386 words → 2 chunks (50-word tail kept — 2 new words is meaningful). Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/extraction/chunker.test.ts | 20 ++++++++++++++++++++ src/server/extraction/chunker.ts | 5 +++++ 2 files changed, 25 insertions(+) diff --git a/src/server/extraction/chunker.test.ts b/src/server/extraction/chunker.test.ts index 65098f8..c658bf3 100644 --- a/src/server/extraction/chunker.test.ts +++ b/src/server/extraction/chunker.test.ts @@ -54,3 +54,23 @@ test("chunker: Chunk shape exports ordinal + text fields", () => { expect(typeof sample.ordinal).toBe("number"); expect(typeof sample.text).toBe("string"); }); + +test("chunker: drops a tail chunk whose new-word content is ≤ 1 word (M6)", () => { + // Audit M6 / finding #16: WINDOW_WORDS+1 = 385 words produces a 49-word + // tail chunk that's 48 words of overlap + 1 net new word — wastes an + // embedding budget and pollutes vec_rank with a near-duplicate. Drop + // such tails (slice.length ≤ OVERLAP_WORDS + 1). + const words = Array.from({ length: 385 }, (_, i) => `w${i}`).join(" "); + const chunks = chunkText(words); + expect(chunks).toHaveLength(1); + expect(chunks[0]!.text.split(/\s+/).length).toBe(384); +}); + +test("chunker: keeps a tail chunk with > 1 word of new content (M6 boundary)", () => { + // Boundary on the other side: 50 tail-words = 48 overlap + 2 net new + // words. Cheap to embed, contributes real new signal — must NOT be dropped. + const words = Array.from({ length: 386 }, (_, i) => `w${i}`).join(" "); + const chunks = chunkText(words); + expect(chunks).toHaveLength(2); + expect(chunks[1]!.text.split(/\s+/).length).toBe(50); +}); diff --git a/src/server/extraction/chunker.ts b/src/server/extraction/chunker.ts index b84305f..f1a9722 100644 --- a/src/server/extraction/chunker.ts +++ b/src/server/extraction/chunker.ts @@ -32,6 +32,11 @@ export function chunkText(text: string): Chunk[] { for (let start = 0; start < words.length; start += step) { const slice = words.slice(start, start + WINDOW_WORDS); if (slice.length === 0) break; + // Audit M6: drop tail chunks whose new-word content (slice.length minus + // OVERLAP_WORDS of prior overlap) is ≤ 1. These contribute one or zero + // net new words while costing an embedding round-trip and polluting + // vec_rank with a near-duplicate of the previous chunk. + if (start > 0 && slice.length <= OVERLAP_WORDS + 1) break; chunks.push({ ordinal, text: slice.join(" ") }); ordinal += 1; if (start + WINDOW_WORDS >= words.length) break; From ed95d9cb0405ee9b7bf79032256359b733add532 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:11:12 -0500 Subject: [PATCH 25/33] =?UTF-8?q?fix(papers):=20raise=20hybrid-search=20ve?= =?UTF-8?q?c=20scan=20LIMIT=20200=20=E2=86=92=201000=20(M5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-paper aggregation step downstream picks MIN(d) per paper_id, so the global LIMIT must be large enough that several distinct papers each get at least one chunk represented in the candidate set. The old LIMIT 200 starved paper diversity on corpora where any one paper had ≥200 close-ranking chunks — the per-paper aggregation collapsed to a single hot paper instead of surfacing other relevant ones. 1000 covers the personal-use scale (audit budget: 5k chunks per corpus). The structurally tighter KNN-per-paper subquery rewrite (audit's primary suggestion) is deferred — it changes vec0 scan shape and needs a real benchmark before adoption. No new test: the change is a one-line constant tuning, and the boundary where the old limit bit (>200 close chunks concentrated in one paper) is hard to construct reliably without a real-scale fixture. Existing hybrid- search tests verify no regression at small scales. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/papers.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/server/tools/papers.ts b/src/server/tools/papers.ts index 51a0116..5356d26 100644 --- a/src/server/tools/papers.ts +++ b/src/server/tools/papers.ts @@ -117,13 +117,20 @@ export async function searchPapers( // sliced views correctly today, but ctx.embed is test-injectable and // future driver swaps may not). const qvec = toTightFloat32(await embed(DEFAULT_EMBED_MODEL, args.q)); + // Audit M5: per-paper aggregation downstream picks MIN(d) per paper_id, + // so the global LIMIT here must be large enough that several papers + // each get at least one chunk represented. The old LIMIT 200 starved + // diversity on corpora where any one paper had ≥200 close-ranking + // chunks. 1000 covers the personal-use scale (5k chunks budget per + // audit note). The deferred KNN-per-paper subquery rewrite would be + // structurally tighter but needs a benchmark; tracked separately. const vecRows = raw.prepare( `SELECT pc.paper_id AS paper_id, vec_distance_cosine(cv.embedding, ?) AS d FROM chunk_vec cv JOIN paper_chunks pc ON pc.id = cv.chunk_id ORDER BY d ASC - LIMIT 200`, + LIMIT 1000`, ).all(qvec) as Array<{ paper_id: string; d: number }>; const best = new Map(); for (const r of vecRows) { From 691daa9fa0a3bb7fc4c9cfb0149a72cc69f19aae Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:11:38 -0500 Subject: [PATCH 26/33] docs(pdf): annotate Win32 Job Object attach-after-spawn race acceptance (M2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The race window between StdioClientTransport's spawn and the subsequent AssignProcessToJobObject call (via attachJobObject) is microseconds wide and only matters for a child that exits synchronously between the two calls. Accepted at v1: the primary purpose of the job is parent-death cleanup of long-lived children, not coverage of the synchronous-crash case. Closing the race would require CreateProcess with CREATE_SUSPENDED + AssignProcessToJobObject before ResumeThread, which means reimplementing the StdioClientTransport spawn path. Deferred until a Win32 test rig exists — flagged in ROADMAP.md under M2 as documented-only acceptance. No source behavior change. Comment-only. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/pdf/lifecycle.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/server/pdf/lifecycle.ts b/src/server/pdf/lifecycle.ts index 4ce1886..7ec299c 100644 --- a/src/server/pdf/lifecycle.ts +++ b/src/server/pdf/lifecycle.ts @@ -150,6 +150,14 @@ export async function spawnPdfChild(opts: SpawnOpts): Promise { // Try to recover the underlying child PID from the transport (private surface). activePid = (transport as unknown as { _process?: { pid?: number } })._process?.pid; if (activePid && process.platform === "win32") { + // Audit M2: attach-after-spawn leaves a microsecond race window where + // a child that exits between spawn and AssignProcessToJobObject escapes + // the job. Accepted at v1: the primary purpose of the job is parent- + // death cleanup of long-lived children, not coverage of the synchronous- + // crash case. Closing the race requires CreateProcess with + // CREATE_SUSPENDED + AssignProcessToJobObject before ResumeThread — + // which would mean reimplementing the StdioClientTransport spawn path. + // Deferred until a Win32 test rig exists; tracked in audits/ROADMAP.md. attachJobObject(activePid); } else if (activePid && process.platform === "linux") { setPdeathsig(activePid); From 42edde2f14b970a5dc0b9beb12c158276b76ebff Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 02:25:58 -0500 Subject: [PATCH 27/33] docs(roadmap): mark M1-M9 landed; link to commits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eight items shipped as Red→Green TDD (M1, M3-M9); M2 documented as acceptance only (Win32 race closure deferred until test rig exists). Suite: 285 pass / 8 skip / 8 unchanged pre-existing failures; tsc clean. Co-Authored-By: Claude Opus 4.7 (1M context) --- docs/audits/ROADMAP.md | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index c4d46c4..20b07c0 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -64,21 +64,23 @@ Each H-item shipped with a regression test that fails pre-fix and passes post-fi --- -## Medium-priority batch (M1–M9) — optional defensive hardening - -Land as a single follow-up plan or skip until first real-world bug bites. - -| ID | Defect | File:line | Why deferrable | -|---|---|---|---| -| M1 | `runtime-config.ts` no parent-dir fsync after rename | `runtime-config.ts:24-49` | App-crash bar met; OS-crash gap rare | -| M2 | Win32 Job Object attach-after-spawn race | `lifecycle.ts:148-155` | Microsecond race window | -| M3 | Float32Array view binding risk | `papers.ts:115-122` | Bun handles correctly; defensive | -| M4 | Settings serialization mismatch (`pdf.ts` writer vs `raw-ddl.ts` reader) | `pdf.ts:105-112` / `raw-ddl.ts:42-47` | Single field | -| M5 | RRF LIMIT 200 truncation bias | `papers.ts:115-122` | Acceptable at v1 corpus scale | -| M6 | Chunker tail-chunk insufficient new content | `chunker.ts:31-39` | Low-impact edge | -| M7 | `countBundledMigrations` swallows errors | `migrations.ts:68-77` | Defensive logging only | -| M8 | Phase-2 throw timing in `annotations.ts` | `annotations.ts:254-256` | Self-healing per §13; add test only | -| M9 | `resolveUnderRoot` doesn't wrap `realpathSync(root)` ENOENT | `primitives.ts:75-91` | Fires only on backup-dest path | +## Medium-priority batch (M1–M9) — defensive hardening ✅ landed 2026-05-29 + +Branch: `worktree-pre-v1-roadmap`. Eight items landed as Red→Green TDD cycles (M3, M8 as defense-in-depth pins). M2 is **documented acceptance**, not a code fix — closing the race needs a Win32 test rig. + +| ID | Defect | File:line | Disposition | Commit | +|---|---|---|---|---| +| M1 | `runtime-config.ts` no parent-dir fsync after rename | `runtime-config.ts:24-49` | Linux/POSIX: post-rename `open(O_DIRECTORY).sync()`. Win32 unchanged (no equivalent) | `b31c7a1` | +| M2 | Win32 Job Object attach-after-spawn race | `lifecycle.ts:148-155` | **Documented acceptance** — race window is µs-wide; closure needs `CREATE_SUSPENDED` + spawn-path rewrite, deferred until Win32 test rig | `691daa9` (docs-only) | +| M3 | Float32Array view binding risk | `papers.ts:115-122`, `pdf.ts:210` | `toTightFloat32` helper wraps both vec0 bind sites. Bun currently honors `byteOffset`/`byteLength` so this is defense-in-depth | `e351c11` | +| M4 | Settings serialization mismatch | `raw-ddl.ts:42-47` | `embedDim` reader switched `Number(raw)` → `JSON.parse + typeof guard` to align with the canonical convention; rejects non-JSON forms like `"0x300"` | `536ab98` | +| M5 | RRF vec scan LIMIT 200 truncation bias | `papers.ts:121` | Raised to `LIMIT 1000` (covers personal-use 5k-chunk budget). KNN-per-paper subquery rewrite deferred — needs benchmark | `ed95d9c` | +| M6 | Chunker tail-chunk insufficient new content | `chunker.ts:31-39` | Drop tail when `slice.length ≤ OVERLAP_WORDS + 1`. Boundary tests pin 385-word (drop) and 386-word (keep) | `00cc76c` | +| M7 | `countBundledMigrations` swallows errors silently | `migrations.ts:79-88` | Narrowed catch to `existsSync(folder) ? scan() : 0`; let scan errors (permission, ENOTDIR) propagate. Function exported for direct testability | `1d4c294` | +| M8 | Phase-2 throw timing in `annotations.ts` | `annotations.ts` (test-only) | Added regression pinning §13 v1.1 "write-then-push": push throw leaves a re-pushable dirty row; retry with same id is idempotent | `5973060` | +| M9 | `resolveUnderRoot` doesn't wrap `realpathSync(root)` ENOENT | `primitives.ts:75-91` | Wrap root realpath in `try/catch` → `PathEscapeError`. Regression test uses real-leaf + missing-root to bypass the existing leaf-stat catch | `d101adb` | + +Full-suite verification: 285 pass / 8 skip / 8 unchanged pre-existing failures (the same UI bundle + pdf.test.ts pdfViews tests that pre-date the M-batch). +11 new tests vs. H-batch baseline. Typecheck clean. The M2 race remains technically open — track Win32 test-rig work separately before claiming it closed. --- From 901a07c11f08cd62fa625f8b707d3931ffdb33e3 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 11:28:57 -0500 Subject: [PATCH 28/33] fix(raw-ddl): throw RawDdlInvariantError on chunk_vec/embed.dim desync (A1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings can desynchronize across chunk_vec.created and embed.dim (manual edit, downgrade artifact, partial write). Pre-A1 the call silently no-op'd when created='true' and dim was missing/invalid, leaving the user with a permanent still_indexing=true and no diagnostic. Surface the inconsistency loudly so the bug is debuggable at first open. RunRawDdl signature is §7.6-frozen (no logger arg available), so throw is the only structured option. M4's hex-rejection test promoted from "silent skip" to "loud throw" for consistency. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/db/raw-ddl.test.ts | 32 ++++++++++++++++++++++---------- src/server/db/raw-ddl.ts | 19 ++++++++++++++++++- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/server/db/raw-ddl.test.ts b/src/server/db/raw-ddl.test.ts index d982214..161993b 100644 --- a/src/server/db/raw-ddl.test.ts +++ b/src/server/db/raw-ddl.test.ts @@ -11,7 +11,7 @@ import { mkdtempSync, rmSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { openWithPragmas } from "./migrations.ts" -import { runRawDdl } from "./raw-ddl.ts" +import { runRawDdl, RawDdlInvariantError } from "./raw-ddl.ts" import { ensureVec0Path } from "%/util" // Ensure vec0 path is discoverable by `Database.loadExtension`. The build // pipeline (foundation's `bun run build:vec`) is expected to land a copy at @@ -74,22 +74,34 @@ test("runRawDdl: creates chunk_vec when settings.embed.dim is set and chunk_vec. expect(tables.map((t) => t.name)).toContain("chunk_vec") }) -test("runRawDdl: embed.dim is parsed as JSON (rejects hex/non-JSON forms) (M4)", () => { +test("runRawDdl: embed.dim is parsed as JSON; hex/non-JSON values trigger RawDdlInvariantError (M4 + A1)", () => { // Audit M4 / finding #14: pdf.ts:materializeChunkVec writes embed.dim via // JSON.stringify(number); the consuming reader in raw-ddl.ts:embedDim used // Number(raw), which accepts non-JSON forms like "0x300" (Number = 768) // and would silently honor a value that the canonical ConfigAccessor.get - // (JSON.parse) would reject. Pin the JSON-only contract: hex-formatted - // values must NOT trigger chunk_vec creation. - const { sqlite, db } = freshExtDb() + // (JSON.parse) would reject. Audit A1 strengthens M4: when chunk_vec.created + // says the table was materialized but embedDim() now returns null (corrupt + // JSON, downgrade artifact, partial settings write), the state is genuinely + // inconsistent — throw rather than silently skip, so the user sees the bug + // immediately instead of staring at a permanent still_indexing=true. + const { db } = freshExtDb() db.run(sql`INSERT INTO settings(key,value) VALUES ('embed.dim','0x300'), ('chunk_vec.created','true')`) - runRawDdl(db) - const has = sqlite - .query("SELECT 1 FROM sqlite_master WHERE name = 'chunk_vec'") - .get() - expect(has).toBeNull() + expect(() => runRawDdl(db)).toThrow(RawDdlInvariantError) +}) + +test("runRawDdl: throws RawDdlInvariantError when chunk_vec.created='true' but embed.dim row is absent (A1)", () => { + // Audit A1 / silent-failure-hunter Finding A1: settings says chunk_vec was + // materialized, but the embed.dim sibling row is gone. Materially + // impossible under the canonical pdf.ts writer (atomic) but possible after + // manual edit, downgrade-then-upgrade, or partial write. Without this + // check raw-ddl silently no-ops and the user sees still_indexing=true + // forever with no diagnostic. Surface the inconsistency. + const { db } = freshExtDb() + db.run(sql`INSERT INTO settings(key,value) VALUES + ('chunk_vec.created','true')`) + expect(() => runRawDdl(db)).toThrow(RawDdlInvariantError) }) test("runRawDdl: skips chunk_vec when settings.chunk_vec.created='false' (deferred)", () => { diff --git a/src/server/db/raw-ddl.ts b/src/server/db/raw-ddl.ts index 7d94616..bfabc1e 100644 --- a/src/server/db/raw-ddl.ts +++ b/src/server/db/raw-ddl.ts @@ -22,6 +22,10 @@ import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite" import { rawClient } from "./raw-client.ts" import type { RunRawDdl } from "../tools/registry.ts" +export class RawDdlInvariantError extends Error { + override name = "RawDdlInvariantError" +} + function readSetting(db: BunSQLiteDatabase, key: string): string | null { try { const row = db.all(sql`SELECT value FROM settings WHERE key = ${key}`) as { @@ -61,7 +65,20 @@ export const runRawDdl: RunRawDdl = (db) => { // flag has flipped to true. The vec0 module supports IF NOT EXISTS, so // re-invocation after the first materialization is a no-op. const dim = embedDim(db) - if (dim !== null && chunkVecCreated(db)) { + const created = chunkVecCreated(db) + // Audit A1: settings can desynchronize across the chunk_vec.created flag and + // the embed.dim row (manual edit, downgrade-then-upgrade, partial write). + // Pre-A1 the call silently no-op'd when created='true' and dim was missing, + // leaving the user with a permanent still_indexing=true and no diagnostic. + // Surface the inconsistency loudly so the bug is debuggable at first open. + if (created && dim === null) { + throw new RawDdlInvariantError( + "settings.chunk_vec.created='true' but embed.dim is missing or invalid — " + + "fix settings (clear chunk_vec.created or restore a numeric JSON embed.dim) " + + "before re-opening the corpus", + ) + } + if (dim !== null && created) { rawClient(db).run( `CREATE VIRTUAL TABLE IF NOT EXISTS chunk_vec USING vec0( chunk_id TEXT PRIMARY KEY, From 8958c2c5bd9701cf6b9322c2cb38d6c8cbf2d004 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 11:29:50 -0500 Subject: [PATCH 29/33] fix(primitives): preserve realpath error via Error.cause on PathEscapeError (A2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M9's wrap discarded err.code (ENOENT vs EACCES vs ELOOP), err.message, and the original stack frame — making a genuine FS bug indistinguishable from "missing root" at the catch site. Bun/V8 supports Error.cause natively; pass it through so debuggers and log readers keep the diagnostic without weakening the typed boundary. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/ingest/primitives.test.ts | 25 +++++++++++++++++++++++++ src/server/ingest/primitives.ts | 7 +++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/server/ingest/primitives.test.ts b/src/server/ingest/primitives.test.ts index 5f69e74..649c66e 100644 --- a/src/server/ingest/primitives.test.ts +++ b/src/server/ingest/primitives.test.ts @@ -82,6 +82,31 @@ test("resolveUnderRoot wraps a missing root in PathEscapeError (M9)", () => { } }); +test("resolveUnderRoot preserves the underlying realpath error via Error.cause (A2)", () => { + // Audit A2 / silent-failure-hunter Finding A2: M9's PathEscapeError wrap + // discarded err.code (ENOENT vs EACCES vs ELOOP), err.message, and the + // original stack frame, making a genuine FS bug indistinguishable from + // "missing root" at the catch site. Bun/V8 supports Error.cause natively; + // pass it through so debuggers (and oncall log readers) keep the diagnostic. + const leafDir = mkdtempSync(join(tmpdir(), "scholar-rur-cause-")); + const leaf = join(leafDir, "ok.txt"); + writeFileSync(leaf, "x"); + const missingRoot = join(tmpdir(), `scholar-rur-cause-missing-${process.pid}-${Date.now()}`); + try { + try { + resolveUnderRoot(leaf, missingRoot); + throw new Error("expected PathEscapeError"); + } catch (err) { + expect(err).toBeInstanceOf(PathEscapeError); + const cause = (err as Error).cause as NodeJS.ErrnoException | undefined; + expect(cause).toBeDefined(); + expect(cause?.code).toBe("ENOENT"); + } + } finally { + rmSync(leafDir, { recursive: true, force: true }); + } +}); + test("resolveUnderRoot throws PathEscapeError on symlink leaf", () => { if (process.platform === "win32") return; // symlinks require admin on Windows const root = mkdtempSync(join(tmpdir(), "scholar-rur-")); diff --git a/src/server/ingest/primitives.ts b/src/server/ingest/primitives.ts index fae2bdc..88fd5e1 100644 --- a/src/server/ingest/primitives.ts +++ b/src/server/ingest/primitives.ts @@ -84,11 +84,14 @@ export function resolveUnderRoot(p: string, root: string): string { const real = realpathSync(resolved); // Audit M9: realpathSync(root) was unguarded, so a missing or unreadable // root leaked a raw ENOENT to callers that only catch PathEscapeError. + // Audit A2: preserve the original error via Error.cause so callers can + // still distinguish ENOENT/EACCES/ELOOP — the typed boundary doesn't + // mean diagnostic loss. let realRoot; try { realRoot = realpathSync(root); - } catch { - throw new PathEscapeError(`root unresolvable: ${root}`); + } catch (err) { + throw new PathEscapeError(`root unresolvable: ${root}`, { cause: err }); } if (!real.startsWith(realRoot + pathSep) || real === realRoot) { throw new PathEscapeError(`escapes root ${realRoot}: ${real}`); From ac6c22523cc5e864c7fc6fddc9915cac0933561b Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 11:36:54 -0500 Subject: [PATCH 30/33] test(papers): pin M5 LIMIT 1000 with diversity-starvation regression test Audit pr-test-analyzer flagged M5 (commit ed95d9c) as cheaply testable but unpinned. Construction: paper A saturates ranks 1..250 with near-zero cosine distances; paper B's chunks land at ~rank 251, paper C's at ~rank 256. Query embedding aligned with A's geometry, lex-non-matching query string isolates the vec_rank path. Verified Red against LIMIT 200 (B/C absent), Green at LIMIT 1000. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/papers.test.ts | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/server/tools/papers.test.ts b/src/server/tools/papers.test.ts index 74decad..22374bf 100644 --- a/src/server/tools/papers.test.ts +++ b/src/server/tools/papers.test.ts @@ -146,6 +146,72 @@ test("hybrid search: tolerates an embed that returns a view-over-larger-buffer ( expect(result.hits[0]!.id).toBe("p1") }) +test("hybrid search: vec scan LIMIT keeps per-paper diversity under chunk saturation (M5)", async () => { + // Audit M5: per-paper aggregation downstream picks MIN(d) per paper_id. + // With the old LIMIT 200, a corpus where any single paper had >=200 chunks + // closer to the query than other papers' best chunks would starve those + // other papers out of vec_rank entirely. LIMIT 1000 covers the personal-use + // 5k-chunk budget without exposing diversity starvation. + // + // Construction: paper A saturates ranks 1..250 with cosine distances near + // zero; paper B's best chunks land near rank 251; paper C's near rank 256. + // Under LIMIT 200 the SQL scan only returns A's chunks — B and C end up + // with no vec_rank entry. Under LIMIT 1000 all three papers surface. + const sqlite = seededDb(); + sqlite.run(`INSERT INTO papers(id,key,title,imported_at) VALUES + ('pA','kA','alpha','2026-01-01T00:00:00.000Z'), + ('pB','kB','beta','2026-01-01T00:00:00.000Z'), + ('pC','kC','gamma','2026-01-01T00:00:00.000Z')`); + + const insChunk = sqlite.prepare( + `INSERT INTO paper_chunks(id,paper_id,ordinal,text,embedded_at) VALUES (?,?,?,?,'2026-01-01T00:00:00.000Z')`, + ); + const insVec = sqlite.prepare( + `INSERT INTO chunk_vec(chunk_id, embedding) VALUES (?, ?)`, + ); + const dim = 768; + function vec(a: number, b: number): Float32Array { + const v = new Float32Array(dim); + v[0] = a; v[1] = b; + return v; + } + for (let i = 0; i < 250; i++) { + const id = `a${i}`; + insChunk.run(id, "pA", i, `a${i}`); + insVec.run(id, vec(1, 0.001 * (i + 1))); + } + for (let i = 0; i < 5; i++) { + const id = `b${i}`; + insChunk.run(id, "pB", i, `b${i}`); + insVec.run(id, vec(1, 0.5)); + } + for (let i = 0; i < 5; i++) { + const id = `c${i}`; + insChunk.run(id, "pC", i, `c${i}`); + insVec.run(id, vec(1, 1.0)); + } + + // Force the query embedding to match A's structure (b=0) so cosine-distance + // ordering is deterministic: A's 250 chunks dominate the closest 250 ranks, + // then B's 5, then C's 5. Use a query string that lex-matches NOTHING so + // result.hits is populated purely via vec_rank. + const ctx = fakeCtx(sqlite) as unknown as { embed: (m: string, p: string) => Promise }; + ctx.embed = async () => vec(1, 0); + + const result = await searchPapers( + ctx as unknown as Parameters[0], + { q: "zzzz-no-lex-match", limit: 50 }, + ); + + const ids = result.hits.map((h) => h.id); + expect(ids).toContain("pA"); + expect(ids).toContain("pB"); + expect(ids).toContain("pC"); + expect(result.hits.find((h) => h.id === "pA")!.vec_rank).toBe(1); + expect(result.hits.find((h) => h.id === "pB")!.vec_rank).toBe(2); + expect(result.hits.find((h) => h.id === "pC")!.vec_rank).toBe(3); +}); + test("hybrid search: degrades to lexical-only when chunk_vec is deferred (still_indexing=true)", async () => { const sqlite = seededDb({ deferred: true }) sqlite.run(`INSERT INTO papers(id,key,title,imported_at) VALUES From a69e13e3056515be798bb0a7d8c5cddae800ef12 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 11:37:42 -0500 Subject: [PATCH 31/33] test(runtime-config): pin M1 fsync via FileHandle.sync spy Audit pr-test-analyzer flagged the M1 test as false-reassurance: spying on fsp.open caught the directory-handle open but not the load-bearing .sync() call. Removing the await dir.sync() left the test green. Wrap each O_DIRECTORY-flagged FileHandle returned from open with spyOn(handle, "sync") and assert at least one was actually invoked. Verified Red against the sync-removed pre-fix scenario, Green against the M1 fix. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/util/runtime-config.test.ts | 41 ++++++++++++++++++-------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/src/server/util/runtime-config.test.ts b/src/server/util/runtime-config.test.ts index a7ac1a6..75d84cb 100644 --- a/src/server/util/runtime-config.test.ts +++ b/src/server/util/runtime-config.test.ts @@ -69,22 +69,39 @@ test("sequential overwrites: last writer wins", async () => { }); test("writeRuntimeConfig fsyncs the parent directory after rename (M1)", async () => { - // Audit M1: POSIX rename is atomic for content but the directory entry isn't - // durable until the parent directory is fsync'd. Without this, an OS-crash - // immediately after rename can lose the new entry. Verified via a spy that - // captures the post-rename directory-handle open + sync. + // Audit M1 + pr-test-analyzer follow-up: POSIX rename is atomic for content + // but the directory entry isn't durable until the parent directory is + // fsync'd. The original test only spied on fsp.open and asserted an + // O_DIRECTORY open occurred — removing the await dir.sync() call would + // have left it green (the open still happens). Pin the load-bearing op: + // wrap each FileHandle returned from a directory-flagged open and assert + // .sync() was invoked on at least one of them before the function returns. if (process.platform === "win32") return; // no directory fsync on Win32 const runtimeRoot = makeTempDir(); - const openSpy = spyOn(fsp, "open"); - try { - await writeRuntimeConfig({ activeCorpusId: "fsync-me" }, runtimeRoot); - const dirOpens = openSpy.mock.calls.filter( - ([path, flags]) => + const realOpen = fsp.open.bind(fsp) as typeof fsp.open; + const dirSyncSpies: Array> = []; + const openSpy = spyOn(fsp, "open").mockImplementation( + (async ( + path: Parameters[0], + flags?: Parameters[1], + mode?: Parameters[2], + ) => { + const handle = await realOpen(path, flags, mode); + if ( path === runtimeRoot && typeof flags === "number" && - (flags & fsConstants.O_DIRECTORY) !== 0, - ); - expect(dirOpens.length).toBeGreaterThanOrEqual(1); + (flags & fsConstants.O_DIRECTORY) !== 0 + ) { + dirSyncSpies.push(spyOn(handle, "sync")); + } + return handle; + }) as typeof fsp.open, + ); + try { + await writeRuntimeConfig({ activeCorpusId: "fsync-me" }, runtimeRoot); + expect(dirSyncSpies.length).toBeGreaterThanOrEqual(1); + const synced = dirSyncSpies.some((s) => s.mock.calls.length >= 1); + expect(synced).toBe(true); } finally { openSpy.mockRestore(); } From 14016e0e989b5951e06ad9f9e7cba76aaa618c77 Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 11:38:48 -0500 Subject: [PATCH 32/33] test(papers): pin M3 toTightFloat32 invocation at the qvec bind site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit pr-test-analyzer flagged the original M3 integration test as false-reassurance: removing the toTightFloat32 wrap from papers.ts left it green because bun:sqlite happens to honor view bind. Replace with a spyOn(vecModule, "toTightFloat32") that pins the CALL — verified Red when the wrap is removed from papers.ts, Green at the M3 fix. The spy also asserts the wrap saw a non-tight (view-over-larger) input so we know the captured call is the qvec path, not some incidental invocation. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/papers.test.ts | 37 +++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/server/tools/papers.test.ts b/src/server/tools/papers.test.ts index 22374bf..ef8a59d 100644 --- a/src/server/tools/papers.test.ts +++ b/src/server/tools/papers.test.ts @@ -4,12 +4,13 @@ // "hybrid lexical + sqlite-vec" envelope. Degrades to lexical-only with // `still_indexing: true` when settings.chunk_vec.created='false' (§11 pill). // scholar.papers.update bumps status_touched_at so reading_queue reorders. -import { test, expect } from "bun:test" +import { test, expect, spyOn } from "bun:test" import { Database } from "bun:sqlite" import { drizzle } from "drizzle-orm/bun-sqlite" import { searchPapers, updatePaper } from "./papers.ts" import { applyMigrations } from "#server/db/migrations.ts" import { runRawDdl } from "#server/db/raw-ddl.ts" +import * as vecModule from "#server/db/sqlite-vec.ts" import { ensureVec0Path } from "%/util" function deterministicEmbedding(dim: number, input: string): Float32Array { @@ -108,12 +109,13 @@ test("hybrid search: returns lexical + semantic hits ranked via RRF (k=60)", asy expect(result.hits.map((h) => h.id)).toContain("p1") }) -test("hybrid search: tolerates an embed that returns a view-over-larger-buffer (M3)", async () => { - // Audit M3: ctx.embed is test-injectable, so future embed providers may - // return Float32Array views over a larger backing buffer. searchPapers - // wraps qvec in toTightFloat32 at the bind site; verify the search still - // converges on the correct paper. (Today's bun:sqlite respects byteOffset - // + byteLength, so this test is defense-in-depth evidence of the contract.) +test("hybrid search: invokes toTightFloat32 at the qvec bind site (M3)", async () => { + // Audit M3 + pr-test-analyzer follow-up: the unit tests in + // sqlite-vec.test.ts pin toTightFloat32's behavior; this test pins the + // CALL — that searchPapers actually routes ctx.embed's output through the + // wrap before binding it to vec_distance_cosine. Spying on the module + // export catches a regression where the wrap is removed from papers.ts + // even on a bun:sqlite version that happens to honor view bind directly. const sqlite = seededDb() sqlite.run(`INSERT INTO papers(id,key,title,imported_at) VALUES ('p1','smith2024','Scaling laws','2026-01-01T00:00:00.000Z'), @@ -131,19 +133,32 @@ test("hybrid search: tolerates an embed that returns a view-over-larger-buffer ( } // Inject an embed that returns a view positioned at a non-zero offset of a - // larger backing buffer. + // larger backing buffer — to verify toTightFloat32 sees a non-tight input. const ctx = fakeCtx(sqlite) as unknown as { embed: (m: string, p: string) => Promise } ctx.embed = async (_m, p) => { const dim = 768 const tight = deterministicEmbedding(dim, p) const big = new ArrayBuffer((dim + 8) * 4) - const view = new Float32Array(big, 4 * 4, dim) // offset 16 bytes into a larger buffer + const view = new Float32Array(big, 4 * 4, dim) view.set(tight) return view } - const result = await searchPapers(ctx as unknown as Parameters[0], { q: "Scaling laws describe model capacity" }) - expect(result.hits[0]!.id).toBe("p1") + const wrapSpy = spyOn(vecModule, "toTightFloat32") + try { + const result = await searchPapers(ctx as unknown as Parameters[0], { q: "Scaling laws describe model capacity" }) + expect(result.hits[0]!.id).toBe("p1") + expect(wrapSpy).toHaveBeenCalled() + // Confirm the spy saw a non-tight input (the injected view), proving the + // wrap site is the qvec path rather than some unrelated incidental call. + const sawView = wrapSpy.mock.calls.some( + ([arr]) => + arr instanceof Float32Array && arr.buffer.byteLength !== arr.byteLength, + ) + expect(sawView).toBe(true) + } finally { + wrapSpy.mockRestore() + } }) test("hybrid search: vec scan LIMIT keeps per-paper diversity under chunk saturation (M5)", async () => { From a5b4301d4a162ddc324ae6e0e1b5ed849864273a Mon Sep 17 00:00:00 2001 From: zaynram Date: Fri, 29 May 2026 11:39:33 -0500 Subject: [PATCH 33/33] test(annotations): pin M8 delete-path push-failure asymmetry vs upsert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit pr-test-analyzer flagged the delete-path as uncovered: M8's original test only pinned the upsert flow. Delete commits a tombstone in phase-1; if phase-2 (remove_annotations push) throws, the retry short-circuits at `already_tombstoned` and does NOT re-push. This is the intentional v1.1 asymmetry — the viewer's stale display reconciles on next paper open, not via scholar-initiated catch-up (matching the §13 v1.1 "no inbound reconciliation" stance applied to outbound failure). Pin the asymmetry as a regression test so any future change to make delete re-pushable surfaces as a deliberate spec edit, not silent drift. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/server/tools/annotations.test.ts | 47 ++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/server/tools/annotations.test.ts b/src/server/tools/annotations.test.ts index cc0576e..a472691 100644 --- a/src/server/tools/annotations.test.ts +++ b/src/server/tools/annotations.test.ts @@ -371,6 +371,53 @@ test("delete: soft-deletes annotation (deleted_at set) and pushes remove_annotat // delete idempotency (unchanged under v1.1) // ============================================================================= +test("delete: push failure tombstones the row; retry short-circuits and does NOT re-push (M8 delete)", async () => { + // Audit M8 + pr-test-analyzer follow-up: write-then-push semantics apply + // to delete too, but the recovery contract differs from upsert. Upsert + // commits a dirty row and the retry re-pushes via the update branch. + // Delete commits a tombstone and the retry short-circuits at + // `already_tombstoned` — there is NO redundant re-push. This is the v1.1 + // "no inbound reconciliation" stance applied to outbound failure: the + // viewer's stale display reconciles on next paper open / refresh, not via + // a scholar-initiated catch-up. Pin the intentional asymmetry so any + // future change to make delete re-pushable is a deliberate spec edit. + const r1 = await dispatch("scholar.annotations.upsert", { + paper_id: TEST_PAPER, + body: "to delete (push will fail)", + }) as { id: string }; + + // First delete: phase-2 (remove_annotations) throws once, then succeed. + let removeCalls = 0; + interactImpl = async (cmd) => { + if (cmd.type === "remove_annotations") { + removeCalls += 1; + if (removeCalls === 1) throw new Error("pdf viewer push failed"); + } + return null; + }; + + await expect( + dispatch("scholar.annotations.delete", { id: r1.id }), + ).rejects.toThrow(/push failed/); + + // Phase-1 tombstone committed despite phase-2 throw. + const tombstoned = rawClient(built.ctx.db!) + .query("SELECT deleted_at FROM annotations WHERE id = ?") + .get(r1.id) as { deleted_at: string | null }; + expect(tombstoned.deleted_at).not.toBeNull(); + expect(removeCalls).toBe(1); + + // Retry: short-circuits as already_tombstoned, NO new remove_annotations push. + // The viewer is expected to catch up on refresh — scholar does not re-push. + const retried = await dispatch("scholar.annotations.delete", { id: r1.id }) as { + deleted: boolean; + reason: string; + }; + expect(retried.deleted).toBe(false); + expect(retried.reason).toBe("already_tombstoned"); + expect(removeCalls).toBe(1); +}); + test("delete on already-tombstoned annotation is no-op: no second pdf.interact, deleted_at unchanged", async () => { const r1 = await dispatch("scholar.annotations.upsert", { paper_id: TEST_PAPER,