diff --git a/docs/audits/ROADMAP.md b/docs/audits/ROADMAP.md index b0ee638..20b07c0 100644 --- a/docs/audits/ROADMAP.md +++ b/docs/audits/ROADMAP.md @@ -16,61 +16,71 @@ ## Showstopper batch (S1–S3) — must land first -### S1 — pdf-viewer interop rewrite + §13 spec amendment +### S1 — pdf-viewer interop rewrite + §13 spec amendment ✅ landed 2026-05-27 -- [ ] **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. +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`). -### S2 — CLI mode argv + SIGINT +- [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). -- [ ] **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. +### S2 — CLI mode argv + SIGINT ✅ landed 2026-05-27 -### S3 — Ollama client timeouts +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). -- [ ] **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. +- [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 ✅ landed 2026-05-27 + +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. --- -## High-priority batch (H1–H5) — land before personal-use ship +## High-priority batch (H1–H5) — land before personal-use ship ✅ landed 2026-05-28 + +Branch: `worktree-pre-v1-roadmap`. All five items landed in separate TDD cycles, one commit per H-item. -| 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 | +| 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. --- -## 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. --- 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..ddfee84 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,39 @@ 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; + // 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 @@ -616,6 +635,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 +810,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 +948,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 +1005,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 +1183,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 +1313,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 +1367,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 +1389,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. 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/src/server/db/migrations.test.ts b/src/server/db/migrations.test.ts index 511cf56..c752f0d 100644 --- a/src/server/db/migrations.test.ts +++ b/src/server/db/migrations.test.ts @@ -4,10 +4,13 @@ // 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 { writeFileSync } from "node:fs"; +import { applyMigrations, openWithPragmas, countBundledMigrations } from "./migrations.ts"; import { rawClient } from "./raw-client.ts"; let dir: string | undefined; @@ -28,3 +31,33 @@ 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("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 + // 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..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"; @@ -40,6 +41,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); @@ -65,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; } diff --git a/src/server/db/raw-ddl.test.ts b/src/server/db/raw-ddl.test.ts index e8af901..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,6 +74,36 @@ 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; 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. 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')`) + 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)", () => { 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..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 { @@ -40,10 +44,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) => { @@ -52,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, diff --git a/src/server/db/sqlite-vec.test.ts b/src/server/db/sqlite-vec.test.ts index 61bf561..b019413 100644 --- a/src/server/db/sqlite-vec.test.ts +++ b/src/server/db/sqlite-vec.test.ts @@ -3,7 +3,8 @@ // 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 { resolveVec0Path } from "./sqlite-vec.ts" +import { tmpdir } from "node:os" +import { resolveVec0Path, toTightFloat32 } from "./sqlite-vec.ts" test("resolveVec0Path returns absolute path with platform-correct extension", () => { const p = resolveVec0Path() @@ -21,3 +22,45 @@ 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 + } +}) + +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 a278dd0..5d6de93 100644 --- a/src/server/db/sqlite-vec.ts +++ b/src/server/db/sqlite-vec.ts @@ -20,16 +20,33 @@ 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", `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/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; 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/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/ingest/primitives.test.ts b/src/server/ingest/primitives.test.ts index e72844c..649c66e 100644 --- a/src/server/ingest/primitives.test.ts +++ b/src/server/ingest/primitives.test.ts @@ -64,6 +64,49 @@ 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 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 aac7b54..88fd5e1 100644 --- a/src/server/ingest/primitives.ts +++ b/src/server/ingest/primitives.ts @@ -82,7 +82,17 @@ 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. + // 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 (err) { + throw new PathEscapeError(`root unresolvable: ${root}`, { cause: err }); + } if (!real.startsWith(realRoot + pathSep) || real === realRoot) { throw new PathEscapeError(`escapes root ${realRoot}: ${real}`); } 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) { 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. 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..7ec299c 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[]; @@ -149,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); @@ -200,26 +209,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 +255,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/annotations.test.ts b/src/server/tools/annotations.test.ts index b708d72..a472691 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 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 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 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,144 @@ test("upsert update: same id, different body → updates row + pushes update_ann }); // ============================================================================= -// Red-3 — delete soft-delete + tombstone atomicity + remove_annotations push +// M8 — phase-2 (push) throw leaves a re-pushable dirty row // ============================================================================= -test("delete: soft-deletes annotation AND inserts annotation_tombstones atomically", async () => { +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) +// ============================================================================= + +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: 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: "p1", + paper_id: TEST_PAPER, body: "x", }) as { id: string }; await dispatch("scholar.annotations.delete", { id: r1.id }); @@ -275,7 +429,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 +440,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 +469,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 +489,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 +497,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 +514,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 +547,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 +// scholar.pdf.open populates ctx.pdfViews (§13 v1.1 invariant — new) // ============================================================================= -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; - }; +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 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); -}); + const result = await dispatch("scholar.pdf.open", { + paper_id: TEST_PAPER, + source: "/tmp/fixture.pdf", + }) as { paper_id: string; viewUUID: string }; -// ============================================================================= -// Red-7b — onConflictDoNothing on same-paper concurrent reconciles -// ============================================================================= - -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; - }; - - 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); -}); - -// ============================================================================= -// 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 +604,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..4ebcfc4 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 }), }; @@ -254,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(); 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/papers.test.ts b/src/server/tools/papers.test.ts index 22f8805..ef8a59d 100644 --- a/src/server/tools/papers.test.ts +++ b/src/server/tools/papers.test.ts @@ -4,11 +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 { @@ -25,12 +27,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 +50,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 } @@ -112,6 +109,124 @@ 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: 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'), + ('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 — 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) + view.set(tight) + return view + } + + 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 () => { + // 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 diff --git a/src/server/tools/papers.ts b/src/server/tools/papers.ts index 97c5f93..5356d26 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,14 +112,25 @@ 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)); + // 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) { diff --git a/src/server/tools/pdf.ts b/src/server/tools/pdf.ts index e614ea8..31a7710 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 @@ -36,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, @@ -128,8 +134,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)) { @@ -192,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; } @@ -231,20 +248,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/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 5eca55e..1033845 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; @@ -169,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); 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/src/server/util/runtime-config.test.ts b/src/server/util/runtime-config.test.ts index 3c169dd..75d84cb 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,45 @@ test("sequential overwrites: last writer wins", async () => { expect(result).toEqual({ activeCorpusId: "second" }); }); +test("writeRuntimeConfig fsyncs the parent directory after rename (M1)", async () => { + // 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 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 + ) { + 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(); + } +}); + 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 { 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 }), } 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) +})