Skip to content

test: root-cause pdf e2e fix + isolated CI lane, coverage hardening - #3

Merged
zaynram merged 19 commits into
mainfrom
simplify/win32-target-install-pivot
Jun 3, 2026
Merged

zaynram merged 19 commits into
mainfrom
simplify/win32-target-install-pivot

Conversation

@zaynram

@zaynram zaynram commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

Summary

Test-suite hardening on the slim-plugin / win32 target-install pivot branch. The
most recent work fixes the pdf-child e2e test handling at the root cause and
wires it into CI as an isolated lane.

pdf e2e — root-cause fix

  • Fixture 4 was broken by construction: it asserted via get_text, which needs a
    live browser viewer and hangs headless (enqueues to the vendor poll queue and
    never returns). Reworked to drive interact({navigate}) against a valid
    one-page PDF, which round-trips headless.
  • Extracted the valid-PDF helper into tests/util/pdf-fixture.ts
    (writeMinimalPdf / makeFixtureRoot), shared between the lifecycle and
    contract tests.
  • Un-gated fixtures 1–3 (they were skipIf(!SCHOLAR_PDF_E2E) yet documented as
    always-run) so they contribute coverage on every run.
  • Fixture 5 (win32 Job Object orphan reap) is now an explicit test.todo rather
    than a vacuous skipped placeholder.

CI

  • Unit lane: bun test src tests --bail (dropped the no-op --only-failures;
    scoped to src+tests).
  • New dedicated e2e job runs SCHOLAR_PDF_E2E=1 bun test src/server/pdf so a
    flaky child spawn/respawn can't --bail the fast unit signal.

Coverage

  • Dispatched unit-gap chore (spec-pipeline scope-maintenance) closed the ollama
    client.ts chat/list/health paths (now 100% lines) and index.ts CLI dispatch
    branches (85.64% lines); +29 tests.

Verification

  • Full suite green locally on bun 1.3.14: 324 pass / 4 skip / 1 todo,
    tsc clean. Coverage deltas confirmed via --coverage.
  • ⚠️ CI pins bun 1.3.11 (scholar.bundledBunVersion for the vec0 ABI); local
    runs were on 1.3.14, so the patch-version skew is unverified until CI runs.
  • ⚠️ The new e2e job's push trigger ([main *]) doesn't match this feature
    branch — it first exercises on this PR to main.

Commits on this branch

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

🤖 Generated with Claude Code

zaynram and others added 19 commits June 1, 2026 21:08
Preserves the working state before the install-script + non-vendored-pdf
refactor. Captures the commands→skills migration, nu module moved to
bin/scholar.nu, build-plugin/tsconfig/package.json edits, and gitignores
the compiled binaries (bin/mcp-scholar*), win32/ staging, and the stray
home/ nested copy so they stay out of history.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Decouple the pdf-child spawn from the vendored-into-package layout, in
prep for the slim-plugin pivot (pdf-server provisioned into
${CLAUDE_PLUGIN_DATA} rather than shipped in the .plugin archive).

resolveChildEntrypoint precedence:
  SCHOLAR_PDF_ENTRYPOINT -> ${CLAUDE_PLUGIN_DATA}/pdf-server/dist/index.js
  -> <repo>/src/vendor/pdf-server/dist/index.js (dev/test fallback)

resolveBunRuntime: SCHOLAR_BUN_PATH ?? process.execPath. scholar itself
runs under the provisioned bun, so execPath is the right default; the env
lets the manifest pin the child runtime explicitly.

Additive only — the in-tree vendor fallback keeps the dev path and the
285-test suite green. §16 vendored .d.ts type surface untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Empirical finding: the vendored pdf-server dist lazy-loads pdfjs-dist via a
dynamic import, so it is NOT standalone as shipped. But `bun build
--target=bun` inlines pdfjs and produces a ~4MB single file that parses PDFs
with zero node_modules — proven by running the real vendor contract gate
(lifecycle.contract.test.ts, SCHOLAR_PDF_E2E=1) against the rebundle via the
SCHOLAR_PDF_ENTRYPOINT seam: 2 pass / 0 fail.

Decision: ship the rebundled standalone pdf-server in-package rather than
provision it at first-run (offline, deterministic, no network race). pdf
stays pinned @1.7.2 and remains scholar's spawned child. Reversible via
SCHOLAR_PDF_ENTRYPOINT.

resolveChildEntrypoint now: env -> ${CLAUDE_PLUGIN_ROOT}/dist/pdf-server/
index.js (existsSync-gated) -> vendored dev fallback.

Full architecture + evidence + open Windows flags recorded in
docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md.

