Work · Repository
retrieval-augmented-generation
Evidence-first literature RAG for small local models: code controls search, evidence, verification and the run log
- Python
- MIT licence
- 1 post
- 53 merged PRs
- 1 star
Posts about it
README
Evidence-first literature research with small local language models. Code controls search, evidence, verification, abstention and the run log; the model only fills in narrow, schema-constrained forms. Every claim in an answer cites a verbatim passage from a full-text paper, and claims that fail a check are removed and counted rather than softened.
The method is described in A RAG protocol that makes the model show its work. The design document gives the rationale, the literature behind each rule, and a table mapping every rule to the code that enforces it and the test that checks it.
[!IMPORTANT] This does not make a language model truthful. It narrows the paths by which unsupported claims reach an answer and makes the remaining uncertainty visible. Read the known limits before relying on an answer.
What it does
There are two ways to use it:
- The pipeline (
research-pipeline ask) answers a question end to end with a local model: plan, search, fetch open-access full text, retrieve and rerank passages, extract evidence, synthesise claims, search again for null results, verify, grade, and writeanswer.mdplus arun.jsonthat records every search, passage, model digest and verdict. - The evidence tools (
rag__*over MCP) let a stronger client model (Claude, ChatGPT) write the answer while this repository holds it to the same deterministic rules: evidence only from the paper library’s passage index, quotes that must occur in the cited passage, and numbers that must occur in the cited evidence. These tools do not judge entailment; the pipeline’s verifier models do. - The quantity tools (
math__*over MCP) give a client model constants and equations to cite instead of recall:math__lookupsearches the research corpus’s calculator records (projects/*/calculators/*.md, found through$RESEARCH_CORPUSor a siblingresearch/checkout) and returns their sections verbatim with the corpus commit;math__bionumberreturns a BioNumbers entry by BNID, verbatim, fetched once and cached. - The shared workbench makes the same gateway available to ChatGPT, Claude, Codex, OpenWebUI and other MCP clients. Completed pipeline runs write a compact, review-required session capsule; research results and code changes cross into repositories only as pull-request proposals.
The pipeline reads general role briefs from PIPELINE_AGENT_PROFILES_DIR and optional private
extends: researcher briefs from PIPELINE_AGENT_EXTENSIONS_DIR. It records the selected file
versions and uses their short Pipeline guidance sections in planning and synthesis without
relaxing evidence checks. Configure both directories locally; see MCP clients.
Finding and indexing papers is not done here. That is the paper library, paper-fetch, reached over MCP: it searches the open-access providers, knows how each scientific discipline is indexed (a profile: its MeSH terms and synonyms), remembers past searches, keeps project collections, stores legal full text, and owns the passage index that retrieval reads. This repository tells it the field and the concepts, then does everything that happens after a passage is found: reading it, judging it, and checking every claim made from it.
| paper-fetch (search and indexing) | this repository (evidence) |
|---|---|
| provider search, discipline profiles, search memory, collections | question planning (with the profile’s vocabulary) |
| open-access fetching, storage, provenance | extraction, study-design classification |
| passage index: chunking, BM25, embeddings, optional cross-encoder | synthesis, verification, grading, critique |
| fetch ordering by relevance to sub-questions | quote, number and retraction checks; the answer and run log |
What each rule guarantees, and what it does not:
| Rule | Enforced by |
|---|---|
| A claim can only cite evidence retrieved in this run | synthesis schema enum, then checked in code |
| A quote must occur in the stored passage | verify.anchor_quote: exact match, or a near-identical repair that may not change a negation or a number |
| A number in a claim must occur in its cited evidence, with a matching unit where the field declares units | verify.unsupported_numbers; a failing claim is removed |
| Verifier disagreement is shown, not averaged | verify.settle → DISPUTED |
| A passage describing another paper is a pointer, not evidence | model judgement plus a citation-marker heuristic that can only demote |
| Retrieved text addressing an AI reader is excluded | an English pattern list: catches careless cases, not a determined adversary |
| Retracted sources support nothing | OpenAlex flag at fetch, Crossref/Retraction Watch at answer time |
| The bibliography is printed from stored records | render.py; the model never types an author, year or DOI |
Requirements
- Python 3.11+ and uv
- The paper library, paper-fetch, over MCP.
Install it with its
mcpandretrievalextras, and give it an embedding model for hybrid retrieval (PAPER_FETCH_EMBED_MODEL=bge-m3, about 1.2 GB in Ollama); without one, retrieval is lexical. - For local-model runs, Ollama with a text model (default
qwen3:4b-instruct-2507, about 2.5 GB). Sized for a machine with 16 GB of memory running one model at a time. Behind MCP the calling model does this work instead.
Install
git clone https://github.com/polarizetech/retrieval-augmented-generation.git
cd retrieval-augmented-generation
uv sync
ollama pull qwen3:4b-instruct-2507
cp config/rag.env.example config/rag.env
cp config/mcp-gateway.example.json config/mcp-gateway.json
uv tool install "paper-fetch[mcp,retrieval] @ git+https://github.com/polarizetech/paper-fetch"
ollama pull bge-m3
echo "PAPER_FETCH_EMBED_MODEL=bge-m3" >> ~/.config/paper-fetch/retrieval.env
paper-fetch-mcp must be on your PATH, or its absolute path in config/mcp-gateway.json.
Reranking is paper-fetch’s cross-encoder: install paper-fetch[rerank] and set
PAPER_FETCH_RERANK_MODEL (see its README); without it passages are read in retrieval order.
Point the plugin at your gateway. The plugin in plugin/scientific-research-rag ships with the placeholder URL https://<your-gateway-host>/retrieval-augmented-generation. Set it to your own gateway’s public base URL (the same value as MCP_PUBLIC_URL, see MCP clients) with python scripts/configure_plugin.py https://your-host/retrieval-augmented-generation, or by putting MCP_PUBLIC_URL in config/rag.env and running the script with no argument, or by editing the url in both plugin/scientific-research-rag/.mcp.json and mcp.json by hand. The plugin will not connect until this is set. Local stdio use (the “As an MCP server” section) does not need it.
Use
uv run research-pipeline index # have the library index the full texts it holds
uv run research-pipeline ask "Does exercise training lower resting blood pressure in adults?"
uv run research-pipeline ask --domain cardiovascular "..." # the field's rules and vocabulary
uv run research-pipeline ask --collection my-review "..." # search, fetch and read in a collection
uv run research-pipeline ask --offline "..." # indexed corpus only: no search, no downloads
uv run research-pipeline status
Each run writes runs/<timestamp>-<slug>/answer.md and run.json. An online run fetches
open-access papers into the paper library; PIPELINE_MAX_FETCH bounds how many. Every search is
remembered by the library, so a later run on the same concept is told what earlier ones found.
MCP runs also write session.json and capsule.md, and index the client, project, strictness and
run location in data/pipeline/sessions.sqlite. The capsule carries the checked bottom line,
promotion candidates, companion records and exact provenance; it is never automatically added to
the trusted research corpus. session__propose sends it through the research repository’s
branch-and-PR gate when a human chooses to preserve it.
Set PIPELINE_VERIFIER_MODEL to a model from a different family than the text model. Without it
the text model checks its own claims, and every answer says so.
Choose explore, grounded (default), or publication with the strictness argument to
pipeline__research_start. Publication mode refuses to start unless a verifier independent of
the claim-writing model is configured. The response reports checks and remaining risk; it does
not claim a calibrated probability of hallucination.
Companion tools: datasets and patents
A run can loop in another tool when the question calls for it. The planner is told what each configured companion is for and may request it, with queries, in the plan it already writes; code then calls the tool and prints what its own records say. No model writes that section, and it never counts as evidence for a claim.
Two companions ship. Both are off until enabled under companions in
config/mcp-gateway.json, and each is asked only when the planner judges that the question calls
for it; most questions call for neither.
datasetsasks dataset-fetch’srecommend(it needs a dataset-fetch with that tool) for datasets that could test the question, and adds a “Datasets that could test this” section: title, catalogue, licence, files, subjects, DOI, a pinned reference and why it was listed. Nothing is downloaded or assessed.patentsruns patent-fetch’spatent-fetch --json searchwhen the question is about a device, a method or another invention, and adds an “Existing patents on this” section: title, publication number, year, applicants or inventors, classes and a link, one entry per invention: the titles closest to the question, then the most recent of the rest. Nothing is fetched or read, and it is not a legal opinion: the section says so, and the limits name every patent service that was not asked or did not answer. Without a patent service account, patent-fetch can only search life-science patents up to 2012; the answer says that too.
The gateway also exposes patent-fetch’s full lifecycle as patents__*: search, fetch a selected
publication into the private library, inspect the normalized record, and read its description or
claims. The dataset upstream similarly exposes its complete reproducible search, describe,
file-list, fetch-plan, table-read, series and screening tools. These source records remain distinct
from passage-grounded scientific evidence.
Adding another tool is one entry in research_pipeline/companions.py: an MCP server or a command
line that prints JSON.
Novelty probe: has someone already done this?
uv run research-pipeline novelty --id CAND-0007 "The candidate claim, written out in full" \
--established "the closest established terminology" \
--queries "phrasing A" "phrasing B" "phrasing C" "phrasing D" \
--research-dir ../research # or set RESEARCH_REPO
An adversarial prior-art search. Its null hypothesis is that the claim is already published, and it tries to prove that:
- It searches every index the paper library federates, once per phrasing. At least five phrasings are required, one of them in the field’s established terms.
- It fetches the nearest open-access papers in full.
- It puts each retrieved passage to the verifier with the candidate as the claim.
A search hit is not prior art; a passage that states the claim is. There are four verdicts:
| Verdict | Meaning |
|---|---|
PRIOR_ART |
Every verifier accepts a passage, its quote is found in the stored text, and every number in the claim is present in it. |
PARTLY_KNOWN |
A passage states a weaker or narrower version, or the verifiers disagree. |
INCONCLUSIVE |
An index refused, the run was offline, or fewer than three of the nearest works could be read. |
CANDIDATE |
None of the above. It describes only the works read, not the literature. |
The dossier (prior-art.md, plus the full run log under runs/) is written into the research
repository at novelty/<ID>/, next to the corpus it concerns. The command refuses any directory
that does not carry that repository’s marker files. The dossier never announces a discovery. It
does quote the statement as given, and reports what the earlier any-hit rule would have said,
alongside what the reading found.
As an MCP server
For Claude Desktop or Claude Code, run the gateway over stdio (no port, no token):
{
"mcpServers": {
"research-rag": {
"command": "/absolute/path/to/retrieval-augmented-generation/.venv/bin/research-rag-gateway",
"args": ["--config", "/absolute/path/to/retrieval-augmented-generation/config/mcp-gateway.json"]
}
}
}
It exposes rag__search, rag__retrieve_evidence, rag__check_citations, rag__save_report,
the paper library as papers__*, the whole pipeline as pipeline__*, patents and datasets,
session capsules, the research-repository proposal gate, and an organization-scoped GitHub
adapter. Through MCP the pipeline
uses the calling model (Claude, ChatGPT) for its model steps by default: code runs every stage and
hands the client batches of tasks with a JSON schema to answer, and Ollama is only needed for
embeddings. See MCP clients for the workflow and the HTTP transport.
Remote clients (claude.ai, ChatGPT) use the plugin or a connector pointed at your public URL; see “Point the plugin at your gateway” above.
Every tool call is recorded in a hosted Postgres database, and each reply links to its record and to the page of any research doc it mentions, with every call that refers to that doc. See the call log for setup and for moving the database.
Domains
The engine is domain-neutral. What a field knows (which study designs count and in what order,
which databases are authoritative, what a unit means, what may not be generalised) lives in a
separately versioned package under domains/, discovered through an entry point. The engine
never imports one; a policy is data and is written into run.json.
uv pip install -e domains/cardiovascular
uv run research-pipeline ask --domain cardiovascular "Does higher baroreflex sensitivity predict lower cardiovascular mortality?"
| Domain | What it adds |
|---|---|
cardiovascular |
Cardiac, vascular and autonomic evidence; a surrogate is not an outcome. |
respiratory |
Breathing, gas exchange and the chemoreflex; lung function is not a clinical endpoint. |
vestibular |
Balance and dizziness, graded by diagnostic accuracy rather than by trial. |
neuroscience |
The nervous system, with the species gap and reverse inference as failure modes. |
Writing your own: domains.
Extensions
An extension is a separately installed package that adds MCP tools and ask steps to the gateway, so you can build your own research-rag without editing this repository. Its one rule: it never changes evidence, retrieval, verification, grading or another step’s results, and its output lives under its own key. Writing one: extensions.
Evaluation
uv run python benchmarks/research/verifier_bench.py # does the verifier reject what it should?
uv run python benchmarks/research/eval_pipeline.py # end-to-end cases, scored from run logs
Both are scored without an LLM judge. The seed sets are small (7 verifier pairs, 4 questions): they are smoke tests and templates, not accuracy estimates. See benchmarking.
Development
uv sync --group dev
uv run pytest --cov # offline: no Ollama, no network
uv run ruff check . && uv run ruff format --check .
uv run pyright
CI runs the same checks on Python 3.11 to 3.13.
Security
Ollama stays on loopback. The local gateway transport also defaults to loopback; when
MCP_PUBLIC_URL is configured it serves OAuth 2.1 authorization with PKCE and an owner consent
key, while TLS remains the front end’s responsibility. Repository writes are bounded separately:
the research and GitHub tools can create branches and pull requests, but cannot merge or write a
default branch. Retrieved papers and repository contents are untrusted input, and profile Markdown
is hashed and routed as data rather than executed as instructions.
Agents can be sandboxed with OpenShell. OpenShell’s telemetry must be off
from the gateway’s first start. That is a hard requirement: scripts/openshell-telemetry-check.sh
checks it.
License
Changelog
Pin paper-fetch at f7c6746 for per-request rerank and embed routes
Bumps paper-fetch from 7001d78 to f7c6746 (polarizetech/paper-fetch#17): rerank_route / embed_route, PAPER_FETCH_RERANK_DEFAULT and PAPER_FETCH_RERANK_LOCAL_MODEL. Without it, ask’s providers={"rerank": ...} fails on the droplet. uv lock --upgrade-package paper-fetch changed only paper-fetch.
Tests: 585 passed, 1 failed (tests/test_pipeline.py::test_no_panel_means_no_comparison, which also fails on main). The 4 test_models_service.py failures on main pass with this pin.
After merge the droplet gets PAPER_FETCH_RERANK_DEFAULT=off: reranking only when an ask asks for it.
🤖 Generated with Claude Code
Skip the fresh search for chatter and repository questions
Quick asks ran a SearXNG search on the message verbatim, so chatter (“approved, go ahead”) and questions about a repo returned junk leads.
config/routing.default.toml: new[fresh] chatterphrase list.research_mcp/routing.py:Rules.chatterandis_chatter().research_mcp/ask.py: quick asks skip_freshfor chatter or whenrepois passed, with aFresh search: skipped (...)progress line. Passage retrieval unchanged.tests/test_ask.py: two tests for the skips.
Tests: tests/test_ask.py and tests/test_routing.py pass (71). The full suite has 5 failures (4 in test_models_service.py, 1 in test_pipeline.py) that fail identically on main.
🤖 Generated with Claude Code
Add an example of what the research tool sends back
What
docs/example-rag-response.md: one example question taken through every call a client model makes (ask on the research route, pipeline__research_continue while running and when done, and ask on the quick route), in the JSON layout the code builds, with placeholder data. It ends with Where the length comes from, a short analysis of why replies are long (the same passages three times, a relay that reports process rather than findings, fixed boilerplate, bookkeeping fields).
Personal paths and real account balances from the original draft are replaced with placeholders (<agents-dir>, ~/.local/share/..., $XX.XX).
Note
The example shows the relay / relay_full reply format from when it was written (early November 2026). ask now returns a compact brief with answer_format, so the Call 1 / 1b shapes are partly out of date; the length analysis is what motivated that change. Docs only.
🤖 Generated with Claude Code
Document sandboxing agents with OpenShell, telemetry off
What
docs/openshell.md: what OpenShell is, a by-hand macOS install with no Homebrew (v0.1.8 release assets, checksums, VM-driver entitlement, mTLS certs, LaunchAgent), how a sandbox reaches the research tool (host.openshell.internal:8891), and caveats.- Hard requirement: telemetry off from the first gateway start. Set by
OPENSHELL_TELEMETRY_ENABLED=falseplus a dead localOPENSHELL_TELEMETRY_ENDPOINT. scripts/openshell-telemetry-check.sh: fails unless the env file has both settings, every runningopenshell-gatewayhas the switch in its environment, and no OpenShell process is connected to NVIDIA’s telemetry host.- README: a short pointer to both.
Docs and a shell check only; no code paths change. The script passes sh -n; it has not been run against a live gateway in this PR.
🤖 Generated with Claude Code
Route research only when asked; choose providers per request
Scope: scope/smart-routing-providers.md (Tier: explore). Depends on polarizetech/paper-fetch#17 (deploy it first) for embed / rerank = modal, mac or droplet; the rest works without it.
Changes
- F1 research only when asked.
config/routing.default.tomlresearch triggers are now evidence-asking phrases (“is it true”, “what does the evidence say”, “systematic review”, …); bare nouns such as “paper”, “study”, “cite”, “evidence”, “mechanism” route to a quick retrieval. Server instructions no longer tell assistants to start runs on their own. - F2 explore tier. Claims are still checked; the bottom line and specialist views skip the verifier, are kept, and are labelled “Explore tier: not checked against the claims.”
- F3 per-step providers.
askandresearch_starttakeproviders={planning|extraction|writing|verify: <[providers.*] name> | client}. A pinned step uses that provider alone, no fallback.clientfor the ladder steps must cover all three;verify=clienthands only the claim checks to the caller. -
F4 retrieval routing. providers.embed= modalmac and providers.rerank= modalmac droplet off, passed through to paper-fetch; deploy/models_router.pyhonoursX-Models-Route(only the named upstream, 503 if it fails, 400 if unknown). - F5
rerank = llm. Newresearch_mcp/llm_rerank.py: one chat call scores up to 12 passages 0–10.
Review notes
llm_rerank.OFFSET = 5maps the 0–10 mark onto the cross-encoder’s logit scale so the existing relevance floor (-3) and coverage levels apply. This calibration is exploratory, not from a paper.- When a pinned retrieval route fails, the library breaker is not counted, but the existing no-reranker / no-embeddings fallback can still run (labelled degraded), unlike the router’s strict 503 for a pin.
Tests
584 passed locally.
🤖 Generated with Claude Code
Remove personal deployment details; placeholder plugin URL with a setup script
What
- Plugin URL:
plugin/scientific-research-rag/.mcp.jsonandmcp.jsonnow shiphttps://<your-gateway-host>/retrieval-augmented-generation. Newscripts/configure_plugin.pysets the real URL from an argument,MCP_PUBLIC_URL, orconfig/rag.env, and refuses an empty, non-https or placeholder value. The README’s Install section (“Point the plugin at your gateway”) explains the script and the manual edit. - Provider ladders:
config/hub.default.tomlships OpenRouter then local. NEAR AI is still defined and joins a ladder fromconfig/hub.toml.tests/test_hub.pyand the docs (hub-plan.md,mcp-clients.md) match. - Names: a private node name removed from
docs/call-log.md, a private repo name from a test comment.
Checks
uv run pytest -q tests/test_hub.py tests/test_agent_profiles.py: 59 passedruff checkandruff format --check: cleanconfigure_plugin.py "<x>"exits 2; with an https URL it rewrites both filesgit grep tailc463aeis empty.tests/test_calllog.pystill uses the example hostpolarize-mcp.example.ts.net.
Operators who relied on the NEAR AI rung should add it back in their own config/hub.toml.
🤖 Generated with Claude Code
Add PIPELINE_RANKER so the calling model can judge passage relevance
What
PIPELINE_RANKER=library(default, unchanged) keeps the paper library’s cross-encoder.PIPELINE_RANKER=clientretrieves withrerank=Falseinask(gateway) and in pipeline runs (pool()). Passages come back unscored, so the relevance floor and coverage levels drop out, and theunscoredcoverage note now tells the calling model to judge each passage itself. Pipeline runs note that the reranker was off.- Documents client-only claim checks:
PIPELINE_MCP_LLM=clientwith an emptyPIPELINE_VERIFIER_MODEL(no code change needed; runs are marked “no independent verifier”).
Why: the local reranker (torch on MPS) and MiniCheck each take about 7 GB on the Mac and were behind 40 s retrieval timeouts. This lets the calling model do both for now, with the local models kept as options.
Checks
uv run pytest -q tests/test_pipeline.py tests/test_ask.py: 55 passedruff checkandruff format --check: clean- New test:
test_the_ranker_setting_reaches_the_library_retrieval - Not covered by a test: the gateway’s
clientbranch itself (checked by hand thataskcallsretrieve(query, limit, 1800)).
🤖 Generated with Claude Code
Make ask replies conversational, with a short tools-and-services footer
What changes
answer_format(research_mcp/brief.py): conversational replies, 2 or 3 sentences when possible, short lists when longer. No narration of what didn’t match, was skipped or wasn’t relevant. Ends with a footer: Tools (steps that ran), Services (provider, model, balance; plusLibrary: no match/weak match), and the links.brief.used(new): the reply’s progress steps minus skipped / not run / left out ones, and the usage line (plus the research model when a run is attached).- Coverage notes for weak and none now say “note it in the footer”, not “say so first”.
- research_mcp/ask.py: the full reply carries
usage; the three “says no passage applies before answering” next-steps are removed. - research_mcp/gateway.py: server instructions match.
Out of scope: the full relay (detail="full") and the research pipeline’s own relay.
Checks
pytest: 539 passed, 2 skippedruff check .: clean- Coder check (code-level diff check): passed
The gateway needs a restart after merge for chats to see the new format.
Source: reply wording (owner’s stated preference).
🤖 Generated with Claude Code
Route model calls through an ordered list of providers, the Mac first
What changed
Models router (deploy/models_router.py). The router on the droplet took one primary (Modal) and one fallback (the Mac). It now takes an ordered list of providers:
MODELS_PROVIDERSis a comma list of names. The default islocal,modal, so the Mac comes first and Modal second.- Each provider reads
MODELS_<NAME>_URLand, optionally,MODELS_<NAME>_PROXY. - Any provider that answers 402 or 429, or can’t be reached, sits out for
MODELS_COOLDOWN_SECONDSwhile the next one serves. When every provider is out, all are still tried in order. GET /router/statusnow returnsorder,usingandout_for_seconds.- The old
MODELS_PRIMARY_URL,MODELS_FALLBACK_URLandMODELS_FALLBACK_PROXYsettings still work and mean modal, then local.
Tests. Five router tests replace the primary/fallback test. They cover the default order, the cooldown, all providers out, the legacy settings, and the error when a provider’s URL is missing.
Docs. docs/models-service.md describes the new settings. This branch also carries an earlier commit that adds the Mac’s memory use and a Cost section (Modal plans and the DigitalOcean GPU droplet price) to the same file.
Why
Modal’s monthly credit ran out in November and the Mac has served since. A list of providers lets the Mac be the default and lets another provider be added by configuration. The next step is DigitalOcean serverless inference for the reranker and bge-m3. On 100 real passages from the paper index, its scores matched ours: the reranker to within 1.1e-5 with the same top 5, and bge-m3 at a cosine similarity of at least 0.9996.
For reviewers
- Deploying alone changes nothing on the droplet. It still uses the legacy settings, which keep Modal first. It goes Mac-first only once its settings switch to
MODELS_PROVIDERS. - Behaviour change: a 402 or 429 from the last provider tried now gives the router’s 503 instead of that provider’s own error.
- Tests: the full suite passes (540) and ruff reports nothing.
🤖 Generated with Claude Code
Add a DigitalOcean provider to the models router
Stacked on #68 (the ordered provider list). Its base is claude/models-providers; once #68 merges, GitHub retargets this PR to main.
What changed
DigitalOcean provider (deploy/models_router.py). A provider with MODELS_<N>_KIND=digitalocean serves reranking and embeddings from DigitalOcean’s serverless inference (https://inference.do-ai.run, models bge-reranker-v2-m3 and bge-m3).
/rerankgoes to DigitalOcean’s/v1/rerank. The answer comes back as{"scores": [...]}in document order, the same shape the Mac and Modal return. The model name paper-fetch sends is replaced with DigitalOcean’s./v1/embeddingsand Ollama’s/api/embed(which the hub calls) go to/v1/embeddings. DigitalOcean’s vectors aren’t unit length (about 26), while Ollama’s are, so the router scales them to unit length.- Every other call goes to the next provider without putting DigitalOcean out: the claim checker’s
/api/chat,/api/tagsand/api/ps. - 401, 402, 403 and 429 put DigitalOcean out for the cooldown. Serverless inference is prepaid, so an empty balance falls back to the next provider.
MODELS_<N>_KEY_FILEsends a provider’s own key in place of the caller’s. The key is never logged.MODELS_<N>_EMBED_MODELandMODELS_<N>_RERANK_MODELset the model names; the defaults arebge-m3andbge-reranker-v2-m3.
Tests. Eight new tests cover:
- the request mapping;
- calls DigitalOcean doesn’t serve;
- the score order;
- unit-length scaling in both response shapes;
- the swap to DigitalOcean’s own key;
/api/chatpassing on to the next provider;- falling back on a 402;
- the settings read from the environment.
The app-level tests use httpx.MockTransport. fastapi and httpx join the dev group, and uv.lock is updated, so CI can run them.
Docs. docs/models-service.md gains a DigitalOcean section and DigitalOcean’s prices under Cost: $0.01 per million tokens for the reranker and $0.02 for bge-m3, prepaid.
Why
Modal’s monthly credit ran out. DigitalOcean serves the same two models per token, with no GPU to wake, for cents a month.
Checks
uv run pytest -q: 548 passed.ruff format --checkandruff checkare clean.- Live check on 2026-11-23. The router ran on the Mac with
MODELS_PROVIDERS=digitalocean,local:
| Call | Result |
|---|---|
/rerank, 20 real passages |
Same scores as the Mac’s full-precision reranker to within 7.8e-6; DigitalOcean took 1.2 s, the Mac 3.7 s |
/api/embed |
Unit-length vectors, cosine similarity of at least 0.99977 with Ollama’s |
/v1/embeddings |
Unit length, in the OpenAI shape |
/api/tags |
Passed through to the Mac |
- An earlier direct comparison on 100 passages matched to within 1.1e-5 (reranker) and a cosine of at least 0.9996 (bge-m3).
For reviewers
- Deploying alone changes nothing on the droplet. It needs
MODELS_PROVIDERS=digitalocean,local,modaland a DigitalOcean model access key inMODELS_DIGITALOCEAN_KEY_FILE. That key hasn’t been created yet. - The claim checker (bespoke-minicheck) is unaffected. It still goes to the Mac, then Modal.
🤖 Generated with Claude Code
Say how to restart the gateway where it runs
Why
Error replies (library and indexing failures in ask, the gateway’s tool errors, and the bridge’s “can’t reach the gateway”) ended with launchctl kickstart -k gui/$(id -u)/com.polarizetech.research-rag, the Mac’s LaunchAgent. The gateway has run on the droplet under systemd since 2026-11-17, so that advice was wrong, and today a session asked for the droplet to be restarted because of it.
What changes
research_mcp/hub/contract.py:restart_hint()readsGATEWAY_RESTART_HINTwhen a reply is made. Without the setting, it falls back to the Mac’s command (DEFAULT_RESTART_HINT). This replaces the hard-codedRESTART_HINT, which was duplicated inbridge.py.research_mcp/ask.py,research_mcp/gateway.py: userestart_hint().research_mcp/bridge.py:restart_advice(url)gives the local command when the gateway is on this machine, and otherwise says “restart it on, where it runs". config/rag.env.example: documents the setting, with the droplet’s value.- Tests:
- the hint follows the setting;
- the bridge names a remote host;
- the existing hint asserts now use
restart_hint().
After merge
On the droplet, add GATEWAY_RESTART_HINT=sudo systemctl restart research-rag research-rag-public to config/rag.env, update the checkout, and restart both gateways.
Checks
535 tests pass, plus ruff check, ruff format and pyright (0 errors).
🤖 Generated with Claude Code
Skip passage retrieval for code asks in the explore tier
Why
Prototype builds were slow. Across 238 scope-related sessions since Nov 10, rag__retrieve_evidence ran 6,144 times at a median of 26.5 s each (about 60 h), and ask ran 3,070 times at 13.5 s. Most of that time went to gathering evidence, not to writing code.
What
research_mcp/ask.py: a code-route ask withstrictness='explore'skips passage retrieval. The progress line says “Retrieval: skipped (explore tier)”.groundedandpublicationare unchanged.research_mcp/gateway.py: adds a description to thestrictnessschema property.tests/test_ask.py: addstest_an_explore_code_task_skips_retrieval.
The client-side rules and guard for the explore tier live in ~/.claude, outside this repo, and are already in place.
Checks
uv run pytest: 534 passedruff checkandruff format --check: cleanpyright research_mcp/ask.py: 0 errors
The change takes effect on the droplet only after this is merged and deployed.
🤖 Generated with Claude Code
Rerank on the Mac's GPU with PyTorch MPS
The Mac fallback reranked on the CPU (int8 onnxruntime), about 36 s for 50 passages under load, so projects hit the 40 s retrieval limit while Modal is out.
TorchRerankerindeploy/models_service.py: bge-reranker-v2-m3 in PyTorch on MPS, chosen withRERANK_BACKEND=torch(RERANK_DEVICE,RERANK_TORCH_REPO). The ONNX path is unchanged and stays the default (Modal).- Docs bullet in
docs/models-service.md.
Checked on the Mac: scores -4.239, -10.884, -11.041, identical to onnx/model.onnx; 50 passages in 3.7 s. ruff and tests/test_models_service.py pass.
Exploratory, in the user’s words: “Mark the GPU reranker exploratory and apply it”.
🤖 Generated with Claude Code
Wake the Modal GPU only for asks that use the models
Why
November’s Modal spend reached about $40. The model app cost $15–16 a day from 18 November, against an estimate of about $27 a month. The droplet’s logs for 19 November show 1,946 tool calls spread over 21 of 24 hours.
The cause: every ask woke the hosted models and waited for them, even code: asks that never touch a model. Every session start woke them too. With a 10-minute idle window, an L4 stayed up about 20 hours that day.
What changes
research_mcp/gateway.py:askclassifies the question first and wakes and waits for the models only when its mode uses them (MODEL_MODES: quick, research, fetch).list_toolsno longer wakes them at session start.
deploy/modal_models.py:scaledown_windowgoes from 600 to 300 s. After more than 5 idle minutes, the next ask waits for a cold start, about 30–50 s.tests/test_remote_models.py: quick and fetch asks need the models; acode:ask doesn’t.
The automatic fallback to the Mac when Modal is out is in polarizetech/retrieval-augmented-generation#63. Both PRs edit deploy/modal_models.py, in different places.
After merge
- Update the droplet (git ff,
uv sync, restart both gateways). - Run
modal deploy deploy/modal_models.pyonce the budget is back.
Checks
531 tests pass, plus ruff check, ruff format and pyright (0 errors).
🤖 Generated with Claude Code
Fall back to the Mac's models when Modal is out
What this does
Modal’s model service ran out of budget and started answering HTTP 429 (“Input rate limit (0/s)”), which took down passage retrieval and the verifier. This adds an automatic fallback to the same models on the Mac.
deploy/models_service.py: the model service as one portable file. It serves Ollama’s API (bge-m3, bespoke-minicheck), plus/rerankfor bge-reranker-v2-m3, behind the bearer key. Modal serves it on a GPU, and the Mac runs it withuv runnext to its native Ollama. The reranker loads on first use and is dropped after 10 idle minutes. It’s loaded from real files in one folder, because onnxruntime refuses the hub cache’s symlinkedmodel.onnx_data.deploy/modal_models.py: serves that same app (add_local_fileandcreate_app) instead of its own copy. The models and their scoring are unchanged.deploy/models_router.py: runs on the droplet at127.0.0.1:8895.- It tries Modal first. On a 402 or 429, or when Modal can’t be reached, it uses the Mac for
MODELS_COOLDOWN_SECONDS(900), then tries Modal again. GET /router/statussays which side is serving.- Only the Mac-bound client uses
MODELS_FALLBACK_PROXY(tailscaled’s loopback proxy; the droplet stays in userspace mode). Neither client reads proxy settings from the environment, so paper and web fetches can’t reach the tailnet.
- It tries Modal first. On a 402 or 429, or when Modal can’t be reached, it uses the Mac for
tests/test_models_service.py: the router’s switching, and the reranker loading on use and dropping when idle.docs/models-service.md: the set-up on each host.
Already live
- The droplet runs the router from
/home/rag/models-router/until this merges. Its three model URLs point at the router, with.before-routerbackups kept. - The Mac runs the service, published tailnet-only on port 8896.
- With Modal still answering 429,
rag__retrieve_evidenceandaskreturn passages through the Mac.
Not yet verified
modal deploywith the shared file: waits until the Modal budget is back.- minicheck through the fallback in a research run.
Checks
532 tests pass, plus ruff check, ruff format and pyright (0 errors).
🤖 Generated with Claude Code
Add ask fetch mode and delegate/strict autonomy
Why
ask asked too many obvious questions (“fallback or stop?” whenever a component failed, “should I fetch/index this paper?”), and any request mentioning a paper ran the whole research pipeline.
What changed
Fetch mode
routing.py/config/routing.default.toml: newfetchmode. Prefixesfetch:andpaper:, a[fetch]trigger list (“get the paper”, “index this paper”, …), or a DOI together with get/fetch/download/index/add (FETCH_VERBS). A DOI on its own (e.g. in a code task) does not route to fetch.ask.py: fetch mode indexes DOIs andpmid:ids withrag__index_paper. A title is searched withpapers__search(limit 3), the top hit is indexed, and the other two are listed as “if this isn’t the paper you meant”. No pipeline, no specialist, no fresh search.gateway.py:call_for_askroutes the ask’srag__index_papercall to the built-in evidence store (it isn’t an upstream tool). Addsfetchto the mode enum and a sentence to the server instructions.
Autonomy
hub/contract.py:AUTONOMY = ("delegate", "strict"),MUST_ASK = ("library", "verifier").ask.py:ask(autonomy=...). Underdelegate(the default) a failing component takes its labelled fallback and the degraded problem is recorded; library and verifier still ask; a session “stop” still wins.strictkeeps today’s behaviour.brief.py: under delegate, the answer format tells the assistant to fetch and index up to five fresh leads and retrieve again; the strict text is unchanged.gateway.py: default from envASK_AUTONOMY(defaultdelegate);autonomyin ask’s inputSchema; delegate instruction sentence.docs/mcp-clients.md: paragraphs on fetch mode and the two autonomy modes.
Notes for reviewers
- Behaviour change on deploy: the default becomes
delegate, so the reranker, embeddings, provider, github and corpus failures no longer stop to ask. SetASK_AUTONOMY=stricton the droplet to keep the old behaviour. - arXiv ids and PMCIDs are not recognised yet (no pattern was specified).
tests/test_hub.py’sRig.asknow defaults toautonomy="strict", since those tests cover asking; delegate is covered in the newtests/test_autonomy.py.- A title fetch uses the hit’s
openalexwork id when it has no DOI.
Checks
uv run pytest -q: 530 passeduv run ruff check .: passeduv run ruff format --check .: 109 files already formatteduv run pyright: 0 errors (1 existing warning,psycopgimport)
🤖 Generated with Claude Code
Point the plugin at the droplet's public gateway
The plugin still named the old Mac host (polarize-mcp), which no longer serves research-rag. It now names the droplet’s public gateway, https://research-rag.tailc463ae.ts.net/retrieval-augmented-generation (OAuth with dynamic client registration, scope rag:use). The plugin version goes to 0.3.1 so installed copies pick up the change.
Checked: the endpoint answers 401 with resource_metadata, and its protected-resource and authorization-server metadata name the same URL.
🤖 Generated with Claude Code
Read each specialist's routing keywords from its own brief
What this does
The core stops carrying anyone’s specialist vocabulary.
- Where the words live now: a brief’s frontmatter names the words that recruit it:
anchors: any one word;anchor_combos:a + b/c, a word from each group, combos separated by;;anchor_unless:w=b, wherewdoesn’t count besideb;domain: the route’s domain when that brief leads.
- Reference stubs: a stub’s keys win over its source’s.
- Briefs without keys: they are still anchored by every distinctive part of their name, as before.
- Removed:
SPECIALIST_TERMS,RAMP_MOTION_WORDS,STRING_SOUND_WORDS,RELATIVE_MAP_WORDS,RELATIVE_METHOD_WORDS, the name-by-name anchor rules and the hard-coded neuroscience domain. The words have moved into the private briefs that use them.
Checks
- Lint and types: ruff and ruff format are clean; pyright reports 0 errors.
- Tests: pytest passes 509, including 4 new tests for the keys. The fixture briefs now carry their keywords as the real ones do.
- Routing comparison: old and new routers, side by side on the real public and private briefs (29 briefs):
- 922,761 word combinations, 0 differences in the anchor test;
- 157 example questions, 0 differences in specialists, domain or roles.
🤖 Generated with Claude Code
Make an ask wait for a hosted model service that is waking up
Why
The Modal model service scales to zero. A cold container takes about 13 s to start and about 35 s to load bge-m3. An ask sent in that window, such as the first ask in a new session or after more than 10 idle minutes, ran into the 40 s retrieval limit and came back as needs_decision.
What
research_mcp/gateway.py:
wake_hosted_models()now records its in-flight request in an event that is set when the request ends, whatever the outcome.models_ready()waits on that event, and returns at once when nothing is in flight.- Before an
askruns, the gateway wakes a hosted Ollama if it has been idle, the same wake-up a new session sends at most once a minute, then waits for any wake-up in flight. Modal answers that request only after the container has started and loaded bge-m3, so retrieval finds the models ready.
There are no new settings: the wait is bounded by the wake-up request’s existing 300 s timeout. A local Ollama (no key) is never woken or waited on.
tests/test_remote_models.py: the wait returns at once with nothing in flight, holds while a wake-up is in flight, and ends when it finishes.
Checked
- ruff, format, pyright clean; full suite: 544 passed, 2 skipped.
- On the droplet, running this branch, with Modal forced to zero containers: a session opened the way
~/.claude.jsonstarts it and asked at once. The ask waited for the service, then answered in 52 s with strong coverage and 5 passages. Before this change, the same ask timed out at 40 s.
Sources
none, exploratory (owner: “Yes, exploratory”; “fix the cold start too”).
🤖 Generated with Claude Code
Move the Polarize code out of the core into an extension package
What this does
The core no longer carries anyone’s own tools. Everything Polarize-specific leaves it and is rebuilt on the extension API (phase 1, #54) in a separate package:
- Extension API, widened (first commit):
- Steps can run
early(after routing, carried into the deadline reply),before_retrieval(and ask for a quick request’s retrieval to be skipped) orafter. - A step can set the summary’s closing limits line.
- An extension can add
math__tools under a shared prefix, never taking a core tool’s name, and can claim one top-level brief key with its ownanswer_formatnote. Context.config_pathgives an extension the gateway’s config file.- Core version 0.4.0.
- Steps can run
- The move (second commit): the sign and audio mixers and physical mixing, polarize-clock’s sky key and sun sight, the polarize tools, and project rules all leave the core, along with their routing sections, config, docs and tests.
- They run as four extensions in a separate package.
- Their tool names are unchanged.
brief.project_ruleskeeps its place through a brief key.
The core now has 15 built-in tools and no Polarize code, routing words or config.
What changes for a client
With the package installed, the tools and replies are the same, except that the results of those steps move under brief.tool_results.extensions.<name>.<step>. Without the package, the core runs as a general research-rag.
Checks
ruff check,ruff format --check: clean.pyright: 0 errors.pytest: 503 passed, 87.3% coverage.- No
polarize-rag/path in either commit.
The step-by-step history of the move (one module at a time, each line compared with its original, and a coder check after every step) is kept in the package’s own repository.
🤖 Generated with Claude Code
Load minicheck in the background so a cold Modal container serves sooner
Why
PR #56 made the Modal container load its models at start. But it loaded bespoke-minicheck (about 90 s) before serving anything, so even embeddings waited on it. A cold session that waited 45 s after opening still hit the 40 s retrieval limit.
What
deploy/modal_models.py: the container loads bge-m3 and the reranker, then starts serving. minicheck loads in a background thread, so only a claim check that arrives before it finishes waits for it.
Checked
- ruff, format and
tests/test_remote_models.pypass. - Deployed to Modal and tested cold, from zero containers: a session opened the way
~/.claude.jsonstarts it, waited 30 s, then asked. The ask answered in 24 s with strong coverage and 5 passages. Before this change, the same test timed out.
Still open
An ask sent within roughly 15 s of opening a session can still meet the 40 s limit while the container starts (about 13 s) and bge-m3 loads (about 35 s).
Sources
none, exploratory (owner: “Yes, exploratory”).
🤖 Generated with Claude Code
Hide the Modal cold start: load models at start, wake them per session
Why
A Modal container that had scaled to zero answered only once its models had loaded from the volume on first use. Measured: container up in 13 s; first bge-m3 embedding 35 s; first minicheck call 90 s. So the first ask after an idle spell ran past the 40 s retrieval limit in research_mcp/ask.py.
What
deploy/modal_models.py: the container loads bge-m3, then bespoke-minicheck, as it starts, and Ollama keeps them loaded (OLLAMA_KEEP_ALIVE=-1). Requests never wait on a model load.research_mcp/gateway.py:wake_hosted_models(). When a client lists tools, which every session does as it starts, the gateway wakes a hosted Ollama with a backgroundGET /api/version. It does this at most once every 60 s, and never for a local Ollama (no key). Errors are ignored.tests/test_remote_models.py: the wake-up is sent once with the key, not again within 60 s, again after, and never without a key.
Checked
- ruff and format pass; full suite: 543 passed, 2 skipped.
Not covered
An ask sent within about a minute of opening a session, or after more than 10 idle minutes inside an open session, can still meet a cold container.
Sources
none, exploratory (owner: “Yes, exploratory”): no paper behind the 60 s interval or the 300 s wake-up timeout.
🤖 Generated with Claude Code
Run the models on Modal: hosted Ollama with a key, and a GPU model service
What
Moves the gateway’s three models off the Mac onto a Modal GPU service, and lets the pipeline and hub call an Ollama that needs a key.
- Keyed Ollama (
research_pipeline/config.py,llm.py,research_mcp/hub/health.py,overlap.py):PIPELINE_OLLAMA_KEY/PIPELINE_OLLAMA_KEY_FILEaddAuthorization: Bearer …to every Ollama call. No key means no header, so local setups are unchanged. The key is kept out ofrepr. deploy/modal_models.py: a Modal app servingbge-m3andbespoke-minicheckthrough Ollama (/api/*,/v1/*);- the
bge-reranker-v2-m3cross-encoder atPOST /rerank({query, documents}→{scores}), the form paper-fetch’s hosted reranker reads.
It runs on a GPU (L4 → A10 → T4 fallback) and loads the full-precision reranker from real files in the volume, because onnxruntime refused the cache symlinks for the external weights. One container takes up to 8 overlapping calls and stays up 10 idle minutes. Every request needs the bearer key (401 otherwise).
config/rag.env.example: documents the two new settings.tests/test_remote_models.py: no key → no header; key read from file and not in repr; pipeline and hub send the header.
Checked
- ruff and format pass; full suite: 542 passed, 2 skipped.
- Against the Mac’s models: same Ollama digests; embeddings cosine 0.99998; 401 without the key.
- Reranker: CUDA provider; 24 passages in 0.6–2.6 s warm (the int8 file took 66 s on the GPU). Its top 5 and top 10 match the int8 CPU reference exactly; the top 3 share 2 of 3, and the single top result differs.
- End to end through the droplet gateway: warm asks take 5–11 s with strong coverage and the fresh search. A cold start (first call after 10 idle minutes) can still pass the 40 s retrieval limit.
Sources
The key plumbing is housekeeping. The owner marked the reranker loading, the concurrency (8) and the idle window (600 s) as exploratory; no paper is behind those settings.
Not in this PR
The droplet’s own config (gateway service, tailnet serve, allowed hosts) lives on the droplet, not in the repo. The README and OpenShell files in the working tree are left out on purpose.
🤖 Generated with Claude Code
Add an extension API so anyone can build their own research-rag
What
An extension API for the gateway. Installed rag-ext-* packages (entry point rag.extensions) can add:
- MCP tools under their own prefix (
<prefix>__<tool>); core prefixes such asrag,papers,pipelineandpolarizeare reserved. asksteps that run when their trigger words appear in a question (extra words can come fromconfig/routing.toml). A step’s result lands inresults["extensions"][<ext>][<step>]and reaches clients asbrief.tool_results.extensions.
It mirrors the existing domain loader in research_pipeline/domains.py: name prefix, core_requires version gate, declare(), discover().
Why
The core should stay a public, general tool. Personal or project-specific features can then live in separate packages that build on it, rather than in this repo. This is phase 1 of that plan. Moving the Polarize, sky and mixer pieces out into their own extension package is a later PR.
The one rule
An extension only adds. It works on a deep copy of results, so it can’t change evidence, retrieval, verification, grading, coverage or another step’s output. A step that raises is recorded as {"error": ...} with a progress line; ask carries on.
Changes
research_mcp/extensions.py(new):declare,discover,loaded,get,matches, and theContext/ToolSpec/StepSpec/StepInput/StepOutputtypes.research_mcp/routing.py:[extensions.<name>]trigger-word tables.research_mcp/ask.py: runs matching steps after the Polarize step; theirfound,next,for_youand relay lines appear in the reply.research_mcp/gateway.py: discovers extensions and lists and dispatches their tools. Gateway config gains adisabledlist and a per-extension config section;gateway_statusgainsextensionsrows (ok,undeclared,incompatible,error,disabled,clash). Tools are refused whenbuiltin_toolsis false.docs/EXTENSIONS.md,docs/extension-template/, README section, config examples.- Core version
0.3.0(uv.lockunchanged).
For reviewers
- Extension steps don’t run on requests
askanswers early (for example the profiles list). They also don’t show in a reply that is still pending when the hub deadline passes; their output reaches the final reply in the ledger. - No paper backs this design: it’s the owner’s own engineering choice. The Gewaltig & Cannon (2014, doi:10.1371/journal.pcbi.1003376) note on plugin support is cited as background only.
Checks
ruff check, ruff format --check, pyright (0 errors; the existing psycopg warning remains), and pytest: 566 passed, 2 skipped (live clock), coverage 87%.
🤖 Generated with Claude Code
Send each polarize project's binding rules with every ask reply
Sessions in the polarize-* projects keep breaking the owner’s rules, but they do call ask. So ask now carries the project’s rules.
What changes
- New
research_mcp/project_rules.py. For a request from a configured project ([project_rules]in the routing config:polarize-*), it reads that project’s rules from its local checkout on every call:- the bold-led rules in
AGENTS.mdandCLAUDE.md, with the owner’s marked “(owner, date)”; - the rule sections of the owner’s shared profile, polarize-thesis
.claude/agents/polarize-integrator.md.
- the bold-led rules in
- A rule that appears in both places is listed once, and the duplicate is noted.
- Reply: the rules go first, in
brief.project_rules. The five nearest the request come in full; the rest are one line each withfile:line. - Instructions:
answer_formatnow starts with the rules. They bind before anything else; a conflict means stop, name the rule and ask; the reply ends with a Rules checked: line. - Exceptions: set aside only by explicit wording (
exception_words: “make an exception to”, “break the rule”, …) that names the rule, and only for that request. Wording that names no rule sets nothing aside, andfor_youasks which rule. - Which project:
ask’sproject, else its repo name, else the client’s folder (the ledger shows Claude Code sessions already arrive taggedpolarize-mixer,polarize-holo, …). - New tool:
rules__project(project, question)returns the same thing directly. Server instructions mention both. - Other:
PROJECT_RULES_DIRSadded torag.env.example; README and docs/mcp-clients.md updated.
Size: a polarize-mixer reply carries 66 rules (31 the owner’s), about 23 KB.
Tests: 10 new tests in tests/test_project_rules.py; the built-in tool count goes to 25. 538 tests pass; ruff and pyright are clean.
🤖 Generated with Claude Code
Add Claude Code cloud sessions to the hosting notes
Adds a dated section to docs/hosting-options.md on Claude Code cloud sessions:
- Cost: no separate machine charge; sessions count against the Claude plan’s usage limits.
- Machine: about 4 vCPU, 16 GB RAM, 30 GB disk; pauses when idle; no ports.
- Setup: GitHub App, environment, network secrets, setup script.
- Fit here: code changes and tests fit; research runs don’t, because the VM can’t reach this machine’s services. research-rag works as a claude.ai connector while the Mac is awake.
- Alternative: Remote Control keeps everything local.
Docs only.
🤖 Generated with Claude Code
Search papers through SearXNG on quick answers, not the library
Fixes quick answers stopping with “Retrieval took longer than 40 s” after #46/#47.
Cause: paper-fetch’s MCP tools are plain synchronous functions, so its server runs them one at a time. The fresh papers__search that #46 ran beside retrieval took 30 s or more uncached and held up the retrieval queued behind it, including other sessions’. After the restart, two live quick questions in a row stopped at the 40 s retrieval limit.
Fix: quick answers no longer call the paper library’s search. The fresh paper leads come from SearXNG’s science engines (arXiv, PubMed, Europe PMC, Semantic Scholar), which return paper links in about a second, and web leads from SearXNG’s general category. The paper library serves only retrieval. The fresh search’s limit drops to 20 s. Research runs are unchanged (they search the library sequentially).
Tests: 528 passed. A test asserts the quick route calls only retrieve on the library.
Follow-up for paper-fetch: run its tools in a thread (or make them async) so one slow search can’t block other callers.
🤖 Generated with Claude Code
Add a polarize tools step: pinned repo reads and holo renders
ask can now answer questions about polarize-holo, -mixer, -particle, -physics and -clock from their own repos, and render audio with polarize-holo. It follows the sky and mixer pattern.
Questions
- Routing words in
[polarize_tools](config/routing.default.toml), one list per tool. askreads README.md and TOOL.toml at each named tool’s newest release tag throughrepos__read_file, falling back togit show <tag>:<path>on the local checkout, plus arepos__search_codesearch (default branch, said in the result). Every file comes back with its tag and commit.- Pins found live (from the local checkouts): holo v0.4.0 (6 commits past it), mixer v0.2.0 (2 past), particle v0.1.0 (38 past), physics v0.4.0 (at HEAD). polarize-clock has no local checkout, so it’s read at its default branch and the answer says it isn’t pinned. A question about polarize-clock with no place no longer triggers the sky-key prompt.
Audio
- With holo named, an audio word and a render’s name,
askruns that holo render. Without a render name it lists them. - The render folder is copied out of holo’s git history with
git archive(at the tag when it’s there, else HEAD, said in the result), and holo’s ownrender_*.pyruns on the copy withuv run. Holo’s checkout is never written to, and the gateway makes no sound itself. - The
uvenvironment is cached outside the output, keyed by the render’s lock file. - The result reports holo’s version and commit, the render’s tool pins, the exact command, each WAV (path, rate, bits, channels, length), any JSON settings and other outputs.
- Script arguments come from the script’s
usage:line: OUT_DIR is the run folder; SUN_AZ_DEG comes from polarize-clock when the request gives a place.
Gateway tools: polarize__read, polarize__renders, polarize__render.
Config: paths come from POLARIZE_TOOLS_DIR (default: the folder beside this repo), POLARIZE_<TOOL>_DIR, POLARIZE_RENDER_DIR and POLARIZE_UV. No home-directory paths in code.
Tests: 522 passed (13 new, on throwaway git repos with a uv shim); ruff and pyright are clean.
Live check: the guitar-pluck render (HEAD, own pinned project) produced two 24-bit 48 kHz WAVs, byte-for-byte identical to holo’s committed files.
Known issue, not changed here: the running gateway’s repos__read_file and repos__search_code both returned HTTP 500 (gh itself can read the repo), so reads currently use the local-checkout fallback.
🤖 Generated with Claude Code
Add a model panel: other models read the same passages
Lets OpenAI (and Gemini) run alongside the research pipeline’s own model, so answers can be compared.
PIPELINE_PANEL=openai,gemininames hub providers (new[providers.openai]and[providers.gemini]inconfig/hub.default.toml).- Search, fetch and passage choice run once. Each panel model reads every passage the run’s model read, in the same order, and drafts its own claims. Panel reading runs on its own API in parallel with local verification of the run’s claims, then every model’s claims go through the same local verifier.
- The answer is unchanged except for a new Model comparison section, computed and never written by a model. It shows per-model counts, passages read in opposite directions, and each verified claim marked with the other models that reached it on the same passages.
- Members with no key, or whose calls fail, are named and skipped. OpenAI’s 30-day retention is stated in the limits of any answer it took part in. The run log keeps each member’s evidence, claims, calls, tokens and cost under
panel.
Live: Gemini 4 Carbon answered through OpenRouter’s zero-retention routing (served by Google, about $0.0014 a call). It rejects “reasoning off”, so it runs with its default reasoning. OpenAI isn’t tested live yet: it needs a key in ~/.config/polarize/openai.key, and the model id gpt-6.1-sol is taken from OpenRouter’s catalogue, not checked against OpenAI’s API.
Tests: 515 passed; ruff and pyright are clean.
🤖 Generated with Claude Code
Give the fresh scholarly search the retrieval time limit
Live, the fresh scholarly search in a quick answer ran past its 25 s limit (library retrieval beside it took 16 s), so no papers were listed. This gives it the same 40 s limit as retrieval, inside the 45 s reply deadline.
🤖 Generated with Claude Code
Search the indexes and the web on every request
Answers said “the library has no passage on this” without looking anywhere else. Now every request searches outside the library:
- Quick answers (
ask): alongside the library retrieval, a freshpapers__searchand a SearXNG web search run in parallel. The brief carries them asfresh_search(titles and links, marked unread and not citable). When coverage is partial, weak or none, the answer lists the closest as Fresh leads and suggestsresearch:. - Research runs: after the scholarly searches, the pipeline web-searches the question and its first planned queries in SearXNG’s science and general categories (
PIPELINE_WEB_QUERIES, default 4;PIPELINE_WEB_HITS, default 8). Result URLs go topapers__leads, and every paper they link to becomes a fetch candidate. Web pages are never evidence. Web results are logged underweb, and Limits says what the search added. - A search that fails or isn’t configured is named, and the answer carries on.
research_pipeline/web.pyis shared byweb__search,askand the pipeline.
Tests: 509 passed; ruff and pyright are clean. Live check: SearXNG’s science category returned arXiv, Europe PMC and DOI links, and the running library’s papers__leads read identifiers from them.
🤖 Generated with Claude Code
Route instrument and string questions to musical-acoustics
What this changes
research_pipeline/agent_profiles.py: anchor terms for the newmusical-acousticsspecialist (guitar, violin, fretboard, strum, pluck, flageolet, soundboard, overtone, timbre and their forms).- “string” anchors it only beside a vibration word (vibrating, vibration, tension, tuning, bowed, instrument), so “parse this string” stays on the general route. “musical” needs “instrument”.
- “resonance”, “pitch”, “note”, “tone” and “harmonics” alone are left out: hearing, neural and signal questions use them.
tests/test_agent_profiles.py: one test covering five instrument questions, three that must not route, and one that must still go to signal-processing.
Checks
pytest tests: 504 passed, 2 skipped.ruff checkandruff format --checkclean on both files.- Routed ten sample questions against the real brief: six instrument questions reached
musical-acoustics, and the FFT, intermodulation, spheromak and data-type questions kept their existing routes.
Goes with
The brief itself is in a pull request on polarizetech/polarize-agents (branch claude/musical-acoustics-profile). Until that merges the terms match no profile and change nothing.
🤖 Generated with Claude Code
Say nothing was retrieved when listing profiles
The profile list reply ended with the quick-answer line “These are passages, not a checked answer”, but nothing is retrieved for a list. It now says “Nothing was retrieved.” The ask test checks it.
🤖 Generated with Claude Code
Let up to three specialists answer one question
What changes
- Up to three specialists per question. Profiles named in the question come first. Then the best-scoring anchored profile joins, then any other anchored profile scoring within 6 of it (two shared words). The cap is three.
- Recruit by name. “ask classical-mechanics”, “@plasma-toroids” and “plasma toroids” each recruit that profile. The
[profiles]words inconfig/routing.tomlstill work. Unknown names are reported in the reply. - A paragraph from each.
- Research runs gain a Specialist views section. A new
specialist_viewstep writes one to three sentences per specialist, using only the verified claims. - Each sentence is judged against its claims like the bottom line. A sentence that outruns its claims is dropped, and the answer says how many were dropped.
- Quick replies carry
brief.specialists, andanswer_formatasks for one short paragraph per specialist.
- Research runs gain a Specialist views section. A new
- List the profiles. “Which profiles are available?” (and similar, in
[profiles_list]) returns every specialist with a one-line summary, without retrieving anything. - With several specialists, guidance reaches the prompts labelled by profile. With one, the prompts and the prompt-version hash are unchanged.
Checks
- ruff, ruff format, pyright: clean.
- pytest: 503 passed, including:
- routing across three fields;
- naming profiles and unknown names;
- the catalogue;
- the ask brief and the profile list;
- a pipeline run where one specialist sentence is dropped.
- On the real profile checkouts, “How does bone conduction change the auditory brainstem response latency?” now routes to both bone-conduction-auditory and auditory-evoked-potentials.
🤖 Generated with Claude Code
Follow sky-clock's rename to polarize-clock
sky-clock is renamed polarize-clock with no compatibility alias (polarizetech/sky-clock#27, released as v0.4.0). Merge after sky-clock#27.
What changed
SKY_CLOCK_URL→POLARIZE_CLOCK_URL(the data server’s address; default stillhttp://127.0.0.1:8803), and the live-test switchSKY_CLOCK_LIVE→POLARIZE_CLOCK_LIVE.- Server instructions, the
sky__*tool descriptions, replies, README and docs name polarize-clock and linkpolarizetech/polarize-clock.source.toolin replies is"polarize-clock". - Tool names kept:
sky__key,sky__measure,sky__locate(they name the sky, not the tool). “sky key” and “sky clock” still trigger it; “polarize-clock” / “polarize clock” now do too.
Checks
ruff check, ruff format --check, pyright on the changed files, and pytest: 495 passed, 2 skipped (the live checks).
When merging: nothing goes dark if
- No env var to change for the gateway itself. The deployed gateway (
com.polarizetech.research-rag→start.sh) doesn’t setSKY_CLOCK_URL; it uses the defaulthttp://127.0.0.1:8803. If you ever setSKY_CLOCK_URLelsewhere (a shell profile, an MCP client config), rename it toPOLARIZE_CLOCK_URL: the old name is no longer read. - The data server on :8803 must keep running. It is the launchd agent
com.polarizetech.sky-clock-key, which runspython -m sky_clock.serverfrom thesky-clock-servecheckout. Once that checkout moves to v0.4.0 the module ispolarize_clock.server: update the plist’sProgramArguments(and anySKY_CLOCK_*keys) and reload it at the same time, orsky__keyanswers “polarize-clock didn’t answer”.
🤖 Generated with Claude Code
Route motion, friction and drag questions to classical-mechanics
Routing for the new classical-mechanics specialist (polarizetech/polarize-agents, the companion PR).
Anchor words: friction, frictional, drag, incline, inclined, kinematics, tribology, stick-slip, restitution, projectile(s), free-body, coefficient-of-friction.
Guarded words:
- “drag” doesn’t count beside “drop”, so drag-and-drop UI questions stay out.
- “terminal” counts only with “velocity”.
- “ramp” counts only beside something that moves on it (ball, block, cart, cylinder, roll, slide), so ramp signals stay with signal-processing.
Left out alone: “energy”, “motion”, “force”, “momentum” and “rolling”. Neural, plasma, signal and optimizer questions use them too.
Tests:
- New:
test_classical_mechanics_routes_motion_not_ui_signals_or_optimisers, with five positive routes and four negatives. - The full suite passes (495), as do ruff and pyright.
Checked against the real briefs:
| Question | Specialist |
|---|---|
| “physics and conservation/transfer of energy, ramp and drag dynamics, motion and friction” | classical-mechanics |
| “Build an Arduino rig with a photodiode to time a ball rolling down a ramp” | macgyver |
| “Generate a ramp signal and compute its FFT” | signal-processing |
| “Implement drag and drop in the web app” | none |
| A spheromak merging question | plasma-toroids |
🤖 Generated with Claude Code
Route DIY rig questions to the macgyver specialist
Adds routing for the new macgyver profile (polarizetech/polarize-agents#9) to SPECIALIST_TERMS.
- Anchors: macgyver, diy, arduino, esp32, breadboard, homemade, household, makeshift, photodiode, contact-mic, plasma-ball and plasma-globe.
- Word pairs: plasma + ball and plasma + globe also count, the way bone + conduction does, because people write them with a space.
- Left out: plasma, coil, mixer and signal on their own, so spheromak and mixing-maths questions keep their specialists.
Test: test_macgyver_routes_diy_rigs_not_plasma_physics_or_mixing_maths. Full suite: 494 passed, 2 skipped; ruff is clean.
Checked against the real briefs (polarize-agents on the profile branch):
- The user’s plasma-ball mixer and pickup questions and an Arduino magnetometer question →
macgyver. - Counter-helicity spheromaks →
plasma-toroids. - Cubic intermodulation →
nonlinear-signal-mixing. - Noise classification →
noise-engineering.
🤖 Generated with Claude Code
Route spheromak and FRC questions to the plasma-toroids specialist
Adds anchor terms for the plasma-toroids overlay profile: spheromak(s), FRC(s), field-reversed, co-/counter-helicity, compact-toroid, plasmoid(s), toroid(s), theta-pinch.
“toroidal” and “helicity” alone are deliberately left out, so questions about toroidal manifolds (e.g. grid cells) keep the general route.
- New test:
test_plasma_toroids_routes_spheromaks_and_frcs_not_grid_cell_tori tests/test_agent_profiles.py: 11 passed; ruff check and format clean.
🤖 Generated with Claude Code
ask: send clients a compact brief to answer from
Why
ask replies were long and unhelpful: each passage appeared twice (results and relay_full), and the model was told to paste relay verbatim instead of answering.
What
research_mcp/brief.pybuilds the client-facing brief:- each passage appears once, with its evidence id, source and score;
- a coverage level from the best reranker score: strong ≥ 1, partial ≥ −1, weak below that, none;
- the specialist’s name and guidance;
found/next/for_youlists and the main limit;answer_format: bottom line, up to five key points each citing an evidence id, gaps, and sources. When coverage is weak or none, the reply says so first.
- Gateway:
askreplies are recorded in full in the call log, and the client gets the compact brief.detail="full"returns the old shape. ask()adds a structuredsummaryto its reply; nothing else in it changes.- The server instructions, the
askdescription anddocs/mcp-clients.mdare updated.
On this morning’s real bone-conduction reply, the client payload drops from 12.9k to 8.1k characters.
Tests
492 passed. New tests cover coverage levels, single-copy passages, research runs and pass-through. The hub gateway test now checks that a needs-decision choice reaches the person through for_you.
Not changed: a finished research run still returns its own relay and answer.
🤖 Generated with Claude Code
math__physical_mix: physical-nonlinear-mixing's pnm as a tool
Adds math__physical_mix, which runs physical-nonlinear-mixing’s pnm as configured under calculators.physical_mixing:
action=calc: tones or an equation in t through a digital model (exact) or the audio interface’s loop (measured, exploratory); returns every line m·f1 + n·f2 with its level.action=calibrate: the loop’s delay, polarity and gain.action=runs: list or read the tool’s recorded runs (the pickle runs among them).action=setup: the tool’s interface and device records.
Arguments are checked and passed as a list (no shell). Built-in tool count 20 → 21 (tests updated). Full suite: 488 passed.
🤖 Generated with Claude Code
ask: a sky word needs a place or time before it runs sky__key
Problem
ask("What does the Sun's position and gravity have to do with the plasmasphere?") matched the sun's position trigger, ran sky__key with no place, and skipped retrieval. A science question got “give the place as decimal latitude and longitude” instead of passages.
Change
- The tool’s own names (
sky key,sun key,sky clock,sky-clock) still always runsky__key. - Every other sky word (
solar time,sunrise,sun's position, …, and[sky] triggers) runs it only when the request also gives decimal coordinates or a time. - Without them, the question is retrieved as usual, and the reply’s “For you” adds one line on how to ask for a sky key (
results["sky_hint"]). config/routing.default.tomlexplains the rule.
“What is the solar time in Victoria?” now goes to the papers with that hint, instead of only asking for coordinates. “Sky key in Victoria” still asks for them.
Checked
- New tests: the plasmasphere question retrieves passages, doesn’t call sky-clock, and shows the hint; sky words with a date or coordinates still trigger; the tool’s name alone still triggers.
- Full suite: 476 passed, 2 skipped (live sky-clock).
ruff checkandruff format --checkclean.
🤖 Generated with Claude Code
ask: lower the relevance floor; gateway: record every tool call with backlinks
Two changes. Each is its own commit, so they can be reviewed separately.
1. ask: lower the reranker relevance floor from 0 to -3 (7d22c35)
RELEVANCE_FLOORinresearch_mcp/ask.pygoes from0.0to-3.0, and the comment now says why.- A new test in
tests/test_ask.pychecks that near-misses (-0.03, -0.95, -2.9) are still shown. Unrelated text at -4.2 and below stays hidden.
The floor from #28 was set from one example of unrelated text, which scored -4 to -6. ask reranks passages against the whole question, which gives lower scores than a short query, so a floor of 0 hid relevant passages. Users got “No passage was relevant enough to show … at most -0.95”.
| Passage | Short query | Whole question via ask |
|---|---|---|
| Alonso et al. 2025: distortion products “about 15%” of the primaries | +1.47 | +0.14 |
| Next-closest passages | — | ≤ -0.03 (hidden at floor 0) |
-3 is based on a handful of queries, not a benchmark. It’s a single constant, easy to tune later.
2. gateway: record every tool call, with record pages and backlinks (b6ac2b5)
Recording
- Every tool call is written to a local SQLite outbox (
calls.sqlite), then copied to Postgres (Neon) whenCALL_LOG_DATABASE_URLis set. - If the database is down, the gateway retries every minute and keeps everything locally.
- Copied rows leave the outbox after
CALL_LOG_LOCAL_DAYS(7). With no database configured, nothing is pruned. - Each record holds client, session, project, tool, arguments, the full response, and its references (
run,run_id,request,doi,url) inmcp_call_refs.
Links in replies
- Replies get a
linksfield:record,researchandrequests. Where a reply has arelay, a Links list is appended to it. - Status tools are recorded but get no links.
- The server instructions now tell clients to keep these links.
Record pages (research_mcp/records.py)
/recordslists recent calls./records/<id>shows one call./records/request/<id>shows a request’s history./records/run/<folder or run id>shows a run’sanswer.mdand every call that refers to it, which are the backlinks.- Pages answer only loopback clients. Requests marked as Funnel, or addressed to the public host, get a 404.
Setup
docs/call-log.mdcovers the Neon setup (connection string in the Keychain,tailscale serveon port 8892,RECORDS_URL).- It also covers moving to DigitalOcean later with
pg_dump/pg_restore. psycopg[binary]is an optional extra:uv sync --extra calllog.
For reviewers
- The copy to a real Postgres is untested here: no local Postgres, and no Neon project yet. The tests cover it with a stand-in connection.
- The tables are plain, with no extensions, so they move between Postgres hosts with a dump and restore.
- Stored responses include questions and passage text; that’s intended, and the doc says so.
uv run pytestafter merging main: 474 passed, 2 skipped (live-only sky tests). The newsky__andmath__audio_mixtools are recorded like every other tool.ruffandpyrightare clean, apart from the optionalpsycopgimport.- The running gateway needs a restart, plus the setup steps in
docs/call-log.md, to start copying to Neon.
🤖 Generated with Claude Code
sky__measure, sky__locate: sun sights from sky-clock, and ask runs them
Adds two built-in tools over sky-clock’s new sun-sight routes (polarizetech/sky-clock#16), so a client can measure the Sun from a stick and its shadow and locate itself from that.
Tools
sky__measure(/api/measure): a plumbed stick and its shadow (length and bearing, or the tip’s east and north offsets) give the Sun’s altitude and azimuth, with the triangle’s legs and residual.sky__locate(/api/locate): the Sun’s altitude and azimuth (or the stick, shadow and bearing) at a UTC time give the places that see the Sun there (up to two), each with its local apparent and mean solar time and how many km it moves per 0.1° of measuring error and per second of clock error.
ask
- Runs a sight from plain words. “Where am I? A 1 m stick casts a 2.69 m shadow pointing 32° at 2026-11-04T22:00Z” returns 48.290, −123.059, local solar time 14:04:10, about 12 km per 0.1°.
- Gives both places when there are two. “the sun is 5 degrees up at azimuth 0 at 2026-06-21T12:00Z” returns the far south at noon and the Arctic at midnight.
- Says what is missing, such as the shadow’s bearing.
- Ignores unrelated “locate” requests (“locate the paper on bee dances”).
- Skips passage retrieval for a sight, as for a sky key.
Also
jd_iso now rounds to the nearest second instead of truncating (21:59:59.9999 read 21:59:59), which also affects sky__key’s event times.
Checks
tests/test_sky_sight.py: the sight parser (five phrasings, things it must leave alone, missing parts), arranging sky-clock’s answer, andaskwith a sight and with a missing bearing. Live tests run withSKY_CLOCK_LIVE=1.- Built-in tool count 18 → 20.
- 466 passed with the live tests against sky-clock on this Mac; ruff check and format are clean.
🤖 Generated with Claude Code
math__audio_mix: mixer=surprise (surprise-only polarity from polarity-calculator v5)
Adds mixer=surprise to math__audio_mix: the polarity-calculator v5 engine’s surprise-only polarity mixer (song treated as noise; polarities of its edges and differences; a loop at the edge of chaos keeps only what it fails to predict; rebuilt from those alone with controls). New arguments are range-checked and passed as an argument list.
Tests: ruff, pyright, 454 passed.
🤖 Generated with Claude Code
math__audio_mix: the sigma-delta loop through polarity-calculator's v5 engine
Adds mixer: "sigma-delta" to math__audio_mix, run by polarity-calculator’s new v5 audio engine (apps/polarity-explorer/v5/engine/engine.py). The engine keeps the same list / run / ledger interface, so sign and voltage runs work unchanged.
provider: "ideal": the exact sigma-delta loop (Julia and Python bit-identical) with physical threshold jitter. On 5 s of the super-8 full mix, the rebuilt sound scores 33.0 dB SI-SDR, against 16.7 dB for v17’s decoder.provider: "ngspice": v17’s BJT circuit with every noise (thermal, shot, channel white, 1/f, telegraph) generated from the physical draw and played in from files. Slow; the engine caps it at 2 s.- Results: each channel reports the rebuild scores, flip rates and the polarity-only edge reading (edge energy and departure spectra against the key-only twin). Each run is logged.
The example config now points calculators.audio_mixer at the engine.
Verified: ruff, format, pyright, pytest --cov (453 passed, 1 skipped by design); a sigma-delta and a sign run through the configured command.
🤖 Generated with Claude Code
math__audio_mix: run audio (local or Spaces) through the polarity-calculator mixers
Adds math__audio_mix, so a chat can run existing audio through polarity-calculator’s nonlinear mixer.
action=list: every audio file in the Spaces snapshots dataset-fetch reads (23 snapshots, about 2,000 files when written).matchnarrows the list.action=run: a Spaces file (spacesref +path) or a local file (full path) through either mixer.- Sign mixer: C1’s derived flip checks from the file’s own signs, and peaks against the key-only twin.
- Voltage mixer,
engine=calculator: the calculator’s equations (diode, diode_r, tanh, poly or sign) atfull_scalevolts, with input noisesigma. - Voltage mixer,
engine=ngspice: ngspice solves a circuit (diode_r, detector, tanh, poly, or your own netlist), fed the noisy input from a file. Instantaneous circuits are cross-checked sample by sample against the calculator. - Settle (the edge-of-chaos gain) is on by default. All noise comes from a fresh physical entropy-fetch draw.
action=ledger: the calculator’s run log (every run’s settings, checks and numbers) as a table, to compare designs.
The calculator runs as a configured command (calculators.audio_mixer). Arguments are validated and passed as a list, with no shell. Audio and outputs stay on the machine.
Verified: ruff, format, pyright, pytest --cov (452 passed, 1 live test skipped by design).
🤖 Generated with Claude Code
math__sign_mix and an ask step: the sign mixer from polarity-calculator
Adds the sign (hard-limiter) mixer as a deterministic quantity tool and an ask step.
math__sign_mix: the derived line table ofsign(a1 cos θ1 + a2 cos θ2). Only odd-order productsm·f1 + n·f2appear, with exact amplitudes, the terms that build each line, and the strong tone’s capture of the weak one (→ 6 dB). Pure Python, no model.- Random run (when
calculators.sign_mixeris configured): runs polarity-calculator’scalculators/nonlinear-mixer/python/random_mix.py --json. That is the keyed mix with the edge-of-chaos gain (settle, on by default), with its key and added noise from a fresh physical entropy-fetch draw (os + CPU jitter). Called as an argument list, no shell. askstep: runs on any route when a[mixer]trigger word and two tones appear (“120 Hz and 210 Hz”), and adds lines torelayandrelay_full.- The built-in tool count goes from 15 to 16 (tests updated).
Verified: ruff, format, pyright, and pytest --cov (440 passed, 86% coverage). A live run of the step against the real calculator passed all its checks and settled at K = 2.906, λ ≈ 0.
🤖 Generated with Claude Code
sky__key: the sky key and clock times from sky-clock, and ask runs it
Adds a built-in tool, sky__key, that asks a running sky-clock data server for the sky key and clock times at a place and time. ask runs it by itself when a request asks for them.
sky__key
Inputs: lat, lon (decimal degrees), optional t (UTC ISO or jd:; default now), h (metres), heading (degrees from north).
It reads /api/key and /api/clocks from SKY_CLOCK_URL (default http://127.0.0.1:8803) and returns:
- Key: the key/1 hash, its bins and code row; the Sun’s azimuth, elevation and direction; gravity.
- Unit triangles: the Sun split against gravity (sin el, cos el), the azimuth as (cos, sin), and with a heading the dance angle (heading × conj(azimuth)), each with its Pythagorean residual.
- Clocks: solar time, mean solar time, the equation of time, lunar time.
- Moon: position, phase, illuminated fraction.
- Events (UTC): sunrise, solar noon, sunset, moonrise, moonset, next transit, next quarter.
- Tide: tidal gravity.
- Source: sky-clock’s version, commit and ephemeris, with every number.
No model runs and nothing is computed here; place names are not looked up.
ask
- A request with a sky trigger (“sky key”, “solar time”, “lunar time”, “moon time”, “sunrise”, …) and decimal coordinates gets the reading in
results.sky, a one-line summary inrelay, and every value inrelay_full. - A quick-mode sky request skips passage retrieval (papers don’t hold clock times).
- Without coordinates, the reply says what to give; if sky-clock is down, it says so and names the URL.
- Extra trigger words go in
[sky]in the routing config.
Checks
tests/test_sky.py: parsing (decimal, N/S/E/W, labelled, dates not read as coordinates), triggers, the triangles and the dance angle, arranging a stubbed answer, andaskwith a reading, with nothing to go on, and with sky-clock down. A live test runs withSKY_CLOCK_LIVE=1.- The built-in tool count goes from 15 to 16 (
test_gateway.py,test_oauth.py). - 436 passed with the live test against sky-clock on this Mac; ruff check and format are clean.
The commit is unsigned: 1Password signing failed in this session, and the owner chose to commit unsigned this once.
🤖 Generated with Claude Code
Follow reference briefs to the repository that maintains them
A profile in the extensions overlay (PIPELINE_AGENT_EXTENSIONS_DIR) can now be a reference: its frontmatter names source, a path relative to the overlay checkout.
agent_profiles.load reads the brief from that file. The route’s repository and path then name the source repository, found as the nearest parent with .git.
A reference whose source is missing is skipped, so routing never uses an absent or stale copy.
This is for polarizetech/polarize-agents, where aramaic-translator now points to polarizetech/aramaic-alphabet. The installer counterpart is in polarizetech/scientific-research-agents.
Tests: tests/test_agent_profiles.py passes (8 tests, two new). The untracked cloud/ files in the checkout are not part of this PR.
🤖 Generated with Claude Code
ask: relevance floor for passages; stricter anchoring for name-derived specialists
Found while auditing structured-noise-identification’s stochastic-resonance bench with ask and rag__retrieve_evidence: two kinds of irrelevant output.
1. Unrelated passages shown when nothing relevant exists
The request “use the reg tool to do an audit … put in a PR” was routed quick and returned 5 passages:
- 3 from an EEG paper on REG/RAND tone sequences
- 1 from a direction-of-arrival paper where PR means “probability of resolution”
- 1 on spike-pattern quality
The reranker scored all 5 between −4.2 and −5.6. Every relevant top hit in the audit scored above 0.4.
Change: ask now drops passages the reranker scores below RELEVANCE_FLOOR = 0.0.
- Below 0, the bge cross-encoder judges a passage more likely irrelevant than relevant.
- If nothing passes, the relay says “No passage was relevant enough to show …” with the best score. If some pass, it says how many weaker ones were left out.
- The floor applies only when the library reports a reranker, because otherwise
scoreis a fused rank on a different scale. rag__retrieve_evidenceis unchanged and still returns raw ranked passages.
2. Wrong specialist from a generic word in its name
“…array-enhanced SR with mean-field coupling…” was routed to antenna-array-engineering (score 14). A profile without curated SPECIALIST_TERMS was anchored by any hyphen-part of its name, so “array” was enough.
Change: a name-derived anchor now needs every distinctive part of the name.
- Generic role words (
engineering,analyst,research, …) don’t count, and a simple plural is accepted. noise-engineeringstill anchors on “noise”.antenna-array-engineeringneeds both “antenna” and “array(s)”.- Curated
SPECIALIST_TERMSprofiles are unchanged. - Trade-off: a multi-part name may now under-route, falling back to the general researcher, which is safe. Before, it could inject the wrong specialist’s guidance into the run.
Not fixed here
These are ranking or corpus issues, not routing bugs:
- Ranking: some relevant-scoring results are still off-topic. Example: “chaotic resonance …” puts a chaotic-MUSIC DOA paper 4th, with a reranker score of 3.0.
- Corpus gaps: no passage was found for Tessone 2006 (diversity-induced resonance), cascaded SR, or the √dt scaling of Euler–Maruyama.
Checks
ruff check,ruff format --check,pyrightandpytest --covall pass: 424 tests, 86.5% coverage.- 3 of the 4 new tests fail on
main. The fourth guards the no-reranker case.
Generated by Claude Code
Drop reply templates; build replies as plain text in code
Replies came out empty after #26: the gateway reads config/replies.default.md on every reply but keeps its code in memory, so a gateway still running the old code filled the new templates with blocks it never wrote.
This removes the templating altogether:
research_pipeline/replies.pyis now three helpers:bullets,short(Results, Next, and For you only when there is something to do) andjoin.relay, the pending reply, the short answer andanswer.mdare laid out in code, in the same order as before.config/replies.default.mdand theconfig/replies.mdoverride are deleted; docs updated.
420 tests pass; ruff check and format are clean.
After merging, update the live checkout and restart the gateway.
🤖 Generated with Claude Code
Make replies three short lists, with the detail on request
Replies from the research tool were too long to read every turn. Now the person sees three short lists, one sentence per item:
- Results: what came back, any problem, and the main limit
- Next: what the assistant does next
- For you: only when the person has something to do (for example, a choice after a failure)
Example:
**Results**
- Found 3 passage(s) from 2 paper(s); the closest is from The waggle dance encodes distance, 2019.
- These are passages, not a checked answer.
**Next**
- The assistant answers from these passages and cites their evidence ids.
Detail on request
- The previous layout is kept as the
ask_full/pending_fulltemplates and returned asrelay_full. Clients show it only when the person asks for more. - Passages still come back in
results, so the assistant’s answer stays grounded. - A finished research run returns a short
relay(up to three sentences of the bottom line plus claim counts). The fullansweris unchanged and shown on request. - The gateway’s server instructions and the
asktool description now say this.
Tests
- Existing tests that check detail now read
relay_full. - New tests cover the short form, a decision landing under For you, and the short finished answer.
pytest: 424 passed.ruff checkandruff format --checkare clean.
Takes effect once merged and the gateway is restarted.
🤖 Generated with Claude Code
Say why an answer is thin
Two research runs on 2026-10-30 came back thin and the answer only listed symptoms under Limits. Their run logs showed the causes: OpenAlex’s budget was spent (it missed all 13 searches), DOAJ was down, PubMed and CORE rate-limited the run (no API keys), the fetch cap read 12 of 155–211 candidates, most papers read gave no usable passage, and three sub-questions ended empty because every passage found was read as neutral and claims are drafted only from passages that report a result.
Change: a “Why this answer is thin” section under the bottom line, written by code from the run’s records (research_pipeline/thin.py), cause by cause with what would change it. Shown only when an answer is thin; says so when nothing technical failed.
Also: run.json no longer stores credentials (the OpenRouter key was written in plain text to every run log; runs/ is gitignored, so nothing reached git).
Checked: ruff check, ruff format --check, pytest --cov (421 passed, 86%); replayed on the two thin runs.
🤖 Generated with Claude Code