diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 4373f2a..1a8ef5e 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,27 +1,38 @@ { - "name": "scholar", - "description": "Literature review workspace. Multi-corpus reading, annotation, semantic search, Ollama-powered syntheses, and a vendored pdf MCP. Inspired by but independent of the Daisy Lit Review artifact.", - "author": { - "name": "zayn" - }, - "keywords": [ - "literature-review", - "research", - "mcp-apps", - "annotations", - "ollama", - "sqlite-vec" - ], - "license": "MIT", - "mcpServers": { - "scholar": { - "command": "${CLAUDE_PLUGIN_ROOT}/build/scholar", - "env": { - "SCHOLAR_RUNTIME_ROOT": "${HOME}/mcp-data/scholar/runtime", - "SCHOLAR_OLLAMA_URL": "http://127.0.0.1:11434", - "SCHOLAR_OLLAMA_EMBED_MODEL": "nomic-embed-text:v1.5", - "SCHOLAR_OLLAMA_CHAT_MODEL": "qwen3:8b" - } + "name": "scholar", + "description": "Literature review workspace. Multi-corpus reading, annotation, semantic search, Ollama-powered syntheses, and a vendored pdf MCP. Inspired by but independent of the Daisy Lit Review artifact.", + "author": { "name": "zayn" }, + "keywords": [ + "literature-review", + "research", + "mcp-apps", + "annotations", + "ollama", + "sqlite-vec" + ], + "license": "MIT", + "mcpServers": { + "scholar": { + "command": "/bin/sh", + "args": ["${CLAUDE_PLUGIN_ROOT}/bin/launch.sh"], + "env": { + "SCHOLAR_RUNTIME_ROOT": "${HOME}/mcp-data/scholar/runtime", + "SCHOLAR_OLLAMA_URL": "http://127.0.0.1:11434", + "SCHOLAR_OLLAMA_EMBED_MODEL": "nomic-embed-text:v1.5", + "SCHOLAR_OLLAMA_CHAT_MODEL": "qwen3:8b" + } + } + }, + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/ensure-bun.sh\"" + } + ] + } + ] } - } -} \ No newline at end of file +} diff --git a/.claude/context/chores.xml b/.claude/context/chores.xml index b6bb525..0bb09fd 100644 --- a/.claude/context/chores.xml +++ b/.claude/context/chores.xml @@ -596,5 +596,31 @@ Fix options (pick A unless reason to keep --cwd=scripts): Acceptance: `bun run build:ui` succeeds and produces `build/ui/app.html`; `bun run measure-bundle` produces `build/ui/bundle-budget.json` matching the shape `bundle.test.ts` asserts (total_kb / threshold_kb / over_budget / per_dep[]); the 3 bundle.test.ts tests go green; full suite reaches 297 pass / 8 skip / 0 fail; typecheck clean. Tier: mechanical-with-interpretation (sonnet) — picking A vs B is a 30-second judgment, the edit itself is ≤5 LOC. Single commit: `fix(build): resolve build:ui + measure-bundle without --cwd=scripts`. + + + + Closed at 75abeaf (+29 tests, suite 324 pass/0 fail, tsc clean): client.ts lines 69.7->100% (listModels/healthCheck/chat covered); index.ts lines 77.7->85.64% (CLI dispatch covered). Two reported non-gaps left intentionally uncovered: client.ts func-counter reads 93.33% as a Bun v1.3.14 artifact despite 100% line coverage; index.ts runServer()/import.meta.main bind stdio and would deadlock a unit test (no source seam warranted). ORIGINAL SCOPE: close the two low-priority unit-coverage gaps flagged by the 2026-06-02 test audit. TEST-ONLY chore: extend the two existing *.test.ts files; do NOT modify source. If a path is genuinely untestable without a source seam (e.g. a fetch-injection point), STOP and raise it via scope-maintenance rather than widening the blast-radius. + +TARGET 1 — src/server/ollama/client.ts (76.9% funcs / 69.7% lines; uncovered lines 142-178). OllamaClientImpl calls the GLOBAL fetch (no constructor / no injection seam), so mock the global fetch the same way the existing timeout tests in client.test.ts already do. Add cases: + (a) chat() success return (line 142): mock fetch to a 200 with {message:{content:'hi'}}; assert chat() resolves 'hi'. Also cover the response-fallback (line 138): mock returns {response:'x'} with no message field; assert resolves 'x'. (chat() empty-content throw and the timeout path are already covered — do not duplicate.) + (b) listModels() (145-162, fully uncovered): success returns the models array; a body with no models key returns []; fetch throws rejects OllamaUnavailableError; res.ok false rejects OllamaUnavailableError. + (c) healthCheck() (164-181, fully uncovered): res.ok true returns {ok:true,url}; res.ok false returns {ok:false,url,error:'HTTP {status}'}; fetch throws returns {ok:false,url,error:message}. + +TARGET 2 — src/server/index.ts (55.3% funcs / 77.7% lines full-suite; the uncovered region is the CLI entrypoint dispatch). index.test.ts currently covers only buildServer / withCorpus snapshot / dispatch-unknown-tool. Add cases for the dispatch surface: parseEntryArgv (line 205), readArgsJson (215), runServer (227), runCli (233), main (287). Drive main()/parseEntryArgv() with synthetic argv and assert the branch selection (serve vs cli mode, the args.json read path, the error/exit-code branches at 294-305). Mock heavy side-effects via the makeDeps() helper already present in index.test.ts; do NOT spawn a real server or pdf child. Cover the buildServer branches at 132/135/138/142 if reachable through makeDeps() variants (e.g. the quiet-logger flag). + +CONSTRAINTS: bun:test only; no new deps; no production behavior change; preserve all existing tests; do not touch chores.xml (dispatcher owns the status flip). + +ACCEPTANCE: client.ts reaches 100% funcs with listModels/healthCheck/chat fully covered; index.ts dispatch functions covered with 85%+ lines; the full suite stays green (295 pass plus the added tests, 0 fail, 1 todo, 4 skip); bunx tsc --noEmit clean. Single work commit, suggested message: `test(coverage): cover ollama listModels/healthCheck/chat + index CLI dispatch`. Print WORK_COMMIT_SHA on completion. Tier: interpretive (sonnet) — mocking the global fetch and driving the argv dispatch require judgment on the seams. Vehicle: spec-pipeline:chore-executor. + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9dad3e1..3da535b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,12 @@ jobs: run: bun run build:vec - name: test - run: bun test --bail --only-failures + # Scoped to src+tests for deterministic discovery (matches the `test` + # package.json script). --bail stops at the first failure; --only-failures + # was a no-op here (no prior-run state in a fresh CI checkout) and is dropped. + # The SCHOLAR_PDF_E2E spawn fixtures stay OUT of this fast lane — see the + # `e2e` job — so a flaky child respawn can't bail the unit signal. + run: bun test src tests --bail - name: smoke run: | @@ -42,3 +47,27 @@ jobs: db.run(r); console.log("CREATE VTAB vec0: ok"); ' + + e2e: + # The pdf-child spawn fixtures gated behind SCHOLAR_PDF_E2E (display_pdf + # round-trip, list_changed, SIGKILL+respawn). Heavier and spawn-flakier than + # the unit lane, so they run here on their own signal — a flake reports + # against this job without bailing `test`. The vendored child is committed + # (src/vendor/pdf-server/dist/index.js) and `bun install` supplies the + # pdfjs-dist it dynamically imports, so no build step is needed. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.3.11 # match scholar.bundledBunVersion + + - name: install + run: bun install --frozen-lockfile + + - name: e2e + env: + SCHOLAR_PDF_E2E: "1" + run: bun test src/server/pdf diff --git a/.gitignore b/.gitignore index 0a1d550..998fc33 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,12 @@ runtime/ .claude/scheduled_tasks.lock .claude/worktrees/** + +# Compiled server binaries + platform staging dirs — build outputs, never commit. +bin/mcp-scholar +bin/mcp-scholar.exe +win32/ +# Stray nested copy from a build script writing to a literal "home/" path. +home/ +# Backup of the deleted build-plugin.test.ts, kept locally during the refactor. +build-plugin-test-old.ts diff --git a/CLAUDE.md b/CLAUDE.md index c497a76..89a646b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,8 +21,13 @@ Chores are cross-cutting work that doesn't belong to any single §6 cycle (licen ## Architecture (target system) -- **scholar MCP server** — Bun + `bun:sqlite` + `drizzle-orm/bun-sqlite` + `sqlite-vec`, shipped as a `bun build --compile` single-file executable. Exposes corpus, ingestion, annotation, digest, prompts, search, and UI-resource tools. Spawns the vendored pdf MCP as a child. -- **vendored pdf MCP** — `@modelcontextprotocol/server-pdf@1.7.2` shipped **unmodified** under `src/vendor/pdf-server/`. Root injection rides the standard MCP `roots/list` + `notifications/roots/list_changed` protocol; scholar implements the client-side responder in `src/server/pdf/lifecycle.ts`. No source patch. +> **Slim-plugin pivot (2026-06-01):** packaging changed from a self-contained +> `--compile` binary + bundled runtime to a slim ~2.9 MB plugin. See +> `docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md`. The bullets below +> reflect the post-pivot model. + +- **scholar MCP server** — Bun + `bun:sqlite` + `drizzle-orm/bun-sqlite` + `sqlite-vec`, shipped as a `bun build --target=bun` bundle (`dist/server.js`, ~2.5 MB, **not** `--compile`). The `bun` runtime is **provisioned** into `${CLAUDE_PLUGIN_DATA}` by `bin/ensure-bun` at first launch (pinned to `scholar.bundledBunVersion` for the vec0 ABI), not shipped. A shell launcher (`bin/launch.{sh,cmd}`, manifest command `/bin/sh` | `cmd.exe`) provisions-then-runs the server (M2 — SessionStart does not block MCP spawn). Exposes corpus, ingestion, annotation, digest, prompts, search, and UI-resource tools. Spawns the pdf MCP as a child. +- **pdf MCP** — `@modelcontextprotocol/server-pdf@1.7.2`. The vendored `src/vendor/pdf-server/` tree stays in-repo **unmodified** as the §16 `.d.ts` truth source and dev fallback. For packaging it is mechanically **rebundled standalone** (`bun build --target=bun` inlines pdfjs-dist) to `dist/pdf-server/index.js` + `mcp-app.html` — no source patch. `resolveChildEntrypoint` (`src/server/pdf/lifecycle.ts`) prefers `SCHOLAR_PDF_ENTRYPOINT` → shipped `dist/pdf-server/` → vendored dev fallback. Root injection rides the standard MCP `roots/list` + `notifications/roots/list_changed` protocol; scholar implements the client-side responder in `lifecycle.ts`. - **single-file UI bundle** — React, built by Bun's HTML bundler (`bun build src/ui/index.html --target=browser`, no vite). Five views: corpus dashboard, paper detail, digest panel, reading prompts, reader progress. - **nu CLI module** — `nu/scholar.nu`, user-facing wrapper that calls scholar MCP tools and shapes responses into nu tables. - **sqlite3-mcp delegation** — query/backup/pack surfaces are delegated; scholar calls `register_db` per corpus and does **not** reimplement those tools. diff --git a/bin/ensure-bun.ps1 b/bin/ensure-bun.ps1 new file mode 100644 index 0000000..9d77e73 --- /dev/null +++ b/bin/ensure-bun.ps1 @@ -0,0 +1,49 @@ +# bin/ensure-bun.ps1 — slim-plugin runtime provisioner (Windows target). +# +# Mirror of ensure-bun.sh. Idempotently provisions the PINNED bun.exe into +# ${CLAUDE_PLUGIN_DATA}\bun (persists across plugin updates). Called +# synchronously by launch.cmd before it launches the server. +# +# ALL diagnostic output goes to stderr (Write-Error / $host.UI write to stderr; +# we use [Console]::Error) — stdout must stay clean for the MCP JSON-RPC stream. +# +# FLAGGED: not executable on the Linux dev host; validate on Windows hardware. +$ErrorActionPreference = "Stop" +$Pin = "1.3.11" # keep in sync with package.json scholar.bundledBunVersion + +if (-not $env:CLAUDE_PLUGIN_DATA) { [Console]::Error.WriteLine("ensure-bun: CLAUDE_PLUGIN_DATA unset"); exit 1 } +$BunDir = Join-Path $env:CLAUDE_PLUGIN_DATA "bun" +$BunBin = Join-Path $BunDir "bun.exe" + +function Test-Ok { + if (-not (Test-Path $BunBin)) { return $false } + try { return ((& $BunBin --version 2>$null) -eq $Pin) } catch { return $false } +} + +if (Test-Ok) { exit 0 } + +New-Item -ItemType Directory -Force -Path $BunDir | Out-Null + +# Coarse single-writer guard (no flock on Windows): a lock dir created atomically. +$Lock = Join-Path $BunDir ".provision.lock" +$haveLock = $false +for ($i = 0; $i -lt 120; $i++) { + try { New-Item -ItemType Directory -Path $Lock -ErrorAction Stop | Out-Null; $haveLock = $true; break } + catch { if (Test-Ok) { exit 0 }; Start-Sleep -Milliseconds 500 } +} +try { + if (Test-Ok) { exit 0 } + $Url = "https://github.com/oven-sh/bun/releases/download/bun-v$Pin/bun-windows-x64.zip" + [Console]::Error.WriteLine("ensure-bun: provisioning bun $Pin (windows-x64) into $BunDir") + $Tmp = Join-Path $BunDir ".dl" + if (Test-Path $Tmp) { Remove-Item -Recurse -Force $Tmp } + New-Item -ItemType Directory -Force -Path $Tmp | Out-Null + $Zip = Join-Path $Tmp "bun.zip" + Invoke-WebRequest -Uri $Url -OutFile $Zip + Expand-Archive -Path $Zip -DestinationPath $Tmp -Force + Move-Item -Force (Join-Path $Tmp "bun-windows-x64\bun.exe") $BunBin + Remove-Item -Recurse -Force $Tmp + [Console]::Error.WriteLine("ensure-bun: provisioned $(& $BunBin --version)") +} finally { + if ($haveLock) { Remove-Item -Recurse -Force $Lock -ErrorAction SilentlyContinue } +} diff --git a/bin/ensure-bun.sh b/bin/ensure-bun.sh new file mode 100644 index 0000000..3c2c2a0 --- /dev/null +++ b/bin/ensure-bun.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# bin/ensure-bun.sh — slim-plugin runtime provisioner (Linux/macOS dev + parity). +# +# Idempotently provisions the PINNED bun runtime into ${CLAUDE_PLUGIN_DATA}/bun. +# ${CLAUDE_PLUGIN_DATA} persists across plugin updates (unlike CLAUDE_PLUGIN_ROOT, +# which is replaced each version), so bun is downloaded at most once per machine. +# +# Called synchronously by launch.sh BEFORE it execs the server — this is the +# correctness guarantee that bun exists before the MCP server needs it (Claude +# Code's SessionStart hooks do NOT block MCP spawn, so provisioning cannot live +# there alone). May also be pre-warmed by a SessionStart hook; the flock below +# serializes concurrent invocations. +# +# ALL diagnostic output goes to stderr — stdout is reserved for the MCP server's +# JSON-RPC stream once launch.sh execs into it. +set -eu + +PIN="1.3.11" # keep in sync with package.json scholar.bundledBunVersion (vec0 ABI) +: "${CLAUDE_PLUGIN_DATA:?CLAUDE_PLUGIN_DATA is unset}" +BUN_DIR="${CLAUDE_PLUGIN_DATA}/bun" +BUN_BIN="${BUN_DIR}/bun" + +ok() { [ -x "$BUN_BIN" ] && [ "$("$BUN_BIN" --version 2>/dev/null || true)" = "$PIN" ]; } + +ok && exit 0 + +mkdir -p "$BUN_DIR" +# Serialize SessionStart-prewarm vs launcher invocations (avoid double-download). +LOCK="${BUN_DIR}/.provision.lock" +if command -v flock >/dev/null 2>&1; then + exec 9>"$LOCK" + flock 9 +fi +ok && exit 0 # another invocation finished while we waited on the lock + +case "$(uname -m)" in + x86_64) ARCH="x64" ;; + aarch64 | arm64) ARCH="aarch64" ;; + *) echo "ensure-bun: unsupported arch $(uname -m)" >&2; exit 1 ;; +esac +URL="https://github.com/oven-sh/bun/releases/download/bun-v${PIN}/bun-linux-${ARCH}.zip" + +echo "ensure-bun: provisioning bun ${PIN} (${ARCH}) into ${BUN_DIR}" >&2 +TMP="${BUN_DIR}/.dl" +rm -rf "$TMP"; mkdir -p "$TMP" +curl -fsSL "$URL" -o "${TMP}/bun.zip" +unzip -q -o "${TMP}/bun.zip" -d "$TMP" +mv "${TMP}/bun-linux-${ARCH}/bun" "$BUN_BIN" +chmod +x "$BUN_BIN" +rm -rf "$TMP" +echo "ensure-bun: provisioned $("$BUN_BIN" --version)" >&2 diff --git a/bin/launch.cmd b/bin/launch.cmd new file mode 100644 index 0000000..0a7cea0 --- /dev/null +++ b/bin/launch.cmd @@ -0,0 +1,20 @@ +@echo off +rem bin/launch.cmd — slim-plugin MCP launcher (Windows target). +rem +rem The plugin manifest spawns this via the always-present cmd.exe (Node/Bun +rem spawn cannot run a .cmd/.ps1 directly, so cmd.exe is the command): +rem "command": "cmd.exe", +rem "args": ["/c", "${CLAUDE_PLUGIN_ROOT}\\bin\\launch.cmd"] +rem +rem 1. ensure-bun.ps1 provisions the pinned bun.exe synchronously (its stdout/ +rem stderr go to stderr; 1>&2 guards stdout for the MCP JSON-RPC stream). +rem 2. Launch bun.exe dist\server.js — its stdio is inherited through cmd. +rem +rem FLAGGED: cmd.exe has no exec-replace, so bun.exe runs as a child of this +rem cmd. If Claude Code does not tree-kill the MCP process on shutdown, bun may +rem orphan and hold runtime\scholar.lock. Validate tree-kill on Windows hardware; +rem mitigate with a Job Object on the cmd side if orphaning is observed. +setlocal +powershell -NoProfile -ExecutionPolicy Bypass -File "%CLAUDE_PLUGIN_ROOT%\bin\ensure-bun.ps1" 1>&2 +if errorlevel 1 exit /b 1 +"%CLAUDE_PLUGIN_DATA%\bun\bun.exe" "%CLAUDE_PLUGIN_ROOT%\dist\server.js" %* diff --git a/bin/launch.sh b/bin/launch.sh new file mode 100644 index 0000000..9c6c22b --- /dev/null +++ b/bin/launch.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# bin/launch.sh — slim-plugin MCP launcher (Linux/macOS). +# +# The plugin manifest spawns this via an always-present shell: +# "command": "/bin/sh", "args": ["${CLAUDE_PLUGIN_ROOT}/bin/launch.sh"] +# Using /bin/sh (not the script directly) sidesteps the zip executable-bit +# problem, and `exec` below REPLACES this shell with bun — so the PID Claude +# Code spawned BECOMES the server (no orphaned wrapper, lock released on kill). +# +# 1. ensure-bun provisions the pinned runtime synchronously (correctness gate). +# 2. exec bun dist/server.js — scholar then runs UNDER the provisioned bun, so +# process.execPath is that bun (the pdf child inherits it) and +# CLAUDE_PLUGIN_ROOT resolves dist/pdf-server + vec0 with no extra env. +set -eu +# Invoke ensure-bun via `sh` (not directly) — the zip does not preserve the +# executable bit, so neither launch.sh nor ensure-bun.sh can rely on +x. +sh "${CLAUDE_PLUGIN_ROOT}/bin/ensure-bun.sh" +exec "${CLAUDE_PLUGIN_DATA}/bun/bun" "${CLAUDE_PLUGIN_ROOT}/dist/server.js" "$@" diff --git a/bin/scholar.nu b/bin/scholar.nu new file mode 100755 index 0000000..dfe89a5 --- /dev/null +++ b/bin/scholar.nu @@ -0,0 +1,134 @@ +#!/usr/bin/env -S nu --stdin +# Usage: nu scholar.nu +const SELF = path self + +def --wrapped "safe extract" [ + ...rest: string + --select # Use `select` over `get`, i.e. to return a table instead of a list +]: oneof -> oneof { + let value = $in + if ($value | describe) == string { + $value + } else if $select { + $value | select --optional ...$rest + } else { + $value | get --optional $rest.0 ...($rest | skip 1) + } +} + +# Resolve the M2 server invocation. The slim-plugin pivot (2026-06-01) dropped +# the compiled `mcp-scholar` binary; scholar now runs as `bun dist/server.js`, +# dispatched in CLI mode via `--call ` (see src/server/index.ts). +# Resolution order: +# 1. SCHOLAR_SERVER_CMD — space-separated override (test/operator escape hatch, +# mirrors SCHOLAR_PDF_ENTRYPOINT / SCHOLAR_BUN_PATH / SCHOLAR_VEC0_PATH). +# 2. the provisioned bun (${CLAUDE_PLUGIN_DATA}/bun/bun) running +# ${CLAUDE_PLUGIN_ROOT}/dist/server.js, located relative to this module +# (nu/scholar.nu → plugin root); falls back to a PATH `bun` for dev. +def server-cmd []: nothing -> list { + if 'SCHOLAR_SERVER_CMD' in $env { + return ($env.SCHOLAR_SERVER_CMD | split row ' ' | where {|t| $t | is-not-empty }) + } + let root = ($SELF | path dirname | path dirname) + let provisioned = ($env.CLAUDE_PLUGIN_DATA? | default '' | path join 'bun' 'bun') + let bun = if ($provisioned | path exists) { $provisioned } else { 'bun' } + [$bun ($root | path join 'dist' 'server.js')] +} + +# Wrapper for the scholar MCP server (M2: `bun dist/server.js --call`). +def main [ + tool?: string # The name of the tool to call on the server + --json: oneof # Parameters to pass through to the tool call +]: oneof -> oneof { + if $tool == null { print --stderr 'tool name is required' | return } + let args = $in | default $json | default {} + let payload = if ($args | describe) == 'string' { $args } else { $args | to json --raw } + let cmd = (server-cmd) + let output = run-external ($cmd | first) ...($cmd | skip 1) '--call' $tool $payload + | complete + | default 0 exit_code + | default '{}' stdout stderr + let text = if ($output.exit_code) == 0 { $output.stdout } else { $output.stderr } + try { $text | str trim | to json --raw } catch { $text } +} + +# List papers in the active corpus (uses ctx.db snapshot — no corpus_id arg). +def "main list" [ + --limit: int = 50 # Maximum number of results to return + --query: string = '' # Filter string to query results with +]: nothing -> oneof { + let res = {q: $query limit: $limit} | main papers.search + if ($res | describe) == string { return $res } + if ($res.still_indexing? | default false) { + print "note: semantic index still building; results are lexical only" + } + $res.hits? | default [] | select id title score +} + +# Show corpus status. +def "main status" [ + corpus?: string # The identifier of a corpus to target (defaults to active ) +]: nothing -> oneof { + if ($corpus | is-empty) { {} } else { {corpus_id: $corpus} } + | main scholar.corpus.status +} + +# Ingest papers from BibTeX/RIS/DOI/arXiv. +# Routes to scholar.ingest.{bibtex,ris,doi,arxiv}. +def "main ingest" [ + corpus: string # The identifier of the corpus to ingest papers into + --bibtex: string # Path to a BibTeX paper to ingest + --ris: string # Path to a RIS paper to ingest + --doi: string # Direct DOI of a paper to ingest + --arxiv: string # arXiv identifier of a paper to ingest +]: nothing -> oneof { + if ($bibtex | is-not-empty) { + {file_path: $bibtex corpus_id: $corpus} + | main scholar.ingest.bibtex + | safe extract imported + } else if ($ris | is-not-empty) { + {file_path: $ris corpus_id: $corpus} + | main scholar.ingest.ris + | safe extract imported + } else if ($doi | is-not-empty) { + {doi: $doi corpus_id: $corpus} + | main scholar.ingest.doi + } else if ($arxiv | is-not-empty) { + {arxiv_id: $arxiv corpus_id: $corpus} + | main scholar.ingest.arxiv + } else { + error make "one of `--bibtex`, `--ris`, `--doi`, `--arxiv` is required" + } +} + +# Search papers (hybrid lexical + semantic via RRF — mode always-on, no mode arg). +# still_indexing=true signals semantic is building; lexical results are returned in the interim. +def "main query" [ + q: string # The query string to match results to + --limit: int = 50 # Maximum number of entries to return +]: nothing -> oneof { + # args: { q: string; limit?: number } — corpus_id and mode DROPPED per extraction-003 contract + main list --limit $limit --query $q +} + +# Generate digest on a scoped set of papers. +def "main digest" [ + --all # Include all papers (default) + --stale # Include only stale papers + --label: string # Include papers by section label + --hash: string # Include papers by selection hash + --claude # Use Claude for running the inference instead of Ollama +]: nothing -> string { + let scope = match {all: $all stale: $stale section: $label selection: $hash} { + {all: true} => 'all' + {stale: true} => 'stale' + {section: $s} if $s != null => $'section:($s)' + {selection: $h} if $h != null => $'selection:($h)' + } | default all + let res = {scope_key: $scope use_claude: $claude} | main scholar.digest.generate + if ($res | describe) =~ table and $res.askClaude? == null { + $res | get --optional body_md | default "(empty body)" + } else { + "digest requires claude opt-in; run with `--claude` or use the Cowork host UI." + } +} diff --git a/commands/digest.md b/commands/digest.md deleted file mode 100644 index ccd76c9..0000000 --- a/commands/digest.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: scholar:digest -description: Generate a synthesis digest for the active corpus scope (Ollama default; --claude opt-in). ---- - -# /scholar:digest - -## Usage - -``` -/scholar:digest -/scholar:digest --scope section:methods -/scholar:digest --scope stale -/scholar:digest --claude -``` - -## Arguments - -| Argument | Type | Default | Description | -|---|---|---|---| -| `--scope` | string | `all` | One of `all`, `stale`, `section: