diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 4373f2a..1a8ef5e 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,27 +1,38 @@
{
- "name": "scholar",
- "description": "Literature review workspace. Multi-corpus reading, annotation, semantic search, Ollama-powered syntheses, and a vendored pdf MCP. Inspired by but independent of the Daisy Lit Review artifact.",
- "author": {
- "name": "zayn"
- },
- "keywords": [
- "literature-review",
- "research",
- "mcp-apps",
- "annotations",
- "ollama",
- "sqlite-vec"
- ],
- "license": "MIT",
- "mcpServers": {
- "scholar": {
- "command": "${CLAUDE_PLUGIN_ROOT}/build/scholar",
- "env": {
- "SCHOLAR_RUNTIME_ROOT": "${HOME}/mcp-data/scholar/runtime",
- "SCHOLAR_OLLAMA_URL": "http://127.0.0.1:11434",
- "SCHOLAR_OLLAMA_EMBED_MODEL": "nomic-embed-text:v1.5",
- "SCHOLAR_OLLAMA_CHAT_MODEL": "qwen3:8b"
- }
+ "name": "scholar",
+ "description": "Literature review workspace. Multi-corpus reading, annotation, semantic search, Ollama-powered syntheses, and a vendored pdf MCP. Inspired by but independent of the Daisy Lit Review artifact.",
+ "author": { "name": "zayn" },
+ "keywords": [
+ "literature-review",
+ "research",
+ "mcp-apps",
+ "annotations",
+ "ollama",
+ "sqlite-vec"
+ ],
+ "license": "MIT",
+ "mcpServers": {
+ "scholar": {
+ "command": "/bin/sh",
+ "args": ["${CLAUDE_PLUGIN_ROOT}/bin/launch.sh"],
+ "env": {
+ "SCHOLAR_RUNTIME_ROOT": "${HOME}/mcp-data/scholar/runtime",
+ "SCHOLAR_OLLAMA_URL": "http://127.0.0.1:11434",
+ "SCHOLAR_OLLAMA_EMBED_MODEL": "nomic-embed-text:v1.5",
+ "SCHOLAR_OLLAMA_CHAT_MODEL": "qwen3:8b"
+ }
+ }
+ },
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/ensure-bun.sh\""
+ }
+ ]
+ }
+ ]
}
- }
-}
\ No newline at end of file
+}
diff --git a/.claude/context/chores.xml b/.claude/context/chores.xml
index b6bb525..0bb09fd 100644
--- a/.claude/context/chores.xml
+++ b/.claude/context/chores.xml
@@ -596,5 +596,31 @@ Fix options (pick A unless reason to keep --cwd=scripts):
Acceptance: `bun run build:ui` succeeds and produces `build/ui/app.html`; `bun run measure-bundle` produces `build/ui/bundle-budget.json` matching the shape `bundle.test.ts` asserts (total_kb / threshold_kb / over_budget / per_dep[]); the 3 bundle.test.ts tests go green; full suite reaches 297 pass / 8 skip / 0 fail; typecheck clean. Tier: mechanical-with-interpretation (sonnet) — picking A vs B is a 30-second judgment, the edit itself is ≤5 LOC. Single commit: `fix(build): resolve build:ui + measure-bundle without --cwd=scripts`.
+
+
+
+ Closed at 75abeaf (+29 tests, suite 324 pass/0 fail, tsc clean): client.ts lines 69.7->100% (listModels/healthCheck/chat covered); index.ts lines 77.7->85.64% (CLI dispatch covered). Two reported non-gaps left intentionally uncovered: client.ts func-counter reads 93.33% as a Bun v1.3.14 artifact despite 100% line coverage; index.ts runServer()/import.meta.main bind stdio and would deadlock a unit test (no source seam warranted). ORIGINAL SCOPE: close the two low-priority unit-coverage gaps flagged by the 2026-06-02 test audit. TEST-ONLY chore: extend the two existing *.test.ts files; do NOT modify source. If a path is genuinely untestable without a source seam (e.g. a fetch-injection point), STOP and raise it via scope-maintenance rather than widening the blast-radius.
+
+TARGET 1 — src/server/ollama/client.ts (76.9% funcs / 69.7% lines; uncovered lines 142-178). OllamaClientImpl calls the GLOBAL fetch (no constructor / no injection seam), so mock the global fetch the same way the existing timeout tests in client.test.ts already do. Add cases:
+ (a) chat() success return (line 142): mock fetch to a 200 with {message:{content:'hi'}}; assert chat() resolves 'hi'. Also cover the response-fallback (line 138): mock returns {response:'x'} with no message field; assert resolves 'x'. (chat() empty-content throw and the timeout path are already covered — do not duplicate.)
+ (b) listModels() (145-162, fully uncovered): success returns the models array; a body with no models key returns []; fetch throws rejects OllamaUnavailableError; res.ok false rejects OllamaUnavailableError.
+ (c) healthCheck() (164-181, fully uncovered): res.ok true returns {ok:true,url}; res.ok false returns {ok:false,url,error:'HTTP {status}'}; fetch throws returns {ok:false,url,error:message}.
+
+TARGET 2 — src/server/index.ts (55.3% funcs / 77.7% lines full-suite; the uncovered region is the CLI entrypoint dispatch). index.test.ts currently covers only buildServer / withCorpus snapshot / dispatch-unknown-tool. Add cases for the dispatch surface: parseEntryArgv (line 205), readArgsJson (215), runServer (227), runCli (233), main (287). Drive main()/parseEntryArgv() with synthetic argv and assert the branch selection (serve vs cli mode, the args.json read path, the error/exit-code branches at 294-305). Mock heavy side-effects via the makeDeps() helper already present in index.test.ts; do NOT spawn a real server or pdf child. Cover the buildServer branches at 132/135/138/142 if reachable through makeDeps() variants (e.g. the quiet-logger flag).
+
+CONSTRAINTS: bun:test only; no new deps; no production behavior change; preserve all existing tests; do not touch chores.xml (dispatcher owns the status flip).
+
+ACCEPTANCE: client.ts reaches 100% funcs with listModels/healthCheck/chat fully covered; index.ts dispatch functions covered with 85%+ lines; the full suite stays green (295 pass plus the added tests, 0 fail, 1 todo, 4 skip); bunx tsc --noEmit clean. Single work commit, suggested message: `test(coverage): cover ollama listModels/healthCheck/chat + index CLI dispatch`. Print WORK_COMMIT_SHA on completion. Tier: interpretive (sonnet) — mocking the global fetch and driving the argv dispatch require judgment on the seams. Vehicle: spec-pipeline:chore-executor.
+
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9dad3e1..3da535b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -27,7 +27,12 @@ jobs:
run: bun run build:vec
- name: test
- run: bun test --bail --only-failures
+ # Scoped to src+tests for deterministic discovery (matches the `test`
+ # package.json script). --bail stops at the first failure; --only-failures
+ # was a no-op here (no prior-run state in a fresh CI checkout) and is dropped.
+ # The SCHOLAR_PDF_E2E spawn fixtures stay OUT of this fast lane — see the
+ # `e2e` job — so a flaky child respawn can't bail the unit signal.
+ run: bun test src tests --bail
- name: smoke
run: |
@@ -42,3 +47,27 @@ jobs:
db.run(r);
console.log("CREATE VTAB vec0: ok");
'
+
+ e2e:
+ # The pdf-child spawn fixtures gated behind SCHOLAR_PDF_E2E (display_pdf
+ # round-trip, list_changed, SIGKILL+respawn). Heavier and spawn-flakier than
+ # the unit lane, so they run here on their own signal — a flake reports
+ # against this job without bailing `test`. The vendored child is committed
+ # (src/vendor/pdf-server/dist/index.js) and `bun install` supplies the
+ # pdfjs-dist it dynamically imports, so no build step is needed.
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.11 # match scholar.bundledBunVersion
+
+ - name: install
+ run: bun install --frozen-lockfile
+
+ - name: e2e
+ env:
+ SCHOLAR_PDF_E2E: "1"
+ run: bun test src/server/pdf
diff --git a/.gitignore b/.gitignore
index 0a1d550..998fc33 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,12 @@ runtime/
.claude/scheduled_tasks.lock
.claude/worktrees/**
+
+# Compiled server binaries + platform staging dirs — build outputs, never commit.
+bin/mcp-scholar
+bin/mcp-scholar.exe
+win32/
+# Stray nested copy from a build script writing to a literal "home/" path.
+home/
+# Backup of the deleted build-plugin.test.ts, kept locally during the refactor.
+build-plugin-test-old.ts
diff --git a/CLAUDE.md b/CLAUDE.md
index c497a76..89a646b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -21,8 +21,13 @@ Chores are cross-cutting work that doesn't belong to any single §6 cycle (licen
## Architecture (target system)
-- **scholar MCP server** — Bun + `bun:sqlite` + `drizzle-orm/bun-sqlite` + `sqlite-vec`, shipped as a `bun build --compile` single-file executable. Exposes corpus, ingestion, annotation, digest, prompts, search, and UI-resource tools. Spawns the vendored pdf MCP as a child.
-- **vendored pdf MCP** — `@modelcontextprotocol/server-pdf@1.7.2` shipped **unmodified** under `src/vendor/pdf-server/`. Root injection rides the standard MCP `roots/list` + `notifications/roots/list_changed` protocol; scholar implements the client-side responder in `src/server/pdf/lifecycle.ts`. No source patch.
+> **Slim-plugin pivot (2026-06-01):** packaging changed from a self-contained
+> `--compile` binary + bundled runtime to a slim ~2.9 MB plugin. See
+> `docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md`. The bullets below
+> reflect the post-pivot model.
+
+- **scholar MCP server** — Bun + `bun:sqlite` + `drizzle-orm/bun-sqlite` + `sqlite-vec`, shipped as a `bun build --target=bun` bundle (`dist/server.js`, ~2.5 MB, **not** `--compile`). The `bun` runtime is **provisioned** into `${CLAUDE_PLUGIN_DATA}` by `bin/ensure-bun` at first launch (pinned to `scholar.bundledBunVersion` for the vec0 ABI), not shipped. A shell launcher (`bin/launch.{sh,cmd}`, manifest command `/bin/sh` | `cmd.exe`) provisions-then-runs the server (M2 — SessionStart does not block MCP spawn). Exposes corpus, ingestion, annotation, digest, prompts, search, and UI-resource tools. Spawns the pdf MCP as a child.
+- **pdf MCP** — `@modelcontextprotocol/server-pdf@1.7.2`. The vendored `src/vendor/pdf-server/` tree stays in-repo **unmodified** as the §16 `.d.ts` truth source and dev fallback. For packaging it is mechanically **rebundled standalone** (`bun build --target=bun` inlines pdfjs-dist) to `dist/pdf-server/index.js` + `mcp-app.html` — no source patch. `resolveChildEntrypoint` (`src/server/pdf/lifecycle.ts`) prefers `SCHOLAR_PDF_ENTRYPOINT` → shipped `dist/pdf-server/` → vendored dev fallback. Root injection rides the standard MCP `roots/list` + `notifications/roots/list_changed` protocol; scholar implements the client-side responder in `lifecycle.ts`.
- **single-file UI bundle** — React, built by Bun's HTML bundler (`bun build src/ui/index.html --target=browser`, no vite). Five views: corpus dashboard, paper detail, digest panel, reading prompts, reader progress.
- **nu CLI module** — `nu/scholar.nu`, user-facing wrapper that calls scholar MCP tools and shapes responses into nu tables.
- **sqlite3-mcp delegation** — query/backup/pack surfaces are delegated; scholar calls `register_db` per corpus and does **not** reimplement those tools.
diff --git a/bin/ensure-bun.ps1 b/bin/ensure-bun.ps1
new file mode 100644
index 0000000..9d77e73
--- /dev/null
+++ b/bin/ensure-bun.ps1
@@ -0,0 +1,49 @@
+# bin/ensure-bun.ps1 — slim-plugin runtime provisioner (Windows target).
+#
+# Mirror of ensure-bun.sh. Idempotently provisions the PINNED bun.exe into
+# ${CLAUDE_PLUGIN_DATA}\bun (persists across plugin updates). Called
+# synchronously by launch.cmd before it launches the server.
+#
+# ALL diagnostic output goes to stderr (Write-Error / $host.UI write to stderr;
+# we use [Console]::Error) — stdout must stay clean for the MCP JSON-RPC stream.
+#
+# FLAGGED: not executable on the Linux dev host; validate on Windows hardware.
+$ErrorActionPreference = "Stop"
+$Pin = "1.3.11" # keep in sync with package.json scholar.bundledBunVersion
+
+if (-not $env:CLAUDE_PLUGIN_DATA) { [Console]::Error.WriteLine("ensure-bun: CLAUDE_PLUGIN_DATA unset"); exit 1 }
+$BunDir = Join-Path $env:CLAUDE_PLUGIN_DATA "bun"
+$BunBin = Join-Path $BunDir "bun.exe"
+
+function Test-Ok {
+ if (-not (Test-Path $BunBin)) { return $false }
+ try { return ((& $BunBin --version 2>$null) -eq $Pin) } catch { return $false }
+}
+
+if (Test-Ok) { exit 0 }
+
+New-Item -ItemType Directory -Force -Path $BunDir | Out-Null
+
+# Coarse single-writer guard (no flock on Windows): a lock dir created atomically.
+$Lock = Join-Path $BunDir ".provision.lock"
+$haveLock = $false
+for ($i = 0; $i -lt 120; $i++) {
+ try { New-Item -ItemType Directory -Path $Lock -ErrorAction Stop | Out-Null; $haveLock = $true; break }
+ catch { if (Test-Ok) { exit 0 }; Start-Sleep -Milliseconds 500 }
+}
+try {
+ if (Test-Ok) { exit 0 }
+ $Url = "https://github.com/oven-sh/bun/releases/download/bun-v$Pin/bun-windows-x64.zip"
+ [Console]::Error.WriteLine("ensure-bun: provisioning bun $Pin (windows-x64) into $BunDir")
+ $Tmp = Join-Path $BunDir ".dl"
+ if (Test-Path $Tmp) { Remove-Item -Recurse -Force $Tmp }
+ New-Item -ItemType Directory -Force -Path $Tmp | Out-Null
+ $Zip = Join-Path $Tmp "bun.zip"
+ Invoke-WebRequest -Uri $Url -OutFile $Zip
+ Expand-Archive -Path $Zip -DestinationPath $Tmp -Force
+ Move-Item -Force (Join-Path $Tmp "bun-windows-x64\bun.exe") $BunBin
+ Remove-Item -Recurse -Force $Tmp
+ [Console]::Error.WriteLine("ensure-bun: provisioned $(& $BunBin --version)")
+} finally {
+ if ($haveLock) { Remove-Item -Recurse -Force $Lock -ErrorAction SilentlyContinue }
+}
diff --git a/bin/ensure-bun.sh b/bin/ensure-bun.sh
new file mode 100644
index 0000000..3c2c2a0
--- /dev/null
+++ b/bin/ensure-bun.sh
@@ -0,0 +1,51 @@
+#!/bin/sh
+# bin/ensure-bun.sh — slim-plugin runtime provisioner (Linux/macOS dev + parity).
+#
+# Idempotently provisions the PINNED bun runtime into ${CLAUDE_PLUGIN_DATA}/bun.
+# ${CLAUDE_PLUGIN_DATA} persists across plugin updates (unlike CLAUDE_PLUGIN_ROOT,
+# which is replaced each version), so bun is downloaded at most once per machine.
+#
+# Called synchronously by launch.sh BEFORE it execs the server — this is the
+# correctness guarantee that bun exists before the MCP server needs it (Claude
+# Code's SessionStart hooks do NOT block MCP spawn, so provisioning cannot live
+# there alone). May also be pre-warmed by a SessionStart hook; the flock below
+# serializes concurrent invocations.
+#
+# ALL diagnostic output goes to stderr — stdout is reserved for the MCP server's
+# JSON-RPC stream once launch.sh execs into it.
+set -eu
+
+PIN="1.3.11" # keep in sync with package.json scholar.bundledBunVersion (vec0 ABI)
+: "${CLAUDE_PLUGIN_DATA:?CLAUDE_PLUGIN_DATA is unset}"
+BUN_DIR="${CLAUDE_PLUGIN_DATA}/bun"
+BUN_BIN="${BUN_DIR}/bun"
+
+ok() { [ -x "$BUN_BIN" ] && [ "$("$BUN_BIN" --version 2>/dev/null || true)" = "$PIN" ]; }
+
+ok && exit 0
+
+mkdir -p "$BUN_DIR"
+# Serialize SessionStart-prewarm vs launcher invocations (avoid double-download).
+LOCK="${BUN_DIR}/.provision.lock"
+if command -v flock >/dev/null 2>&1; then
+ exec 9>"$LOCK"
+ flock 9
+fi
+ok && exit 0 # another invocation finished while we waited on the lock
+
+case "$(uname -m)" in
+ x86_64) ARCH="x64" ;;
+ aarch64 | arm64) ARCH="aarch64" ;;
+ *) echo "ensure-bun: unsupported arch $(uname -m)" >&2; exit 1 ;;
+esac
+URL="https://github.com/oven-sh/bun/releases/download/bun-v${PIN}/bun-linux-${ARCH}.zip"
+
+echo "ensure-bun: provisioning bun ${PIN} (${ARCH}) into ${BUN_DIR}" >&2
+TMP="${BUN_DIR}/.dl"
+rm -rf "$TMP"; mkdir -p "$TMP"
+curl -fsSL "$URL" -o "${TMP}/bun.zip"
+unzip -q -o "${TMP}/bun.zip" -d "$TMP"
+mv "${TMP}/bun-linux-${ARCH}/bun" "$BUN_BIN"
+chmod +x "$BUN_BIN"
+rm -rf "$TMP"
+echo "ensure-bun: provisioned $("$BUN_BIN" --version)" >&2
diff --git a/bin/launch.cmd b/bin/launch.cmd
new file mode 100644
index 0000000..0a7cea0
--- /dev/null
+++ b/bin/launch.cmd
@@ -0,0 +1,20 @@
+@echo off
+rem bin/launch.cmd — slim-plugin MCP launcher (Windows target).
+rem
+rem The plugin manifest spawns this via the always-present cmd.exe (Node/Bun
+rem spawn cannot run a .cmd/.ps1 directly, so cmd.exe is the command):
+rem "command": "cmd.exe",
+rem "args": ["/c", "${CLAUDE_PLUGIN_ROOT}\\bin\\launch.cmd"]
+rem
+rem 1. ensure-bun.ps1 provisions the pinned bun.exe synchronously (its stdout/
+rem stderr go to stderr; 1>&2 guards stdout for the MCP JSON-RPC stream).
+rem 2. Launch bun.exe dist\server.js — its stdio is inherited through cmd.
+rem
+rem FLAGGED: cmd.exe has no exec-replace, so bun.exe runs as a child of this
+rem cmd. If Claude Code does not tree-kill the MCP process on shutdown, bun may
+rem orphan and hold runtime\scholar.lock. Validate tree-kill on Windows hardware;
+rem mitigate with a Job Object on the cmd side if orphaning is observed.
+setlocal
+powershell -NoProfile -ExecutionPolicy Bypass -File "%CLAUDE_PLUGIN_ROOT%\bin\ensure-bun.ps1" 1>&2
+if errorlevel 1 exit /b 1
+"%CLAUDE_PLUGIN_DATA%\bun\bun.exe" "%CLAUDE_PLUGIN_ROOT%\dist\server.js" %*
diff --git a/bin/launch.sh b/bin/launch.sh
new file mode 100644
index 0000000..9c6c22b
--- /dev/null
+++ b/bin/launch.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+# bin/launch.sh — slim-plugin MCP launcher (Linux/macOS).
+#
+# The plugin manifest spawns this via an always-present shell:
+# "command": "/bin/sh", "args": ["${CLAUDE_PLUGIN_ROOT}/bin/launch.sh"]
+# Using /bin/sh (not the script directly) sidesteps the zip executable-bit
+# problem, and `exec` below REPLACES this shell with bun — so the PID Claude
+# Code spawned BECOMES the server (no orphaned wrapper, lock released on kill).
+#
+# 1. ensure-bun provisions the pinned runtime synchronously (correctness gate).
+# 2. exec bun dist/server.js — scholar then runs UNDER the provisioned bun, so
+# process.execPath is that bun (the pdf child inherits it) and
+# CLAUDE_PLUGIN_ROOT resolves dist/pdf-server + vec0 with no extra env.
+set -eu
+# Invoke ensure-bun via `sh` (not directly) — the zip does not preserve the
+# executable bit, so neither launch.sh nor ensure-bun.sh can rely on +x.
+sh "${CLAUDE_PLUGIN_ROOT}/bin/ensure-bun.sh"
+exec "${CLAUDE_PLUGIN_DATA}/bun/bun" "${CLAUDE_PLUGIN_ROOT}/dist/server.js" "$@"
diff --git a/bin/scholar.nu b/bin/scholar.nu
new file mode 100755
index 0000000..dfe89a5
--- /dev/null
+++ b/bin/scholar.nu
@@ -0,0 +1,134 @@
+#!/usr/bin/env -S nu --stdin
+# Usage: nu scholar.nu
+const SELF = path self
+
+def --wrapped "safe extract" [
+ ...rest: string
+ --select # Use `select` over `get`, i.e. to return a table instead of a list
+]: oneof
-> oneof {
+ let value = $in
+ if ($value | describe) == string {
+ $value
+ } else if $select {
+ $value | select --optional ...$rest
+ } else {
+ $value | get --optional $rest.0 ...($rest | skip 1)
+ }
+}
+
+# Resolve the M2 server invocation. The slim-plugin pivot (2026-06-01) dropped
+# the compiled `mcp-scholar` binary; scholar now runs as `bun dist/server.js`,
+# dispatched in CLI mode via `--call ` (see src/server/index.ts).
+# Resolution order:
+# 1. SCHOLAR_SERVER_CMD — space-separated override (test/operator escape hatch,
+# mirrors SCHOLAR_PDF_ENTRYPOINT / SCHOLAR_BUN_PATH / SCHOLAR_VEC0_PATH).
+# 2. the provisioned bun (${CLAUDE_PLUGIN_DATA}/bun/bun) running
+# ${CLAUDE_PLUGIN_ROOT}/dist/server.js, located relative to this module
+# (nu/scholar.nu → plugin root); falls back to a PATH `bun` for dev.
+def server-cmd []: nothing -> list {
+ if 'SCHOLAR_SERVER_CMD' in $env {
+ return ($env.SCHOLAR_SERVER_CMD | split row ' ' | where {|t| $t | is-not-empty })
+ }
+ let root = ($SELF | path dirname | path dirname)
+ let provisioned = ($env.CLAUDE_PLUGIN_DATA? | default '' | path join 'bun' 'bun')
+ let bun = if ($provisioned | path exists) { $provisioned } else { 'bun' }
+ [$bun ($root | path join 'dist' 'server.js')]
+}
+
+# Wrapper for the scholar MCP server (M2: `bun dist/server.js --call`).
+def main [
+ tool?: string # The name of the tool to call on the server
+ --json: oneof # Parameters to pass through to the tool call
+]: oneof -> oneof {
+ if $tool == null { print --stderr 'tool name is required' | return }
+ let args = $in | default $json | default {}
+ let payload = if ($args | describe) == 'string' { $args } else { $args | to json --raw }
+ let cmd = (server-cmd)
+ let output = run-external ($cmd | first) ...($cmd | skip 1) '--call' $tool $payload
+ | complete
+ | default 0 exit_code
+ | default '{}' stdout stderr
+ let text = if ($output.exit_code) == 0 { $output.stdout } else { $output.stderr }
+ try { $text | str trim | to json --raw } catch { $text }
+}
+
+# List papers in the active corpus (uses ctx.db snapshot — no corpus_id arg).
+def "main list" [
+ --limit: int = 50 # Maximum number of results to return
+ --query: string = '' # Filter string to query results with
+]: nothing -> oneof {
+ let res = {q: $query limit: $limit} | main papers.search
+ if ($res | describe) == string { return $res }
+ if ($res.still_indexing? | default false) {
+ print "note: semantic index still building; results are lexical only"
+ }
+ $res.hits? | default [] | select id title score
+}
+
+# Show corpus status.
+def "main status" [
+ corpus?: string # The identifier of a corpus to target (defaults to active )
+]: nothing -> oneof {
+ if ($corpus | is-empty) { {} } else { {corpus_id: $corpus} }
+ | main scholar.corpus.status
+}
+
+# Ingest papers from BibTeX/RIS/DOI/arXiv.
+# Routes to scholar.ingest.{bibtex,ris,doi,arxiv}.
+def "main ingest" [
+ corpus: string # The identifier of the corpus to ingest papers into
+ --bibtex: string # Path to a BibTeX paper to ingest
+ --ris: string # Path to a RIS paper to ingest
+ --doi: string # Direct DOI of a paper to ingest
+ --arxiv: string # arXiv identifier of a paper to ingest
+]: nothing -> oneof {
+ if ($bibtex | is-not-empty) {
+ {file_path: $bibtex corpus_id: $corpus}
+ | main scholar.ingest.bibtex
+ | safe extract imported
+ } else if ($ris | is-not-empty) {
+ {file_path: $ris corpus_id: $corpus}
+ | main scholar.ingest.ris
+ | safe extract imported
+ } else if ($doi | is-not-empty) {
+ {doi: $doi corpus_id: $corpus}
+ | main scholar.ingest.doi
+ } else if ($arxiv | is-not-empty) {
+ {arxiv_id: $arxiv corpus_id: $corpus}
+ | main scholar.ingest.arxiv
+ } else {
+ error make "one of `--bibtex`, `--ris`, `--doi`, `--arxiv` is required"
+ }
+}
+
+# Search papers (hybrid lexical + semantic via RRF — mode always-on, no mode arg).
+# still_indexing=true signals semantic is building; lexical results are returned in the interim.
+def "main query" [
+ q: string # The query string to match results to
+ --limit: int = 50 # Maximum number of entries to return
+]: nothing -> oneof {
+ # args: { q: string; limit?: number } — corpus_id and mode DROPPED per extraction-003 contract
+ main list --limit $limit --query $q
+}
+
+# Generate digest on a scoped set of papers.
+def "main digest" [
+ --all # Include all papers (default)
+ --stale # Include only stale papers
+ --label: string # Include papers by section label
+ --hash: string # Include papers by selection hash
+ --claude # Use Claude for running the inference instead of Ollama
+]: nothing -> string {
+ let scope = match {all: $all stale: $stale section: $label selection: $hash} {
+ {all: true} => 'all'
+ {stale: true} => 'stale'
+ {section: $s} if $s != null => $'section:($s)'
+ {selection: $h} if $h != null => $'selection:($h)'
+ } | default all
+ let res = {scope_key: $scope use_claude: $claude} | main scholar.digest.generate
+ if ($res | describe) =~ table and $res.askClaude? == null {
+ $res | get --optional body_md | default "(empty body)"
+ } else {
+ "digest requires claude opt-in; run with `--claude` or use the Cowork host UI."
+ }
+}
diff --git a/commands/digest.md b/commands/digest.md
deleted file mode 100644
index ccd76c9..0000000
--- a/commands/digest.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-name: scholar:digest
-description: Generate a synthesis digest for the active corpus scope (Ollama default; --claude opt-in).
----
-
-# /scholar:digest
-
-## Usage
-
-```
-/scholar:digest
-/scholar:digest --scope section:methods
-/scholar:digest --scope stale
-/scholar:digest --claude
-```
-
-## Arguments
-
-| Argument | Type | Default | Description |
-|---|---|---|---|
-| `--scope` | string | `all` | One of `all`, `stale`, `section:`, `selection:` (SA3 enum — spec §9.3, §8.2) |
-| `--corpus` | string | active | Corpus slug |
-| `--claude` | flag | false | Opt in to Claude (cowork.askClaude) for this single request (spec §11) |
-
-## Behavior
-
-Calls `scholar.digest.generate` with `{scope_key, use_claude}`. Default LLM is local Ollama (`qwen3:8b` by default). **SA4 invariant (CLAUDE.md):** mechanical LLM work routes through Ollama; `--claude` is per-request opt-in only — never the default path.
-
-Result field is `body_md` (extraction-003 §6.8 contract). When the server returns a `structuredContent.askClaude` sentinel (typically: Ollama unavailable + askClaude opt-in not set), the CLI prints the opt-in hint rather than the digest body.
diff --git a/commands/ingest.md b/commands/ingest.md
deleted file mode 100644
index a2fad15..0000000
--- a/commands/ingest.md
+++ /dev/null
@@ -1,31 +0,0 @@
----
-name: scholar:ingest
-description: Ingest a paper into the active scholar corpus from a DOI, arXiv ID, BibTeX file, or RIS file.
----
-
-# /scholar:ingest
-
-## Usage
-
-```
-/scholar:ingest --doi 10.1234/example
-/scholar:ingest --arxiv 2401.00001
-/scholar:ingest --bibtex /path/to/refs.bib
-/scholar:ingest --ris /path/to/refs.ris
-```
-
-## Arguments
-
-| Argument | Type | Description |
-|---|---|---|
-| `--doi` | string | CrossRef DOI (e.g. `10.1038/s41586-021-03819-2`) |
-| `--arxiv` | string | arXiv ID or URL (e.g. `2401.00001` or `arxiv:cs.AI/2401.00001`) |
-| `--bibtex` | path | `.bib` file path |
-| `--ris` | path | `.ris` file path |
-| `--corpus` | string | Target corpus slug (active corpus used if omitted) |
-
-## Behavior
-
-Routes to one of `scholar.ingest.doi`, `scholar.ingest.arxiv`, `scholar.ingest.bibtex`, or `scholar.ingest.ris` based on the supplied flag. All metadata is sanitized at the ingestion boundary via §12.0 primitives (`sanitizeText`, `wrapUntrusted`, `encodeDoi`, `validateArxivId`). Duplicate DOI / arXiv entries UPSERT (not re-insert).
-
-Backed by the `scholar` nu module wrapper at `nu/scholar.nu` — invoke directly with `scholar ingest --doi …` after `use nu/scholar.nu *`.
diff --git a/commands/status.md b/commands/status.md
deleted file mode 100644
index e1f49ca..0000000
--- a/commands/status.md
+++ /dev/null
@@ -1,28 +0,0 @@
----
-name: scholar:status
-description: Show paper counts by status, stale papers, and last-opened timestamp for a corpus.
----
-
-# /scholar:status
-
-## Usage
-
-```
-/scholar:status
-/scholar:status --corpus daisy
-```
-
-## Arguments
-
-| Argument | Type | Default | Description |
-|---|---|---|---|
-| `--corpus` | string | active | Corpus slug to inspect |
-
-## Behavior
-
-Calls `scholar.corpus.status` and renders the returned record. Output includes:
-- Per-status counts (`pending`, `reading`, `reviewed`, `skip`)
-- `last_opened_at` ISO timestamp
-- Stale-paper summary (papers whose `last_read_at` predates the most recent corpus change)
-
-Backed by the `scholar status` subcommand in `nu/scholar.nu`.
diff --git a/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md b/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md
new file mode 100644
index 0000000..30e1f26
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md
@@ -0,0 +1,154 @@
+# Slim-plugin pivot (2026-06-01)
+
+Amendment to `2026-05-22-scholar-plugin-design.md`. Target platform: **Windows**;
+development platform: **Linux/WSL**. Driver: the **~200 MB unpacked-plugin upload
+limit**. This document records the architecture, the empirical evidence behind
+each load-bearing decision, and the deviations from prior locked choices.
+
+## Problem
+
+The pre-pivot packaging shipped a fully self-contained runtime:
+
+| Artifact | Size | Fate |
+| --- | --- | --- |
+| `bin/mcp-scholar.exe` (`bun build --compile`) | ~96 MB | **dropped** |
+| bundled bun runtime (the pdf-child spawn target) | ~90 MB | **dropped** (provisioned instead) |
+| vendored pdf-server `dist/` | 6.7 MB | **rebundled** to one standalone file |
+
+The 96 MB came from `--compile` inlining all of `node_modules` into the binary.
+The 90 MB bundled bun was a redundant second copy of the runtime. Together they —
+not the 6.7 MB vendored pdf — were the bloat.
+
+## Architecture (slim)
+
+- **scholar server** ships as a single `bun build --target=bun` bundle
+ (`dist/server.js`, **2.46 MB**, 419 modules inlined) — **no `--compile`**. The
+ provisioned bun runs it directly: `bun dist/server.js`.
+- **pdf-server@1.7.2** ships as a single rebundled standalone file
+ (`dist/pdf-server/index.js`, **~4 MB**) + `mcp-app.html` beside it. pdfjs-dist
+ and all deps are inlined by `bun build`; **no runtime provisioning, no network
+ at first-run.** pdf remains scholar's spawned child (roots injection, the
+ `scholar.pdf.*` proxy, supervisor/respawn, §13 push path all unchanged).
+- **bun** (the runtime) is the *only* thing provisioned into the persistent
+ per-plugin data dir `${CLAUDE_PLUGIN_DATA}`, by a SessionStart hook that fires
+ before the MCP server connects. Pinned to **1.3.11** for the vec0 ABI (below).
+- **vec0** ships in-package for **both** platforms (`vec0.so` for dev, `vec0.dll`
+ for target) — it is KB-scale and its ABI is build-time-coupled to bun's SQLite.
+- **Windows `koffi.node`** (native, used only by the Job-Object orphan-reaper on
+ win32) is provisioned/shipped for the target; it can never be JS-bundled.
+
+### Runtime resolution seams (`src/server/pdf/lifecycle.ts`)
+
+- `resolveChildEntrypoint`: `SCHOLAR_PDF_ENTRYPOINT` → `${CLAUDE_PLUGIN_ROOT}/dist/pdf-server/index.js`
+ (shipped bundle, `existsSync`-gated) → `/src/vendor/pdf-server/dist/index.js`
+ (dev fallback, resolves pdfjs from repo node_modules).
+- `resolveBunRuntime`: `SCHOLAR_BUN_PATH` → `process.execPath` (scholar itself
+ runs under the provisioned bun, so execPath is already correct).
+
+## Empirical evidence (verified on Linux, 2026-06-01)
+
+1. `bun build src/server/index.ts --target=bun` → 2.46 MB `server.js`; ran from a
+ dir with **no node_modules**, dispatched `scholar.corpus.list`, reached the DB
+ (structured `no such table` error — expected on an empty temp root). ajv stayed
+ external but **dormant** (scholar validates with zod, not ajv).
+2. Rebundled pdf-server ran from `/tmp/pdf-bundle/` (no node_modules up-tree) and
+ passed the **real** vendor contract gate
+ (`lifecycle.contract.test.ts`, `SCHOLAR_PDF_E2E=1`, `SCHOLAR_PDF_ENTRYPOINT`
+ override): **2 pass / 0 fail** — `display_pdf` parsed the PDF (pdfjs inlined),
+ `interact({navigate})` + `add/remove_annotations` round-tripped.
+3. Baseline preserved through the seam edits: `bunx tsc --noEmit` clean;
+ `bun test` **285 pass / 8 skip / 0 fail**.
+4. **Production resolution paths exercised from the assembled package under the
+ pinned bun 1.3.11** (not the dev override / not a standalone probe):
+ - `resolveChildEntrypoint`'s `existsSync(${CLAUDE_PLUGIN_ROOT}/dist/pdf-server/index.js)`
+ branch — run with `CLAUDE_PLUGIN_ROOT` pointed at the installed package and
+ **no** `SCHOLAR_PDF_ENTRYPOINT` override — spawned the pdf child under the
+ provisioned bun (`process.execPath`). `lifecycle.contract.test.ts`: **2 pass**,
+ `[pdf-server] Ready` confirmed on stderr, `display_pdf` parsed.
+ - scholar's own `resolveVec0Path()` resolved the packaged
+ `${CLAUDE_PLUGIN_ROOT}/build/vendor/sqlite-vec/vec0.so` branch; `loadExtension`
+ + a `vec0` virtual table + a KNN `MATCH` all succeeded under bun 1.3.11
+ (`vec_version v0.1.9`). The ABI pin-gate now passes through scholar's
+ production resolver, not the build-time probe alone.
+
+## Deviations from prior locked decisions (for user review)
+
+- **"provision pdf-server@1.7.2 at first-run" → "ship a rebundled standalone pdf
+ bundle in-package."** Evidence (2) shows the bundle parses PDFs offline with no
+ node_modules; shipping ~4 MB is deterministic, offline, and avoids a first-run
+ network race. pdf still ships pinned @1.7.2 and stays the child process — only
+ the on-disk delivery changes. **Reversible** via `SCHOLAR_PDF_ENTRYPOINT` if a
+ provisioned model is ever preferred.
+- **CLAUDE.md "vendored pdf shipped unmodified / no source patch" still holds** —
+ the bundle is a mechanical `bun build` of the unmodified vendor dist; the
+ vendored tree stays in-repo as the §16 `.d.ts` truth source and dev fallback.
+
+## Build system (validated 2026-06-01)
+
+`scripts/build-plugin.ts` rewritten to the slim model; `SCHOLAR_BUILD_WIN`
+selects target. Both packages build on the Linux host:
+
+- **linux** `scholar.plugin` 2.8 MB / 15 files — unzipped and launched via the
+ generated manifest (`/bin/sh ${ROOT}/bin/launch.sh`) with a fresh
+ `CLAUDE_PLUGIN_DATA`: ensure-bun provisioned bun 1.3.11, MCP `initialize`
+ returned clean JSON-RPC on stdout. **Fully validated end-to-end.**
+- **win32** `scholar.plugin` 2.9 MB / 15 files — `vec0.dll` (PE32+ confirmed)
+ fetched from the `sqlite-vec-windows-x64` npm tarball at the version-parity
+ pin; Windows launcher set + `cmd.exe /c launch.cmd` manifest staged.
+ **Structure validated; launch path requires Windows hardware.**
+
+Launch is **M2** (see `bin/`): an always-present shell (`/bin/sh` | `cmd.exe`)
+runs `launch.{sh,cmd}`, which calls the idempotent `ensure-bun` provisioner then
+runs the server. A `SessionStart` hook pre-warms `ensure-bun` (latency only —
+the launcher is the correctness gate, because SessionStart does not block MCP
+spawn). On Linux the launcher `exec`s into bun (no orphaned wrapper).
+
+## Resolved (was open, now verified on Linux)
+
+- **bun pin vs vec0 ABI** — `loadExtension(vec0)` + a `vec0` virtual table
+ function under the *pinned* bun 1.3.11 (sqlite-vec 0.1.9). Linux build runs
+ the ABI probe as a hard gate.
+- **vec0.dll for the target** — obtained from the npm tarball (no mingw cross-
+ compile); 283 KB PE32+ x86-64 DLL.
+- **`@napi-rs/canvas`** — confirmed benign: scholar's pdf surface has no
+ rasterize/render-to-image call (grep clean); browser renders, `get_text` uses
+ the text layer.
+
+## Still open (require Windows-hardware validation — cannot verify from WSL)
+
+- **Windows launch orphan**: `cmd.exe /c launch.cmd` has no exec-replace, so
+ `bun.exe` runs as a child of cmd. If Claude Code does not tree-kill the MCP
+ process on shutdown, bun may orphan. Verify tree-kill; mitigate with a Job
+ Object on the cmd side if observed. **Note:** the chained "orphan holds
+ `runtime/scholar.lock` → next session `SCHOLAR_LOCKED`" DoS is **moot today** —
+ the single-active-session flock is a frozen v1 *spec* invariant (CLAUDE.md) but
+ is **not yet implemented** (`grep` of `src/server/index.ts` finds no lock
+ acquisition). When that flock is wired, harden it against a stale holder
+ (liveness/staleness check) so a dead-but-lock-holding PID cannot wedge startup.
+- **ensure-bun.ps1**: the PowerShell download/extract path is unexecuted on the
+ dev host. Validate `Invoke-WebRequest`/`Expand-Archive` + the lock-dir guard.
+- **koffi.node (win32-x64) — KNOWN REGRESSION (decided: accept + document).**
+ `attachJobObject` does a runtime `require("koffi")` inside `server.js`. `bun
+ build --target=bun` keeps native modules external, and the slim package ships
+ **no `node_modules`**, so on Windows that `require` throws and is swallowed by
+ the existing `try/catch` (lifecycle.ts:365) — Job-Object reaping of the **pdf
+ child** is OFF by default. The `--compile` binary embedded koffi and had it; the
+ slim bundle does not. This is accepted for the slim pivot because: (a) the reaper
+ is best-effort, already `try/catch` graceful-degrade by explicit design
+ (lifecycle.ts:372, "Foundation accepts the limitation"); (b) its only effect is
+ pdf-child orphaning *if* Claude Code also fails to tree-kill (the open flag
+ above) — the two must both fail to bite; (c) the lock-DoS escalation is moot
+ (flock unimplemented). **Remediation if pdf-child orphaning is observed on
+ Windows hardware:** fetch `@koromix/koffi-win32-x64`'s `.node` from npm (the
+ `os:win32` native is not installed on the Linux build host) and lay it out so
+ koffi's loader resolves it (e.g. `KOFFI_DIR` / a co-located
+ `node_modules/koffi`), *or* tree-kill the pdf child from the cmd-side launcher.
+ Not done blind here — koffi's native-binding resolution cannot be validated off
+ the target.
+- **UI bundling**: `build:ui` emits `ui/index.html` + a `chunk-*.js` (two files,
+ pre-existing behavior — not single-file as CLAUDE.md §14.1 implies). Both are
+ packaged; if the MCP UI resource requires a single inline file, the UI build
+ config (not the slim pivot) needs a follow-up.
+- **MCP connect timeout**: first launch blocks on the bun download (~tens of MB).
+ If Claude Code imposes a short MCP spawn/connect timeout, the SessionStart
+ pre-warm mitigates but does not guarantee; confirm the timeout is generous.
diff --git a/nu/scholar.nu b/nu/scholar.nu
deleted file mode 100644
index a1633fb..0000000
--- a/nu/scholar.nu
+++ /dev/null
@@ -1,117 +0,0 @@
-# nu/scholar.nu — Scholar CLI module. Usage: use nu/scholar.nu *
-# Transport: ^scholar --call (foundation-007, cycle 6.1 dual-mode)
-# Prereq: scholar binary on PATH (packaging cycle 6.13)
-#
-# Contract sources (cross-plan):
-# - extraction-003 lines 1167-1169, 1237 — papers.search args {q, limit?} and result {hits, still_indexing}
-# - extraction-003 lines 1485-1486, 1496 — digest.generate args {scope_key, use_claude?} and result {body_md, askClaude?}
-# - CLAUDE.md load-bearing invariants — SA4 use_claude defaults to false (Ollama default)
-
-# Transport wrapper — exported as `main` so calling the module name
-# (`scholar "tool" {args}`) invokes it. Nu forbids exporting a command with
-# the same name as the module; `main` is the canonical workaround per nu docs.
-# Uses `| complete` to capture stdout/stderr/exit_code as a record.
-# Foundation-009 contract: exit_code=0 → stdout=JSON+\n; exit_code!=0 → stderr=structured-error JSON.
-# Naïve `^scholar --call ... | from json` loses the error shape on failure.
-export def main [
- tool: string # MCP tool name e.g. "scholar.corpus.activate"
- args: record = {} # tool arguments as a record
-] {
- let payload = ($args | to json)
- let result = (^scholar --call $tool $payload | complete)
- if $result.exit_code != 0 {
- # Reverse-walk stderr to find the first line that is a JSON object with an `error` key.
- # Foundation warn logs may interleave; `lines | last` would grab the wrong line.
- let err_line = (
- $result.stderr
- | lines
- | reverse
- | where { |line| ($line | str trim | str starts-with "{") }
- | first
- )
- let err = (if ($err_line | is-empty) {
- { error: "non_json_stderr", message: $result.stderr }
- } else {
- $err_line | from json
- })
- error make {
- msg: $err.message,
- label: { text: $err.error, span: (metadata $tool).span }
- }
- }
- $result.stdout | from json
-}
-
-# List papers in the active corpus (uses ctx.db snapshot — no corpus_id arg).
-# Contract (extraction-003 lines 1167-1169, 1237):
-# args: { q: string; limit?: number } — corpus_id/mode DROPPED
-# result: { hits: SearchHit[]; still_indexing: boolean }
-# --status is applied client-side in v1 (search result lacks status field).
-export def "scholar list" [
- --status: string # filter: pending|reading|reviewed|skip (client-side post-filter in v1)
- --limit: int = 50
-] {
- let args = {q: "" limit: $limit}
- let res = main "scholar.papers.search" $args
- let hits = ($res | get hits)
- let still_indexing = ($res | get still_indexing)
- if $still_indexing {
- print "Note: semantic index still building — results are lexical only (still indexing)"
- }
- $hits | select id title score
-}
-
-# Show corpus status.
-export def "scholar status" [--corpus: string] {
- let args = if ($corpus | is-empty) { {} } else { {corpus_id: $corpus} }
- main "scholar.corpus.status" $args
-}
-
-# Ingest papers from BibTeX/RIS/DOI/arXiv.
-# Routes to scholar.ingest.{bibtex,ris,doi,arxiv}.
-export def "scholar ingest" [
- --corpus: string --bibtex: string --ris: string
- --doi: string --arxiv: string
-] {
- if not ($bibtex | is-empty) {
- main "scholar.ingest.bibtex" {file_path: $bibtex corpus_id: $corpus} | get imported
- } else if not ($ris | is-empty) {
- main "scholar.ingest.ris" {file_path: $ris corpus_id: $corpus} | get imported
- } else if not ($doi | is-empty) {
- main "scholar.ingest.doi" {doi: $doi corpus_id: $corpus}
- } else if not ($arxiv | is-empty) {
- main "scholar.ingest.arxiv" {arxiv_id: $arxiv corpus_id: $corpus}
- } else {
- error make { msg: "Specify one of: --bibtex, --ris, --doi, --arxiv" }
- }
-}
-
-# Search papers (hybrid lexical + semantic via RRF — mode always-on, no mode arg).
-# still_indexing=true signals semantic is building; lexical results are returned in the interim.
-export def "scholar query" [
- q: string # search query
- --limit: int = 20
-] {
- # args: { q: string; limit?: number } — corpus_id and mode DROPPED per extraction-003 contract
- let res = main "scholar.papers.search" {q: $q limit: $limit}
- if ($res | get still_indexing) {
- print "Note: semantic index still building — results are lexical only (still indexing)"
- }
- $res | get hits | select id title score
-}
-
-# Generate digest. scope: "all" | "section:" | "stale" | "selection:"
-# SA4 (CLAUDE.md load-bearing invariant): --claude is opt-in only; default is Ollama
-# ("Mechanical LLM → local Ollama … cowork.askClaude is an explicit per-request opt-in
-# only — never the default path"). Result field: body_md (extraction-003 line 1496).
-export def "scholar digest" [
- --scope: string = "all" --claude
-] {
- # args: { scope_key, use_claude? } — corpus_id DROPPED (per-corpus ctx.db snapshot)
- let res = main "scholar.digest.generate" {scope_key: $scope use_claude: $claude}
- if ($res | get -o askClaude | is-empty) {
- $res | get body_md
- } else {
- "Digest requires Claude opt-in — run with --claude or use the UI in a Cowork host."
- }
-}
diff --git a/nu/scholar.test.ts b/nu/scholar.test.ts
deleted file mode 100644
index 1957770..0000000
--- a/nu/scholar.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// nu/scholar.test.ts
-// Red/Green tests for cycle 6.10 — nu module behavior + structural anchors.
-//
-// Tests split into two groups:
-// 1. nu-spawn tests (skip if nu not on PATH) — exercise the actual module
-// 2. grep tests (always run) — pin tool-name references in source
-//
-// Grep tests fail at Red phase (file not yet created). nu-spawn tests skip
-// or fail with "Cannot find module" at Red phase.
-import { test, expect } from "bun:test";
-
-// Synchronous detection so test.skipIf() evaluates correctly at definition time.
-const nuAvailable = (() => {
- try { return Bun.spawnSync(["nu", "--version"]).exitCode === 0; } catch { return false; }
-})();
-
-if (!nuAvailable) console.warn("WARNING: nu not on PATH — nu-spawn tests will be skipped");
-
-test.skipIf(!nuAvailable)("nu/scholar.nu parses without errors", async () => {
- const result = await Bun.$`nu --commands "use ./nu/scholar.nu *; echo ok"`.quiet();
- expect(result.stdout.toString().trim()).toBe("ok");
-});
-
-test.skipIf(!nuAvailable)("scholar list is defined", async () => {
- const r = await Bun.$`nu --commands "use ./nu/scholar.nu *; help commands | where name == 'scholar list' | length"`.quiet();
- expect(parseInt(r.stdout.toString().trim())).toBe(1);
-});
-
-test.skipIf(!nuAvailable)("scholar status is defined", async () => {
- const r = await Bun.$`nu --commands "use ./nu/scholar.nu *; help commands | where name == 'scholar status' | length"`.quiet();
- expect(parseInt(r.stdout.toString().trim())).toBe(1);
-});
-
-test.skipIf(!nuAvailable)("scholar ingest is defined", async () => {
- const r = await Bun.$`nu --commands "use ./nu/scholar.nu *; help commands | where name == 'scholar ingest' | length"`.quiet();
- expect(parseInt(r.stdout.toString().trim())).toBe(1);
-});
-
-test.skipIf(!nuAvailable)("scholar query is defined", async () => {
- const r = await Bun.$`nu --commands "use ./nu/scholar.nu *; help commands | where name == 'scholar query' | length"`.quiet();
- expect(parseInt(r.stdout.toString().trim())).toBe(1);
-});
-
-test.skipIf(!nuAvailable)("scholar digest is defined", async () => {
- const r = await Bun.$`nu --commands "use ./nu/scholar.nu *; help commands | where name == 'scholar digest' | length"`.quiet();
- expect(parseInt(r.stdout.toString().trim())).toBe(1);
-});
-
-// Transport argv-shape test: injects a stub `scholar` binary on PATH, verifies
-// the nu `scholar` wrapper passes --call + tool name + JSON-serialized args.
-// Foundation-007 contract: ^scholar --call .
-test.skipIf(!nuAvailable)("scholar transport calls ^scholar --call with JSON-serialized args", async () => {
- const stubDir = "/tmp/scholar-nu-transport-test";
- const stubBin = `${stubDir}/scholar`;
- await Bun.$`mkdir -p ${stubDir}`.quiet();
- await Bun.write(
- stubBin,
- `#!/bin/bash\necho "{\\"flag\\":\\"$1\\",\\"tool\\":\\"$2\\",\\"args\\":$3,\\"ok\\":true}"\n`,
- );
- await Bun.$`chmod +x ${stubBin}`.quiet();
- try {
- const result = await Bun.$`nu --commands "use ./nu/scholar.nu *; scholar 'corpus.activate' {slug: 'test'} | to json"`
- .env({ ...process.env, PATH: `${stubDir}:${process.env.PATH ?? ""}` })
- .quiet();
- const parsed = JSON.parse(result.stdout.toString().trim());
- expect(parsed.flag).toBe("--call");
- expect(parsed.tool).toBe("corpus.activate");
- expect(parsed.args.slug).toBe("test");
- expect(parsed.ok).toBe(true);
- } finally {
- await Bun.$`rm -rf ${stubDir}`.quiet().catch(() => {});
- }
-});
-
-// Grep tests — tool names must appear in source (stable across transport changes
-// and resilient to test-host nu version drift). These always run.
-test("scholar.nu references scholar.papers.search", async () => {
- expect(await Bun.file("./nu/scholar.nu").text()).toContain("scholar.papers.search");
-});
-test("scholar.nu references scholar.corpus.status", async () => {
- expect(await Bun.file("./nu/scholar.nu").text()).toContain("scholar.corpus.status");
-});
-test("scholar.nu references scholar.ingest", async () => {
- expect(await Bun.file("./nu/scholar.nu").text()).toContain("scholar.ingest");
-});
-test("scholar.nu references scholar.digest.generate", async () => {
- expect(await Bun.file("./nu/scholar.nu").text()).toContain("scholar.digest.generate");
-});
diff --git a/package.json b/package.json
index e02cda8..18e9e7f 100644
--- a/package.json
+++ b/package.json
@@ -1,53 +1,46 @@
{
- "name": "scholar",
- "version": "0.1.0",
- "type": "module",
- "private": true,
- "engines": {
- "bun": ">=1.1.27"
- },
- "bin": {
- "mcp-scholar": "./src/server/index.ts"
- },
- "scripts": {
- "typecheck": "tsc --noEmit",
- "test": "bun test",
- "db:generate": "drizzle-kit generate",
- "build:server": "tsc --noEmit && bun build src/server/index.ts --compile --target=bun-windows-x64 --outfile build/scholar.exe",
- "build:ui": "bun scripts/build-ui.ts",
- "build:ui:dev": "UI_MINIFY=false bun -q build:ui",
- "build:pdf": "bun --cwd=scripts vendor-pdf-server",
- "build:vec": "bun --cwd=scripts build-vec0",
- "build:plugin": "bun --cwd=scripts build-plugin",
- "measure-bundle": "bun scripts/measure-bundle.ts",
- "serve": "bun --cwd=scripts start-server.ts"
- },
- "dependencies": {
- "@modelcontextprotocol/sdk": "^1.29.0",
- "@retorquere/bibtex-parser": "latest",
- "chart.js": "latest",
- "drizzle-orm": "latest",
- "fflate": "latest",
- "js-tiktoken": "latest",
- "koffi": "latest",
- "pdfjs-dist": "latest",
- "react": "latest",
- "react-dom": "latest",
- "reactive-context-toolkit": "github:zaynram/reactive-context-toolkit",
- "sqlite-vec": "latest",
- "ulidx": "latest",
- "zod": "latest"
- },
- "devDependencies": {
- "@happy-dom/global-registrator": "^20.9.0",
- "@types/react": "latest",
- "@types/react-dom": "latest",
- "bun-types": "latest",
- "drizzle-kit": "latest",
- "typescript": "^5"
- },
- "scholar": {
- "bunSqliteVersion": "3.51.2",
- "bundledBunVersion": "1.3.11"
- }
+ "name": "scholar",
+ "version": "0.1.0",
+ "type": "module",
+ "private": true,
+ "engines": { "bun": ">=1.1.27" },
+ "scripts": {
+ "typecheck": "tsc --noEmit",
+ "test": "bun test src tests",
+ "db:generate": "drizzle-kit generate",
+ "build:server": "tsc --noEmit && bun build src/server/index.ts --target=bun --outfile=dist/server.js",
+ "build:ui": "bun --silent scripts/build-ui",
+ "build:ui:dev": "UI_MINIFY=false bun -q build:ui",
+ "build:pdf": "bun --silent scripts/vendor-pdf-server",
+ "build:pdf-bundle": "bun build src/vendor/pdf-server/dist/index.js --target=bun --outfile=dist/pdf-server/index.js && cp src/vendor/pdf-server/dist/mcp-app.html dist/pdf-server/mcp-app.html",
+ "build:vec": "bun --silent scripts/build-vec0",
+ "build": "bun --silent scripts/build-plugin",
+ "build:linux": "SCHOLAR_BUILD_WIN=0 bun --silent run build",
+ "measure-bundle": "bun --silent scripts/measure-bundle"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@retorquere/bibtex-parser": "latest",
+ "chart.js": "latest",
+ "drizzle-orm": "latest",
+ "fflate": "latest",
+ "js-tiktoken": "latest",
+ "koffi": "latest",
+ "pdfjs-dist": "latest",
+ "react": "latest",
+ "react-dom": "latest",
+ "reactive-context-toolkit": "github:zaynram/reactive-context-toolkit",
+ "sqlite-vec": "latest",
+ "ulidx": "latest",
+ "zod": "latest"
+ },
+ "devDependencies": {
+ "@happy-dom/global-registrator": "^20.9.0",
+ "@types/react": "latest",
+ "@types/react-dom": "latest",
+ "bun-types": "latest",
+ "drizzle-kit": "latest",
+ "typescript": "^5"
+ },
+ "scholar": { "bunSqliteVersion": "3.51.2", "bundledBunVersion": "1.3.11" }
}
diff --git a/scripts/build-plugin.ts b/scripts/build-plugin.ts
index d13c0c1..e89ce02 100644
--- a/scripts/build-plugin.ts
+++ b/scripts/build-plugin.ts
@@ -1,305 +1,280 @@
// scripts/build-plugin.ts
//
-// Build orchestrator for scholar.plugin — §14.1 seven-step build pipeline.
-// Run: bun scripts/build-plugin.ts
-// Fixture mode: BUILD_FIXTURE=1 bun scripts/build-plugin.ts
-// Skips compilation steps (1, 2, 3, 4, 6); validates pre-assembly
-// invariants (version match, vec0 presence) then runs assembly + zip.
-// SCHOLAR_BUILD_ROOT overrides the repo root (for tests).
-// SCHOLAR_PLUGIN_OUT overrides the output directory (for tests).
+// Slim-plugin build orchestrator. See docs/superpowers/specs/2026-06-01-slim-
+// plugin-pivot.md. Produces a per-OS scholar.plugin archive that ships only:
+// - dist/server.js scholar server, `bun build --target=bun` (no --compile)
+// - dist/pdf-server/{index.js,mcp-app.html} pdf-server@1.7.2 rebundled standalone
+// - build/vendor/sqlite-vec/vec0. platform vec0 (so | dll)
+// - ui/index.html single-file UI bundle
+// - nu/scholar.nu nu CLI module
+// - bin/ M2 launcher + ensure-bun provisioner
+// - .claude-plugin/plugin.json GENERATED per-OS (M2 command/args + hooks)
+// - skills/**
+// The bun runtime is NOT shipped — it is provisioned into ${CLAUDE_PLUGIN_DATA}
+// by ensure-bun at first launch. No compiled binary, no bundled runtime.
+//
+// Run: bun scripts/build-plugin.ts (Windows target, default)
+// Linux pkg: SCHOLAR_BUILD_WIN=0 bun scripts/build-plugin.ts
-import { zipSync } from "fflate"
+import util, { OUTPUT } from './util'
+import { zipSync } from 'fflate'
import {
- existsSync,
- copyFileSync,
- cpSync,
- mkdirSync,
- readFileSync,
- readdirSync,
-} from "node:fs"
-import path, { join } from "node:path"
-import { compileVec0FromSource, probeVec0Abi } from "./build-vec0"
-import { getVec0Extension } from "^src/server/db/sqlite-vec"
-import util, { OUTPUT, FIXTURE } from "./util"
-import env from "./util/env"
-
-const VEC0 = `vec0.${getVec0Extension()}`
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ copyFileSync,
+ rmSync,
+} from 'node:fs'
+import { join, relative } from 'node:path'
-// ── Pre-flight: version invariant (steps 4 ↔ 5) ─────────────────────────────
-// Reads scholar.bundledBunVersion and scholar.bunSqliteVersion from package.json
-// and aborts with SCHOLAR_BUILD_MISMATCH if either is missing or empty.
-//
-// These two fields record DIFFERENT facts about the same Bun release:
-// - bundledBunVersion: the Bun runtime version (value of `bun --version` at build time)
-// - bunSqliteVersion: the SQLite library version Bun's bun:sqlite statically links against
-// Their string values are expected to differ (e.g. "1.3.11" vs "3.51.2").
-// The invariant is that BOTH are populated and non-empty — not that they are equal.
-// Both fields must be set from the same Bun release by foundation cycle 6.1.
+const WIN = process.env.SCHOLAR_BUILD_WIN !== '0'
+const NAME = WIN ? 'win32' : 'linux'
+const VEC0_EXT = WIN ? 'dll' : 'so'
+const DIR = util.subpath('build', NAME) // staging tree — an exact mirror of the package
-function assertVersionInvariant(): void {
- const pkgRaw = readFileSync(util.subpath("package.json"), "utf8")
- const pkg = JSON.parse(pkgRaw) as {
+// ── Version invariant ─────────────────────────────────────────────────────────
+// bundledBunVersion (the bun release ensure-bun provisions) and bunSqliteVersion
+// (the SQLite the vec0 ABI targets) must both be populated. Different facts about
+// the same release; both load-bearing for the pinned-runtime / vec0 ABI contract.
+function readPkg(): {
scholar?: { bundledBunVersion?: string; bunSqliteVersion?: string }
- }
- const bv = pkg.scholar?.bundledBunVersion
- const sv = pkg.scholar?.bunSqliteVersion
- if (!bv || !bv.trim() || !sv || !sv.trim()) {
- util.abort(
- "SCHOLAR_BUILD_MISMATCH",
- "package.json is missing scholar.bundledBunVersion or scholar.bunSqliteVersion " +
- "(both record different facts about the same Bun release; both must be populated). " +
- `Got bundledBunVersion=${JSON.stringify(bv)}, bunSqliteVersion=${JSON.stringify(sv)}.`,
- )
- }
- // No string-equality check: bundledBunVersion (Bun runtime version) and
- // bunSqliteVersion (SQLite library version) record different facts about
- // the same Bun release and are expected to differ.
+} {
+ return JSON.parse(readFileSync(util.subpath('package.json'), 'utf8'))
}
-
-// ── Step 1: Build server binary ───────────────────────────────────────────────
-// bun run build:server → tsc typecheck + bun build --compile src/server/index.ts
-// Also writes extension-less build/scholar sibling (resolved: copy, not shim).
-//
-// Exported and parameterised so the sibling-copy branch can be unit-tested in
-// isolation. fixture=true skips the shell-out but still performs the copy.
-
-export async function step1_buildServer(
- root?: string,
- fixture: boolean = FIXTURE,
-): Promise {
- function dynResolve(name: string) {
- return root ? path.join(root, "build", name) : util.subpath("build", name)
- }
- // Explicit `fixture` parameter (default: env-derived FIXTURE) lets the
- // sibling-copy branch be unit-tested without spawning the real build:server.
- // Don't use the util.onfixture combinator here — sync-defaults-around-async
- // is the same footgun that produced the prior step5 incident.
- if (!fixture) {
- await util.sh`bun run build:server`
- }
- const binaries = {
- src: dynResolve("scholar.exe"),
- dst: dynResolve("scholar"),
- } as const
- if (existsSync(binaries.src)) copyFileSync(binaries.src, binaries.dst)
+function assertVersionInvariant(): void {
+ const s = readPkg().scholar ?? {}
+ if (!s.bundledBunVersion?.trim() || !s.bunSqliteVersion?.trim())
+ util.abort(
+ 'SCHOLAR_BUILD_MISMATCH',
+ 'package.json missing scholar.bundledBunVersion or scholar.bunSqliteVersion ' +
+ `(got ${JSON.stringify(s)}).`
+ )
}
-// ── Step 2: Build UI bundle ───────────────────────────────────────────────────
-// bun build src/ui/index.html --target=browser --outfile build/ui/app.html
-// Target ≤ 4.5 MB (bundle-budget gate resolved upstream by frontends cycle 6.9).
-
-async function step2_buildUI(): Promise {
- await util.onfixture(util.noop, {
- async default() {
- mkdirSync(util.subpath("build", "ui"), { recursive: true })
- await util.sh`bun run build:ui`
- },
- })
+// ── Bundle scholar server (platform-neutral) ──────────────────────────────────
+async function buildServer(): Promise {
+ await util.sh`tsc --noEmit`
+ await util.sh`bun build src/server/index.ts --target=bun --outfile ${join(DIR, 'dist', 'server.js')}`
}
-// ── Step 3: Copy vendored pdf dist ────────────────────────────────────────────
-// Copies src/vendor/pdf-server/ → build/vendor/pdf-server/.
-// No transpilation, no patch step (vendor is unmodified per §7.2).
-
-async function step3_copyPdf(): Promise {
- await util.onfixture(util.noop, {
- default() {
- const src = util.subpath("src/vendor/pdf-server")
- const dest = util.subpath("build/vendor/pdf-server")
- mkdirSync(dest, { recursive: true })
- cpSync(src, dest, { recursive: true })
- },
- })
+// ── Rebundle pdf-server standalone (pdfjs inlined) + its mcp-app.html ──────────
+async function buildPdf(): Promise {
+ const out = join(DIR, 'dist', 'pdf-server', 'index.js')
+ await util.sh`bun build src/vendor/pdf-server/dist/index.js --target=bun --outfile ${out}`
+ copyFileSync(
+ util.subpath('src', 'vendor', 'pdf-server', 'dist', 'mcp-app.html'),
+ join(DIR, 'dist', 'pdf-server', 'mcp-app.html')
+ )
}
-// ── Step 4: Copy Bun runtime ──────────────────────────────────────────────────
-// Copies bun(.exe) from the build host's Bun install to build/runtime/.
-// The bundled runtime is the pdf-child spawn target.
-
-async function step4_copyRuntime(): Promise {
- await util.onfixture(util.noop, {
- default() {
- const name = env.dynamic({ win32: "bun.exe", default: "bun" })
- const path = Bun.which(name)
- if (!path)
- return util.abort(
- "SCHOLAR_BUILD_RUNTIME_MISSING",
- "Cannot locate bun binary on PATH. Ensure bun is installed on the build host.",
- )
- const [firstLine = ""] = path.split("\n")
- const bunSrc = firstLine.trim()
- const destDir = util.subpath("build/runtime")
- mkdirSync(destDir, { recursive: true })
- copyFileSync(bunSrc, join(destDir, name))
- },
- })
+// ── UI single-file bundle ─────────────────────────────────────────────────────
+async function buildUI(): Promise {
+ process.env.UI_OUTDIR = join(DIR, 'ui')
+ mkdirSync(process.env.UI_OUTDIR, { recursive: true })
+ await util.sh`bun run build:ui`.env(process.env)
}
-// ── Step 5: vec0 shared library — ABI probe then compile fallback ─────────────
-// Production: probeVec0Abi on the prebuilt; if ABI matches, copy it; otherwise
-// (or if absent) fall back to compileVec0FromSource (§14.1 step 5 / §16).
-// Fixture (no FORCE_COMPILE): skip ABI probe (stubs aren't real extensions);
-// copy stub prebuilt directly. Abort if stub is absent.
-// Fixture + FORCE_COMPILE: skip prebuilt; exercise compile path with a stub CC.
-
-async function step5_copyVec(): Promise {
- const libName = `vec0.${getVec0Extension()}`
- const prebuilt = util.subpath(`runtime/vendor/sqlite-vec/${libName}`)
- const destDir = util.subpath("build/vendor/sqlite-vec")
- mkdirSync(destDir, { recursive: true })
- const destPath = join(destDir, libName)
+// ── vec0 shared library (per-OS) ──────────────────────────────────────────────
+// Linux dev: copy the prebuilt from the installed sqlite-vec-linux-x64 package.
+// Windows target: fetch the prebuilt vec0.dll from the sqlite-vec-windows-x64 npm
+// tarball at the SAME version (no mingw cross-compile). The dll cannot be
+// ABI-probed on Linux — the pinned-bun load gate runs on the target.
+async function stageVec0(): Promise {
+ const dest = join(DIR, 'build', 'vendor', 'sqlite-vec', `vec0.${VEC0_EXT}`)
+ mkdirSync(join(DIR, 'build', 'vendor', 'sqlite-vec'), { recursive: true })
+ const ver = JSON.parse(
+ readFileSync(util.subpath('node_modules', 'sqlite-vec-linux-x64', 'package.json'), 'utf8')
+ ).version as string
- await util.onfixture(
- () =>
- util.oncompile(() => compileVec0FromSource(destPath), {
- default() {
- if (!existsSync(prebuilt))
- // Fixture: skip ABI probe; just assert prebuilt stub is staged and copy it.
+ if (!WIN) {
+ const src = util.subpath('node_modules', 'sqlite-vec-linux-x64', 'vec0.so')
+ if (!existsSync(src))
+ util.abort('SCHOLAR_BUILD_VEC_MISSING', `linux vec0 prebuilt absent: ${src}`)
+ copyFileSync(src, dest)
+ // ABI probe is cheap on the dev host — fail fast on a bad pin.
+ const { probeVec0Abi } = await import('./build-vec0')
+ if (!probeVec0Abi(dest))
util.abort(
- "SCHOLAR_BUILD_VEC_MISSING",
- `Prebuilt ${libName} not found at ${prebuilt} [fixture mode]. ` +
- "Ensure FIXTURE_FILES stages both vec0.dll and vec0.so.",
+ 'SCHOLAR_BUILD_VEC_ABI',
+ `vec0.so failed ABI probe under bun ${Bun.version} (SQLite mismatch).`
)
- else copyFileSync(prebuilt, destPath)
- },
- }),
- {
- async default() {
- await util.oncompile(() => compileVec0FromSource(destPath), {
- async default() {
- if (existsSync(prebuilt) && probeVec0Abi(prebuilt)) {
- copyFileSync(prebuilt, destPath)
- return
- }
- const reason = existsSync(prebuilt)
- ? "prebuilt ABI probe failed (SQLite version mismatch between vec0 and Bun's bundled engine)"
- : `prebuilt ${libName} not found`
- console.warn(`vec0 ${reason} — falling back to source compilation`)
- await compileVec0FromSource(destPath)
- },
- })
- },
- },
- )
-}
-
-// ── Step 6: Copy nu module ────────────────────────────────────────────────────
+ return
+ }
-async function step6_copyNu(): Promise {
- await util.onfixture(util.noop, {
- default() {
- const src = util.subpath("nu/scholar.nu")
- const dest = util.subpath("build/nu/scholar.nu")
- mkdirSync(util.subpath("build/nu"), { recursive: true })
- copyFileSync(src, dest)
- },
- })
+ const cache = util.subpath('build', '.cache', `sqlite-vec-windows-x64-${ver}`)
+ const dll = join(cache, 'package', 'vec0.dll')
+ if (!existsSync(dll)) {
+ mkdirSync(cache, { recursive: true })
+ const url = `https://registry.npmjs.org/sqlite-vec-windows-x64/-/sqlite-vec-windows-x64-${ver}.tgz`
+ const res = await fetch(url)
+ if (!res.ok)
+ util.abort('SCHOLAR_BUILD_VEC_FETCH', `fetch ${url} -> HTTP ${res.status}`)
+ const tgz = join(cache, 'pkg.tgz')
+ await Bun.write(tgz, await res.arrayBuffer())
+ await util.sh`tar xzf ${tgz} -C ${cache}`
+ }
+ if (!existsSync(dll))
+ util.abort('SCHOLAR_BUILD_VEC_MISSING', `windows vec0.dll not extracted at ${dll}`)
+ copyFileSync(dll, dest)
}
-// ── Step 7: Assemble plugin tree + zip ────────────────────────────────────────
-// Assembles the complete file map then produces scholar.plugin via fflate.
-// Uses fflate (Ruling #2, 2026-05-24) — imported at top of file.
-
-async function step7_assemblePlugin(): Promise {
- // Files to include in the archive: [src-abs-path, archive-relative-path]
+// ── nu module + per-OS launcher set ───────────────────────────────────────────
+function stageBin(): void {
+ mkdirSync(join(DIR, 'bin'), { recursive: true })
+ mkdirSync(join(DIR, 'nu'), { recursive: true })
+ const nu = existsSync(util.subpath('nu', 'scholar.nu'))
+ ? util.subpath('nu', 'scholar.nu')
+ : util.subpath('bin', 'scholar.nu')
+ copyFileSync(nu, join(DIR, 'nu', 'scholar.nu'))
+ const launchers = WIN
+ ? ['launch.cmd', 'ensure-bun.ps1']
+ : ['launch.sh', 'ensure-bun.sh']
+ for (const f of launchers)
+ copyFileSync(util.subpath('bin', f), join(DIR, 'bin', f))
+}
- const manifest: [string, string][] = [
- ".claude-plugin/plugin.json",
- ".mcp.json",
- "build/scholar.exe",
- "build/scholar",
- "build/ui/app.html",
- `build/runtime/bun${env.dynamic({ win32: ".exe", default: "" })}`,
- `build/vendor/sqlite-vec/${VEC0}`,
- "nu/scholar.nu",
- ].map((p) => [util.subpath(p), p] as const)
+// ── Generate the per-OS plugin.json (M2 launch + pre-warm hook) ────────────────
+// Pure construction (exported for build-plugin.test.ts): given the base dev
+// manifest, produce the per-OS M2 manifest. win=true → cmd.exe/launch.cmd +
+// PowerShell pre-warm; win=false → /bin/sh/launch.sh + sh pre-warm. The `bin`
+// field (compiled-binary leftover) is stripped. No I/O — generateManifest wraps
+// this with the read/write so the launch-model logic is unit-testable.
+export function buildManifest(
+ base: Record,
+ win: boolean,
+): Record {
+ const ROOT = '${CLAUDE_PLUGIN_ROOT}'
+ const runtimeRoot = win
+ ? '${USERPROFILE}\\mcp-data\\scholar\\runtime'
+ : '${HOME}/mcp-data/scholar/runtime'
+ const command = win ? 'cmd.exe' : '/bin/sh'
+ const args = win ? ['/c', `${ROOT}\\bin\\launch.cmd`] : [`${ROOT}/bin/launch.sh`]
- // Recursively collect all files from a directory into the manifest.
- // Used for pdf dist, slash commands, and skills — so frontends can add
- // a file without requiring a packaging revision.
- function collect(archBase: string): void {
- const srcBase = util.subpath(archBase)
- if (!existsSync(srcBase)) return // gracefully skip absent optional dirs
- for (const entry of readdirSync(srcBase, { withFileTypes: true })) {
- const srcPath = join(srcBase, entry.name)
- const archPath = archBase + "/" + entry.name
- if (entry.isDirectory()) {
- collect(archPath)
- } else {
- manifest.push([srcPath, archPath])
- }
+ const manifest = {
+ ...base,
+ mcpServers: {
+ scholar: {
+ command,
+ args,
+ env: {
+ SCHOLAR_RUNTIME_ROOT: runtimeRoot,
+ SCHOLAR_OLLAMA_URL: 'http://127.0.0.1:11434',
+ SCHOLAR_OLLAMA_EMBED_MODEL: 'nomic-embed-text:v1.5',
+ SCHOLAR_OLLAMA_CHAT_MODEL: 'qwen3:8b',
+ },
+ },
+ },
+ // Pre-warm: start provisioning early. SessionStart does NOT block MCP
+ // spawn, so this is a latency optimization only — launch.{sh,cmd} is the
+ // correctness gate. ensure-bun is idempotent + lock-guarded.
+ hooks: {
+ SessionStart: [
+ {
+ hooks: [
+ {
+ type: 'command',
+ command: win
+ ? `powershell -NoProfile -ExecutionPolicy Bypass -File "${ROOT}\\bin\\ensure-bun.ps1"`
+ : `sh "${ROOT}/bin/ensure-bun.sh"`,
+ },
+ ],
+ },
+ ],
+ },
}
- }
-
- collect("build/vendor/pdf-server")
- // Slash commands + skills (frontends cycle 6.10).
- collect("commands")
- collect("skills")
+ delete (manifest as { bin?: unknown }).bin
+ return manifest
+}
- // Validate every source file exists before attempting zip.
- const missing = manifest.map(([src]) => src).filter((src) => !existsSync(src))
- if (missing.length > 0)
- return util.abort(
- "SCHOLAR_BUILD_MISSING_ARTIFACT",
- `Expected artifact(s) not found: ${missing.join(", ")}. ` +
- "Ensure all upstream plans have completed their cycles.",
- )
+function generateManifest(): void {
+ const base = JSON.parse(readFileSync(util.subpath('.claude-plugin', 'plugin.json'), 'utf8'))
+ const manifest = buildManifest(base, WIN)
+ mkdirSync(join(DIR, '.claude-plugin'), { recursive: true })
+ Bun.write(join(DIR, '.claude-plugin', 'plugin.json'), JSON.stringify(manifest, null, 2))
+}
- // Build fflate-compatible file map.
- const fileMap: Record = {}
- for (const [src, archPath] of manifest) {
- fileMap[archPath] = new Uint8Array(readFileSync(src))
- }
+// ── Skills ────────────────────────────────────────────────────────────────────
+function stageSkills(): void {
+ const src = util.subpath('skills')
+ if (!existsSync(src)) return
+ cpDir(src, join(DIR, 'skills'))
+}
+function cpDir(from: string, to: string): void {
+ mkdirSync(to, { recursive: true })
+ for (const e of readdirSync(from, { withFileTypes: true })) {
+ const s = join(from, e.name)
+ const d = join(to, e.name)
+ if (e.isDirectory()) cpDir(s, d)
+ else copyFileSync(s, d)
+ }
+}
- const zipped = zipSync(fileMap, { level: 6 })
+// ── Assemble + zip the staging tree ───────────────────────────────────────────
+function collectFiles(base: string, acc: string[] = []): string[] {
+ for (const e of readdirSync(base, { withFileTypes: true })) {
+ const p = join(base, e.name)
+ if (e.isDirectory()) collectFiles(p, acc)
+ else acc.push(p)
+ }
+ return acc
+}
+async function assemble(): Promise {
+ const files = collectFiles(DIR)
+ const fileMap: Record = {}
+ for (const abs of files)
+ fileMap[relative(DIR, abs).split('\\').join('/')] = new Uint8Array(readFileSync(abs))
- // Determine output paths.
- mkdirSync(OUTPUT, { recursive: true })
- const primaryOut = join(OUTPUT, "scholar.plugin")
- await Bun.write(primaryOut, zipped)
- console.log(`scholar.plugin written to: ${primaryOut}`)
+ const required = [
+ '.claude-plugin/plugin.json',
+ 'dist/server.js',
+ 'dist/pdf-server/index.js',
+ 'dist/pdf-server/mcp-app.html',
+ `build/vendor/sqlite-vec/vec0.${VEC0_EXT}`,
+ WIN ? 'bin/launch.cmd' : 'bin/launch.sh',
+ ]
+ const missing = required.filter(r => !(r in fileMap))
+ if (missing.length)
+ util.abort('SCHOLAR_BUILD_MISSING_ARTIFACT', `missing: ${missing.join(', ')}`)
- // Best-effort secondary copy to COWORK_PLUGINS_DIR if set.
- const stagingEnv = env.static("COWORK_PLUGINS_DIR")
+ const zipped = zipSync(fileMap, { level: 6 })
+ mkdirSync(OUTPUT, { recursive: true })
+ const out = join(OUTPUT, 'scholar.plugin')
+ await Bun.write(out, zipped)
+ const mb = (zipped.length / 1024 / 1024).toFixed(1)
+ process.stdout.write(`scholar.plugin (${NAME}, ${mb} MB, ${files.length} files) -> ${out}\n`)
- if (stagingEnv) {
- try {
- mkdirSync(stagingEnv, { recursive: true })
- const secondaryOut = join(stagingEnv, "scholar.plugin")
- await Bun.write(secondaryOut, zipped)
- console.log(`scholar.plugin also copied to staging: ${secondaryOut}`)
- } catch (e) {
- console.warn(
- `Warning: could not copy to COWORK_PLUGINS_DIR (${stagingEnv}): ` +
- `${(e as Error).message}`,
- )
+ const staging = process.env.COWORK_PLUGINS_DIR
+ if (staging) {
+ try {
+ mkdirSync(staging, { recursive: true })
+ await Bun.write(join(staging, 'scholar.plugin'), zipped)
+ process.stdout.write(`also copied to staging: ${staging}\n`)
+ } catch (e) {
+ process.stderr.write(`warn: COWORK_PLUGINS_DIR copy failed: ${(e as Error).message}\n`)
+ }
}
- }
}
// ── Orchestrator ──────────────────────────────────────────────────────────────
-
async function main(): Promise {
- const tag = `[${util.onfixture(() => "scholar-fixture", {
- default: () => "scholar",
- })}]`
- console.log(`${tag} plugin build`)
- assertVersionInvariant() // pre-flight: steps 4 ↔ 5 version match
- await step1_buildServer() // §14.1 step 1
- await step2_buildUI() // §14.1 step 2
- await step3_copyPdf() // §14.1 step 3
- await step4_copyRuntime() // §14.1 step 4
- await step5_copyVec() // §14.1 step 5 (also runs in fixture for vec0 check)
- await step6_copyNu() // §14.1 step 6
- await step7_assemblePlugin() // §14.1 step 7
- console.log(`${tag} build complete.`)
+ process.stdout.write(`[scholar] slim plugin build (${NAME})\n`)
+ rmSync(DIR, { recursive: true, force: true })
+ mkdirSync(DIR, { recursive: true })
+ assertVersionInvariant()
+ await buildServer()
+ await buildPdf()
+ await buildUI()
+ await stageVec0()
+ stageBin()
+ generateManifest()
+ stageSkills()
+ await assemble()
+ process.stdout.write(`[scholar] build complete\n`)
}
-// Guard main() so the module can be imported by tests without triggering the
-// build pipeline. import.meta.main is true only when this file is the entry point.
-if (import.meta.main) {
- main().catch((e) => {
- process.stderr.write(`Unhandled build error: ${(e as Error).message}\n`)
- process.exit(1)
- })
-}
+if (import.meta.main)
+ main().catch(async e => {
+ process.stderr.write(`unhandled build error: ${String(e)}\n`)
+ process.exit(1)
+ })
diff --git a/scripts/build-ui.ts b/scripts/build-ui.ts
index 83acdb5..8f5a8d4 100644
--- a/scripts/build-ui.ts
+++ b/scripts/build-ui.ts
@@ -13,27 +13,27 @@
// sourcemap option (Bun default is "none"), so this helper matches exactly.
export interface BuildUIOptions {
- outdir: string; // e.g., "build/ui"
- minify?: boolean; // default true (prod); pass false for dev
- sourcemap?: "none" | "linked" | "external" | "inline"; // default "none"
+ outdir: string // e.g., "build/ui"
+ minify?: boolean // default true (prod); pass false for dev
+ sourcemap?: 'none' | 'linked' | 'external' | 'inline' // default "none"
}
export async function buildUI(opts: BuildUIOptions): Promise {
- const result = await Bun.build({
- entrypoints: ["src/ui/index.html"],
- target: "browser",
- outdir: opts.outdir,
- minify: opts.minify ?? true,
- sourcemap: opts.sourcemap ?? "none",
- });
- if (!result.success) {
- const messages = result.logs.map((l) => l.message ?? String(l)).join("\n");
- throw new Error(`build-ui failed:\n${messages}`);
- }
+ const result = await Bun.build({
+ entrypoints: ['src/ui/index.html'],
+ target: 'browser',
+ outdir: opts.outdir,
+ minify: opts.minify ?? true,
+ sourcemap: opts.sourcemap ?? 'none',
+ })
+ if (!result.success) {
+ const messages = result.logs.map(l => l.message ?? String(l)).join('\n')
+ throw new Error(`build-ui failed:\n${messages}`)
+ }
}
if (import.meta.main) {
- const outdir = process.env.UI_OUTDIR ?? "build/ui";
- const minify = process.env.UI_MINIFY !== "false";
- await buildUI({ outdir, minify });
+ const outdir = process.env.UI_OUTDIR ?? `build/${process.platform}/ui`
+ const minify = process.env.UI_MINIFY !== 'false'
+ await buildUI({ outdir, minify })
}
diff --git a/scripts/start-server.ts b/scripts/start-server.ts
deleted file mode 100644
index d067830..0000000
--- a/scripts/start-server.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import util from "./util"
-import env from "./util/env"
-
-async function main() {
- const bin = util.subpath(
- "build",
- `scholar${env.dynamic({ win32: ".exe", default: "" })}`,
- )
- 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)
- main().catch((e) => {
- process.stderr.write(
- `server exited with errors: ${e instanceof Error ? e.message : String(e)}`,
- )
- process.exit(1)
- })
diff --git a/scripts/util/index.ts b/scripts/util/index.ts
index 2930d7f..cd17282 100644
--- a/scripts/util/index.ts
+++ b/scripts/util/index.ts
@@ -1,41 +1,43 @@
-import path from "node:path"
-import { homedir } from "node:os"
-import { resolveRoot } from "./resolve"
-import env from "./env"
+import env from './env'
+import { resolveRoot } from './resolve'
+import { homedir } from 'node:os'
+import path from 'node:path'
export const ROOT = resolveRoot()
-export const OUTPUT = env.static("SCHOLAR_PLUGIN_OUT", {
- default: env.dynamic({
- win32: path.join(homedir(), "Documents", "Cowork", "System"),
- default: path.join(ROOT, "out"),
- }),
+export const OUTPUT = env.static('SCHOLAR_PLUGIN_OUT', {
+ default: env.dynamic({
+ win32: path.join(homedir(), 'Documents', 'Cowork', 'System'),
+ default: path.join(ROOT, 'out'),
+ }),
})
-export const FIXTURE = env.flag("SCHOLAR_BUILD_FIXTURE")
-export const COMPILE = env.flag("SCHOLAR_BUILD_VEC_FORCE_COMPILE")
+export const FIXTURE = env.flag('SCHOLAR_BUILD_FIXTURE')
+export const COMPILE = env.flag('SCHOLAR_BUILD_VEC_FORCE_COMPILE')
export function noop() {}
const createHook =
- (condition: boolean) =>
- async (
- callback: () => T | Promise,
- options?: { default?: () => T | Promise },
- ) =>
- await (condition ? callback() : options?.default && options.default())
+ (condition: boolean) =>
+ async unknown = () => unknown>(
+ callback: F,
+ options?: { default?: F }
+ ): Promise>> =>
+ (condition
+ ? await callback()
+ : options?.default && (await options.default())) as Awaited>
export default {
- noop,
- sh: (
- array: TemplateStringsArray,
- ...expressions: Bun.ShellExpression[]
- ): Bun.$.ShellPromise => Bun.$(array, ...expressions).cwd(ROOT),
- subpath(...segments: string[]) {
- return path.join(ROOT, ...segments)
- },
- abort(code: string, message: string): never {
- process.stderr.write(`${code}: ${message}\n`)
- process.exit(1)
- },
- onfixture: createHook(FIXTURE),
- oncompile: createHook(COMPILE),
+ noop,
+ sh: (
+ array: TemplateStringsArray,
+ ...expressions: Bun.ShellExpression[]
+ ): Bun.$.ShellPromise => Bun.$(array, ...expressions).cwd(ROOT),
+ subpath(...segments: string[]) {
+ return path.join(ROOT, ...segments)
+ },
+ abort(code: string, message: string): never {
+ process.stderr.write(`${code}: ${message}\n`)
+ process.exit(1)
+ },
+ onfixture: createHook(FIXTURE),
+ oncompile: createHook(COMPILE),
}
diff --git a/skills/digest/SKILL.md b/skills/digest/SKILL.md
new file mode 100644
index 0000000..1244406
--- /dev/null
+++ b/skills/digest/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: digest
+description: Generate a synthesis digest for the active corpus scope (Ollama default; --claude opt-in).
+user-invocable: true
+arguments: [scope corpus claude]
+argument-hint:
+ - all|stale|section:>|selection:>
+ - "[--corpus=]"
+ - "[--claude]"
+---
+
+# Digest
+
+## Arguments
+
+| Argument | Type | Default | Description | User-Provided Value |
+|---|---|---|---|---|
+| `--scope` | string | `all` | One of `all`, `stale`, `section:`, `selection:` | `$scope` |
+| `--corpus` | string | active | Corpus slug | `$corpus` |
+| `--claude` | flag | `False` | Opt in to Claude (cowork.askClaude) for this single request | `$claude` |
+
+## Behavior
+
+Call the `scholar.digest.generate` tool with `{scope_key: $scope, use_claude: $claude}`.
+Default LLM is local Ollama (`qwen3:8b` by default).
+
+When the server returns a `structuredContent.askClaude` sentinel
+(typically: Ollama unavailable + askClaude opt-in not set),
+the CLI prints the opt-in hint rather than the digest body.
diff --git a/skills/ingest/SKILL.md b/skills/ingest/SKILL.md
new file mode 100644
index 0000000..4dea2fe
--- /dev/null
+++ b/skills/ingest/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: ingest
+description: Ingest a paper into the active scholar corpus from a DOI, arXiv ID, BibTeX file, or RIS file.
+user-invocable: true
+arguments: [flag value]
+argument-hint:
+ - [--doi|--arxiv|--bibtext|--ris]
+ -
+---
+
+# Ingest
+
+## Arguments
+
+| Argument | Type | Description |
+|---|---|---|
+| `--doi` | string | CrossRef DOI (e.g. `10.1038/s41586-021-03819-2`) |
+| `--arxiv` | string | arXiv ID or URL (e.g. `2401.00001` or `arxiv:cs.AI/2401.00001`) |
+| `--bibtex` | path | `.bib` file path |
+| `--ris` | path | `.ris` file path |
+| `--corpus` | string | Target corpus slug (active corpus used if omitted) |
+
+Resolve the `flag` (`$flag`) provided by the user to the table,
+then apply the `value` (`$value`) appropriately as described below.
+
+## Behavior
+
+Routes to one of
+`scholar.ingest.doi`, `scholar.ingest.arxiv`, `scholar.ingest.bibtex`, or `scholar.ingest.ris`
+based on the supplied flag.
+
+All metadata is sanitized at the ingestion boundary
+(`sanitizeText`, `wrapUntrusted`, `encodeDoi`, `validateArxivId`).
+Duplicate DOI / arXiv entries UPSERT (not re-insert).
diff --git a/skills/status/SKILL.md b/skills/status/SKILL.md
new file mode 100644
index 0000000..16b70f8
--- /dev/null
+++ b/skills/status/SKILL.md
@@ -0,0 +1,21 @@
+---
+name: status
+description: Show paper counts by status, stale papers, and last-opened timestamp for a corpus.
+arguments: [corpus]
+argument-hint: []
+user-invocable: true
+---
+
+# Status
+
+## Arguments
+
+The corpus to target is: `$corpus`
+
+- If no corpus was provided by the user, use the `active` corpus.
+If there is no `active` corpus, request one to be specified by the user and return.
+
+## Behavior
+
+Call the `scholar.corpus.status` with `{"corpus_id": "$corpus"}`.
+(or the active corpus if none was provided)
diff --git a/src/server/db/sqlite-vec.ts b/src/server/db/sqlite-vec.ts
index 5d6de93..425f3c8 100644
--- a/src/server/db/sqlite-vec.ts
+++ b/src/server/db/sqlite-vec.ts
@@ -2,17 +2,17 @@
//
// Returns the absolute path to the bundled vec0 shared library. Loading is the
// caller's responsibility — see loadVecAndProbeDim in src/server/ingest/primitives.ts.
-import { join } from "path"
+import { join } from 'path'
export function getVec0Extension() {
- switch (process.platform) {
- case "win32":
- return "dll"
- case "darwin":
- return "dylib"
- default:
- return "so"
- }
+ switch (process.platform) {
+ case 'win32':
+ return 'dll'
+ case 'darwin':
+ return 'dylib'
+ default:
+ return 'so'
+ }
}
/**
@@ -26,14 +26,14 @@ export function getVec0Extension() {
* is the production fallback the packaged binary sets; keep that branch.
*/
export const resolveVec0Path = (): string =>
- process.env.SCHOLAR_VEC0_PATH ??
- join(
- process.env.CLAUDE_PLUGIN_ROOT ?? join(import.meta.dir, "..", "..", ".."),
- "build",
- "vendor",
- "sqlite-vec",
- `vec0.${getVec0Extension()}`,
- )
+ process.env.SCHOLAR_VEC0_PATH ??
+ join(
+ 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.
@@ -48,5 +48,5 @@ export const resolveVec0Path = (): string =>
* 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)
+ return arr.buffer.byteLength === arr.byteLength ? arr : Float32Array.from(arr)
}
diff --git a/src/server/index.test.ts b/src/server/index.test.ts
index f4f3811..8f412c0 100644
--- a/src/server/index.test.ts
+++ b/src/server/index.test.ts
@@ -4,8 +4,16 @@
// `dispatch` is foundation-internal (NOT §7.6 frozen) — added foundation-009
// so `--call` CLI mode can dispatch a tool by name without round-tripping
// through the stdio MCP transport.
-import { test, expect } from "bun:test";
-import { buildServer, spawnPdfChild, type BuildServerDeps } from "./index.ts";
+//
+// chore cover-ollama-client-and-index-dispatch-unit-gaps (2026-06-02):
+// Added parseEntryArgv, main() dispatch-branch, buildServer quiet-logger,
+// and pdf-stub-throws coverage. NOTE: runServer and the import.meta.main block
+// are intentionally NOT covered — runServer binds a live StdioServerTransport
+// to stdin/stdout, which would hang or corrupt the test process. The 85%+
+// line target is met without those two regions.
+import { test, expect, afterEach } from "bun:test";
+import { mkdirSync, rmSync, existsSync } from "node:fs";
+import { buildServer, parseEntryArgv, main, spawnPdfChild, type BuildServerDeps } from "./index.ts";
function makeDeps(overrides: Partial = {}): BuildServerDeps {
return {
@@ -61,3 +69,163 @@ test("dispatch throws structured unknown_tool error for unregistered tools", asy
tool: "scholar.does.not.exist",
});
});
+
+// ─── chore cover-ollama-client-and-index-dispatch-unit-gaps (2026-06-02) ────
+
+// ─── parseEntryArgv ──────────────────────────────────────────────────────────
+
+test("parseEntryArgv: no --call flag → server mode", () => {
+ expect(parseEntryArgv([])).toEqual({ mode: "server" });
+ expect(parseEntryArgv(["--some", "--other"])).toEqual({ mode: "server" });
+});
+
+test("parseEntryArgv: --call → cli mode with both fields", () => {
+ const parsed = parseEntryArgv(["--call", "scholar.corpus.list", "{}"]);
+ expect(parsed).toEqual({
+ mode: "cli",
+ toolName: "scholar.corpus.list",
+ argsSource: "{}",
+ });
+});
+
+test("parseEntryArgv: --call only → cli mode, argsSource undefined", () => {
+ const parsed = parseEntryArgv(["--call", "scholar.corpus.list"]);
+ expect(parsed).toEqual({
+ mode: "cli",
+ toolName: "scholar.corpus.list",
+ argsSource: undefined,
+ });
+});
+
+test("parseEntryArgv: --call alone → cli mode, both tool and argsSource undefined", () => {
+ const parsed = parseEntryArgv(["--call"]);
+ expect(parsed).toEqual({
+ mode: "cli",
+ toolName: undefined,
+ argsSource: undefined,
+ });
+});
+
+test("parseEntryArgv: --call - → cli mode, argsSource is '-'", () => {
+ const parsed = parseEntryArgv(["--call", "scholar.corpus.list", "-"]);
+ expect(parsed).toEqual({
+ mode: "cli",
+ toolName: "scholar.corpus.list",
+ argsSource: "-",
+ });
+});
+
+// ─── main() return codes — pure-arg branches (no real DB) ────────────────────
+
+test("main(['--call']) returns exit code 2 (missing tool + argsSource)", async () => {
+ const code = await main(["--call"]);
+ expect(code).toBe(2);
+});
+
+test("main(['--call','x']) returns exit code 2 (missing argsSource)", async () => {
+ const code = await main(["--call", "x"]);
+ expect(code).toBe(2);
+});
+
+test("main(['--call','x','{bad json']) returns exit code 2 (invalid_args_json)", async () => {
+ const code = await main(["--call", "x", "{bad json"]);
+ expect(code).toBe(2);
+});
+
+// ─── main() branches that build a real config DB ─────────────────────────────
+// These create a temp SCHOLAR_RUNTIME_ROOT so the config DB lives in a
+// throwaway directory and doesn't pollute the test workspace.
+
+let testRuntimeRoot: string | null = null;
+
+afterEach(() => {
+ if (testRuntimeRoot && existsSync(testRuntimeRoot)) {
+ rmSync(testRuntimeRoot, { recursive: true, force: true });
+ }
+ testRuntimeRoot = null;
+ delete process.env.SCHOLAR_RUNTIME_ROOT;
+});
+
+function makeTempRuntime(): string {
+ const dir = `/tmp/scholar-index-test-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+ mkdirSync(`${dir}/dbs`, { recursive: true });
+ testRuntimeRoot = dir;
+ process.env.SCHOLAR_RUNTIME_ROOT = dir;
+ return dir;
+}
+
+test("main(['--call','scholar.unknown.tool','{}']) returns exit code 2 (unknown_tool)", async () => {
+ makeTempRuntime();
+ const code = await main(["--call", "scholar.unknown.tool", "{}"]);
+ expect(code).toBe(2);
+});
+
+test("main(['--call','scholar.corpus.status','{}']) dispatches tool-error and returns 1", async () => {
+ // scholar.corpus.status requires an active corpus DB with the migrations applied.
+ // The temp DB is blank (no migrations run) → tool throws a DB error → return 1.
+ makeTempRuntime();
+ const code = await main(["--call", "scholar.corpus.status", "{}"]);
+ // tool_error → exit 1
+ expect(code).toBe(1);
+});
+
+// ─── runCli return-0 analog: withCorpus throws without corpus (tool_error path) ─
+// runCli's return-0 path (dispatch succeeds) is exercised at the unit level via
+// the existing `dispatch unknown_tool` test (the dispatch closure is the same code
+// path). The main() test below exercises the full stack including the return-1
+// (tool_error) exit from runCli.
+
+// ─── buildServer: pdf-stub throws on all PdfChild methods (no deps.spawnPdfChild) ──
+
+test("buildServer pdf stub: interact throws PDF_CHILD_UNAVAILABLE", async () => {
+ const { ctx } = buildServer(makeDeps({ spawnPdfChild: undefined }));
+ await expect(
+ ctx.pdf.interact({ type: "get_text" } as never, { viewUUID: "stub-uuid" }),
+ ).rejects.toThrow("PDF_CHILD_UNAVAILABLE");
+});
+
+test("buildServer pdf stub: getText throws PDF_CHILD_UNAVAILABLE", async () => {
+ const { ctx } = buildServer(makeDeps({ spawnPdfChild: undefined }));
+ await expect(ctx.pdf.getText({ viewUUID: "stub-uuid" })).rejects.toThrow("PDF_CHILD_UNAVAILABLE");
+});
+
+test("buildServer pdf stub: displayPdf throws PDF_CHILD_UNAVAILABLE", async () => {
+ const { ctx } = buildServer(makeDeps({ spawnPdfChild: undefined }));
+ await expect(ctx.pdf.displayPdf("/some/path.pdf")).rejects.toThrow("PDF_CHILD_UNAVAILABLE");
+});
+
+test("buildServer pdf stub: setRoots throws PDF_CHILD_UNAVAILABLE", async () => {
+ const { ctx } = buildServer(makeDeps({ spawnPdfChild: undefined }));
+ await expect(ctx.pdf.setRoots(["/root"])).rejects.toThrow("PDF_CHILD_UNAVAILABLE");
+});
+
+test("buildServer pdf stub: isHealthy returns alive:false", () => {
+ const { ctx } = buildServer(makeDeps({ spawnPdfChild: undefined }));
+ const health = ctx.pdf.isHealthy();
+ expect(health.alive).toBe(false);
+ expect(health.lastOkAt).toBeNull();
+ expect(health.stdioOpen).toBe(false);
+});
+
+// ─── buildServer: quiet logger branch ────────────────────────────────────────
+
+test("buildServer quiet:true mutes trace/debug/info but not warn/error", () => {
+ // Quiet mode suppresses the three verbose levels; warn/error still log.
+ // We just verify the methods are callable without throwing (they write to stderr).
+ const { ctx } = buildServer(makeDeps({ quiet: true }));
+ // No assertions on output — just confirm the methods don't throw.
+ ctx.log.trace("trace-msg");
+ ctx.log.debug("debug-msg");
+ ctx.log.info("info-msg");
+ ctx.log.warn("warn-msg");
+ ctx.log.error("error-msg");
+});
+
+test("buildServer quiet:false emits all log levels without throwing", () => {
+ const { ctx } = buildServer(makeDeps({ quiet: false }));
+ ctx.log.trace("trace-msg");
+ ctx.log.debug("debug-msg");
+ ctx.log.info("info-msg");
+ ctx.log.warn("warn-msg");
+ ctx.log.error("error-msg");
+});
diff --git a/src/server/ollama/client.test.ts b/src/server/ollama/client.test.ts
index eb6bdff..cf18678 100644
--- a/src/server/ollama/client.test.ts
+++ b/src/server/ollama/client.test.ts
@@ -11,6 +11,9 @@
// 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.
+//
+// chore cover-ollama-client-and-index-dispatch-unit-gaps (2026-06-02):
+// Added chat success/fallback, listModels, and healthCheck coverage.
import { test, expect, afterEach } from "bun:test";
import {
ollama,
@@ -94,3 +97,130 @@ test("chat throws OllamaUnavailableError when the request exceeds the chat timeo
const elapsed = Date.now() - start;
expect(elapsed, `expected timeout near 250ms, got ${elapsed}ms`).toBeLessThan(5_000);
});
+
+// ─── chore cover-ollama-client-and-index-dispatch-unit-gaps ─────────────────
+// chat(), listModels(), and healthCheck() success/failure branches.
+// All use Bun.serve fixture servers (same pattern as the timeout tests above)
+// rather than global-fetch monkey-patching, which matches the file's existing
+// style and avoids any potential cross-test contamination.
+
+// --- helpers ---
+
+/** Start a fixture server that returns a canned JSON body with the given HTTP status. */
+function startJsonServer(body: unknown, status = 200): string {
+ const srv = Bun.serve({
+ port: 0,
+ fetch() {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+ },
+ });
+ jsonServers.push(srv);
+ return `http://127.0.0.1:${srv.port}`;
+}
+
+const jsonServers: ReturnType[] = [];
+
+afterEach(() => {
+ for (const srv of jsonServers.splice(0)) srv.stop(true);
+});
+
+// ─── embed() success (complement to the timeout test above) ──────────────────
+
+test("embed() returns a Float32Array on success (embedding field)", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ embedding: [1, 2, 3] });
+ const result = await ollama.embed("nomic-embed-text:v1.5", "hello");
+ expect(result).toBeInstanceOf(Float32Array);
+ expect(result.length).toBe(3);
+ expect(result[0]).toBe(1);
+});
+
+test("embed() returns a Float32Array on success (embeddings[] field fallback)", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ embeddings: [[4, 5, 6]] });
+ const result = await ollama.embed("nomic-embed-text:v1.5", "hello");
+ expect(result).toBeInstanceOf(Float32Array);
+ expect(result.length).toBe(3);
+ expect(result[0]).toBe(4);
+});
+
+// ─── chat() ──────────────────────────────────────────────────────────────────
+
+test("chat() resolves the message.content string on success", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({
+ message: { content: "hello from ollama" },
+ });
+ const result = await ollama.chat("test-model", [{ role: "user", content: "hi" }]);
+ expect(result).toBe("hello from ollama");
+});
+
+test("chat() falls back to response field when message is absent", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ response: "fallback text" });
+ const result = await ollama.chat("test-model", [{ role: "user", content: "hi" }]);
+ expect(result).toBe("fallback text");
+});
+
+test("chat() throws when both message.content and response are empty/absent", async () => {
+ // Both fields absent → "" content → throw (lines 139–141)
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({});
+ await expect(
+ ollama.chat("test-model", [{ role: "user", content: "hi" }]),
+ ).rejects.toThrow();
+});
+
+// ─── listModels() ─────────────────────────────────────────────────────────────
+
+test("listModels() returns the models array on success", async () => {
+ const models = [{ name: "llama3", size: 1234, modified_at: "2025-01-01T00:00:00Z" }];
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ models });
+ const result = await ollama.listModels();
+ expect(result).toEqual(models);
+});
+
+test("listModels() returns [] when the models key is absent", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({});
+ const result = await ollama.listModels();
+ expect(result).toEqual([]);
+});
+
+test("listModels() rejects OllamaUnavailableError when fetch throws (unreachable host)", async () => {
+ // Point at a guaranteed-dead port by starting then immediately stopping a server.
+ const dead = Bun.serve({ port: 0, fetch: () => new Response("ok") });
+ const deadUrl = `http://127.0.0.1:${dead.port}`;
+ dead.stop(true);
+ process.env.SCHOLAR_OLLAMA_URL = deadUrl;
+ await expect(ollama.listModels()).rejects.toBeInstanceOf(OllamaUnavailableError);
+});
+
+test("listModels() rejects OllamaUnavailableError when res.ok is false", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ error: "not found" }, 503);
+ await expect(ollama.listModels()).rejects.toBeInstanceOf(OllamaUnavailableError);
+});
+
+// ─── healthCheck() ────────────────────────────────────────────────────────────
+
+test("healthCheck() returns ok:true when the server responds with 200", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ models: [] });
+ const result = await ollama.healthCheck();
+ expect(result.ok).toBe(true);
+ expect(typeof result.url).toBe("string");
+});
+
+test("healthCheck() returns ok:false with HTTP error string when res.ok is false", async () => {
+ process.env.SCHOLAR_OLLAMA_URL = startJsonServer({ error: "gone" }, 503);
+ const result = await ollama.healthCheck();
+ expect(result.ok).toBe(false);
+ expect(result.error).toBe("HTTP 503");
+});
+
+test("healthCheck() returns ok:false with error message when fetch throws", async () => {
+ const dead = Bun.serve({ port: 0, fetch: () => new Response("ok") });
+ const deadUrl = `http://127.0.0.1:${dead.port}`;
+ dead.stop(true);
+ process.env.SCHOLAR_OLLAMA_URL = deadUrl;
+ const result = await ollama.healthCheck();
+ expect(result.ok).toBe(false);
+ expect(typeof result.error).toBe("string");
+ expect(result.error!.length).toBeGreaterThan(0);
+});
diff --git a/src/server/pdf/lifecycle.contract.test.ts b/src/server/pdf/lifecycle.contract.test.ts
index fd15830..e6a86ab 100644
--- a/src/server/pdf/lifecycle.contract.test.ts
+++ b/src/server/pdf/lifecycle.contract.test.ts
@@ -18,11 +18,10 @@
// 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 { rmSync } from "node:fs";
import { spawnPdfChild, type PdfChildHandle } from "./lifecycle.ts";
import { ulid } from "../db/nowIso.ts";
+import { makeFixtureRoot } from "%/util/pdf-fixture";
const E2E = process.env.SCHOLAR_PDF_E2E === "1";
@@ -40,46 +39,9 @@ afterEach(async () => {
}
});
-/**
- * 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 };
-}
+// The valid-minimal-PDF fixture (writeMinimalPdf / makeFixtureRoot) lives in
+// tests/util/pdf-fixture.ts — shared with lifecycle.test.ts FIXTURE 4, which
+// likewise needs a vendor-openable document for its display_pdf round-trip.
// =============================================================================
// FIXTURE C1 — display_pdf returns a viewUUID and `interact` accepts the
diff --git a/src/server/pdf/lifecycle.resolvers.test.ts b/src/server/pdf/lifecycle.resolvers.test.ts
new file mode 100644
index 0000000..eb63205
--- /dev/null
+++ b/src/server/pdf/lifecycle.resolvers.test.ts
@@ -0,0 +1,93 @@
+// src/server/pdf/lifecycle.resolvers.test.ts — slim-plugin pivot (2026-06-01).
+//
+// Pure, always-run unit tests for the two runtime-resolution seams the pivot
+// introduced. The spawn supervisor itself is exercised by the SCHOLAR_PDF_E2E
+// fixtures in lifecycle.test.ts; these cover the branch logic those fixtures
+// reach only indirectly (and which CI, without SCHOLAR_PDF_E2E, never runs).
+// They retire the manual package-path verification done during the pivot:
+// - resolveChildEntrypoint's existsSync(${CLAUDE_PLUGIN_ROOT}/dist/...) branch
+// - resolveBunRuntime's process.execPath default
+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 {
+ resolveChildEntrypoint,
+ resolveBunRuntime,
+} from "./lifecycle.ts";
+
+// Save/restore the env keys these resolvers read so cases don't bleed.
+const ENV_KEYS = [
+ "SCHOLAR_PDF_ENTRYPOINT",
+ "CLAUDE_PLUGIN_ROOT",
+ "SCHOLAR_BUN_PATH",
+] as const;
+const saved: Record = {};
+for (const k of ENV_KEYS) saved[k] = process.env[k];
+const tmpDirs: string[] = [];
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ for (const d of tmpDirs.splice(0)) rmSync(d, { recursive: true, force: true });
+});
+
+function freshRoot(withShippedBundle: boolean): string {
+ const root = mkdtempSync(join(tmpdir(), "scholar-resolve-"));
+ tmpDirs.push(root);
+ if (withShippedBundle) {
+ const dir = join(root, "dist", "pdf-server");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "index.js"), "// shipped bundle stub\n");
+ }
+ return root;
+}
+
+// ── resolveChildEntrypoint ────────────────────────────────────────────────
+test("resolveChildEntrypoint: explicit override beats every other source", () => {
+ process.env.SCHOLAR_PDF_ENTRYPOINT = "/env/pdf.js";
+ process.env.CLAUDE_PLUGIN_ROOT = freshRoot(true);
+ expect(resolveChildEntrypoint("/override/pdf.js")).toBe("/override/pdf.js");
+});
+
+test("resolveChildEntrypoint: SCHOLAR_PDF_ENTRYPOINT wins when no override", () => {
+ process.env.SCHOLAR_PDF_ENTRYPOINT = "/env/pdf.js";
+ process.env.CLAUDE_PLUGIN_ROOT = freshRoot(true);
+ expect(resolveChildEntrypoint()).toBe("/env/pdf.js");
+});
+
+test("resolveChildEntrypoint: packaged branch — returns shipped bundle when it exists", () => {
+ delete process.env.SCHOLAR_PDF_ENTRYPOINT;
+ const root = freshRoot(true);
+ process.env.CLAUDE_PLUGIN_ROOT = root;
+ expect(resolveChildEntrypoint()).toBe(
+ join(root, "dist", "pdf-server", "index.js"),
+ );
+});
+
+test("resolveChildEntrypoint: dev fallback — vendored dist when no shipped bundle", () => {
+ delete process.env.SCHOLAR_PDF_ENTRYPOINT;
+ const root = freshRoot(false);
+ process.env.CLAUDE_PLUGIN_ROOT = root;
+ expect(resolveChildEntrypoint()).toBe(
+ join(root, "src", "vendor", "pdf-server", "dist", "index.js"),
+ );
+});
+
+// ── resolveBunRuntime ─────────────────────────────────────────────────────
+test("resolveBunRuntime: explicit override beats env and execPath", () => {
+ process.env.SCHOLAR_BUN_PATH = "/env/bun";
+ expect(resolveBunRuntime("/override/bun")).toBe("/override/bun");
+});
+
+test("resolveBunRuntime: SCHOLAR_BUN_PATH wins when no override", () => {
+ process.env.SCHOLAR_BUN_PATH = "/env/bun";
+ expect(resolveBunRuntime()).toBe("/env/bun");
+});
+
+test("resolveBunRuntime: defaults to process.execPath (the provisioned bun)", () => {
+ delete process.env.SCHOLAR_BUN_PATH;
+ expect(resolveBunRuntime()).toBe(process.execPath);
+});
diff --git a/src/server/pdf/lifecycle.test.ts b/src/server/pdf/lifecycle.test.ts
index c61f3e8..f0c1f00 100644
--- a/src/server/pdf/lifecycle.test.ts
+++ b/src/server/pdf/lifecycle.test.ts
@@ -1,12 +1,17 @@
// src/server/pdf/lifecycle.test.ts — foundation cycle 6.2 (Task 2.2)
//
-// The drift-canary fixture suite per §16. Foundation iterates: fixture 1 (spawn)
-// passes first, then 2 (roots/list), then 3 (list_changed), then 4 (viewUUID),
-// then 5 (Windows Job Object — skipped on POSIX), then 6 (supervised respawn).
+// The drift-canary fixture suite per §16. Gating is by COST, not by importance:
//
-// Heavy fixtures (4 and 6) require an actual pdf-child round-trip + valid PDF
-// parsing; they gate behind SCHOLAR_PDF_E2E=1 to keep the default `bun test`
-// run fast and deterministic. The protocol-shape fixtures (1, 2, 3) always run.
+// • Fixtures 1–3 (spawn → roots/list → list_changed) are protocol-shape: they
+// start the child and exercise the roots responder + mutation path WITHOUT
+// opening a PDF. Cheap and deterministic, so they ALWAYS run (local + CI).
+// • Fixtures 4 + 6 do a real PDF round-trip (display_pdf) / a SIGKILL+respawn
+// timing window. Heavier and spawn-flakier, so they gate behind
+// SCHOLAR_PDF_E2E=1 — kept out of the fast default `bun test`, run in CI's
+// dedicated e2e job. NB: fixture 4 asserts viewUUID survival via
+// interact({navigate}), NOT get_text — get_text needs a live browser viewer
+// and hangs headless (see lifecycle.contract.test.ts "Why no C3 for get_text?").
+// • Fixture 5 (Windows Job Object) is a test.todo pending a Win32 CI rig.
import { test, expect, afterEach } from "bun:test";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, realpathSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -17,6 +22,7 @@ import {
buildClientCapabilities,
type PdfChildHandle,
} from "./lifecycle.ts";
+import { makeFixtureRoot } from "%/util/pdf-fixture";
let handle: PdfChildHandle | undefined;
let tmpRoot: string | undefined;
@@ -69,7 +75,7 @@ test("sanitizeRoots dedupes, resolves symlinks, and drops missing paths", () =>
// =========================================================================
// FIXTURE 1: Spawn lifecycle — child starts, initializes, exposes a healthy handle.
// =========================================================================
-test.skipIf(!E2E)("FIXTURE 1 — spawn lifecycle: child initializes and reports healthy", async () => {
+test("FIXTURE 1 — spawn lifecycle: child initializes and reports healthy", async () => {
tmpRoot = makeTempPdfRoot();
handle = await spawnPdfChild({ initialRoots: [tmpRoot] });
const health = handle.isHealthy();
@@ -80,7 +86,7 @@ test.skipIf(!E2E)("FIXTURE 1 — spawn lifecycle: child initializes and reports
// =========================================================================
// FIXTURE 2: roots/list responder — scholar replies with currentRoots as file:// URIs.
// =========================================================================
-test.skipIf(!E2E)(
+test(
"FIXTURE 2 — roots/list responder: returns currentRoots as file:// URIs on demand",
async () => {
tmpRoot = makeTempPdfRoot();
@@ -93,7 +99,7 @@ test.skipIf(!E2E)(
// =========================================================================
// FIXTURE 3: list_changed round-trip — setRoots mutates without respawn.
// =========================================================================
-test.skipIf(!E2E)("FIXTURE 3 — list_changed round-trip: setRoots mutates without respawn", async () => {
+test("FIXTURE 3 — list_changed round-trip: setRoots mutates without respawn", async () => {
tmpRoot = makeTempPdfRoot();
const secondRoot = mkdtempSync(join(tmpdir(), "scholar-pdf-root2-"));
try {
@@ -114,17 +120,31 @@ test.skipIf(!E2E)("FIXTURE 3 — list_changed round-trip: setRoots mutates witho
// FIXTURE 4: viewUUID survival across root mutation (heavy — E2E only).
// =========================================================================
test.skipIf(!E2E)("FIXTURE 4 — viewUUID survives across a root mutation", async () => {
- tmpRoot = makeTempPdfRoot();
- handle = await spawnPdfChild({ initialRoots: [tmpRoot] });
+ // Open a real PDF, mutate the root set, then prove the original viewUUID is
+ // still addressable. Survival is asserted via interact({navigate}) — a
+ // fire-and-ack wire op that round-trips headless. The earlier form called
+ // handle.getText(), which requires a live browser viewer to answer; headless
+ // it enqueues to the vendor's poll queue and never returns, so the test hung
+ // to its timeout (see lifecycle.contract.test.ts "Why no C3 for get_text?").
+ // Uses a VALID minimal PDF (makeFixtureRoot) — the vendor's display_pdf
+ // rejects the synthetic header blob the spawn-only fixtures use.
+ const fix = makeFixtureRoot();
+ tmpRoot = fix.root;
+ handle = await spawnPdfChild({ initialRoots: [fix.root] });
+
// §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 { viewUUID } = await handle.displayPdf(fix.pdf);
+ expect(typeof 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");
+ await handle.setRoots([fix.root, secondRoot]);
+ // The root mutation must not drop the open view: a navigate against the
+ // pre-mutation viewUUID still round-trips (vendor returns null on success).
+ await expect(
+ handle.interact({ type: "navigate", page: 1 }, { viewUUID }),
+ ).resolves.toBeDefined();
} finally {
rmSync(secondRoot, { recursive: true, force: true });
}
@@ -133,29 +153,44 @@ test.skipIf(!E2E)("FIXTURE 4 — viewUUID survives across a root mutation", asyn
// =========================================================================
// FIXTURE 5: Job Object kills child when scholar dies (Windows only).
// =========================================================================
-test.skipIf(process.platform !== "win32")(
- "FIXTURE 5 — Job Object reaps the orphan child on parent SIGKILL",
- async () => {
- // Implementation deferred — uses Bun.spawn for the harness and process.kill(pid, 0)
- // to probe liveness. Foundation pins attachJobObject as best-effort; the test only
- // runs on win32 and confirms the child does NOT outlive the parent.
- expect(true).toBe(true); // placeholder; executor wires the harness in a Windows CI run
- },
-);
+// test.todo, NOT a passing placeholder: the prior `expect(true).toBe(true)` on
+// win32 reported a vacuous green for a behavior that is never actually verified.
+// Implement once a Win32 CI rig exists — spawn under attachJobObject, SIGKILL
+// the parent, then assert the child is gone (process.kill(childPid, 0) throws
+// ESRCH). Tracked in docs/audits/ROADMAP.md.
+test.todo("FIXTURE 5 — Job Object reaps the orphan child on parent SIGKILL (win32)", () => {});
// =========================================================================
// FIXTURE 6: Supervised respawn (heavy — E2E only).
// =========================================================================
-test.skipIf(!E2E)("FIXTURE 6 — supervised respawn: setRoots survives a child SIGKILL", async () => {
- tmpRoot = makeTempPdfRoot();
- handle = await spawnPdfChild({ initialRoots: [tmpRoot] });
- const pidBefore = handle.childPid();
- expect(pidBefore).toBeDefined();
- process.kill(pidBefore!, "SIGKILL");
- // Supervisor first-bucket is 1s; allow a 500ms slack window for SDK re-handshake.
- await new Promise((r) => setTimeout(r, 1_500));
- expect(handle.currentRoots()).toEqual([realpathSync(tmpRoot)]);
- const h = handle.isHealthy();
- expect(h.alive).toBe(true);
- expect(handle.childPid()).not.toBe(pidBefore);
-});
+test.skipIf(!E2E)(
+ "FIXTURE 6 — supervised respawn: setRoots survives a child SIGKILL",
+ async () => {
+ tmpRoot = makeTempPdfRoot();
+ handle = await spawnPdfChild({ initialRoots: [tmpRoot] });
+ const pidBefore = handle.childPid();
+ expect(pidBefore).toBeDefined();
+ process.kill(pidBefore!, "SIGKILL");
+
+ // Respawn is asynchronous and has NO fixed duration: the supervisor waits
+ // BACKOFF_MS[0]=1s after onclose, then spawns a fresh child AND completes an
+ // MCP re-handshake before activePid flips (lifecycle.ts childPid → activePid).
+ // That total (1s backoff + spawn + handshake) intermittently exceeds a fixed
+ // sleep and varies with bun version / host load — a 1.5s sleep flaked 2-of-3
+ // under the CI-pinned bun 1.3.11. Poll for the new PID instead of guessing a
+ // duration; the explicit test timeout below (not bun's 5s default) bounds a
+ // genuine hang.
+ const deadline = Date.now() + 15_000;
+ while (Date.now() < deadline) {
+ const pid = handle.childPid();
+ if (pid !== undefined && pid !== pidBefore && handle.isHealthy().alive) break;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+
+ expect(handle.currentRoots()).toEqual([realpathSync(tmpRoot)]);
+ const h = handle.isHealthy();
+ expect(h.alive).toBe(true);
+ expect(handle.childPid()).not.toBe(pidBefore);
+ },
+ 20_000,
+);
diff --git a/src/server/pdf/lifecycle.ts b/src/server/pdf/lifecycle.ts
index 7ec299c..564a60c 100644
--- a/src/server/pdf/lifecycle.ts
+++ b/src/server/pdf/lifecycle.ts
@@ -27,7 +27,7 @@ export interface SpawnOpts {
initialRoots: string[];
/** Override the child entrypoint path (test harness uses a stub). */
childEntrypoint?: string;
- /** Override the bun runtime path (default: process.execPath). */
+ /** Override the bun runtime path (default: SCHOLAR_BUN_PATH ?? process.execPath). */
bunRuntime?: string;
/** Disable supervised respawn (test harness, default false). */
disableSupervisor?: boolean;
@@ -95,17 +95,35 @@ const BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 30_000] as const;
const CRASH_LOOP_THRESHOLD_MS = 1_000;
const CRASH_LOOP_TRIPS = 5;
-function resolveChildEntrypoint(override?: string): string {
+export function resolveChildEntrypoint(override?: string): string {
if (override) return override;
+ // Slim-plugin model: pdf-server@1.7.2 ships as a single rebundled standalone
+ // file (pdfjs-dist + all deps inlined by `bun build --target=bun`; verified to
+ // parse PDFs with no node_modules — see lifecycle.contract.test.ts run under
+ // SCHOLAR_PDF_ENTRYPOINT). mcp-app.html sits beside it (vendor reads it from
+ // import.meta.dirname). Resolution order:
+ // 1. SCHOLAR_PDF_ENTRYPOINT — explicit override the manifest wires in.
+ // 2. ${CLAUDE_PLUGIN_ROOT}/dist/pdf-server/index.js — the shipped standalone
+ // bundle (present only in the packaged plugin, not the dev checkout).
+ // 3. /src/vendor/pdf-server/dist/index.js — dev/test fallback; the
+ // upstream dist whose pdfjs-dist dynamic import resolves from the repo
+ // node_modules. §16 keeps this vendored tree as the .d.ts type source.
+ const fromEnv = process.env.SCHOLAR_PDF_ENTRYPOINT;
+ if (fromEnv) return fromEnv;
const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT ?? resolve(import.meta.dir, "..", "..", "..");
+ const shipped = join(pluginRoot, "dist", "pdf-server", "index.js");
+ if (existsSync(shipped)) return shipped;
return join(pluginRoot, "src", "vendor", "pdf-server", "dist", "index.js");
}
-function resolveBunRuntime(override?: string): string {
+export function resolveBunRuntime(override?: string): string {
if (override) return override;
- // Bun is the runtime in dev AND packaged (build/runtime/bun{.exe}). The
- // dispatcher gets process.execPath at runtime so this works in both layouts.
- return process.execPath;
+ // Slim-plugin model: scholar itself is launched by the provisioned bun
+ // (manifest command = ${CLAUDE_PLUGIN_DATA}/bun{.exe}), so process.execPath is
+ // already that bun and serves as the default. SCHOLAR_BUN_PATH lets the
+ // manifest pin the child's runtime explicitly, decoupling it from however the
+ // parent happened to be launched (e.g. a wrapper, or a dev `bun run`).
+ return process.env.SCHOLAR_BUN_PATH ?? process.execPath;
}
export async function spawnPdfChild(opts: SpawnOpts): Promise {
diff --git a/src/server/tools/annotations.test.ts b/src/server/tools/annotations.test.ts
index a472691..cf02c03 100644
--- a/src/server/tools/annotations.test.ts
+++ b/src/server/tools/annotations.test.ts
@@ -100,41 +100,27 @@ function findInteract(type: string): InteractCall[] {
// 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: TEST_PAPER }))
- .rejects.toMatchObject({ code: "NO_ACTIVE_CORPUS" });
- expect(interactCalls).toHaveLength(0);
- } finally {
- built.ctx.db = saved;
- }
-});
-
-test("scholar.annotations.upsert 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.upsert", { paper_id: TEST_PAPER, body: "x" }))
- .rejects.toMatchObject({ code: "NO_ACTIVE_CORPUS" });
- expect(interactCalls).toHaveLength(0);
- } finally {
- built.ctx.db = saved;
- }
-});
-
-test("scholar.annotations.delete 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.delete", { id: "01ABCD" }))
- .rejects.toMatchObject({ code: "NO_ACTIVE_CORPUS" });
- expect(interactCalls).toHaveLength(0);
- } finally {
- built.ctx.db = saved;
- }
-});
+// All three handlers must guard ctx.db === undefined identically (§13 invariant
+// 4): reject NO_ACTIVE_CORPUS before any pdf-child I/O. Table-driven — one row
+// per handler, with that handler's minimal valid arg shape.
+test.each([
+ ["scholar.annotations.list", { paper_id: TEST_PAPER }],
+ ["scholar.annotations.upsert", { paper_id: TEST_PAPER, body: "x" }],
+ ["scholar.annotations.delete", { id: "01ABCD" }],
+] as [string, unknown][])(
+ "%s NO_ACTIVE_CORPUS guard fires when ctx.db is undefined",
+ async (tool, args) => {
+ const saved = built.ctx.db;
+ built.ctx.db = undefined;
+ try {
+ await expect(dispatch(tool, args))
+ .rejects.toMatchObject({ code: "NO_ACTIVE_CORPUS" });
+ expect(interactCalls).toHaveLength(0);
+ } finally {
+ built.ctx.db = saved;
+ }
+ },
+);
// =============================================================================
// NO_OPEN_VIEWER guards (§13 v1.1 invariant 5 — new)
@@ -512,23 +498,21 @@ test("upsert accepts valid 4-element finite rect JSON", async () => {
expect(JSON.parse(row.rect)).toEqual([10, 20, 200, 300]);
});
-test("upsert rejects rect with 3 elements", async () => {
- await expect(dispatch("scholar.annotations.upsert", {
- 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: 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: TEST_PAPER, body: "x", rect: '{"x":10}',
- })).rejects.toMatchObject({ code: "INVALID_RECT" });
-});
+// Malformed rect strings all reject with INVALID_RECT. Table-driven; the
+// valid-accept case stays separate above (it asserts a successful DB round-trip,
+// not a rejection).
+test.each([
+ ["3 elements", "[10, 20, 200]"],
+ ["non-finite", "[10, 20, 200, 1e9999]"],
+ ["wrong shape (object)", '{"x":10}'],
+] as [string, string][])(
+ "upsert rejects malformed rect JSON: %s",
+ async (_label, rect) => {
+ await expect(dispatch("scholar.annotations.upsert", {
+ paper_id: TEST_PAPER, body: "x", rect,
+ })).rejects.toMatchObject({ code: "INVALID_RECT" });
+ },
+);
// =============================================================================
// Paper-level note + serializeForViewer fallback rect
diff --git a/src/server/util/p-limit.test.ts b/src/server/util/p-limit.test.ts
new file mode 100644
index 0000000..54218fb
--- /dev/null
+++ b/src/server/util/p-limit.test.ts
@@ -0,0 +1,61 @@
+// src/server/util/p-limit.test.ts — foundation cycle 6.2 (Task 2.2)
+//
+// The single-slot mutex underpins the §13 annotation-reconciliation push path
+// (lifecycle.ts:146 `pLimit(1)`): pdf-child round-trips must serialize so a
+// concurrent annotations.list cannot interleave with an in-flight push. These
+// tests pin the three load-bearing properties — rejects non-1 concurrency,
+// serializes, and survives a rejecting task — without any process spawning.
+import { test, expect } from "bun:test";
+import pLimit from "./p-limit.ts";
+
+test("rejects any concurrency other than 1 (the only shape lifecycle needs)", () => {
+ expect(() => pLimit(2)).toThrow(/concurrency=1/);
+ expect(() => pLimit(0)).toThrow(/concurrency=1/);
+ expect(() => pLimit(1)).not.toThrow();
+});
+
+test("returns the wrapped task's resolved value to the caller", async () => {
+ const limit = pLimit(1);
+ expect(await limit(async () => "hi")).toBe("hi");
+ expect(await limit(async () => 42)).toBe(42);
+});
+
+test("serializes: a queued task does not start until the prior one settles", async () => {
+ const limit = pLimit(1);
+ const events: string[] = [];
+ let release!: () => void;
+ const blocked = new Promise((r) => {
+ release = r;
+ });
+
+ const p1 = limit(async () => {
+ events.push("1:start");
+ await blocked;
+ events.push("1:end");
+ });
+ const p2 = limit(async () => {
+ events.push("2:start");
+ events.push("2:end");
+ });
+
+ // While task 1 is blocked, task 2 must not have begun.
+ await Bun.sleep(5);
+ expect(events).toEqual(["1:start"]);
+
+ release();
+ await Promise.all([p1, p2]);
+ // Strict ordering: 1 fully completes before 2 begins.
+ expect(events).toEqual(["1:start", "1:end", "2:start", "2:end"]);
+});
+
+test("a rejecting task propagates to its caller but does NOT kill the queue", async () => {
+ const limit = pLimit(1);
+ const failing = limit(async () => {
+ throw new Error("boom");
+ });
+ const following = limit(async () => "survived");
+
+ await expect(failing).rejects.toThrow("boom");
+ // The chain swallows the rejection internally so the next task still runs.
+ expect(await following).toBe("survived");
+});
diff --git a/tests/build-plugin.test.ts b/tests/build-plugin.test.ts
index 6de4636..9b3016c 100644
--- a/tests/build-plugin.test.ts
+++ b/tests/build-plugin.test.ts
@@ -1,469 +1,48 @@
-// scripts/build-plugin.test.ts
-import { test, expect, beforeAll, afterAll } from "bun:test"
-import {
- mkdirSync,
- writeFileSync,
- existsSync,
- rmSync,
- mkdtempSync,
- readFileSync,
-} from "node:fs"
-import { join } from "node:path"
-import { tmpdir } from "node:os"
-import { unzipSync } from "fflate" // pre-declared by foundation; no CLI dependency
-import util from "^scripts/util"
-import env from "^scripts/util/env.ts"
-import { getVec0Extension } from "^src/server/db/sqlite-vec.ts"
-
-// Fixture root — a temp dir acting as the repo root for the test run
-const FIXTURE_ROOT = mkdtempSync(join(tmpdir(), "scholar-build-test-"))
-const OUTPUT_DIR = join(FIXTURE_ROOT, "dist")
-
-// Paths the build script expects to find (fixture stubs).
-// BOTH platform variants for runtime and vec0 are staged so the test suite
-// passes on any dev host (Linux/WSL or Windows). step7_assemblePlugin picks
-// the platform-appropriate variant at archive assembly time.
-// build/scholar (extension-less sibling) is intentionally absent — step1
-// creates it from build/scholar.exe even in fixture mode (M1 coverage).
-const FIXTURE_FILES: [string, string][] = [
- ["build/scholar.exe", '{"stub":"server-binary"}'],
- ["build/ui/app.html", "stub"],
- ["build/vendor/pdf-server/dist/index.js", "// stub pdf server"],
- // Both vec0 platform variants (step5 copies from src/ to build/)
- ["runtime/vendor/sqlite-vec/vec0.dll", "stub-dll-win"],
- ["build/vendor/sqlite-vec/vec0.dll", "stub-dll-win"],
- ["runtime/vendor/sqlite-vec/vec0.so", "stub-so-linux"],
- ["build/vendor/sqlite-vec/vec0.so", "stub-so-linux"],
- // sqlite-vec source for compile fallback (build-time only; NOT archived).
- // Source filename is sqlite-vec.c per spec §14.1 step 5 + §7.2.1.
- ["src/vendor/sqlite-vec/sqlite-vec.c", "/* stub sqlite-vec source */"],
- ["src/vendor/sqlite-vec/sqlite3.h", "/* stub sqlite3 header */"],
- // Both Bun runtime platform variants
- ["build/runtime/bun.exe", "stub-runtime-win"],
- ["build/runtime/bun", "stub-runtime-posix"],
- ["nu/scholar.nu", "# stub nu module"],
- // Slash commands — frontends cycle 6.10
- ["commands/ingest.md", "# stub ingest command"],
- ["commands/digest.md", "# stub digest command"],
- ["commands/status.md", "# stub status command"],
- // Skills — frontends cycle 6.10
- ["skills/scholar-workflow/SKILL.md", "# stub scholar-workflow skill"],
- ["skills/scholar-ingest/SKILL.md", "# stub scholar-ingest skill"],
- [
- ".claude-plugin/plugin.json",
- JSON.stringify({
- name: "scholar",
- version: "0.1.0",
- description: "stub",
- author: { name: "zayn" },
- keywords: [],
- license: "MIT",
- }),
- ],
- [
- ".mcp.json",
- JSON.stringify({
- mcpServers: {
- scholar: { command: "./build/scholar", args: [], env: {} },
- },
- }),
- ],
-]
-
-// package.json with both version fields populated (intentionally differing values —
-// bundledBunVersion records the Bun runtime version, bunSqliteVersion records the
-// SQLite library version Bun's bun:sqlite links against; they record different facts
-// about the same Bun release and are expected to differ).
-const PKG_JSON = {
- name: "scholar",
- version: "0.1.0",
- scripts: {
- "build:server": "echo skip-in-fixture",
- "build:ui": "echo skip-in-fixture",
- "build:pdf": "echo skip-in-fixture",
- "build:runtime": "echo skip-in-fixture",
- "build:vec": "echo skip-in-fixture",
- "build:nu": "echo skip-in-fixture",
- "build:plugin": "echo skip-in-fixture",
- },
- scholar: {
- bundledBunVersion: "1.2.3", // fake Bun runtime version
- bunSqliteVersion: "3.45.0", // fake SQLite library version (intentionally different)
- },
- dependencies: {},
- devDependencies: {},
-}
-
-beforeAll(() => {
- for (const [relPath, content] of FIXTURE_FILES) {
- const abs = join(FIXTURE_ROOT, relPath)
- mkdirSync(join(abs, ".."), { recursive: true })
- writeFileSync(abs, content, "utf8")
- }
- mkdirSync(join(FIXTURE_ROOT, "scripts"), { recursive: true })
- writeFileSync(
- join(FIXTURE_ROOT, "package.json"),
- JSON.stringify(PKG_JSON, null, 2),
- )
- mkdirSync(OUTPUT_DIR, { recursive: true })
-})
-
-afterAll(() => {
- rmSync(FIXTURE_ROOT, { recursive: true, force: true })
-})
-
-// Helper: spawn the build script with fixture env, collect exit code + stderr.
-// process.execPath is used instead of "bun" to avoid PATH-resolution failure
-// when the SCHOLAR_BUILD_NO_C_TOOLCHAIN test overrides PATH to an empty dir —
-// Bun.spawn resolves the executable name from the env-supplied PATH.
-async function runBuildScript(
- buildRoot: string,
- pluginOut: string,
- extraEnv: Record = {},
-) {
- const proc = Bun.spawn(
- [process.execPath, util.subpath("scripts/build-plugin.ts")],
- {
- env: {
- ...process.env,
- SCHOLAR_BUILD_FIXTURE: "1",
- SCHOLAR_ROOT: buildRoot,
- SCHOLAR_PLUGIN_OUT: pluginOut,
- ...extraEnv,
- },
- stdout: "pipe",
- stderr: "pipe",
- cwd: util.subpath(),
- },
- )
- const exitCode = await proc.exited
- const stderr = await new Response(proc.stderr).text()
- return { exitCode, stderr }
-}
-
-// Helper: read archive with fflate — platform-independent, no unzip CLI needed.
-function readArchive(archivePath: string): Record {
- return unzipSync(new Uint8Array(readFileSync(archivePath)))
-}
-
-test("build-plugin produces a .plugin archive with the required layout", async () => {
- const { exitCode, stderr } = await runBuildScript(FIXTURE_ROOT, OUTPUT_DIR)
- expect(exitCode, `build script exited non-zero:\n${stderr}`).toBe(0)
-
- const archivePath = join(OUTPUT_DIR, "scholar.plugin")
- expect(existsSync(archivePath)).toBe(true)
-
- const entries = readArchive(archivePath)
- const entryNames = Object.keys(entries)
-
- // Platform-specific variants — step7 picks based on process.platform
- const runtimeEntry = `build/runtime/bun${env.dynamic({ win32: ".exe", default: "" })}`
- const vec0Entry = `build/vendor/sqlite-vec/vec0.${getVec0Extension()}`
- const requiredEntries = [
- ".claude-plugin/plugin.json",
- ".mcp.json",
- "build/scholar.exe",
- "build/scholar", // extension-less sibling (step1)
- "build/ui/app.html",
- "build/vendor/pdf-server/dist/index.js",
- runtimeEntry,
- vec0Entry,
- "nu/scholar.nu",
- // Slash commands (frontends cycle 6.10) — packed recursively via collectDir
- "commands/ingest.md",
- "commands/digest.md",
- "commands/status.md",
- // Skills (frontends cycle 6.10)
- "skills/scholar-workflow/SKILL.md",
- "skills/scholar-ingest/SKILL.md",
- ]
-
- for (const entry of requiredEntries) {
- expect(entryNames, `Missing archive entry: ${entry}`).toContain(entry)
- }
-
- // Posture-B preservation guard: sqlite3-mcp must NOT appear in the archive.
- // Scholar reimplements §10 query/backup/inspect in-process via bun:sqlite per
- // user posture-B ruling 2026-05-24; no Python binary is vendored or shipped.
- for (const name of entryNames) {
- expect(
- name,
- `sqlite3-mcp artifact found in archive (posture-B violation): ${name}`,
- ).not.toMatch(/sqlite3.mcp|server-sqlite3/)
- }
-})
-
-test("archive plugin.json is valid JSON matching the scholar manifest schema", async () => {
- const archivePath = join(OUTPUT_DIR, "scholar.plugin")
- const entries = readArchive(archivePath)
- const raw = new TextDecoder().decode(entries[".claude-plugin/plugin.json"])
- const parsed = JSON.parse(raw) // throws if invalid JSON
-
- expect(parsed.name).toBe("scholar")
- expect(typeof parsed.version).toBe("string")
- expect(parsed.license).toBe("MIT")
-})
-
-test("archive .mcp.json is valid JSON and command path is present in archive", async () => {
- const archivePath = join(OUTPUT_DIR, "scholar.plugin")
- const entries = readArchive(archivePath)
- const raw = new TextDecoder().decode(entries[".mcp.json"])
- const parsed = JSON.parse(raw)
-
- const serverEntry = Object.values(
- parsed.mcpServers as Record,
- )[0]
- expect(serverEntry).toBeDefined()
-
- // Strip leading ./ and verify the command binary is present in the archive
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- const commandRel = serverEntry!.command.replace(/^\.\//, "")
- expect(
- Object.keys(entries),
- `command path '${commandRel}' not found in archive`,
- ).toContain(commandRel)
-})
-
-test("step1_buildServer creates extension-less build/scholar sibling (sibling-copy branch coverage)", async () => {
- // Exercises the copyFileSync branch that has zero coverage under the full
- // fixture-mode integration test (which pre-stages build/scholar). Here we
- // deliberately provide only build/scholar.exe and assert step1 produces the sibling.
- const tmpDir = mkdtempSync(join(tmpdir(), "scholar-step1-"))
- try {
- mkdirSync(join(tmpDir, "build"), { recursive: true })
- writeFileSync(join(tmpDir, "build/scholar.exe"), "stub-binary-content")
-
- // step1_buildServer is exported and accepts (buildRoot, fixture) explicitly
- // so it can be called in isolation without module-level env var coupling.
- const { step1_buildServer } =
- (await import("^scripts/build-plugin.ts")) as {
- step1_buildServer: (root: string, fixture: boolean) => Promise
- }
- await step1_buildServer(tmpDir, true) // fixture=true skips shell-out; runs copy
-
- const siblingPath = join(tmpDir, "build/scholar")
- expect(
- existsSync(siblingPath),
- "extension-less sibling not created by step1",
- ).toBe(true)
- expect(readFileSync(siblingPath, "utf8")).toBe("stub-binary-content")
- } finally {
- rmSync(tmpDir, { recursive: true, force: true })
- }
-})
-
-test("build-plugin aborts with SCHOLAR_BUILD_MISMATCH when bundledBunVersion is missing", async () => {
- // scholar.bundledBunVersion omitted entirely — the invariant is that BOTH fields
- // must be populated and non-empty (they record different facts about the same Bun
- // release; string-equality is NOT required).
- const missingBvRoot = mkdtempSync(
- join(tmpdir(), "scholar-build-mismatch-bv-"),
- )
- try {
- for (const [relPath, content] of FIXTURE_FILES) {
- const abs = join(missingBvRoot, relPath)
- mkdirSync(join(abs, ".."), { recursive: true })
- writeFileSync(abs, content, "utf8")
- }
- const missingBvPkg = {
- ...PKG_JSON,
- scholar: { bunSqliteVersion: "3.45.0" }, // bundledBunVersion absent
- }
- writeFileSync(
- join(missingBvRoot, "package.json"),
- JSON.stringify(missingBvPkg, null, 2),
- )
- mkdirSync(join(missingBvRoot, "dist"), { recursive: true })
-
- const { exitCode, stderr } = await runBuildScript(
- missingBvRoot,
- join(missingBvRoot, "dist"),
- )
- expect(exitCode).not.toBe(0)
- expect(stderr).toContain("SCHOLAR_BUILD_MISMATCH")
- } finally {
- rmSync(missingBvRoot, { recursive: true, force: true })
- }
-})
-
-test("build-plugin aborts with SCHOLAR_BUILD_MISMATCH when bunSqliteVersion is empty", async () => {
- // scholar.bunSqliteVersion present but empty string — the invariant catches
- // both missing and empty-string values.
- const emptySvRoot = mkdtempSync(join(tmpdir(), "scholar-build-mismatch-sv-"))
- try {
- for (const [relPath, content] of FIXTURE_FILES) {
- const abs = join(emptySvRoot, relPath)
- mkdirSync(join(abs, ".."), { recursive: true })
- writeFileSync(abs, content, "utf8")
- }
- const emptySvPkg = {
- ...PKG_JSON,
- scholar: { bundledBunVersion: "1.2.3", bunSqliteVersion: "" }, // empty string
- }
- writeFileSync(
- join(emptySvRoot, "package.json"),
- JSON.stringify(emptySvPkg, null, 2),
- )
- mkdirSync(join(emptySvRoot, "dist"), { recursive: true })
-
- const { exitCode, stderr } = await runBuildScript(
- emptySvRoot,
- join(emptySvRoot, "dist"),
- )
- expect(exitCode).not.toBe(0)
- expect(stderr).toContain("SCHOLAR_BUILD_MISMATCH")
- } finally {
- rmSync(emptySvRoot, { recursive: true, force: true })
- }
-})
-
-test("build-plugin aborts with SCHOLAR_BUILD_VEC_MISSING when vec0 prebuilt is absent", async () => {
- const noVecRoot = mkdtempSync(join(tmpdir(), "scholar-build-novec-"))
- try {
- for (const [relPath, content] of FIXTURE_FILES) {
- // Omit all src/vendor/sqlite-vec/ entries (both .dll and .so) — the script
- // must detect the platform-appropriate prebuilt is absent and abort.
- if (relPath.startsWith("runtime/vendor/sqlite-vec/")) continue
- const abs = join(noVecRoot, relPath)
- mkdirSync(join(abs, ".."), { recursive: true })
- writeFileSync(abs, content, "utf8")
- }
- writeFileSync(
- join(noVecRoot, "package.json"),
- JSON.stringify(PKG_JSON, null, 2),
- )
- mkdirSync(join(noVecRoot, "dist"), { recursive: true })
-
- const { exitCode, stderr } = await runBuildScript(
- noVecRoot,
- join(noVecRoot, "dist"),
- )
- expect(exitCode).not.toBe(0)
- expect(stderr).toContain("SCHOLAR_BUILD_VEC_MISSING")
- } finally {
- rmSync(noVecRoot, { recursive: true, force: true })
- }
-})
-
-// ── Compile-fallback tests (I2 ruling) ───────────────────────────────────────
-// SCHOLAR_BUILD_VEC_FORCE_COMPILE=1 bypasses the ABI probe and jumps directly
-// to compileVec0FromSource, enabling fixture-mode testing of the compile path
-// without requiring a real ABI-mismatched binary.
-
-test("probeVec0Abi returns false for a file that is not a valid SQLite extension", async () => {
- // Unit test for the ABI probe helper. probeVec0Abi must be exported.
- const { probeVec0Abi } = (await import("^scripts/build-vec0.ts")) as {
- probeVec0Abi: (extPath: string) => boolean
- }
- const stubPath = join(FIXTURE_ROOT, "runtime/vendor/sqlite-vec/vec0.dll")
- // The fixture stub contains plain text ("stub-dll-win"), not a real extension.
- // loadExtension must throw, and probeVec0Abi must return false.
- const result = probeVec0Abi(stubPath)
- expect(result).toBe(false)
-})
-
-test("compile fallback produces vec0 artifact when SCHOLAR_BUILD_VEC_FORCE_COMPILE=1", async () => {
- // Verify that compileVec0FromSource is invoked when SCHOLAR_BUILD_VEC_FORCE_COMPILE=1,
- // and that the compiled artifact ends up at build/vendor/sqlite-vec/.
- //
- // The stub CC script writes dummy bytes to the output path (the -o argument).
- // This validates the compile path mechanics without requiring a real C toolchain.
- const compileRoot = mkdtempSync(join(tmpdir(), "scholar-compile-"))
- try {
- for (const [relPath, content] of FIXTURE_FILES) {
- // Skip both the runtime/ cache and the build/ destination so the compile
- // path actually fires: compileVec0FromSource short-circuits on a cached
- // artifact at runtime/vendor/sqlite-vec/, and a pre-staged destination
- // would make existsSync(compiledPath) pass without the stub CC running.
- if (relPath.startsWith("runtime/vendor/sqlite-vec/")) continue
- if (relPath.startsWith("build/vendor/sqlite-vec/")) continue
- const abs = join(compileRoot, relPath)
- mkdirSync(join(abs, ".."), { recursive: true })
- writeFileSync(abs, content, "utf8")
- }
- writeFileSync(
- join(compileRoot, "package.json"),
- JSON.stringify(PKG_JSON, null, 2),
- )
- mkdirSync(join(compileRoot, "dist"), { recursive: true })
-
- // Cross-platform stub CC: a small Bun script that parses -o from
- // argv and writes stub bytes there. The build script invokes: CC -o
- const ccStubPath = join(compileRoot, "stub-cc.ts")
- writeFileSync(
- ccStubPath,
- `
-const args = process.argv.slice(2);
-const oIdx = args.indexOf("-o");
-if (oIdx !== -1 && args[oIdx + 1]) {
- await Bun.write(args[oIdx + 1], "stub-compiled-vec0");
-} else {
- // MSVC /Fe: convention
- const feArg = args.find(a => a.startsWith("/Fe:"));
- if (feArg) await Bun.write(feArg.slice(4), "stub-compiled-vec0");
+// tests/build-plugin.test.ts — slim-plugin pivot (2026-06-01).
+//
+// Pins the per-OS M2 manifest the build emits (scripts/build-plugin.ts
+// buildManifest). The static dev manifest is pinned by manifests.test.ts; this
+// covers the GENERATED output — the launch-model branch (cmd.exe vs /bin/sh),
+// the platform runtime root, and the pre-warm hook — which was untested.
+import { test, expect } from 'bun:test'
+import { buildManifest } from '^scripts/build-plugin.ts'
+
+// Minimal base carrying a leftover compiled-binary `bin` field to prove it is
+// stripped, plus identity fields to prove base passthrough.
+const base = {
+ name: 'scholar',
+ license: 'MIT',
+ keywords: ['literature-review'],
+ bin: { 'mcp-scholar': './bin/mcp-scholar' },
}
-`,
- "utf8",
- )
-
- const { exitCode, stderr } = await runBuildScript(
- compileRoot,
- join(compileRoot, "dist"),
- {
- SCHOLAR_BUILD_VEC_FORCE_COMPILE: "1",
- CC: `bun ${ccStubPath}`,
- },
- )
-
- expect(exitCode, `compile-fallback path exited non-zero:\n${stderr}`).toBe(
- 0,
- )
-
- // Compiled artifact should exist at build/vendor/sqlite-vec/
- // AND contain the stub CC's output — proves the compile path actually ran
- // rather than copying a pre-staged stub.
- const libName = `vec0.${getVec0Extension()}`
- const compiledPath = join(compileRoot, "build/vendor/sqlite-vec", libName)
- expect(
- existsSync(compiledPath),
- `compiled vec0 not found at ${compiledPath}`,
- ).toBe(true)
- expect(readFileSync(compiledPath, "utf8")).toBe("stub-compiled-vec0")
- } finally {
- rmSync(compileRoot, { recursive: true, force: true })
- }
-})
-
-test("build-plugin aborts with SCHOLAR_BUILD_NO_C_TOOLCHAIN when no compiler is available", async () => {
- const noCcRoot = mkdtempSync(join(tmpdir(), "scholar-no-cc-"))
- try {
- for (const [relPath, content] of FIXTURE_FILES) {
- if (relPath.startsWith("runtime/vendor/sqlite-vec/")) continue
- const abs = join(noCcRoot, relPath)
- mkdirSync(join(abs, ".."), { recursive: true })
- writeFileSync(abs, content, "utf8")
- }
- writeFileSync(
- join(noCcRoot, "package.json"),
- JSON.stringify(PKG_JSON, null, 2),
- )
- mkdirSync(join(noCcRoot, "dist"), { recursive: true })
-
- // CC set to a non-existent binary and PATH cleared of known compilers
- const { exitCode, stderr } = await runBuildScript(
- noCcRoot,
- join(noCcRoot, "dist"),
- {
- SCHOLAR_BUILD_VEC_FORCE_COMPILE: "1",
- CC: "nonexistent-compiler-that-does-not-exist",
- // Override PATH to prevent fallback to system cc/gcc/clang
- PATH: join(noCcRoot, "empty-bin"),
- },
- )
- expect(exitCode).not.toBe(0)
- expect(stderr).toContain("SCHOLAR_BUILD_NO_C_TOOLCHAIN")
- } finally {
- rmSync(noCcRoot, { recursive: true, force: true })
- }
+test('buildManifest(linux): /bin/sh launcher + HOME runtime root + sh pre-warm', () => {
+ const m = buildManifest(base, false) as any
+ expect(m.name).toBe('scholar') // base passthrough
+ expect(m.bin).toBeUndefined() // compiled-binary leftover stripped
+ const s = m.mcpServers.scholar
+ expect(s.command).toBe('/bin/sh')
+ expect(s.args).toEqual(['${CLAUDE_PLUGIN_ROOT}/bin/launch.sh'])
+ expect(s.env.SCHOLAR_RUNTIME_ROOT).toBe('${HOME}/mcp-data/scholar/runtime')
+ expect(s.env.SCHOLAR_OLLAMA_EMBED_MODEL).toBe('nomic-embed-text:v1.5')
+ expect(s.env.SCHOLAR_OLLAMA_CHAT_MODEL).toBe('qwen3:8b')
+ const hook = m.hooks.SessionStart[0].hooks[0].command
+ expect(hook).toContain('ensure-bun.sh')
+ expect(hook.startsWith('sh ')).toBe(true)
+})
+
+test('buildManifest(win32): cmd.exe launcher + USERPROFILE root + PowerShell pre-warm', () => {
+ const m = buildManifest(base, true) as any
+ expect(m.bin).toBeUndefined()
+ const s = m.mcpServers.scholar
+ expect(s.command).toBe('cmd.exe')
+ expect(s.args).toEqual(['/c', '${CLAUDE_PLUGIN_ROOT}\\bin\\launch.cmd'])
+ expect(s.env.SCHOLAR_RUNTIME_ROOT).toBe(
+ '${USERPROFILE}\\mcp-data\\scholar\\runtime',
+ )
+ // Ollama defaults are platform-independent.
+ expect(s.env.SCHOLAR_OLLAMA_EMBED_MODEL).toBe('nomic-embed-text:v1.5')
+ const hook = m.hooks.SessionStart[0].hooks[0].command
+ expect(hook).toContain('ensure-bun.ps1')
+ expect(hook).toContain('powershell')
})
diff --git a/tests/manifests.test.ts b/tests/manifests.test.ts
index 532cc63..f55cd76 100644
--- a/tests/manifests.test.ts
+++ b/tests/manifests.test.ts
@@ -1,24 +1,36 @@
-// manifests.test.ts — foundation cycle 6.1 (Task 1.11)
+import pluginManifest from '^.claude-plugin/plugin.json'
+// manifests.test.ts — foundation cycle 6.1 (Task 1.11), amended 2026-06-01.
//
-// Pins plugin manifest + .mcp.json verbatim against spec §7.1.
-import { test, expect } from "bun:test"
-import pluginManifest from "^/.claude-plugin/plugin.json"
-import mcpManifest from "^/.mcp.json"
+// Pins the dev plugin manifest (`.claude-plugin/plugin.json`, the Linux base
+// form). The slim-plugin pivot (docs/superpowers/specs/2026-06-01-slim-plugin-
+// pivot.md) SUPERSEDES design-spec §7.1: the manifest no longer points `command`
+// at a `bun build --compile` binary (`${CLAUDE_PLUGIN_ROOT}/build/scholar`).
+// Launch is now M2 — an always-present shell runs the launcher, which provisions
+// bun then execs `dist/server.js`. The `.mcp.json` pinned by the original §7.1
+// was removed in 84a292c (mcpServers now live in plugin.json). The per-OS
+// GENERATED manifest (cmd.exe on win32, hooks) is produced by
+// scripts/build-plugin.ts — covered separately.
+import { test, expect } from 'bun:test'
-test("plugin manifest matches spec §7.1", () => {
- expect(pluginManifest.name).toBe("scholar")
- expect(pluginManifest.license).toBe("MIT")
- expect(pluginManifest.keywords).toContain("literature-review")
+test('plugin manifest matches spec §7.1 (identity fields)', () => {
+ expect(pluginManifest.name).toBe('scholar')
+ expect(pluginManifest.license).toBe('MIT')
+ expect(pluginManifest.keywords).toContain('literature-review')
})
-test(".mcp.json points command at the compiled binary placeholder", () => {
- expect(mcpManifest.mcpServers.scholar.command).toBe(
- "${CLAUDE_PLUGIN_ROOT}/build/scholar",
- )
- expect(mcpManifest.mcpServers.scholar.env.SCHOLAR_OLLAMA_EMBED_MODEL).toBe(
- "nomic-embed-text:v1.5",
- )
- expect(mcpManifest.mcpServers.scholar.env.SCHOLAR_OLLAMA_CHAT_MODEL).toBe(
- "qwen3:8b",
- )
+test('mcpServers.scholar uses the M2 shell launcher (pivot supersedes §7.1 compiled-binary command)', () => {
+ const scholar = pluginManifest.mcpServers.scholar
+ // M2: shell launcher, not the dropped compiled binary.
+ expect(scholar.command).toBe('/bin/sh')
+ expect(scholar.args).toEqual(['${CLAUDE_PLUGIN_ROOT}/bin/launch.sh'])
+ // Ollama model defaults are unchanged by the pivot.
+ expect(scholar.env.SCHOLAR_OLLAMA_EMBED_MODEL).toBe('nomic-embed-text:v1.5')
+ expect(scholar.env.SCHOLAR_OLLAMA_CHAT_MODEL).toBe('qwen3:8b')
+})
+
+test('SessionStart hook pre-warms the bun provisioner (M2 latency optimization)', () => {
+ // The hook is a pre-warm only — launch.sh is the correctness gate, because
+ // SessionStart does not block MCP spawn. Pin that ensure-bun is invoked.
+ const cmd = pluginManifest.hooks?.SessionStart?.[0]?.hooks?.[0]?.command
+ expect(cmd).toContain('ensure-bun.sh')
})
diff --git a/tests/scholar.test.ts b/tests/scholar.test.ts
new file mode 100644
index 0000000..f978b50
--- /dev/null
+++ b/tests/scholar.test.ts
@@ -0,0 +1,154 @@
+import util, { ROOT } from '^scripts/util'
+import env from '^scripts/util/env'
+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+// nu/scholar.test.ts
+// Red/Green tests for cycle 6.10 — nu module behavior + structural anchors.
+//
+// Tests split into two groups:
+// 1. nu-spawn tests (skip if nu not on PATH) — exercise the actual module
+// 2. grep tests (always run) — pin tool-name references in source
+//
+// Grep tests fail at Red phase (file not yet created). nu-spawn tests skip
+// or fail with "Cannot find module" at Red phase.
+import { test, expect } from 'bun:test'
+
+const SCRIPT_PATH = util.subpath('bin', 'scholar.nu')
+const SCRIPT_FILE = Bun.file(SCRIPT_PATH)
+const SCRIPT_TEXT = await SCRIPT_FILE.text()
+
+const ESEP = env.dynamic({ win32: ';', default: ':' })
+const PATH = [util.subpath('bin'), ...(process.env.PATH ?? '').split(ESEP)].join(ESEP)
+
+if (!Bun.which('nu')) {
+ await Bun.stderr.write('WARNING: nu not on PATH — running minimal grep suite')
+ test('scholar.nu references scholar.papers.search', async () => {
+ expect(SCRIPT_TEXT).toContain('scholar.papers.search')
+ })
+ test('scholar.nu references scholar.corpus.status', async () => {
+ expect(SCRIPT_TEXT).toContain('scholar.corpus.status')
+ })
+ test('scholar.nu references scholar.ingest', async () => {
+ expect(SCRIPT_TEXT).toContain('scholar.ingest')
+ })
+ test('scholar.nu references scholar.digest.generate', async () => {
+ expect(SCRIPT_TEXT).toContain('scholar.digest.generate')
+ })
+ process.exit(0)
+}
+
+interface ScriptOptions {
+ pipe?: object | 'null'
+ path?: string[]
+ vars?: Record
+ args?: string[]
+}
+
+function runScript(
+ { pipe = 'null', path = [], vars = {}, args = [] }: ScriptOptions = {},
+ ...lines: string[]
+): Bun.$.ShellPromise {
+ const script: string[] = [
+ JSON.stringify(pipe),
+ `| to json --raw`,
+ `| ^bin/scholar.nu ${args.join(' ')}`,
+ ...lines,
+ ]
+ return Bun.$`nu --commands ${script.join('\n')};`
+ .cwd(ROOT)
+ .env({ ...process.env, PATH: [...path, PATH].join(ESEP), ...vars })
+ .quiet()
+}
+
+test('module parses without errors', async () =>
+ await runScript({}, 'echo ok').then(output =>
+ expect(output.text().trim()).toBe('ok')
+ ))
+
+test('scholar subcommands are all defined', async () =>
+ await Promise.all(
+ ['list', 'status', 'ingest', 'query', 'digest'].map(
+ async subcommand =>
+ await runScript({ args: [subcommand, '--help'] })
+ .text()
+ .then(text => expect(text).not.toMatch(/Error:/))
+ )
+ ))
+
+// Transport argv-shape test (M2): the slim pivot dropped the compiled
+// `mcp-scholar` binary, so the nu wrapper now invokes the server via the
+// SCHOLAR_SERVER_CMD seam. Foundation-007 contract is unchanged: the server
+// receives `--call `. The stub RECORDS argv to a file the test
+// reads back — asserting inside the stub is ineffective because nu's `complete`
+// swallows the stub's exit code, so a bad invocation would not fail the test.
+test('scholar transport invokes the server with --call (M2)', async () => {
+ const stubDir = '/tmp/scholar-nu-transport'
+ await Bun.$`mkdir -p ${stubDir}`.quiet()
+ const stub = `${stubDir}/stub-server.ts`
+ const argvFile = `${stubDir}/argv.json`
+ await Bun.write(
+ stub,
+ [
+ `import { writeFileSync } from 'node:fs'`,
+ `writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv.slice(2)))`,
+ ].join('\n')
+ )
+ try {
+ await runScript({
+ pipe: { slug: 'test' },
+ args: ['corpus.activate'],
+ vars: { SCHOLAR_SERVER_CMD: `bun ${stub}` },
+ })
+ const argv = JSON.parse(await Bun.file(argvFile).text())
+ expect(argv).toEqual([
+ '--call',
+ 'corpus.activate',
+ JSON.stringify({ slug: 'test' }),
+ ])
+ } finally {
+ await Bun.$`rm -rf ${stubDir}`.quiet().catch(() => {})
+ }
+})
+
+// Production-resolution test (M2): with NO SCHOLAR_SERVER_CMD override and NO
+// CLAUDE_PLUGIN_DATA, `server-cmd` must resolve the server bundle from the
+// module's own location — `path self → dirname → dirname` = plugin root, then
+// `dist/server.js` — and fall back to a PATH `bun`. The override-driven test
+// above never exercises this branch; this one lays the real /nu +
+// /dist layout in a temp dir and confirms the SELF-relative resolution
+// reaches the bundle. (Verified by execution, not construction — see the
+// repeated override-only blind spot the slim pivot repoint nearly repeated.)
+test('server-cmd resolves dist/server.js relative to the module (M2 production path, no override)', async () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'scholar-nu-prod-'))
+ try {
+ mkdirSync(join(tmp, 'nu'))
+ mkdirSync(join(tmp, 'dist'))
+ await Bun.write(join(tmp, 'nu', 'scholar.nu'), SCRIPT_TEXT)
+ const argvFile = join(tmp, 'argv.json')
+ // argv-echo stub at the SELF-relative dist/server.js the module computes.
+ await Bun.write(
+ join(tmp, 'dist', 'server.js'),
+ [
+ `import { writeFileSync } from 'node:fs'`,
+ `writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv.slice(2)))`,
+ ].join('\n')
+ )
+ // Strip both seams so the production branch + PATH-bun fallback run.
+ const cleanEnv: Record = { ...process.env, PATH }
+ delete cleanEnv.SCHOLAR_SERVER_CMD
+ delete cleanEnv.CLAUDE_PLUGIN_DATA
+ await Bun.$`nu ${join(tmp, 'nu', 'scholar.nu')} corpus.activate --json ${JSON.stringify({ slug: 'test' })}`
+ .env(cleanEnv)
+ .quiet()
+ .nothrow()
+ const argv = JSON.parse(await Bun.file(argvFile).text())
+ expect(argv).toEqual([
+ '--call',
+ 'corpus.activate',
+ JSON.stringify({ slug: 'test' }),
+ ])
+ } finally {
+ rmSync(tmp, { recursive: true, force: true })
+ }
+})
diff --git a/tests/start-server.test.ts b/tests/start-server.test.ts
deleted file mode 100644
index 5a143fb..0000000
--- a/tests/start-server.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-// 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)
-})
diff --git a/tests/util/pdf-fixture.ts b/tests/util/pdf-fixture.ts
new file mode 100644
index 0000000..5f3524e
--- /dev/null
+++ b/tests/util/pdf-fixture.ts
@@ -0,0 +1,50 @@
+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+
+/**
+ * Minimal valid PDF (one empty A4 page, with xref + trailer). The vendored
+ * @modelcontextprotocol/server-pdf parses this via pdf-lib and `display_pdf`
+ * accepts it as openable. Generated offline with pdf-lib 1.17; bytes are stable.
+ *
+ * Distinct from the synthetic `%PDF-1.4`-magic blob used by the spawn-only
+ * fixtures (1–3) in lifecycle.test.ts: those never open the file, so a header
+ * stub suffices. Any fixture that calls `display_pdf` needs THIS valid document
+ * — the vendor refuses the synthetic blob.
+ */
+export function writeMinimalPdf(path: string): void {
+ 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)
+}
+
+/**
+ * Temp PDF root containing `papers/fixture.pdf` (a valid minimal PDF). Returns
+ * both the root (pass as an initial root to spawnPdfChild) and the pdf path
+ * (pass to handle.displayPdf). Caller owns cleanup of `root`.
+ */
+export function makeFixtureRoot(): { root: string; pdf: string } {
+ const root = mkdtempSync(join(tmpdir(), "scholar-pdf-fixture-"))
+ mkdirSync(join(root, "papers"), { recursive: true })
+ const pdf = join(root, "papers", "fixture.pdf")
+ writeMinimalPdf(pdf)
+ return { root, pdf }
+}
diff --git a/tsconfig.json b/tsconfig.json
index 423bcea..3636ab6 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,50 +1,32 @@
{
- "compilerOptions": {
- "target": "ES2022",
- "module": "ESNext",
- "moduleResolution": "bundler",
- "lib": [
- "ES2022",
- "DOM"
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ES2022", "DOM"],
+ "jsx": "react-jsx",
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "types": ["bun-types"],
+ "noEmit": true,
+ "resolveJsonModule": true,
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": false,
+ "paths": {
+ "^*": ["./*"],
+ "#*": ["./src/*"],
+ "&/*": ["./scripts/*"],
+ "%/*": ["./tests/*"]
+ }
+ },
+ "include": [
+ "src/**/*.ts",
+ "src/**/*.tsx",
+ "scripts/**/*.ts",
+ "*.test.ts",
+ "tests/**/*.ts"
],
- "jsx": "react-jsx",
- "strict": true,
- "noUncheckedIndexedAccess": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "types": [
- "bun-types"
- ],
- "noEmit": true,
- "resolveJsonModule": true,
- "allowImportingTsExtensions": true,
- "verbatimModuleSyntax": false,
- "paths": {
- "^*": [
- "./*"
- ],
- "#*": [
- "./src/*"
- ],
- "&/*": [
- "./scripts/*"
- ],
- "%/*": [
- "./tests/*"
- ]
- }
- },
- "include": [
- "src/**/*.ts",
- "src/**/*.tsx",
- "scripts/**/*.ts",
- "*.test.ts",
- "tests/**/*.ts"
- ],
- "exclude": [
- "node_modules",
- "build",
- "runtime",
- "src/vendor"
- ]
-}
\ No newline at end of file
+ "exclude": ["node_modules", "build", "runtime", "src/vendor"]
+}