tsc clean; 285 pass / 8 skip / 0 fail (baseline preserved).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
build:server: drop `--compile --target=bun-windows-x64` (which inlined all
of node_modules into a 96MB binary) for `--target=bun --outfile=dist/
server.js` — a 2.46MB platform-neutral bundle the provisioned bun runs
directly. Verified: runs under pinned bun 1.3.11 from a no-node_modules dir,
dispatches a tool, reaches the DB.

build:pdf-bundle: rebundle the vendored pdf-server dist standalone
(pdfjs-dist inlined) + copy mcp-app.html beside it -> dist/pdf-server/.

Drop dead `bin.mcp-scholar` pointer (compiled binary eliminated).

vec0 pin gate PASSED: loadExtension + vec0 virtual table function under
bun 1.3.11 (bunSqliteVersion 3.51.2 / sqlite-vec 0.1.9).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Launch model M2: an always-present shell spawns a launcher that provisions
the pinned bun into ${CLAUDE_PLUGIN_DATA} synchronously, THEN runs the server.
Required because Claude Code SessionStart hooks do NOT block MCP spawn (guide-
confirmed), so provisioning cannot live in a hook alone.

- bin/launch.sh  (manifest: /bin/sh launch.sh): `exec`s into bun so the spawned
  PID BECOMES the server — no orphaned wrapper, lock released on kill.
- bin/ensure-bun.sh: idempotent, flock-guarded, downloads bun 1.3.11; ALL
  diagnostics to stderr so stdout stays clean JSON-RPC.
