diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 1a8ef5e..b643b26 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -13,10 +13,9 @@ "license": "MIT", "mcpServers": { "scholar": { - "command": "/bin/sh", - "args": ["${CLAUDE_PLUGIN_ROOT}/bin/launch.sh"], + "command": "bun", + "args": ["${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs"], "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" @@ -29,7 +28,7 @@ "hooks": [ { "type": "command", - "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/ensure-bun.sh\"" + "command": "bun \"${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs\" --provision-only" } ] } diff --git a/.gitattributes b/.gitattributes index ec35825..ba716fd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,10 @@ -# Windows batch launcher must materialize with CRLF on every checkout, or -# cmd.exe mis-parses the rem block (byte-offset misalignment → '' is not -# recognized noise on every launch). Confirmed via Cowork field test 2026-06-05. -# Scoped to *.cmd ONLY — the POSIX launchers (launch.sh, ensure-bun.sh) must -# stay LF, so do NOT add a blanket `* text=auto eol=crlf` rule here. -*.cmd text eol=crlf +# Prebuilt native extensions committed for the source-sync marketplace install +# (build/vendor/sqlite-vec/vec0.{so,dll}; .dylib reserved for a future mac drop). +# These are the repo's FIRST committed binaries and the marketplace performs a +# real `git checkout` on Windows. Git's text=auto heuristic already detects ELF/PE +# by their leading NUL bytes and skips EOL conversion (even under +# core.autocrlf=true), so this is belt-and-suspenders: mark them binary explicitly +# so no misconfigured checkout can ever CRLF-mangle the byte stream koffi loads. +*.so binary +*.dll binary +*.dylib binary diff --git a/.gitignore b/.gitignore index 998fc33..af738bd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,17 @@ node_modules/ -build/ +# Build outputs are ignored, EXCEPT the prebuilt vec0 sqlite-vec extensions that +# the source-sync marketplace install needs at runtime (resolveVec0Path's +# /build/vendor/sqlite-vec/vec0.{so,dll} rung). Git cannot re-include a file +# under an ignored parent, so the path is un-ignored level-by-level. macOS +# (.dylib) is intentionally absent — source-sync on mac boots but fails at the +# first vector op (known partial; see HUMAN.md). +build/* +!build/vendor/ +build/vendor/* +!build/vendor/sqlite-vec/ +build/vendor/sqlite-vec/* +!build/vendor/sqlite-vec/vec0.so +!build/vendor/sqlite-vec/vec0.dll dist/ out/ runtime/ diff --git a/CLAUDE.md b/CLAUDE.md index 3f10e2a..4a0b4fd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ This file orients future Claude Code instances working in this repository. It ca - `.claude/context/plans.xml` — the spec-pipeline plan registry (one plan-group, seven children, all closed). - `.claude/context/chores.xml` — the spec-pipeline chore registry (all closed; one governance-tooling item dropped — see `HUMAN.md`). - `src/` — the implemented server, tool modules, db layer, ingest adapters, pdf lifecycle, Ollama client, and React UI sources. -- `bin/` + `dist/` — the slim-plugin launcher/provisioner scripts (`launch.{sh,cmd}`, `ensure-bun.{sh,ps1}`, `scholar.nu`) and the built `server.js` + `pdf-server/` bundles. +- `bin/` + `dist/` — the slim-plugin launcher/provisioner scripts (`launch.mjs`, `ensure-bun.{sh,ps1}`, `scholar.nu`) and the built `server.js` + `pdf-server/` bundles. - `docs/audits/` — the production-readiness roadmap (S/H/M batches) and the `2026-06-02-maintenance-readiness.md` assessment. The remaining gates before reliable day-to-day use are **operational**, not code: the Ollama models must be installed and a live end-to-end workflow must be exercised. Both are tracked in `HUMAN.md` (repo root) and `docs/runbooks/e2e-smoke-test.md`. @@ -30,7 +30,7 @@ Chores are cross-cutting work that doesn't belong to any single §6 cycle (licen > `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. +- **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 cross-OS launcher (`bin/launch.mjs`, manifest command `bun`) 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** — `bin/scholar.nu`, user-facing wrapper that calls scholar MCP tools and shapes responses into nu tables. diff --git a/HUMAN.md b/HUMAN.md index e6e635f..e118c8a 100644 --- a/HUMAN.md +++ b/HUMAN.md @@ -89,6 +89,25 @@ root). So the provisioning + spawn + migrate + activate spine is no longer an assumption — the **only** unproven leg is the PDF *viewer* (`displayPdf`/`getText`, step 7), which can only be exercised by a human at the desktop. +> **Superseded 2026-06-06 — bun-launcher unification.** The 2026-06-03 proof above +> was of the now-retired `/bin/sh launch.sh` path (`exec`-replace into bun). Both +> targets now launch via `bun ${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs`; `launch.sh` and +> `launch.cmd` are deleted. The new Linux entry paths are **not** an assumption — +> **both** were re-driven **end-to-end headless (2026-06-06)** under a *non-pinned* +> on-PATH bun (1.3.14), each cold-provisioning the pinned **1.3.11** into a fresh +> `CLAUDE_PLUGIN_DATA` and returning a clean single-line MCP `initialize` (pdf child +> `Ready`, graceful exit on stdin-EOF): (a) the **built-bundle** path (`dist/server.js` +> present), and (b) the **source-sync from-src** path — `CLAUDE_PLUGIN_ROOT` set to the +> git-tracked ship set (no `dist/`, no `node_modules`), where `launch.mjs` falls through +> to `src/server/index.ts` and the pinned bun **cold-auto-installs the whole import +> graph** into the `BUN_INSTALL` cache under `CLAUDE_PLUGIN_DATA` (~67 MB) **without +> writing a local `node_modules`** into the shipped tree. That second path is exactly +> what the Cowork Linux sandbox runs, so the launcher's auto-install assumption is now +> validated empirically, not on faith. `ensure-bun.sh` and the server spine are +> unchanged. The **only** leg this does NOT cover is Windows — a bare `bun` resolving on +> PATH at the Claude Desktop spawn (CreateProcess PATH semantics differ from POSIX +> `execvp`); that is now the dominant residual risk, tracked in **§5 leg 2**. + > **Note (2026-06-04, updated):** the PDF viewer is an **MCP App** the Claude Code > terminal can't render — the actual home for that leg is **Claude Desktop** via the > `.mcpb` extension. See **§5** for the build + install + the Windows verification @@ -121,9 +140,9 @@ can't be simulated from Linux. See leg 6. bun run build:mcpb # -> out/scholar.mcpb (win32, ~2.9 MB, 20 files) ``` The build runs `mcpb validate` then `mcpb pack`. The manifest is `manifest.json` -at the bundle root (mcpb schema **0.2**), `server.type:"binary"`, command -`cmd.exe /c ${__dirname}\bin\launch.cmd`. It does **not** modify the launcher: the -manifest `env` aliases the two vars `launch.cmd`/`ensure-bun.ps1` already read — +at the bundle root (mcpb schema **0.2**), `server.type:"binary"` (`bun` is a binary +on PATH), command `bun` with args `[${__dirname}\bin\launch.mjs]`. It does **not** +modify the launcher: the manifest `env` aliases the two vars `launch.mjs`/`ensure-bun.ps1` already read — `CLAUDE_PLUGIN_ROOT := ${__dirname}` and `CLAUDE_PLUGIN_DATA := ${user_config.data_dir}` — so the win32 launch chain runs byte-identical to the Claude Code plugin. @@ -141,9 +160,10 @@ different host, set the Ollama URL field at install. Proven from Linux: the manifest validates against the real `mcpb` schema (0.1–0.4 all pass — no version-specific field), packs + unpacks to the correct structure -(manifest at root; `bin/launch.cmd`, `dist/server.js`, `dist/pdf-server/{index.js, -mcp-app.html}`, `build/vendor/sqlite-vec/vec0.dll`, `ui/`, `nu/`, migrations all -present; no `.claude-plugin/` cruft), and the source path-resolution chain reads +(manifest at root; `bin/launch.mjs`, `bin/ensure-bun.ps1`, `dist/server.js`, +`dist/pdf-server/{index.js, mcp-app.html}`, `build/vendor/sqlite-vec/vec0.dll`, +`ui/`, `nu/`, migrations all present; no `.claude-plugin/` cruft), and the source +path-resolution chain reads the two aliased vars (vec0 + pdf entry off `CLAUDE_PLUGIN_ROOT`, bun off `process.execPath`). **None of that proves Desktop runs it.** These legs can only be checked on Windows — each with the symptom to watch for: @@ -151,20 +171,31 @@ be checked on Windows — each with the symptom to watch for: 1. **Desktop accepts manifest_version 0.2** — *symptom:* the Install dialog rejects the extension up front. *Fix:* bump `MCPB_MANIFEST_VERSION` in `scripts/build-plugin.ts` (0.2 → 0.3 → 0.4), `bun run build:mcpb`, reinstall. -2. **Desktop spawns `cmd.exe`/`type:"binary"`** — *symptom:* extension installs but - the MCP never connects ("server failed to start"). Means Desktop won't launch an - arbitrary command for this extension type. +2. **Desktop spawns `bun`/`type:"binary"` AND a bare `bun` resolves on PATH** — the + **dominant residual risk** of the bun-launcher unification. On POSIX the host's + `execvp` searches PATH; Windows `CreateProcess` does not search PATH the same way, + so a bare `bun` resolves only if Desktop passes a PATH-aware spawn env. *symptom:* + extension installs but the MCP never connects ("server failed to start") — either + Desktop won't launch this command for `type:"binary"`, or `bun` was not found on + PATH. *First check:* `bun --version` in a fresh Windows shell (bun must be + installed system-wide — it is a dependency of these servers). *Fallback if PATH is + the problem:* edit the manifest `command` to an absolute `bun.exe` path (e.g. + `%USERPROFILE%\.bun\bin\bun.exe`) and reinstall. 3. **Variable substitution** (`${__dirname}`, `${user_config.data_dir}`, `${HOME}`) - — *symptom:* `ensure-bun: CLAUDE_PLUGIN_DATA unset` on stderr, or launch.cmd - can't find `dist\server.js`. Means a `${…}` token wasn't expanded. (`${HOME}` + — *symptom:* `ensure-bun: CLAUDE_PLUGIN_DATA unset` on stderr, or `launch.mjs` + dies with `CLAUDE_PLUGIN_ROOT is unset` / can't find `dist\server.js`. Means a + `${…}` token wasn't expanded. (`${HOME}` is confirmed a documented mcpb substitution var, usable in `user_config` defaults — mcpb `MANIFEST.md` — and Desktop maps it to the Windows user profile, so the `data_dir` default `${HOME}\scholar` is portable, not a bug.) 4. **bun provisioning** (ensure-bun.ps1 downloads bun-windows-x64 **1.3.11** into `%CLAUDE_PLUGIN_DATA%\bun`) — *symptom:* long first-launch then `bun.exe` not - found; or PowerShell blocked by ExecutionPolicy (the hook passes - `-ExecutionPolicy Bypass`, but Desktop spawns via cmd.exe, not the hook). Check - `%data_dir%\bun\bun.exe --version` prints `1.3.11`. + found; or PowerShell blocked by ExecutionPolicy. (Improved by the bun + unification: `launch.mjs` now invokes the provisioner as `powershell -NoProfile + -ExecutionPolicy Bypass -File ensure-bun.ps1` on **both** the server-spawn path + *and* the `--provision-only` SessionStart pre-warm — the old cmd.exe launcher + only bypassed on the hook — so a machine ExecutionPolicy should not block it.) + Check `%data_dir%\bun\bun.exe --version` prints `1.3.11`. **Field-confirmed 2026-06-05 (Cowork):** on a *brand-new* data dir the first connect can time out *during* this download — the ~110 MB fetch overran the host's 30 s MCP connect budget (`Connection timeout triggered after 30027ms`), @@ -257,9 +288,12 @@ be checked on Windows — each with the symptom to watch for: *Caveat (salient uncertainty):* the conformance reading is grounded in SEP-1865 + the version-matched pdf-server reference + the ext-apps `.d.ts`, but the live render path has not been exercised on a real Claude Desktop from this environment. -7. **Clean shutdown / no orphaned lock** — `launch.cmd` runs `bun.exe` as a *child* - of cmd.exe (no exec-replace on Windows). *symptom:* after quitting/restarting - Desktop, the next launch refuses with `SCHOLAR_LOCKED`. The pid-liveness reclaim +7. **Clean shutdown / no orphaned lock** — `bun launch.mjs` spawns `bun.exe` as a + *child* (the same parent+child shape on both OSes now — the prior Linux + `exec`-replace is gone; launch.mjs forwards SIGINT/SIGTERM/SIGHUP and exits when + the child does; see slim-plugin-pivot.md "Launch orphan"). *symptom:* after + quitting/restarting Desktop, the next launch refuses with `SCHOLAR_LOCKED`. The + pid-liveness reclaim in `session-lock.ts` should clear a stale `runtime\scholar.lock` on the next start (unless the OS reused the pid) — confirm a restart recovers cleanly. diff --git a/bin/ensure-bun.ps1 b/bin/ensure-bun.ps1 index 9d77e73..0ec0acf 100644 --- a/bin/ensure-bun.ps1 +++ b/bin/ensure-bun.ps1 @@ -2,7 +2,7 @@ # # 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. +# synchronously by launch.mjs 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. diff --git a/bin/ensure-bun.sh b/bin/ensure-bun.sh index 3c2c2a0..0c3684b 100644 --- a/bin/ensure-bun.sh +++ b/bin/ensure-bun.sh @@ -5,14 +5,14 @@ # ${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 +# Called synchronously by launch.mjs BEFORE it spawns 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. +# there alone). May also be pre-warmed by a SessionStart hook (launch.mjs +# --provision-only); 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. +# JSON-RPC stream once launch.mjs spawns it. set -eu PIN="1.3.11" # keep in sync with package.json scholar.bundledBunVersion (vec0 ABI) diff --git a/bin/launch.cmd b/bin/launch.cmd deleted file mode 100644 index bae2baa..0000000 --- a/bin/launch.cmd +++ /dev/null @@ -1,20 +0,0 @@ -@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.mjs b/bin/launch.mjs new file mode 100644 index 0000000..6711e3f --- /dev/null +++ b/bin/launch.mjs @@ -0,0 +1,107 @@ +// bin/launch.mjs — cross-OS MCP launcher for the source-sync (cowork-marketplace) +// install AND the built per-OS .plugin/.mcpb bundles (one launcher, all targets). +// +// The marketplace installs by copy-only and serves ONE committed manifest to +// every OS, so the launcher cannot be a per-OS shell script — it must invoke a +// single command present on all hosts. `bun` is that command: the rest of these +// servers already depend on a system-wide bun install, so requiring it here is +// consistent with that convention (and it sidesteps the "use bundled node" +// Claude Desktop option that has since been removed from settings). bun runs +// this `.mjs` directly under its node-compat runtime (process.argv, +// process.platform, node:child_process all work). +// +// KEYSTONE ASSUMPTION: `bun` must be on PATH at MCP spawn. On POSIX the host's +// execvp resolves a bare `bun` against PATH; on Windows, CreateProcess does NOT +// search PATH the same way, so a bare `bun` resolves only if the host passes a +// PATH-aware environment to the spawn. The Claude Desktop spawn env is the most +// locked-down, so bun-on-PATH at Desktop MCP spawn is the dominant unproven risk +// and must be validated on Windows hardware. +// +// The on-PATH bun that runs THIS shim need NOT be the pinned ABI version: it +// only executes launch.mjs. The shim then PROVISIONS the pinned bun (vec0-ABI +// matched, see ensure-bun) and SPAWNS *that* bun as a child with stdio:"inherit" +// to run the server. The MCP JSON-RPC stream therefore flows client <-> pinned +// bun directly on fd 0/1; the launcher bun never touches the protocol bytes. The +// F1 graceful-teardown invariant (makeServerTeardown: stdin-EOF / SIGINT / +// SIGTERM) holds on the PRIMARY path because the child inherits fd0 and sees the +// client's stdin-close EOF itself. The signal forwarding below is a secondary +// net (Windows has no catchable SIGTERM; graceful shutdown there rides the +// stdin-EOF path, and a hard kill only leaves a pidfile reclaimed on next start +// via pid-liveness). +// +// Modes: +// bun launch.mjs provision bun, then run the server +// bun launch.mjs --provision-only pre-warm bun and exit (SessionStart hook) + +import { spawn, spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; + +const isWin = process.platform === "win32"; +const die = (msg) => { + process.stderr.write(`launch.mjs: ${msg}\n`); + process.exit(1); +}; + +const root = process.env.CLAUDE_PLUGIN_ROOT; +const data = process.env.CLAUDE_PLUGIN_DATA; +if (!root) die("CLAUDE_PLUGIN_ROOT is unset"); +if (!data) die("CLAUDE_PLUGIN_DATA is unset"); + +// ── 1. Provision the pinned bun runtime (synchronous correctness gate) ─────── +// Delegates to the same ensure-bun.{sh,ps1} the built bundles use. ALL of the +// provisioner's output is mapped to OUR stderr (the stdio integer `2` shares the +// parent's fd 2): stdout (fd 1) stays clean for the JSON-RPC stream the child +// bun will own. +const provision = isWin + ? spawnSync( + "powershell", + ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(root, "bin", "ensure-bun.ps1")], + { stdio: ["ignore", 2, 2], windowsHide: true }, + ) + : spawnSync("sh", [join(root, "bin", "ensure-bun.sh")], { stdio: ["ignore", 2, 2] }); +if (provision.error) die(`failed to launch provisioner: ${provision.error.message}`); +if (provision.status !== 0) die(`provisioner exited with status ${provision.status}`); + +if (process.argv.includes("--provision-only")) process.exit(0); + +// ── 2. Resolve bun + the server entrypoint ─────────────────────────────────── +const bun = join(data, "bun", isWin ? "bun.exe" : "bun"); +if (!existsSync(bun)) die(`provisioned bun not found at ${bun}`); +// Built bundle (dist/server.js) wins if present; source-sync has no dist/, so it +// falls through to the TS entrypoint bun runs directly (auto-installing the +// reached import graph into BUN_INSTALL's cache on first call). +const entry = existsSync(join(root, "dist", "server.js")) + ? join(root, "dist", "server.js") + : join(root, "src", "server", "index.ts"); + +// ── 3. Cross-OS env defaults derived from the REAL env var ─────────────────── +// CLAUDE_PLUGIN_DATA persists across plugin updates and is set on every host, so +// it is the correct cross-OS anchor for both the bun auto-install cache and +// runtime state. We derive these in JS (not via manifest ${...} interpolation) +// so the manifest needs no CLAUDE_PLUGIN_DATA expansion. An already-set value +// (manifest env or user shell) wins. +const env = { ...process.env }; +if (!env.BUN_INSTALL) env.BUN_INSTALL = join(data, "bun-cache"); +if (!env.SCHOLAR_RUNTIME_ROOT) env.SCHOLAR_RUNTIME_ROOT = join(data, "runtime"); + +// ── 4. Spawn bun. stdio:"inherit" → client <-> bun own fd 0/1 directly. ────── +const passthrough = process.argv.slice(2).filter((a) => a !== "--provision-only"); +const child = spawn(bun, [entry, ...passthrough], { + stdio: "inherit", + cwd: root, + env, + windowsHide: true, +}); + +for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) { + process.on(sig, () => { + try { + child.kill(sig); + } catch { + /* child already gone */ + } + }); +} +child.on("error", (err) => die(`failed to spawn bun: ${err.message}`)); +child.on("exit", (code, signal) => process.exit(signal ? 1 : (code ?? 0))); diff --git a/bin/launch.sh b/bin/launch.sh deleted file mode 100644 index 9c6c22b..0000000 --- a/bin/launch.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/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 index bde089d..798c21e 100755 --- a/bin/scholar.nu +++ b/bin/scholar.nu @@ -68,10 +68,16 @@ def "resolve js" [...roots: string]: nothing -> string { # Run a `tool` from the `scholar` MCP server. # Parameters may be provided as the `json` argument or by piping in a string or record. +# +# Streams stay isolated: the server writes its JSON result to stdout and its +# structured logs + error payload to stderr. Take the LAST non-empty line of +# the relevant stream and deserialize once (deduplicated). On stdout this also +# defends against a bunx provisioning preamble ("Saved lockfile") prepended to +# the result; on stderr the error record trails the log lines. def main [ tool: string # Name of the MCP server tool json: string = '{}' # Argument payload as a JSON string -]: oneof -> oneof { +]: oneof -> oneof { let json: string = match ($in | describe) { string => $in record => { $in | to json --raw } @@ -88,21 +94,10 @@ def main [ let output = run-external ...$args | complete | default 0 exit_code - # Streams stay isolated: the server writes its JSON result to stdout and its - # structured logs + error payload to stderr. Take the LAST non-empty line of - # the relevant stream and deserialize once (deduplicated). On stdout this also - # defends against a bunx provisioning preamble ("Saved lockfile") prepended to - # the result; on stderr the error record trails the log lines. let raw: string = (if $output.exit_code == 0 { $output.stdout? } else { $output.stderr? }) - | default '' - | lines - | where ($it | str trim | is-not-empty) - | last - | default '{}' - - let parsed = try { - $raw | from json - } catch { + | default '' | lines | where ($it | str trim | is-not-empty) | last | default '{}' + + let parsed = try { $raw | from json } catch { error make --unspanned { msg: "unable to parse tool output as JSON" code: `scholar::main::json_decode_error` @@ -168,11 +163,18 @@ def "main ingest" [ } # 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 { main list --limit $limit --query $q } + query?: string # Query string to filter papers by + --label (-l): string = 'cli-query' # Descriptor to attach to the query result +]: [ + nothing -> oneof + list> -> oneof + table -> oneof +] { + append (if $query != null { {label: $label query: $query} } else { [] }) + | compact + | if ($in | is-not-empty) { $in | main scholar.query } +} # Generate digest on a scoped set of papers. # By default, all papers are included. diff --git a/build/vendor/sqlite-vec/vec0.dll b/build/vendor/sqlite-vec/vec0.dll new file mode 100644 index 0000000..83a6749 Binary files /dev/null and b/build/vendor/sqlite-vec/vec0.dll differ diff --git a/build/vendor/sqlite-vec/vec0.so b/build/vendor/sqlite-vec/vec0.so new file mode 100644 index 0000000..a4f59a7 Binary files /dev/null and b/build/vendor/sqlite-vec/vec0.so differ diff --git a/docs/audits/2026-06-02-maintenance-readiness.md b/docs/audits/2026-06-02-maintenance-readiness.md index b3d9538..606c926 100644 --- a/docs/audits/2026-06-02-maintenance-readiness.md +++ b/docs/audits/2026-06-02-maintenance-readiness.md @@ -29,6 +29,17 @@ been run** against a live server. Everything else is tidiness. | UI bundle (`measure-bundle`) | 1014 KB single-file, within budget | | Launch chain | `plugin.json` → `/bin/sh bin/launch.sh` → `ensure-bun.sh` (pins bun 1.3.11) → `exec bun dist/server.js` — statically sound, vec0-ABI pin intact | +> **Superseded 2026-06-06 (bun-launcher unification, PR #4).** The launch chain is +> now `plugin.json` → `bun ${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs` → +> `ensure-bun.{sh,ps1}` (pins bun 1.3.11) → **child** `bun {dist/server.js | src/server/index.ts}`. +> The retired per-OS `launch.{sh,cmd}` pair and its `exec`-replace shape are gone; +> the spawned bun is now a child (signal-forwarded, fd0-inherited). Unlike the +> static 2026-06-02 snapshot above, **both** entry paths are now verified live, +> headless, on Linux: the built `dist/server.js` path *and* the source-sync +> `src/server/index.ts` path (cold pinned-bun provision + cold bun auto-install of +> the import graph into the `CLAUDE_PLUGIN_DATA` cache, leaving the shipped tree +> pristine → clean MCP `initialize`). vec0-ABI pin unchanged. + --- ## GATES — do these before relying on it for real reviews diff --git a/docs/runbooks/e2e-smoke-test.md b/docs/runbooks/e2e-smoke-test.md index 4d69d21..e84dd50 100644 --- a/docs/runbooks/e2e-smoke-test.md +++ b/docs/runbooks/e2e-smoke-test.md @@ -31,12 +31,14 @@ Two ways to drive the tools below: ## G3 — Install + spawn (do this first, in a real session) 1. Install the built plugin (`out/scholar.plugin`) into Claude Code, or run from - source. On first launch `bin/launch.sh` calls `ensure-bun.sh`, which provisions - the pinned bun 1.3.11 into `${CLAUDE_PLUGIN_DATA}/bun` (one-time download). + source. On first launch `bun bin/launch.mjs` calls `ensure-bun.sh`, which + provisions the pinned bun 1.3.11 into `${CLAUDE_PLUGIN_DATA}/bun` (one-time + download). 2. Confirm the `scholar` MCP server appears connected and tools are listed. - - *Already proven on Linux at pivot time:* manifest → `launch.sh` → ensure-bun → - clean MCP `initialize` (slim-pivot spec §"linux"). The **un**proven part is - everything below — a real corpus workflow — plus the Windows launch path. + - *Already proven on Linux at pivot time:* manifest → `bun launch.mjs` → + ensure-bun → clean MCP `initialize` (slim-pivot spec §"linux"). The + **un**proven part is everything below — a real corpus workflow — plus the + Windows launch path. **If the server doesn't spawn:** check `${CLAUDE_PLUGIN_DATA}` is set (ensure-bun hard-fails without it) and that `curl`/`unzip` are available for the bun download. diff --git a/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md b/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md index 214fc26..9a01c92 100644 --- a/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md +++ b/docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md @@ -85,6 +85,34 @@ not the 6.7 MB vendored pdf — were the bloat. ## Build system (validated 2026-06-01) +> **Superseded 2026-06-05 — bun-launcher unification.** The per-OS shell-pair +> launcher described in this section (`/bin/sh launch.sh` | `cmd.exe /c +> launch.cmd`) was retired. Both targets now launch via the single cross-OS shim +> `bun ${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs` — the same command the committed +> source-sync `.claude-plugin/plugin.json` uses. `bin/launch.{sh,cmd}` are +> deleted; only `bin/launch.mjs` + the per-OS `ensure-bun.{sh,ps1}` provisioner +> ship. Rationale: a bare `node` invocation no longer resolves reliably under +> Claude Desktop (its "use bundled node" option was removed from settings), and +> bun is the operator's systemwide convention across these servers. The generated +> manifests were **re-verified against the real build artifacts 2026-06-06**: +> linux `command:"bun" args:["${ROOT}/bin/launch.mjs"]`, +> `SCHOLAR_RUNTIME_ROOT=${HOME}/mcp-data/scholar/runtime`; win32 identical bar +> `SCHOLAR_RUNTIME_ROOT=${USERPROFILE}\mcp-data\scholar\runtime`; both stage only +> `launch.mjs` + their `ensure-bun`. **Both** Linux entry paths were also driven +> **end-to-end headless (2026-06-06)** under a non-pinned on-PATH bun 1.3.14, each +> cold-provisioning the pinned 1.3.11 into a fresh `CLAUDE_PLUGIN_DATA` and returning +> a clean single-line MCP `initialize` (pdf child `Ready`, graceful exit on stdin-EOF): +> the **built-bundle** path (`dist/server.js` present) and the **source-sync from-src** +> path (`CLAUDE_PLUGIN_ROOT` = the git-tracked ship set with no `dist/` and no +> `node_modules`, where `launch.mjs` falls through to `src/server/index.ts` and the +> pinned bun **cold-auto-installs the whole import graph** into the `BUN_INSTALL` cache +> under `CLAUDE_PLUGIN_DATA` without writing a local `node_modules`). The second path is +> exactly what the Cowork Linux sandbox runs, so the launcher's auto-install assumption +> is validated, not assumed. The only unproven leg stays Windows bun-on-PATH at the +> Desktop spawn. The dated 2026-06-01 record below (sizes, +> `launch.sh`/`launch.cmd`) captures the retired shell-pair state and is kept as +> history. + `scripts/build-plugin.ts` rewritten to the slim model; `SCHOLAR_BUILD_WIN` selects target. Both packages build on the Linux host: @@ -97,11 +125,18 @@ selects target. Both packages build on the Linux host: 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). +Launch is **M2** (see `bin/`): on both OSes `bun` runs `bin/launch.mjs`, which +calls the idempotent `ensure-bun` provisioner then spawns the pinned bun on the +server entry. A `SessionStart` hook pre-warms `ensure-bun` via `bun launch.mjs +--provision-only` (latency only — the launcher is the correctness gate, because +SessionStart does not block MCP spawn). **Shape change (2026-06-05):** the old +Linux launcher `exec`ed into bun, so the PID Claude Code spawned *became* the +server (no wrapper); `bun launch.mjs` instead spawns the pinned bun as a **child** +on both OSes — always a parent+child pair cross-OS. Mitigated, not a regression: +the child inherits fd0 (sees stdin-EOF directly), `launch.mjs` forwards +SIGINT/SIGTERM/SIGHUP, and `child.on("exit") → process.exit` ties parent liveness +to the child; only a hard `SIGKILL` of the wrapper leaves the pidfile, reclaimed +on next start by pid-liveness. ## Claude Desktop `.mcpb` packaging target (maintenance addendum 2026-06-04) @@ -122,14 +157,15 @@ Design intent (deliberately minimal — no new launch surface): validate) and packs via the official **`mcpb` CLI** (`mcpb validate` gate → `mcpb pack` → `out/scholar.mcpb`, ~2.9 MB / 20 files). Pure `buildMcpbManifest` is unit-pinned; `mcpb validate` is the authoritative schema gate. -- **The win32 launcher is not modified.** `server.type:"binary"`, command - `cmd.exe /c ${__dirname}\bin\launch.cmd`. The manifest `env` aliases the two vars +- **The launcher is not mcpb-specific.** `server.type:"binary"` (`bun` is a + binary on PATH), command `bun` with args `[${__dirname}\bin\launch.mjs]`. The + manifest `env` aliases the two vars the launcher already reads — `CLAUDE_PLUGIN_ROOT := ${__dirname}` and `CLAUDE_PLUGIN_DATA := ${user_config.data_dir}` — so the launch chain runs byte-identical to the Code plugin. `SCHOLAR_BUN_PATH`/`SCHOLAR_VEC0_PATH`/ `SCHOLAR_PDF_ENTRYPOINT` are intentionally unset: their defaults derive from `CLAUDE_PLUGIN_ROOT` (vec0, pdf entry) and `process.execPath` (the provisioned - bun that `launch.cmd` runs `server.js` with). `data_dir` is collected at install + bun that `launch.mjs` runs `server.js` with). `data_dir` is collected at install via `user_config` (directory, required); Ollama URL/models are optional fields. Proven on Linux (2026-06-04): manifest validates against the real `mcpb` schema @@ -137,7 +173,7 @@ Proven on Linux (2026-06-04): manifest validates against the real `mcpb` schema `dist/server.js`, `dist/pdf-server/{index.js,mcp-app.html}`, `vec0.dll`, `ui/`, `nu/`, migrations present; no `.claude-plugin/` cruft), and the source path-resolution chain reads the two aliased vars. **Not proven** (Windows-only): -Desktop accepting the manifest, spawning `cmd.exe`/`type:binary`, `${…}` +Desktop accepting the manifest, spawning `bun`/`type:binary`, `${…}` substitution, bun provisioning, and vec0 ABI under the provisioned bun — each enumerated with its failure symptom in **HUMAN.md §5**. @@ -181,10 +217,14 @@ enumerated with its failure symptom in **HUMAN.md §5**. ## 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 the host 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. **Update 2026-06-04:** the chained "orphan holds +- **Launch orphan (cross-OS, mitigated)**: `bun launch.mjs` spawns the pinned bun + as a child on both OSes — the prior Linux `exec`-replace is gone (see the M2 + shape-change note above), so there is always a parent+child pair. If the host + does not tree-kill the MCP process tree on shutdown, the child bun may orphan. + Mitigated in `launch.mjs` (SIGINT/SIGTERM/SIGHUP forwarding + child-exit → + `process.exit` propagation); a Job Object is **not** added (no Linux equivalent — + would be over-engineering). Verify tree-kill on Windows hardware. + **Update 2026-06-04:** the chained "orphan holds `runtime/scholar.lock` → next session `SCHOLAR_LOCKED`" path is **now live** — the single-active-session lock *is* implemented (a **pidfile**, not literal flock: `src/server/session-lock.ts`, `O_EXCL` create + `process.kill(pid,0)` liveness @@ -232,8 +272,8 @@ enumerated with its failure symptom in **HUMAN.md §5**. `Connection timeout triggered after 30027ms` vs `timeout of 30000ms`). One-shot, no retry; the host abandons the connection. **Self-heals on restart** — warm boot is `Test-Ok → exit 0` (~2 s), well inside budget, and connects cleanly. - Fix options, ascending invasiveness: (a) **fail-fast** in `launch.cmd` when bun - is absent — a clear error beats a silent 30 s hang, but it only makes cold start + Fix options, ascending invasiveness: (a) **fail-fast** in `launch.mjs` when the + pinned bun is absent — a clear error beats a silent 30 s hang, but it only makes cold start legible, it does not remove it; (b) **generous first-run budget** — document / ship a larger `MCP_TIMEOUT` so the cold download fits (safe, but a real hang now surfaces slower; uncertain the plugin manifest can set the client-side @@ -245,6 +285,12 @@ enumerated with its failure symptom in **HUMAN.md §5**. newer-but-different bun can load an incompatible `sqlite-vec` and fail later at a far harder-to-diagnose point than a clean timeout. Not implemented blind — pick the approach, then validate on Windows. + **Note (2026-06-05 bun-unification):** the launcher is now `bun` itself, so an + on-PATH bun is already required to run the shim. That makes option (a)'s + fail-fast naturally live in `launch.mjs`, and collapses option (c) to a cheap + check the shim can do before dispatching to `ensure-bun` (if the on-PATH + `bun --version` *equals* the pin, skip the download). Still pick + validate on + Windows before implementing. - **`launch.cmd` CRLF + non-ASCII — RESOLVED 2026-06-05 (Cowork field test).** The shipped `bin/launch.cmd` was LF-only with em-dashes in its `rem` header. cmd.exe seeks batch files by byte offset assuming CRLF, so LF-only lines @@ -259,3 +305,8 @@ enumerated with its failure symptom in **HUMAN.md §5**. is 20/20 CRLF with no non-ASCII; the linux `.plugin` is unaffected (ships `launch.sh`). The one leg that can only run on the target — does cmd.exe stop emitting the noise — is the user's next Cowork session. + **Now moot (bun-launcher unification, 2026-06-05):** `bin/launch.cmd` was deleted + — the unified launcher is `bun launch.mjs`, no `.cmd` ships in any bundle, and the + `*.cmd text eol=crlf` `.gitattributes` rule was removed (its only target was + gone). cmd.exe never parses a scholar batch file now, so the CRLF byte-offset + mangle class can no longer occur. Retained as the diagnosis record. diff --git a/scripts/build-plugin.ts b/scripts/build-plugin.ts index a327459..e2c9bbf 100644 --- a/scripts/build-plugin.ts +++ b/scripts/build-plugin.ts @@ -7,7 +7,7 @@ // - build/vendor/sqlite-vec/vec0. platform vec0 (so | dll) // - ui/app.html single-file inlined UI bundle (MCP-App) // - nu/scholar.nu nu CLI module -// - bin/ M2 launcher + ensure-bun provisioner +// - bin/launch.mjs + ensure-bun.{sh|ps1} cross-OS launcher + per-OS 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} @@ -19,7 +19,8 @@ // - Claude Desktop .mcpb (SCHOLAR_PACKAGE=mcpb): emits a top-level manifest.json // (mcpb schema) and packs via the `mcpb` CLI to out/scholar.mcpb. Forces the // win32 target — the in-app PDF viewer is an MCP App the Code terminal can't -// render, so Desktop is the only consumer and only the win32 launcher ships. +// render, so Desktop is the only consumer and only the win32 provisioner +// (ensure-bun.ps1) ships alongside the cross-OS launch.mjs. // // Run: bun scripts/build-plugin.ts (Claude Code plugin, win32) // Linux pkg: SCHOLAR_BUILD_WIN=0 bun scripts/build-plugin.ts @@ -161,29 +162,35 @@ function stageBin(): void { ? 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'] + // launch.mjs is the single cross-OS launcher (run via `bun`); only the + // ensure-bun provisioner it dispatches to is per-OS. + const launchers = ['launch.mjs', WIN ? 'ensure-bun.ps1' : 'ensure-bun.sh'] for (const f of launchers) copyFileSync(util.subpath('bin', f), join(DIR, 'bin', f)) } // ── 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. +// manifest, produce the per-OS M2 manifest. The launcher is the single cross-OS +// `bun ${ROOT}/bin/launch.mjs` (same shim the committed source-sync manifest +// uses); only `win` still varies the per-OS runtime root and the ensure-bun +// provisioner launch.mjs dispatches to. 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}' + // The built bundle still PINS the runtime root per-OS (legacy ${HOME}/ + // ${USERPROFILE} layout); launch.mjs honors an already-set + // SCHOLAR_RUNTIME_ROOT, so this overrides its CLAUDE_PLUGIN_DATA-derived + // default. The committed source-sync manifest omits it and takes that default. 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`] + const command = 'bun' + const args = [`${ROOT}/bin/launch.mjs`] const manifest = { ...base, @@ -200,17 +207,16 @@ export function buildManifest( }, }, // 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. + // spawn, so this is a latency optimization only — `bun launch.mjs` (no + // flag) is the correctness gate. --provision-only runs the same shim, + // which dispatches to the per-OS ensure-bun (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"`, + command: `bun "${ROOT}/bin/launch.mjs" --provision-only`, }, ], }, @@ -234,13 +240,14 @@ function generateManifest(): void { // through from the Claude Code plugin.json base; the server/compatibility/ // user_config blocks are Desktop-specific. // -// Launcher is NOT modified: the manifest aliases the two vars launch.cmd + +// Launcher is NOT modified: the manifest aliases the two vars launch.mjs + // ensure-bun.ps1 already read — CLAUDE_PLUGIN_ROOT := ${__dirname} (extension // dir) and CLAUDE_PLUGIN_DATA := the user-chosen data directory — so the win32 -// launch chain runs byte-identical to the Claude Code plugin. SCHOLAR_BUN_PATH / +// launch chain runs byte-identical to the Claude Code plugin. The command is +// `bun` (run via PATH, matching the source-sync manifest); SCHOLAR_BUN_PATH / // SCHOLAR_VEC0_PATH / SCHOLAR_PDF_ENTRYPOINT are intentionally unset: their // defaults derive from CLAUDE_PLUGIN_ROOT (vec0, pdf entry) and process.execPath -// (the provisioned bun that launch.cmd runs server.js with). +// (the provisioned bun that launch.mjs runs server.js with). export function buildMcpbManifest( base: Record, version: string, @@ -258,10 +265,10 @@ export function buildMcpbManifest( keywords: (base.keywords as string[]) ?? [], server: { type: 'binary', - entry_point: 'bin/launch.cmd', + entry_point: 'bin/launch.mjs', mcp_config: { - command: 'cmd.exe', - args: ['/c', `${DIRNAME}\\bin\\launch.cmd`], + command: 'bun', + args: [`${DIRNAME}\\bin\\launch.mjs`], env: { CLAUDE_PLUGIN_ROOT: DIRNAME, CLAUDE_PLUGIN_DATA: DATA, @@ -356,7 +363,7 @@ async function assemble(): Promise { 'dist/pdf-server/mcp-app.html', `build/vendor/sqlite-vec/vec0.${VEC0_EXT}`, 'ui/app.html', // single-file MCP-App UI — resource.ts serves /ui/app.html - WIN ? 'bin/launch.cmd' : 'bin/launch.sh', + 'bin/launch.mjs', ] const missing = required.filter(r => !(r in fileMap)) if (missing.length) @@ -396,7 +403,7 @@ async function assembleMcpb(): Promise { 'dist/pdf-server/mcp-app.html', `build/vendor/sqlite-vec/vec0.${VEC0_EXT}`, 'ui/app.html', // single-file MCP-App UI — resource.ts serves /ui/app.html - 'bin/launch.cmd', + 'bin/launch.mjs', 'bin/ensure-bun.ps1', ] const missing = required.filter(r => !existsSync(join(DIR, r))) diff --git a/src/server/pdf/lifecycle.test.ts b/src/server/pdf/lifecycle.test.ts index f0c1f00..a6af9fd 100644 --- a/src/server/pdf/lifecycle.test.ts +++ b/src/server/pdf/lifecycle.test.ts @@ -20,6 +20,7 @@ import { spawnPdfChild, sanitizeRoots, buildClientCapabilities, + parseGetTextResult, type PdfChildHandle, } from "./lifecycle.ts"; import { makeFixtureRoot } from "%/util/pdf-fixture"; @@ -53,6 +54,37 @@ const E2E = process.env.SCHOLAR_PDF_E2E === "1"; // PURE-LOGIC FIXTURES (no spawn — always run) // ========================================================================= +test("parseGetTextResult flattens success content to a string", () => { + const r = { + content: [ + { type: "text", text: "page one " }, + { type: "image", data: "..." }, + { type: "text", text: "page two" }, + ], + }; + expect(parseGetTextResult(r)).toBe("page one page two"); +}); + +test("parseGetTextResult passes a bare string through", () => { + expect(parseGetTextResult("already a string")).toBe("already a string"); +}); + +test("parseGetTextResult THROWS on the vendor isError envelope (no error text ingested as document text)", () => { + // The vendor returns failures as {content:[{type:text,text:}], isError:true}; + // callTool passes it through. Without this throw, refreshExtraction would chunk + // the sentinel and report a bogus chunks_written:1 (Cowork field report). + const errEnvelope = { + content: [{ type: "text", text: "No PDF is currently open for that viewUUID" }], + isError: true, + }; + expect(() => parseGetTextResult(errEnvelope)).toThrow(/PDF_GET_TEXT_FAILED/); + expect(() => parseGetTextResult(errEnvelope)).toThrow(/No PDF is currently open/); +}); + +test("parseGetTextResult throws a labelled error even when isError carries no message", () => { + expect(() => parseGetTextResult({ isError: true, content: [] })).toThrow(/PDF_GET_TEXT_FAILED/); +}); + test("buildClientCapabilities advertises roots.listChanged=true (load-bearing per §7.2)", () => { const caps = buildClientCapabilities(); expect(caps.roots).toBeDefined(); diff --git a/src/server/pdf/lifecycle.ts b/src/server/pdf/lifecycle.ts index 4831dd3..d3afd06 100644 --- a/src/server/pdf/lifecycle.ts +++ b/src/server/pdf/lifecycle.ts @@ -87,6 +87,42 @@ function fileUrlToPath(uri: string): string { return new URL(uri).pathname.replace(/^\/([A-Za-z]):/, "$1:"); } +/** + * Parse the vendor's `interact{action:"get_text"}` result into a plain string, + * THROWING when the child signalled failure. + * + * Bug (Cowork field report 2026-06-05): the vendor returns failures as the + * standard MCP error envelope `{ content:[{type:"text",text:}], isError:true }` + * (see vendor/pdf-server processInteractCommand), and the SDK's `callTool` does + * NOT throw on `isError` — it is an in-band tool error meant for the model to + * read. The previous flatten-only code returned that error text as if it were + * document text, so refreshExtraction chunked + embedded the one-line sentinel + * and reported a bogus `chunks_written: 1`, silently poisoning the corpus. Detect + * `isError` and propagate instead. + * + * Pure (no transport) so it is unit-testable directly, mirroring `sanitizeRoots` + * / `buildClientCapabilities`. + */ +export function parseGetTextResult(r: unknown): string { + if (typeof r === "string") return r; + if (r && typeof r === "object") { + const obj = r as { isError?: boolean; content?: Array<{ type: string; text?: string }> }; + const flat = Array.isArray(obj.content) + ? obj.content + .filter((c) => c.type === "text" && typeof c.text === "string") + .map((c) => c.text!) + .join("") + : ""; + if (obj.isError === true) { + throw new Error( + `PDF_GET_TEXT_FAILED: ${flat || "pdf child get_text returned an error with no message"}`, + ); + } + if (Array.isArray(obj.content)) return flat; + } + return JSON.stringify(r); +} + // ========================================================================= // Supervised spawn implementation. // ========================================================================= @@ -276,17 +312,12 @@ export async function spawnPdfChild(opts: SpawnOpts): Promise { undefined, { timeout: opts.timeoutMs ?? 120_000 }, ); + // The child responded, so it is alive even if extraction failed — keep the + // liveness stamp. parseGetTextResult flattens the success content and THROWS + // on the vendor's isError envelope (callTool does not), so a failed extract + // never gets ingested as document text. lastOkAt = Date.now(); - // The upstream get_text returns structured content; flatten to a string. - if (typeof r === "string") return r; - const content = (r as { content?: Array<{ type: string; text?: string }> }).content; - if (Array.isArray(content)) { - return content - .filter((c) => c.type === "text" && typeof c.text === "string") - .map((c) => c.text!) - .join(""); - } - return JSON.stringify(r); + return parseGetTextResult(r); }, async displayPdf(source, opts) { // Vendor `display_pdf` is a separate vendor tool (NOT an interact action). diff --git a/src/server/tools/corpus.test.ts b/src/server/tools/corpus.test.ts index 5cbc138..79b5237 100644 --- a/src/server/tools/corpus.test.ts +++ b/src/server/tools/corpus.test.ts @@ -6,8 +6,10 @@ import { test, expect, describe, beforeEach, afterEach, mock, spyOn } from "bun: import { mkdtempSync, rmSync, existsSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { sql } from "drizzle-orm"; import { buildServer, type BuiltServer } from "../index.ts"; import { openWithPragmas, applyMigrations } from "../db/migrations.ts"; +import { reopenPersistedCorpus } from "./corpus.ts"; import type { PdfChild } from "./registry.ts"; // ─── helpers ───────────────────────────────────────────────────────────────── @@ -284,6 +286,123 @@ test("corpus.status returns counts and last_opened_at", async () => { expect(result).toMatchObject({ paper_count: expect.any(Number) }); }); +test("corpus.status reports db_open:true with a numeric count for the active, open corpus (Bug #3)", async () => { + await createCorpus("open-status"); + await dispatch("scholar.corpus.activate", { slug: "open-status" }); + const result = await dispatch("scholar.corpus.status", { slug: "open-status" }) as { + paper_count: number; + db_open: boolean; + }; + expect(result.db_open).toBe(true); + expect(result.paper_count).toEqual(expect.any(Number)); +}); + +test("corpus.status reports db_open:false (not a misleading 0) when the active corpus DB isn't open in this process (Bug #3)", async () => { + await createCorpus("restart-sim"); + await dispatch("scholar.corpus.activate", { slug: "restart-sim" }); + // Simulate a fresh process / failed startup rehydration: activeCorpusId is still + // persisted in config, but ctx.db is unset (no open handle this process). + built.ctx.db = undefined; + const result = await dispatch("scholar.corpus.status", { slug: "restart-sim" }) as { + paper_count: number; + db_open: boolean; + }; + // The old code returned paper_count:0 SILENTLY here — indistinguishable from an + // empty corpus. db_open:false now disambiguates the 0. + expect(result.db_open).toBe(false); + expect(result.paper_count).toBe(0); +}); + +test("reopenPersistedCorpus warns (not silently) when a persisted activeCorpusId has no corpus row (Bug #3b diagnostic)", () => { + const warn = spyOn(built.ctx.log, "warn"); + // Anomalous state: an activeCorpusId is persisted but points at a corpus that + // doesn't exist. The old code returned undefined with NO trace; the diagnostic + // warn is what lets the next field run pinpoint why rehydration gave up. + built.ctx.db = undefined; + built.ctx.config.set("activeCorpusId", "ghost-slug-never-created"); + const result = reopenPersistedCorpus(built.ctx, dir); + expect(result).toBeUndefined(); + expect(built.ctx.db).toBeUndefined(); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); +}); + +test("reopenPersistedCorpus stays silent when no corpus has ever been activated (normal fresh install)", () => { + const warn = spyOn(built.ctx.log, "warn"); + // No activeCorpusId persisted (fresh harness) — the NORMAL state must NOT warn, + // or the diagnostic cries wolf on every clean startup. + built.ctx.db = undefined; + const result = reopenPersistedCorpus(built.ctx, dir); + expect(result).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); +}); + +test("reopenPersistedCorpus rehydrates ctx.db from the on-disk corpus DB across a simulated process restart (Bug #3b real-path discriminator)", async () => { + // The two #3b unit tests above hand-set `ctx.db = undefined` to prove the + // SYMPTOM surface (db_open:false / diagnostic warns). They do NOT exercise the + // real rehydration PATH — which is exactly the gap the Cowork field report + // flagged: "query/digest still require manual re-activation" after a restart. + // This test opens a SECOND server against the SAME on-disk runtimeRoot, with a + // FRESH config-DB handle (a new openWithPragmas on the same file, NOT the + // shared `configDb` the harness injected into Server A), and asserts that + // reopenPersistedCorpus actually re-opens the per-corpus DB the prior session + // wrote and recovers its rows. If this goes RED, the field symptom reproduces + // locally and #3 needs a root-cause fix, not just diagnostics. + + // ── Server A (the beforeEach `built`): create + activate, seed one paper ── + await createCorpus("restart-real"); + await dispatch("scholar.corpus.activate", { slug: "restart-real" }); + expect(built.ctx.db).toBeDefined(); + // Seed directly into the live corpus handle so there is durable on-disk content + // to recover. Auto-commit (no explicit txn) flushes it to the DB file before B + // opens its own connection. + built.ctx.db!.run(sql` + INSERT INTO papers (id, key, title, imported_at) + VALUES ('p-restart-1', 'restart-key-1', 'Seeded Across Restart', '2026-06-05T00:00:00Z') + `); + + // ── Server B: a fresh process simulation on the SAME runtimeRoot ── + // A new openWithPragmas handle on the same config-DB file reads A's persisted + // activeCorpusId + corpora rows back off disk — no shared in-memory state. B + // never calls activate; reopenPersistedCorpus is the only recovery path. + const freshConfigDb = openWithPragmas(join(dir, "dbs", "scholar-config.db")); + const builtB = buildServer({ + runtimeRoot: dir, + openConfigDb: () => freshConfigDb, + spawnPdfChild: () => ({ + interact: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, + getText: async () => { throw new Error("PDF_CHILD_UNAVAILABLE"); }, + currentRoots: () => [], + setRoots: async () => {}, + displayPdf: async () => ({ viewUUID: "stub-view-uuid" }), + isHealthy: () => ({ alive: false, lastOkAt: null, stdioOpen: false }), + }), + }); + + expect(builtB.ctx.db).toBeUndefined(); // fresh process: nothing open yet + const reopened = reopenPersistedCorpus(builtB.ctx, dir); + + // The real path must recover the slug AND open the on-disk handle … + expect(reopened).toBe("restart-real"); + expect(builtB.ctx.db).toBeDefined(); + // … and that handle must see the row Server A committed to the per-corpus file. + const rows = builtB.ctx.db!.all( + sql`SELECT key, title FROM papers`, + ) as { key: string; title: string }[]; + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ key: "restart-key-1", title: "Seeded Across Restart" }); + + // Production read-path proof: corpus.status on B reports the recovered count, + // not the misleading 0 of #3 — db_open:true, paper_count:1, no manual activate. + const status = (await builtB.dispatch("scholar.corpus.status", { slug: "restart-real" })) as { + db_open: boolean; + paper_count: number; + }; + expect(status.db_open).toBe(true); + expect(status.paper_count).toBe(1); +}); + test("corpus.reset-init clears initOnce slot allowing re-create after failure", async () => { // The slot for a failed create should be cleared on error (retry semantics) // corpus.reset-init explicitly clears the corpus: slot diff --git a/src/server/tools/corpus.ts b/src/server/tools/corpus.ts index 634b7ab..b3a836c 100644 --- a/src/server/tools/corpus.ts +++ b/src/server/tools/corpus.ts @@ -207,11 +207,31 @@ export function reopenPersistedCorpus( ): string | undefined { if (ctx.db) return ctx.config.activeCorpusId(); // already open (defensive; runCli never hits this) const slug = ctx.config.activeCorpusId(); + // No persisted active corpus is the NORMAL fresh-install / never-activated + // state — stay silent so the diagnostic warns below don't cry wolf on every + // clean startup. if (!slug) return undefined; + // Bug #3b diagnostic (Cowork field report 2026-06-05): when an activeCorpusId + // IS persisted but rehydration still can't open the DB, every active-corpus + // tool (query, digest, papers, pdf) keeps failing NO_ACTIVE_CORPUS until a + // manual re-activate. The old code returned undefined SILENTLY in two of the + // three failure branches, leaving no trace of *why* rehydration gave up. Warn + // on each anomalous branch (id persisted but unusable) so the next field run + // pinpoints the cause — this is the diagnostic, not a root-cause fix (the + // wiring in runServer/runCli already calls this once at startup; the symptom + // implies one of these branches fires, and we couldn't reproduce which from + // static analysis). const row = ctx.config.corpora().find(c => c.id === slug); - if (!row || row.archived_at) return undefined; + if (!row) { + ctx.log.warn("reopenPersistedCorpus: persisted activeCorpusId has no matching corpus row; leaving ctx.db unset", { slug }); + return undefined; + } + if (row.archived_at) { + ctx.log.warn("reopenPersistedCorpus: persisted active corpus is archived; leaving ctx.db unset", { slug, archived_at: row.archived_at }); + return undefined; + } if (!existsSync(corpusDbPath(slug, runtimeRoot))) { - ctx.log.warn("reopenPersistedCorpus: persisted active corpus DB file missing; leaving ctx.db unset", { slug }); + ctx.log.warn("reopenPersistedCorpus: persisted active corpus DB file missing; leaving ctx.db unset", { slug, path: corpusDbPath(slug, runtimeRoot) }); return undefined; } ctx.db = openCorpusDb(slug, runtimeRoot); @@ -415,9 +435,19 @@ async function handleStatus(args: unknown, ctx: ServerContext): Promise const row = ctx.config.corpora().find(c => c.id === targetSlug); if (!row) throw new CorpusError("CORPUS_NOT_FOUND", `Corpus not found: "${targetSlug}"`); - // Paper count — available only if this corpus is currently the active (open) one. + // Paper count + db_open (Bug #3 — Cowork field report 2026-06-05). The old code + // returned a SILENT paper_count:0 whenever the target's DB wasn't open in THIS + // process (e.g. a restart whose startup rehydration found nothing to open) — + // indistinguishable from a genuinely empty corpus. We count only when the target + // IS the active corpus AND its DB is open here, and we surface `db_open` so a 0 + // is never ambiguous. paper_count stays a number (no contract break). We do NOT + // rehydrate here: reopenPersistedCorpus already runs once at server/CLI startup — + // re-running it per status call would just repeat a failed open and re-log; if + // the DB is unset by now, db_open:false reports that outcome truthfully. + const isActive = ctx.config.activeCorpusId() === targetSlug; + const dbOpen = isActive && _db !== undefined; let paperCount = 0; - if (ctx.config.activeCorpusId() === targetSlug && _db) { + if (isActive && _db) { const rows = _db.all(sql`SELECT COUNT(*) AS cnt FROM papers`) as { cnt: number }[]; paperCount = rows[0]?.cnt ?? 0; } @@ -429,6 +459,7 @@ async function handleStatus(args: unknown, ctx: ServerContext): Promise last_opened_at: row.last_opened_at, archived_at: row.archived_at, paper_count: paperCount, + db_open: dbOpen, }; } diff --git a/src/server/tools/pdf.test.ts b/src/server/tools/pdf.test.ts index d65b4b1..c7697ec 100644 --- a/src/server/tools/pdf.test.ts +++ b/src/server/tools/pdf.test.ts @@ -8,6 +8,7 @@ import { test, expect } from "bun:test" import { Database } from "bun:sqlite" import { drizzle } from "drizzle-orm/bun-sqlite" import { refreshExtraction } from "./pdf.ts" +import { parseGetTextResult } from "../pdf/lifecycle.ts" import { runRawDdl } from "#server/db/raw-ddl.ts" import { ensureVec0Path } from "%/util" @@ -332,3 +333,57 @@ test("refresh-extraction: NO_ACTIVE_CORPUS guard when ctx.db is undefined", asyn ), ).rejects.toThrow(/NO_ACTIVE_CORPUS/) }) + +test("refresh-extraction: propagates a pdf get_text error envelope and writes ZERO chunks (Cowork field finding #2 — caller)", async () => { + // parseGetTextResult unit tests (lifecycle.test.ts) prove the SEAM throws on the + // vendor isError envelope. THIS pins the CALLER behavior the field report named: + // refreshExtraction must propagate that failure instead of chunking the error + // sentinel and reporting a bogus chunks_written:1. Highest fidelity short of a + // real spawn: getText runs the REAL parseGetTextResult on an isError envelope — + // exactly what the production lifecycle.ts getText does — so this exercises the + // wired path child-error → getText throws → caller propagates, not a hand-rolled + // stand-in. (Before the #2 fix, getText flattened the sentinel to a 1-line string, + // chunkText produced one chunk, and the transaction wrote it: chunks_written:1.) + const sqlite = freshExtractionDb() + sqlite.run(`INSERT INTO settings(key,value) VALUES + ('embed.model','"nomic-embed-text:v1.5"'), + ('embed.dim','768'), + ('chunk_vec.created','true')`) + runRawDdl(drizzle(sqlite)) + sqlite.run(`INSERT INTO papers(id,key,title,imported_at) + VALUES ('perr','errpaper','Error paper','2026-05-22T00:00:00.000Z')`) + + const errEnvelope = { + content: [{ type: "text", text: "No PDF is currently open for that viewUUID" }], + isError: true, + } + const ctx = fakeCtx(sqlite, { + paperId: "perr", + // parseGetTextResult throws synchronously on the isError envelope, so the + // async getText rejects with PDF_GET_TEXT_FAILED — the same rejection the + // real child handle produces. + text: async () => parseGetTextResult(errEnvelope), + }) + + await expect( + refreshExtraction(ctx, { paper_id: "perr" }), + ).rejects.toThrow(/PDF_GET_TEXT_FAILED/) + + // The failure must short-circuit BEFORE the write transaction: zero chunks, zero + // chunk_vec rows. This is the "not chunks_written:1" assertion in concrete form. + const chunkN = ( + sqlite + .query("SELECT COUNT(*) AS n FROM paper_chunks WHERE paper_id='perr'") + .get() as { n: number } + ).n + expect(chunkN).toBe(0) + const vecN = ( + sqlite + .query( + `SELECT COUNT(*) AS n FROM chunk_vec + WHERE chunk_id IN (SELECT id FROM paper_chunks WHERE paper_id='perr')`, + ) + .get() as { n: number } + ).n + expect(vecN).toBe(0) +}) diff --git a/src/server/tools/registry.test.ts b/src/server/tools/registry.test.ts index b058940..80a09d0 100644 --- a/src/server/tools/registry.test.ts +++ b/src/server/tools/registry.test.ts @@ -21,7 +21,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { registerAll, type ToolRegistry } from "./registry.ts"; -import { APP_URI } from "../ui/resource.ts"; +import { APP_URI, MCP_APP_MIME, UI_EXTENSION_ID, registerUiResource } from "../ui/resource.ts"; const VIEW_OPENERS = [ "scholar.dashboard", @@ -161,6 +161,40 @@ test("real SDK serializes view-opener _meta.ui.resourceUri into the tools/list w } }); +test("real SDK advertises the MCP Apps UI extension on the initialize capabilities", async () => { + // Render Layer 3 (Cowork field report 2026-06-05). Layers 1+2 — view-opener + // tool `_meta.ui.resourceUri` and the MCP_APP_MIME resource — are INERT unless + // the server also tells the host it speaks MCP Apps: a host checks + // `capabilities.extensions["io.modelcontextprotocol/ui"]` in the initialize + // result BEFORE rendering any iframe (the field test saw every view invisible + // until this landed). Prove the declaration survives onto the SERIALIZED + // initialize result the client parsed off the wire — getServerCapabilities() + // returns exactly that — not merely that registerCapabilities() was called. + const server = new McpServer({ name: "scholar-test", version: "0.0.0" }); + registerAll(server, fakeCtx()); + registerUiResource(server, fakeCtx()); // folds in declareUiAppCapability (Layer 3) + + const client = new Client({ name: "registry-test-client", version: "0.0.0" }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + try { + const caps = client.getServerCapabilities() as + | { extensions?: Record } + | undefined; + const ui = caps?.extensions?.[UI_EXTENSION_ID]; + expect(ui, `server must advertise extensions["${UI_EXTENSION_ID}"]`).toBeDefined(); + // Value is the spec's `{ mimeTypes }` shape carrying exactly the mime scholar + // serves — satisfies a host that reads the sub-field and one that only checks + // presence. + expect(ui?.mimeTypes, "advertised mimeTypes must include the MCP Apps profile mime") + .toContain(MCP_APP_MIME); + } finally { + await client.close(); + await server.close(); + } +}); + test("MCP wrapper leaves non-view-opener results as text-only", async () => { const wrappers = new Map Promise>(); const fakeServer = { diff --git a/src/server/ui/resource.ts b/src/server/ui/resource.ts index 18c7e05..92745f8 100644 --- a/src/server/ui/resource.ts +++ b/src/server/ui/resource.ts @@ -34,6 +34,40 @@ export const APP_URI = "ui://scholar/app.html"; // bundle (dist/server.js) does not pull in the client-side ext-apps package. export const MCP_APP_MIME = "text/html;profile=mcp-app"; +// MCP Apps capability extension id (SEP-1865). Mirrors ext-apps' EXTENSION_ID; +// hardcoded locally for the same reason as MCP_APP_MIME (no ext-apps import in +// the server bundle). +export const UI_EXTENSION_ID = "io.modelcontextprotocol/ui"; + +/** + * Advertise MCP Apps support in the server's `initialize` capabilities. + * + * THIRD render layer (2026-06-05 Cowork field report). Layers 1+2 already shipped: + * each view-opener tool DEF carries `_meta.ui.resourceUri` (registry.ts) and the + * UI resource is served with MCP_APP_MIME (below). But a host checks whether the + * SERVER itself speaks MCP Apps — `capabilities.extensions["io.modelcontextprotocol/ui"]` + * in the initialize result — BEFORE it renders any `_meta.ui` iframe. Without this + * key every view is inert: the field test saw all views invisible until the + * declaration was added. (Note: ext-apps' own helpers declare NO server-side + * extension — getUiCapability only READS the client's; the directions are + * orthogonal, so declaring server-side is purely additive.) + * + * Value: the spec's capability shape is `{ mimeTypes?: string[] }`, whose own + * schema description says it must include `text/html;profile=mcp-app`. We declare + * exactly the mime scholar serves rather than a bare `{}`, so a host that reads + * the sub-field is satisfied and a host that only checks presence is too. + * + * registerCapabilities MERGES (preserving the tools/resources capabilities the + * McpServer auto-registers) and MUST run before connect(); registerUiResource is + * always called pre-connect by buildServer, so folding the declaration in here + * makes "serve the UI resource ⟹ advertise the extension" true by construction. + */ +export function declareUiAppCapability(server: McpServer): void { + server.server.registerCapabilities({ + extensions: { [UI_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME] } }, + }); +} + /** * Build the `_meta` block that links a view-opener tool to ui://scholar/app.html. * @@ -82,6 +116,10 @@ function resolveUiHtmlPath(): string | null { } export function registerUiResource(server: McpServer, ctx: ServerContext): void { + // ── (0) advertise MCP Apps support so the host renders the views at all ──── + // Must precede connect(); buildServer calls registerUiResource pre-connect. + declareUiAppCapability(server); + // ── (1) ui://scholar/app.html ───────────────────────────────────────────── server.registerResource( "scholar-ui", diff --git a/tests/build-plugin.test.ts b/tests/build-plugin.test.ts index e35ad89..dc17a93 100644 --- a/tests/build-plugin.test.ts +++ b/tests/build-plugin.test.ts @@ -1,9 +1,12 @@ -// tests/build-plugin.test.ts — slim-plugin pivot (2026-06-01). +// tests/build-plugin.test.ts — slim-plugin pivot (2026-06-01), +// bun-launcher unification (2026-06-05). // // 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. +// covers the GENERATED output. The launch model no longer branches per-OS — both +// targets run the same `bun ${ROOT}/bin/launch.mjs` shim — so what stays per-OS +// is the platform runtime root and the pre-warm hook (now also unified on the +// bun shim). Both are asserted below. import { test, expect } from 'bun:test' import { buildManifest, buildMcpbManifest } from '^scripts/build-plugin.ts' @@ -16,42 +19,45 @@ const base = { bin: { 'mcp-scholar': './bin/mcp-scholar' }, } -test('buildManifest(linux): /bin/sh launcher + HOME runtime root + sh pre-warm', () => { +test('buildManifest(linux): bun launch.mjs + HOME runtime root + bun 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.command).toBe('bun') + expect(s.args).toEqual(['${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs']) 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) + expect(hook).toContain('launch.mjs') + expect(hook).toContain('--provision-only') + expect(hook.startsWith('bun ')).toBe(true) }) -test('buildManifest(win32): cmd.exe launcher + USERPROFILE root + PowerShell pre-warm', () => { +test('buildManifest(win32): bun launch.mjs + USERPROFILE root + bun 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']) + // Same cross-OS launcher as linux; only the runtime root differs per-OS. + expect(s.command).toBe('bun') + expect(s.args).toEqual(['${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs']) 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') + expect(hook).toContain('launch.mjs') + expect(hook).toContain('--provision-only') + expect(hook.startsWith('bun ')).toBe(true) }) // ── Claude Desktop .mcpb manifest ───────────────────────────────────────────── // Unit-pins buildMcpbManifest. `mcpb validate` (run during SCHOLAR_PACKAGE=mcpb // build) is the authoritative schema gate; this guards the load-bearing // launcher-alias contract the validator can't see — that the env block aliases -// the two vars launch.cmd + ensure-bun.ps1 read (CLAUDE_PLUGIN_ROOT := ${__dirname}, +// the two vars launch.mjs + ensure-bun.ps1 read (CLAUDE_PLUGIN_ROOT := ${__dirname}, // CLAUDE_PLUGIN_DATA := ${user_config.data_dir}) so the win32 launch chain runs // byte-identical to the Claude Code plugin. test('buildMcpbManifest: base metadata passthrough + version', () => { @@ -64,20 +70,20 @@ test('buildMcpbManifest: base metadata passthrough + version', () => { expect(m.bin).toBeUndefined() // base `bin` leftover not carried into mcpb shape }) -test('buildMcpbManifest: cmd.exe/launch.cmd entry under type:binary, no relaunch of /bin/sh', () => { +test('buildMcpbManifest: bun launch.mjs entry under type:binary, win32-only', () => { const m = buildMcpbManifest(base, '0.1.0') as any - expect(m.server.type).toBe('binary') - expect(m.server.entry_point).toBe('bin/launch.cmd') - expect(m.server.mcp_config.command).toBe('cmd.exe') - expect(m.server.mcp_config.args).toEqual(['/c', '${__dirname}\\bin\\launch.cmd']) + expect(m.server.type).toBe('binary') // bun is a binary on PATH + expect(m.server.entry_point).toBe('bin/launch.mjs') + expect(m.server.mcp_config.command).toBe('bun') + expect(m.server.mcp_config.args).toEqual(['${__dirname}\\bin\\launch.mjs']) expect(m.compatibility.platforms).toEqual(['win32']) }) test('buildMcpbManifest: env aliases the two vars the launcher reads (no launcher edit)', () => { const env = (buildMcpbManifest(base, '0.1.0') as any).server.mcp_config.env - // launch.cmd reads %CLAUDE_PLUGIN_ROOT% + %CLAUDE_PLUGIN_DATA%; ensure-bun.ps1 - // reads $env:CLAUDE_PLUGIN_DATA. Aliasing both is what lets the launcher run - // unmodified under Claude Desktop. + // launch.mjs reads process.env.CLAUDE_PLUGIN_ROOT + CLAUDE_PLUGIN_DATA; + // ensure-bun.ps1 reads $env:CLAUDE_PLUGIN_DATA. Aliasing both is what lets the + // launcher run unmodified under Claude Desktop. expect(env.CLAUDE_PLUGIN_ROOT).toBe('${__dirname}') expect(env.CLAUDE_PLUGIN_DATA).toBe('${user_config.data_dir}') expect(env.SCHOLAR_RUNTIME_ROOT).toBe('${user_config.data_dir}\\runtime') diff --git a/tests/manifests.test.ts b/tests/manifests.test.ts index f55cd76..e820005 100644 --- a/tests/manifests.test.ts +++ b/tests/manifests.test.ts @@ -1,15 +1,26 @@ import pluginManifest from '^.claude-plugin/plugin.json' -// manifests.test.ts — foundation cycle 6.1 (Task 1.11), amended 2026-06-01. +// manifests.test.ts — foundation cycle 6.1 (Task 1.11), amended 2026-06-01, +// repivoted 2026-06-05 for source-sync. // -// 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. +// Pins the COMMITTED plugin manifest (`.claude-plugin/plugin.json`). The +// source-sync pivot (cowork-marketplace distribution) SUPERSEDES the prior M2 +// per-OS shell-launcher form for THIS file: the marketplace installs by +// copy-only and serves one committed manifest to every OS, so the committed +// manifest must use a single cross-OS command. That command is `bun` (the +// system-wide runtime these servers already depend on — and the replacement for +// the now-removed "use bundled node" Claude Desktop option), which runs +// `bin/launch.mjs`: the shim provisions the pinned bun then spawns the server +// from source (auto-installing the reached import graph). The per-OS GENERATED +// manifest used by the built `.plugin`/`.mcpb` bundles runs the SAME +// `bun bin/launch.mjs` launcher; it differs only in pinning SCHOLAR_RUNTIME_ROOT +// per-OS and shipping the matching ensure-bun provisioner. It is produced by +// scripts/build-plugin.ts buildManifest() and covered separately in +// build-plugin.test.ts — changing this committed manifest does NOT affect those +// bundles, because buildManifest rebuilds mcpServers + hooks from scratch. +// (Earlier history: the launcher was a per-OS shell pair (cmd.exe/launch.cmd | +// /bin/sh/launch.sh) until the 2026-06-05 bun-unification; the slim-plugin pivot +// 2026-06-01 dropped the §7.1 `bun build --compile` binary; the §7.1 `.mcp.json` +// was removed in 84a292c.) import { test, expect } from 'bun:test' test('plugin manifest matches spec §7.1 (identity fields)', () => { @@ -18,19 +29,30 @@ test('plugin manifest matches spec §7.1 (identity fields)', () => { expect(pluginManifest.keywords).toContain('literature-review') }) -test('mcpServers.scholar uses the M2 shell launcher (pivot supersedes §7.1 compiled-binary command)', () => { +test('mcpServers.scholar uses the cross-OS bun launcher (source-sync supersedes the per-OS shell launcher)', () => { 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']) + // Source-sync: `bun` is the one command present on every host (the systemwide + // bun install these servers already depend on); it runs the launch.mjs shim + // (provision pinned bun → spawn server from source). + expect(scholar.command).toBe('bun') + expect(scholar.args).toEqual(['${CLAUDE_PLUGIN_ROOT}/bin/launch.mjs']) + // SCHOLAR_RUNTIME_ROOT is NOT pinned in the committed env: launch.mjs derives + // it cross-OS from CLAUDE_PLUGIN_DATA (the POSIX-only ${HOME} default would + // break on Windows). Its absence here is the contract, not an oversight. + // Key-dynamic access: TS infers the committed env type WITHOUT this key, so a + // direct `.SCHOLAR_RUNTIME_ROOT` is a compile error — which is itself the proof + // it's absent. Cast to a record to assert that absence at runtime too. + expect((scholar.env as Record).SCHOLAR_RUNTIME_ROOT).toBeUndefined() // 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. +test('SessionStart hook pre-warms the bun provisioner via the cross-OS shim', () => { + // The hook is a pre-warm only — launch.mjs (no flag) is the correctness gate, + // because SessionStart does not block MCP spawn. Here it runs --provision-only + // so the same shim resolves the sh-vs-powershell provisioner per-OS. const cmd = pluginManifest.hooks?.SessionStart?.[0]?.hooks?.[0]?.command - expect(cmd).toContain('ensure-bun.sh') + expect(cmd).toContain('launch.mjs') + expect(cmd).toContain('--provision-only') }) diff --git a/ui/app.html b/ui/app.html new file mode 100644 index 0000000..9b29845 --- /dev/null +++ b/ui/app.html @@ -0,0 +1,449 @@ + + + + + + Scholar + + + +
+ + +