Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
f8ffd27
checkpoint: WIP win32-target / build-simplification work in progress
zaynram Jun 2, 2026
b2b701c
slim: env seams for pdf entrypoint + bun runtime resolution
zaynram Jun 2, 2026
bc50f8a
slim: ship rebundled standalone pdf-server; record pivot architecture
zaynram Jun 2, 2026
2e79318
slim: build:server bundles (no --compile); add build:pdf-bundle
zaynram Jun 2, 2026
e9f9cb7
slim: M2 launcher + idempotent bun provisioner (Linux verified)
zaynram Jun 2, 2026
98823c8
slim: rewrite build-plugin for slim package + per-OS manifest generation
zaynram Jun 2, 2026
7d85cb7
docs: record validated slim build + update CLAUDE.md architecture
zaynram Jun 2, 2026
8a4aa11
docs(pivot): record production-path validations + explicit koffi deci…
zaynram Jun 2, 2026
1e2a43a
test: fix pivot-stale manifest assertion + scope discovery (Phase 0)
zaynram Jun 2, 2026
6101ac8
test: expand coverage — p-limit, lifecycle resolvers, generateManifes…
zaynram Jun 2, 2026
a1c9011
test: repoint nu CLI to M2 + prune dead serve path (Chunk B)
zaynram Jun 2, 2026
a58814e
test: consolidate annotations guard + rect cases into test.each (Chun…
zaynram Jun 2, 2026
7cc5ee3
test(nu): cover production server-cmd resolution (no override)
zaynram Jun 2, 2026
624209e
fix(pdf-e2e): repair fixture 4 (get_text hang) + un-gate protocol fix…
zaynram Jun 2, 2026
8518c35
ci: drop no-op --only-failures, add dedicated e2e job
zaynram Jun 2, 2026
7a6e2e3
chore(scope): file cover-ollama-client-and-index-dispatch-unit-gaps
zaynram Jun 2, 2026
75abeaf
test(coverage): cover ollama listModels/healthCheck/chat + index CLI …
zaynram Jun 2, 2026
dda2870
chore(scope): close cover-ollama-client-and-index-dispatch-unit-gaps …
zaynram Jun 2, 2026
2a82b18
fix(pdf-e2e): de-flake FIXTURE 6 respawn — poll instead of fixed sleep
zaynram Jun 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 36 additions & 25 deletions .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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\""
}
]
}
]
}
}
}
}
26 changes: 26 additions & 0 deletions .claude/context/chores.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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`.</synopsis>
</chore>

<!--
Low-priority unit-coverage gaps surfaced by the 2026-06-02 test audit
(residual-gaps item 3, reported after the e2e-handling fix). Filed
post-execution (plan-group 2026-05-22-scholar-plugin is closed) as a
test-only code chore; dispatched to spec-pipeline:chore-executor (sonnet)
with the dispatcher owning the status flip per invariant 5.
-->
<chore id="cover-ollama-client-and-index-dispatch-unit-gaps"
status="closed"
fulfillment="75abeaf"
blast-radius="src/server/ollama/client.test.ts src/server/index.test.ts"
blocks-plans="">
<synopsis>Closed at 75abeaf (+29 tests, suite 324 pass/0 fail, tsc clean): client.ts lines 69.7-&gt;100% (listModels/healthCheck/chat covered); index.ts lines 77.7-&gt;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.</synopsis>
</chore>
</chores>
</reference>
31 changes: 30 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand All @@ -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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 7 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
49 changes: 49 additions & 0 deletions bin/ensure-bun.ps1
Original file line number Diff line number Diff line change
@@ -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 }
}
51 changes: 51 additions & 0 deletions bin/ensure-bun.sh
Original file line number Diff line number Diff line change
@@ -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
20 changes: 20 additions & 0 deletions bin/launch.cmd
Original file line number Diff line number Diff line change
@@ -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" %*
18 changes: 18 additions & 0 deletions bin/launch.sh
Original file line number Diff line number Diff line change
@@ -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" "$@"
Loading
Loading