- bin/launch.cmd + bin/ensure-bun.ps1: Windows mirrors (cmd.exe /c launch.cmd;
  ps1 download). FLAGGED — cannot run on the Linux dev host; cmd has no exec-
  replace so bun runs as a child (orphan risk if Claude Code doesn't tree-kill).

Scripts are invoked via the shell (sh/powershell -File), never relying on the
executable bit — the zip does not preserve +x. Caught and fixed in testing.

Verified on Linux against the staged package layout (CLAUDE_PLUGIN_ROOT=stage,
fresh CLAUDE_PLUGIN_DATA):
  - first launch downloads bun 1.3.11; second is a silent no-op (idempotent)
  - real MCP `initialize` round-trips: clean JSON-RPC on stdout, empty stderr
  - resolveBunRuntime/PdfEntrypoint/Vec0Path all resolve from CLAUDE_PLUGIN_ROOT
    with zero extra env (scholar runs under the provisioned bun)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Replaces the 7-step compile/bundle-bun/vendor-copy pipeline with the slim
model. The package now ships ~2.9MB (was ~200MB):
  dist/server.js                bun build --target=bun (no --compile)
  dist/pdf-server/{index,mcp-app.html}   rebundled standalone pdf-server@1.7.2
  build/vendor/sqlite-vec/vec0.<ext>     linux: node_modules prebuilt (+ABI probe);
                                         win: vec0.dll fetched from npm tarball
  ui/, nu/scholar.nu, skills/**, bin/<per-OS launcher set>
  .claude-plugin/plugin.json    GENERATED per-OS (M2 command/args + SessionStart prewarm)

The bun runtime is no longer shipped — ensure-bun provisions it into
${CLAUDE_PLUGIN_DATA} at first launch. Dropped: --compile binary, bundled bun
copy, vendored-pdf tree copy, fixture mode (no build tests gate it).

Per-OS manifest:
  linux  command=/bin/sh  args=[${ROOT}/bin/launch.sh]   runtime=${HOME}/...
  win32  command=cmd.exe  args=[/c, ${ROOT}\bin\launch.cmd]  runtime=${USERPROFILE}\...

Checked-in .claude-plugin/plugin.json updated to the Linux M2 dev form (was a
dangling pointer at the removed binary); the build regenerates per-OS.

VERIFIED:
  - tsc clean; bun test 285 pass / 8 skip / 0 fail (baseline preserved)
  - linux build -> unzip -> launch via generated manifest with fresh
    CLAUDE_PLUGIN_DATA: ensure-bun provisions bun 1.3.11, MCP initialize
    returns clean JSON-RPC on stdout
  - win32 build runs on Linux: vec0.dll (PE32+) fetched, win launcher set +
    manifest staged. Launch path itself FLAGGED for Windows-hardware validation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Pivot doc: build-system outcomes (both packages built; linux fully launched
end-to-end, win32 structurally validated), resolved flags (pin gate PASSED,
vec0.dll from npm, @napi-rs/canvas benign), and the remaining Windows-hardware
unknowns (cmd orphan, ensure-bun.ps1, koffi.node, UI chunk, MCP connect timeout).

CLAUDE.md: scholar server is now a --target=bun bundle run by a provisioned
bun (not a --compile binary); pdf-server stays vendored as .d.ts truth + dev
fallback but ships rebundled-standalone. Pointer to the pivot doc added.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…sion

Close the two Linux-testable integration gaps the advisor flagged: the
prior `initialize` smoke test proved boot only — it never spawned the pdf
child (empty stderr, no `[pdf-server] Ready`) nor loaded vec0 through
scholar's own code, and every spawn test used the SCHOLAR_PDF_ENTRYPOINT
override under dev bun 1.3.14.

Now verified from the assembled package under the pinned bun 1.3.11:
- resolveChildEntrypoint existsSync branch (no override) spawns the pdf
  child under provisioned bun — contract test 2 pass, [pdf-server] Ready.
- scholar's own resolveVec0Path() resolves the packaged
  ${CLAUDE_PLUGIN_ROOT}/build/vendor/sqlite-vec/vec0.so; loadExtension +
  vec0 virtual table + KNN MATCH succeed (vec_version v0.1.9).

koffi: upgrade the flag to an explicit decided regression. The slim
bundle ships no node_modules, so the runtime require("koffi") in
attachJobObject fails on Windows -> pdf-child Job-Object reaping is off
(the --compile binary had it). Accepted for the pivot: reaper is
best-effort try/catch by design, only bites if Claude Code also fails to
tree-kill, and the lock-DoS escalation is moot because the single-session
flock is a frozen spec invariant that is NOT yet implemented in
src/server/index.ts. Remediation paths documented; not done blind
(koffi native resolution is untestable off-target).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The slim pivot changed the launch model but left the test suite asserting
the removed --compile binary, leaving `bun test` RED on a clean checkout:

- tests/manifests.test.ts pinned command = ${CLAUDE_PLUGIN_ROOT}/bin/mcp-scholar
  (the dropped compiled binary). Reconcile to the M2 shell launcher
  (/bin/sh -> bin/launch.sh) and cite the 2026-06-01 pivot as the deliberate
  amendment superseding design-spec §7.1. Add a SessionStart pre-warm
  assertion; drop the stale .mcp.json comment (file removed in 84a292c).

- package.json "test" -> `bun test src tests`: scope discovery to the real
  suite. Bare `bun test` walked untracked-but-present staging junk; the
  scoped form runs exactly 41 real files (37 .test.ts + 4 .test.tsx) with
  zero pollutants. CI (bare `bun test`) is unaffected — the junk is
  gitignored and absent on a clean checkout.

Also removed 288 MB of stale untracked staging dirs (home/ doubled-path
accident, win32/ pre-pivot output) — regenerable, not produced by the
current build-plugin.ts (which writes build/<name>). The live worktree
.claude/worktrees/pre-v1-roadmap is left untouched.

bun run test: 280 pass / 8 skip / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…t (Chunk A)

Close the three real coverage gaps the audit surfaced:

- util/p-limit.ts (was 0%): the live §13 reconciliation mutex. 4 pure tests
  pin rejects-non-1-concurrency, value passthrough, strict serialization, and
  rejection-does-not-kill-the-queue. No process spawning.

- pdf/lifecycle.ts resolvers (file was 11%): export resolveChildEntrypoint and
  resolveBunRuntime (visibility only — internal helpers, not §7.6 contracts) and
  add 7 always-run unit tests for their branches. These cover exactly the
  production paths verified by hand during the pivot (existsSync shipped-bundle,
  env overrides, process.execPath default) — which CI never reached, since the
  spawn fixtures are SCHOLAR_PDF_E2E-gated and CI does not set it.

- scripts/build-plugin.ts generateManifest (0 tests): extract the pure per-OS
  construction into an exported buildManifest(base, win); generateManifest now
  just reads+writes. tests/build-plugin.test.ts pins the M2 launch contract for
  both platforms (/bin/sh+launch.sh vs cmd.exe+launch.cmd, runtime root, the
  ensure-bun pre-warm hook, bin-field stripping).

Also fix a tsc regression from Phase 0: the new SessionStart assertion in
manifests.test.ts indexed possibly-undefined tuple slots (caught by tsc, not
bun test — CI runs tsc as a separate step). Optional-chained.

bun run test: 293 pass / 8 skip / 0 fail. tsc: clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The pivot dropped the compiled binary but left two launch paths invoking it,
green only via stubs. Per the repoint-nu/prune-serve decision:

Repoint the user-facing nu CLI (bin/scholar.nu):
- mcp-scholar --call ... -> resolve the M2 server (provisioned bun running
  ${CLAUDE_PLUGIN_ROOT}/dist/server.js, located relative to the module via
  `path self`), dispatched with --call <tool> <json>. Add a SCHOLAR_SERVER_CMD
  override seam (mirrors SCHOLAR_PDF_ENTRYPOINT / SCHOLAR_BUN_PATH /
  SCHOLAR_VEC0_PATH). Args serialized explicitly with `to json --raw`.
- tests/scholar.test.ts: drive the repointed path via SCHOLAR_SERVER_CMD, and
  FIX a latent efficacy bug — the old stub asserted with expect() in a
  subprocess whose non-zero exit nu's `complete` swallows, so a wrong argv
  never failed the test. The stub now records argv to a file the test reads
  back and asserts `['--call','corpus.activate','{"slug":"test"}']`. Verified
  against real nu (run-external coercion confirmed empirically).

Prune the dead dev `serve` wrapper:
- delete scripts/start-server.ts (spawned the dropped build/scholar binary) +
  tests/start-server.test.ts (tested it via a stub) + the package.json `serve`
  script. M2 dev entry is `bun src/server/index.ts`.

bun run test: 291 pass / 8 skip / 0 fail. tsc: clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…k C)

Per the "also consolidate" decision. Identical coverage, fewer LOC, per-case
reporting retained:

- 3 NO_ACTIVE_CORPUS guard tests (list/upsert/delete) -> one test.each row per
  handler with that handler's minimal arg shape.
- 3 malformed-rect rejection tests (3-elem / non-finite / wrong-shape) -> one
  test.each. The valid-accept case stays separate (it asserts a DB round-trip,
  not a rejection — different shape, not redundant).

annotations.test.ts still reports 24 tests; bun run test green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The Chunk B repoint added a SCHOLAR_SERVER_CMD override seam and a test
for it, but every nu-spawn test drove that override — the production
`server-cmd` branch (path self → dirname → dirname = plugin root, then
dist/server.js, with PATH-bun fallback) was never executed. That is the
same override-only blind spot the pre-pivot lifecycle spawn tests had.

Lay the real <root>/nu + <root>/dist layout in a temp dir, drop an
argv-echo stub at the SELF-relative dist/server.js, run with no
SCHOLAR_SERVER_CMD and no CLAUDE_PLUGIN_DATA, and assert the module
resolves to that bundle with `--call <tool> <json>`. Verified by
execution, not construction.

Efficacy sweep over all 39 test files alongside this: 0 assertion-free
(tautological) test blocks; 0 assertions buried inside swallowed-exit
subprocess stubs (the one that existed — the transport stub — was fixed
earlier this session). tsc clean; 292 pass / 8 skip / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…tures

Fixture 4 ("viewUUID survives a root mutation") asserted via handle.getText(),
whose get_text action needs a live browser viewer; headless it enqueues to the
vendor poll queue and never returns, so the test hung to its 5s timeout. Written
in cycle 6.2 before the 2026-05-27 get_text insight landed in the contract test
("Why no C3 for get_text?") and never reconciled — masked in CI because
SCHOLAR_PDF_E2E is never set there. The fault was a broken test, not the source.

Root-cause fixes (not a flag flip):
- Fixture 4 now asserts viewUUID survival via interact({navigate}) — a
  fire-and-ack wire op that round-trips headless — on a VALID minimal PDF
  (vendor display_pdf rejects the synthetic header blob).
- Extract the valid-PDF helper to tests/util/pdf-fixture.ts; the contract test
  imports it instead of carrying a private copy.
- Un-gate fixtures 1-3 (spawn / roots.list / list_changed): protocol-shape, no
  PDF parse, fast+deterministic — they now run in every `bun test`, matching the
  header's long-standing "always run" intent. 4 + 6 stay gated.
- Fixture 5 (win32 Job Object): replace the vacuous expect(true).toBe(true)
  placeholder (a false green on win32) with test.todo.

Verified: `bun test src/server/pdf` -> 12 pass/4 skip/1 todo; SCHOLAR_PDF_E2E=1
-> 16 pass/1 todo (fixture 4 green). Full suite 295 pass/0 fail, tsc clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- test lane: remove --only-failures (no prior-run state in a fresh CI checkout,
  so it silently ran the full suite anyway); scope to `bun test src tests` to
  match the package.json test script's deterministic discovery.
- new e2e job: runs the SCHOLAR_PDF_E2E=1 pdf-child spawn fixtures (display_pdf
  round-trip, list_changed, SIGKILL+respawn) on their own signal, so a flaky
  child respawn reports against `e2e` without bailing the fast unit lane. No
  build step needed — the vendored child is committed and bun install supplies
  pdfjs-dist.

Closes the "E2E never runs in CI" residual gap from the test audit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Register the test-audit residual-gaps item 3 as a test-only code chore:
raise coverage on ollama/client.ts (listModels/healthCheck/chat success +
fallback, lines 142-178) and index.ts CLI dispatch (parseEntryArgv/readArgsJson/
runServer/runCli/main). Filed post-execution (plan-group closed); dispatched to
spec-pipeline:chore-executor (sonnet), dispatcher owns the status flip.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…dispatch

Closes chore cover-ollama-client-and-index-dispatch-unit-gaps.

TARGET 1 — src/server/ollama/client.ts:
  - embed() success via embedding field + embeddings[] fallback field
  - chat() success (message.content), response-fallback, empty-content throw
  - listModels() success, missing-models-key→[], fetch-throws→OllamaUnavailableError,
    res.ok-false→OllamaUnavailableError
  - healthCheck() ok:true, ok:false (HTTP status), fetch-throws (error message)
  All use Bun.serve fixture servers (matching the existing timeout-test pattern).
  Coverage delta: lines 69.7%→100% (all lines covered). Funcs reports 93.33%
  in Bun v1.3.14; all source lines are 100% covered. The function-boundary
  discrepancy (14/15 counted) is a Bun coverage-counter artifact — the tool
  counts 15 function boundaries in the file but every line in every method is
  executed. No source seam is needed to close the gap.

TARGET 2 — src/server/index.ts:
  - parseEntryArgv: no-flag, --call tool args, --call tool only, --call alone,
    --call tool '-' stdin marker (5 cases)
  - main() exit codes: missing args →2, missing argsSource →2,
    invalid_args_json →2, unknown_tool →2, tool_error →1
  - buildServer pdf-stub throws: interact/getText/displayPdf/setRoots all throw
    PDF_CHILD_UNAVAILABLE; isHealthy returns alive:false
  - buildServer quiet:true vs quiet:false logger branches exercised
  NOTE: runServer and import.meta.main are intentionally uncovered — runServer
  binds a live StdioServerTransport to stdin/stdout and would hang the test
  process. 85%+ line target met (85.64%) without those regions.
  Coverage delta: funcs 55.3%→81.6%, lines 77.7%→85.6%.

Gate: bun test 324 pass / 0 fail / 4 skip / 1 todo; bunx tsc --noEmit clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…5abeaf)

Dispatcher status flip after spec-pipeline:chore-executor (sonnet) landed the
work at 75abeaf: +29 tests, suite 324 pass / 0 fail / 4 skip / 1 todo, tsc clean.
client.ts lines 69.7->100%; index.ts lines 77.7->85.64%. Two non-gaps left
intentionally uncovered and recorded in the synopsis (Bun func-counter artifact;
stdio-binding runServer/import.meta.main).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The supervised-respawn fixture asserted the new child PID after a flat 1.5s
sleep ("1s backoff + 500ms slack"). But respawn has no fixed duration: the
supervisor waits BACKOFF_MS[0]=1s after onclose, then spawns a fresh child AND
completes an MCP re-handshake before activePid flips. That total intermittently
exceeds 1.5s and varies with bun version / host load — it flaked 2-of-3 under
the CI-pinned bun 1.3.11 (the version the new e2e job runs), while passing on
local 1.3.14. Masked until now because the e2e job never executed.

Root cause is the test's wall-clock assumption, not the supervisor (which
respawns correctly). Replace the sleep with a bounded poll for the new PID and
set an explicit 20s per-test timeout so bun's 5s default can't kill a slow
(but valid) respawn first. All three assertions (roots survive, alive, new
PID) are preserved — coverage is unchanged. Deterministic 5-of-5 under 1.3.11.

Verified under pinned 1.3.11 (bunx bun@1.3.11):
  e2e   SCHOLAR_PDF_E2E=1 bun test src/server/pdf  -> 16 pass / 1 todo / 0 fail
  unit  bun test src tests --bail                  -> 324 pass / 4 skip / 1 todo / 0 fail
  tsc --noEmit clean

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings June 2, 2026 22:27

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens the test suite around the slim-plugin pivot, fixes a root-cause hang in pdf-child E2E coverage, and restructures CI to isolate heavier/flakier pdf E2E fixtures from the fast unit signal.

Changes:

  • Fix pdf E2E root cause by avoiding get_text headless hangs, introducing a valid minimal PDF fixture helper, and improving respawn assertions via polling.
  • Add an isolated CI e2e job for SCHOLAR_PDF_E2E=1 pdf tests; keep the main unit lane fast and deterministic.
  • Expand/reshape unit coverage (ollama client + CLI dispatch), introduce slim-plugin packaging/provisioning scripts, and update manifests/docs accordingly.

Reviewed changes

Copilot reviewed 32 out of 39 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tsconfig.json Reformat/normalize TS config (includes/paths preserved).
tests/util/pdf-fixture.ts New shared helper to generate a minimal valid PDF + fixture root.
tests/start-server.test.ts Removes old start-server wrapper regression tests.
tests/scholar.test.ts Rehomes/expands nu wrapper tests into tests/ for the new layout.
tests/manifests.test.ts Updates manifest assertions for slim-plugin M2 launcher + hooks.
tests/build-plugin.test.ts Refocuses build-plugin tests on generated per-OS manifest output.
src/server/util/p-limit.test.ts Adds unit tests for single-slot pLimit behavior.
src/server/tools/annotations.test.ts Refactors repeated guard/rect tests into table-driven forms.
src/server/pdf/lifecycle.ts Adds slim-plugin resolution seams (child entrypoint + bun runtime), exports resolvers for testing.
src/server/pdf/lifecycle.test.ts Ungates cheap fixtures 1–3, fixes fixture 4 hang, improves fixture 6 stability (polling).
src/server/pdf/lifecycle.resolvers.test.ts Adds always-run unit tests for new resolver seams.
src/server/pdf/lifecycle.contract.test.ts Deduplicates minimal-PDF fixture by importing the shared helper.
src/server/ollama/client.test.ts Adds missing branch coverage for chat/listModels/healthCheck/embed success paths.
src/server/index.test.ts Adds coverage for CLI argv parsing + main() branches + pdf stub + quiet logger behavior.
src/server/db/sqlite-vec.ts Formatting-only changes.
skills/status/SKILL.md Adds a user-invocable “status” skill definition.
skills/ingest/SKILL.md Adds a user-invocable “ingest” skill definition.
skills/digest/SKILL.md Adds a user-invocable “digest” skill definition.
scripts/util/index.ts Refactors util exports/types and hook helper typing.
scripts/start-server.ts Removes start-server wrapper script.
scripts/build-ui.ts Updates UI build helper and its defaults.
scripts/build-plugin.ts Rewrites packaging to slim-plugin model (provisioned bun, bundled server/pdf, generated manifest).
package.json Updates scripts for slim-plugin build + CI test scoping; removes compiled-bin entrypoint.
nu/scholar.test.ts Removes old nu test location/file.
nu/scholar.nu Removes old nu module location/file.
docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md Adds the slim-plugin pivot design/spec doc with evidence/risks.
commands/status.md Removes old slash-command doc (replaced by skills).
commands/ingest.md Removes old slash-command doc (replaced by skills).
commands/digest.md Removes old slash-command doc (replaced by skills).
CLAUDE.md Updates architecture notes for slim-plugin pivot.
bin/scholar.nu Adds the new nu module location/implementation for M2 transport.
bin/launch.sh Adds POSIX launcher (ensure-bun + exec bun server).
bin/launch.cmd Adds Windows launcher (ensure-bun.ps1 + run bun server).
bin/ensure-bun.sh Adds POSIX bun provisioner (pinned bun download/unzip with lock).
bin/ensure-bun.ps1 Adds Windows bun provisioner (pinned bun download/extract with lock dir).
.gitignore Adds additional ignored build artifacts.
.github/workflows/ci.yml Splits fast unit lane from pdf E2E lane (SCHOLAR_PDF_E2E=1).
.claude/context/chores.xml Records a closed coverage-hardening chore and its scope.
.claude-plugin/plugin.json Updates dev plugin manifest to M2 launcher + SessionStart pre-warm hook.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/scholar.test.ts
Comment on lines +24 to +39
if (!Bun.which('nu')) {
await Bun.stderr.write('WARNING: nu not on PATH — running minimal grep suite')
test('scholar.nu references scholar.papers.search', async () => {
expect(SCRIPT_TEXT).toContain('scholar.papers.search')
})
test('scholar.nu references scholar.corpus.status', async () => {
expect(SCRIPT_TEXT).toContain('scholar.corpus.status')
})
test('scholar.nu references scholar.ingest', async () => {
expect(SCRIPT_TEXT).toContain('scholar.ingest')
})
test('scholar.nu references scholar.digest.generate', async () => {
expect(SCRIPT_TEXT).toContain('scholar.digest.generate')
})
process.exit(0)
}
Comment thread tests/scholar.test.ts
Comment on lines +64 to +77
test('module parses without errors', async () =>
await runScript({}, 'echo ok').then(output =>
expect(output.text().trim()).toBe('ok')
))

test('scholar subcommands are all defined', async () =>
await Promise.all(
['list', 'status', 'ingest', 'query', 'digest'].map(
async subcommand =>
await runScript({ args: [subcommand, '--help'] })
.text()
.then(text => expect(text).not.toMatch(/Error:/))
)
))
Comment thread tests/scholar.test.ts
// receives `--call <tool> <json>`. The stub RECORDS argv to a file the test
// reads back — asserting inside the stub is ineffective because nu's `complete`
// swallows the stub's exit code, so a bad invocation would not fail the test.
test('scholar transport invokes the server with --call <tool> <json> (M2)', async () => {
Comment thread tests/scholar.test.ts
// <root>/dist layout in a temp dir and confirms the SELF-relative resolution
// reaches the bundle. (Verified by execution, not construction — see the
// repeated override-only blind spot the slim pivot repoint nearly repeated.)
test('server-cmd resolves dist/server.js relative to the module (M2 production path, no override)', async () => {
Comment thread scripts/build-plugin.ts
Comment on lines +190 to +195
function generateManifest(): void {
const base = JSON.parse(readFileSync(util.subpath('.claude-plugin', 'plugin.json'), 'utf8'))
const manifest = buildManifest(base, WIN)
mkdirSync(join(DIR, '.claude-plugin'), { recursive: true })
Bun.write(join(DIR, '.claude-plugin', 'plugin.json'), JSON.stringify(manifest, null, 2))
}
Comment thread scripts/build-plugin.ts
await buildUI()
await stageVec0()
stageBin()
generateManifest()
@zaynram
zaynram merged commit 0f2838b into main Jun 3, 2026
3 checks passed
@zaynram
zaynram deleted the simplify/win32-target-install-pivot branch June 3, 2026 04:03
zaynram added a commit that referenced this pull request Jun 3, 2026
Post-merge readiness pass after PR #3. All seven plans closed and suite
green; the remaining gaps were operational + tidiness, not code.

- docs(readiness): add docs/audits/2026-06-02-maintenance-readiness.md +
  docs/runbooks/e2e-smoke-test.md (G2/G3) and HUMAN.md (operator gates).
- G1: Windows ollama.exe unreachable from WSL → deferred to HUMAN.md with
  pull commands + WSL→Windows daemon-URL caveat.
- T1: CLAUDE.md rewritten from "Pre-implementation" to shipped/maintenance
  reality; nu/scholar.nu → bin/scholar.nu.
- T2: drop spec-pipeline chore redesign-registry-schemas (status=dropped);
  desired XSD changes captured in HUMAN.md for upstream reconciliation.
- T3: dedupe skills — merge scholar-ingest→ingest, rename
  scholar-workflow→workflow (fix stale nu/ + commands/ refs).
- T5: rebuild measured win32 2.9 MB / linux 2.8 MB, both 14 files; correct
  slim-pivot spec file count 15→14 (the T3 dedup accounts for −1).
- T6: harden bin/scholar.nu bun resolution — honor SCHOLAR_BUN_PATH (parity
  with lifecycle.ts resolveBunRuntime), prefer the pinned provisioned bun,
  warn loudly on unpinned PATH-bun fallback (item-4 vec0-ABI edge).

(T4 binary cleanup — bin/mcp-scholar{,.exe}, out/scholar.heavy.plugin — was
gitignored local disk only; no tracked change.)

tsc clean; bun test src tests → 324 pass / 4 skip / 1 todo / 0 fail.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
zaynram added a commit that referenced this pull request Jun 3, 2026
… bundle migrations

First end-to-end drive of the packaged dist/server.js surfaced four init/wiring
defects that the src-mocked suite hid (it injects a pre-migrated config DB + a sync
pdf stub and never drives runServer/runCli or a stateful multi-call workflow).

- #3 production never spawned the pdf child. The async lifecycle.spawnPdfChild
  ((opts)=>Promise<PdfChildHandle>) was signature-incompatible with the sync
  BuildServerDeps.spawnPdfChild (()=>PdfChild), so no entry point wired it and ctx.pdf
  was always the throwing stub. New resolvePdfSpawnFactory() awaits the async spawn
  once (bounded by a 15s timeout so a hung MCP handshake can't block scholar's own
  initialize), then returns a sync ()=>handle closure (PdfChildHandle extends PdfChild).
  runServer wires it; runCli keeps the stub by design (--call is single-shot/stateless).
  Degrade-to-stub on failure is VISIBLE (corpus.status.pdf_child = isHealthy()), not
  silent — a degraded spawn is otherwise indistinguishable from "wiring never landed".

- #2a corpus.activate hard-failed on an absent pdf child: it committed durable state
  then threw at ctx.pdf.setRoots. Root push is now best-effort (try/catch + warn);
  the corpus is already durably active.

- #2a' activate's idempotency early-return trusted a persisted activeCorpusId, but a
  fresh runServer process has ctx.db === undefined — so activate no-op'd and never
  opened the corpus DB (every corpus-scoped tool then failed). Guard is now
  `activeCorpusId === slug && ctx.db`; currentStatusPayload's dbOpen now reflects the
  real handle (ctx.db !== undefined), not the persisted id.

- #5 the slim plugin never staged drizzle migrations into dist/. applyMigrations
  resolves join(import.meta.dir,"migrations") = <dist>/migrations in the bundle, so
  the packaged server died on the first DB op with "Can't find meta/_journal.json".
  New scripts/stage-migrations.ts copies src/server/db/migrations -> <dist>/migrations;
  wired into build:server (repo dist) and build-plugin.ts (zipped staging tree, plus
  the required-artifacts check). Also hardened resolveChildEntrypoint's no-env dev
  fallback for the bundle layout (CLAUDE_PLUGIN_ROOT path unchanged).

Verified: full suite 334/0, tsc clean. The real dist/server.js bundle driven over
stdio (host-shape) activates the real daisy-lit-review corpus to a LIVE pdf child
(pdf_child.alive=true, dbOpen=true, real corpus roots pushed). Bounded: proves
spawn+handshake+setRoots (what activate exercises); displayPdf/getText (viewer/parse)
hang headless and still need the live session.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
zaynram added a commit that referenced this pull request Jun 6, 2026
…lures (#3)

Cowork field test (2026-06-05), two restart-state issues:

#3a — corpus.status 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. Now status
surfaces an explicit `db_open` boolean and only counts when the corpus is active
AND open here; the 0 is no longer ambiguous. paper_count stays a number (no
contract change) — db_open is additive. (We deliberately do NOT rehydrate inside
status: reopenPersistedCorpus already runs once at server/CLI startup; re-running
per call would just repeat a failed open and re-log.)

#3b — when an activeCorpusId IS persisted but rehydration still can't open the
DB, every active-corpus tool (query, digest, papers, pdf — all pure ctx.db
readers with identical NO_ACTIVE_CORPUS gating) keeps failing until a manual
re-activate. reopenPersistedCorpus returned undefined SILENTLY in two of three
failure branches, leaving no trace of WHY. It now warns on each anomalous branch
(id persisted but the row is missing / archived / its DB file is absent) while
staying silent on the normal fresh-install "no activeCorpusId" branch so the
diagnostic doesn't cry wolf. This is the diagnostic, not a root-cause fix: the
wiring already calls reopenPersistedCorpus at startup in both runServer and
runCli and looks correct from static analysis, so the field symptom implies one
of these branches fires for a reason that needs the next run's logs to pinpoint.

Tests: status db_open true (active+open) / false (active, db unset) + diagnostic
warn on missing-row branch + silence on the fresh-install branch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
zaynram added a commit that referenced this pull request Jun 6, 2026
…start (#3b)

The two #3b unit tests hand-set ctx.db = undefined to prove the symptom
surface (db_open:false / diagnostic warns). They do not exercise the real
rehydration path the Cowork field report implicated ("query/digest still
require manual re-activation" after a restart).

This adds the advisor-prescribed discriminator: a second buildServer on the
same on-disk runtimeRoot, with a FRESH config-DB handle (new openWithPragmas
on the same file, not the harness-injected handle), never calls activate, and
relies solely on reopenPersistedCorpus to recover. It seeds one paper into the
prior session's corpus DB, then asserts the fresh server recovers the slug,
re-opens the on-disk per-corpus handle, reads the seeded row back, and reports
db_open:true / paper_count:1 via corpus.status.

Result: GREEN. The rehydration mechanism is sound when (a) activeCorpusId is
persisted, (b) the corpus row exists and is not archived, (c) the DB file
exists under the SAME runtimeRoot. So the field symptom is not an in-process
logic bug — it must arise from a now-warned anomalous branch (most plausibly a
runtimeRoot mismatch across the host restart → DB-file-missing branch). This
confirms #3 is correctly diagnostic-only; the new warns will pinpoint the
real-world branch on the next field run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
zaynram added a commit that referenced this pull request Nov 7, 2026
… in corpus tests; bump to v0.1.1

Move all slim-plugin launcher scripts (launch.mjs, ensure-bun.{sh,ps1},
launch.d.mts, scholar.nu) from bin/ to launcher/ for clearer separation
from the former compiled-binary era. Update all test references, the
build script, and CLAUDE.md accordingly.

Fix four Windows-only SQLite EBUSY failures in corpus.test.ts that blocked
the test suite from running cleanly after the rename:
- builtB two-server test: use `let` + null-before-GC pattern for Drizzle wrappers
- export metacharacters: skip on win32 (`"` invalid in dir names)
- Δ7 runtimeRoot test: declare builtA/configDbA outside try so finally can clean up
- Bug #3 db_open:false: register corpus DB handle via module-level tracker
  (extraRawToClose) so afterEach closes it after the full drop-GC sequence,
  avoiding zombie-state WAL locks from the async test generator still being live

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DWrHojfpbK8vz7TUWHiHY7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants