Developer guide¶
For people changing Paperful. Setup, tests, and pull requests are in CONTRIBUTING. The design reference is architecture. This page is the rules a change has to keep, and where things go.
The rule: mirror first¶
Reference managers are flaky. Paperful copies the user’s files and metadata
into its own mirror (out/, state/) and works from that copy. The manager
API is a narrow door with three uses:
Refresh the mirror. One listing of what changed.
Write back when asked. Attach,
--apply, a note. Always explicit.Check the door.
ping, write support, authorize.
Anything else is a call Paperful should not make. Before adding a manager call, ask which of the three it is. If it is none, read the mirror.
What a command gets¶
cli._connect(cfg) is how a command opens the library. It returns a
MirrorFirstBackend (catalogue.py):
_connect
├─ manager answers → run_sync (what changed) → MirrorFirstBackend(catalogue, live)
├─ manager down, mirror on disk → MirrorFirstBackend(catalogue, None)
└─ manager down, no mirror → exit 2 with next steps
Call on the backend |
Served by |
|---|---|
|
|
|
|
|
|
|
|
|
the item folder; the manager only when the folder has no PDF |
|
the manager, then that item is re-read into its folder. |
With the manager down, the write calls raise LibraryError and
supports_write() is false. Check it before a batch and exit 2 with
_no_write(backend).
Use cli._live_backend(cfg) only when comparing the manager with the mirror
is the command’s job. Today that is sync, snapshot, and restore.
attachments reads the mirror (_connect) and uses the manager only to
probe stored bytes the mirror folder lacks, and for --apply.
Rules for new code¶
A verb that only reads never needs the manager running. Add it to
READ_VERBSintests/test_mirror_first.py; the test runs it with the manager closed.A verb that writes goes through the backend it was given. The write-through is in
MirroredBackend(library.py). A new write method on an adapter needs a matching method there, or the mirror goes stale until the next refresh.Could not read is never “nothing there”. Adapter reads raise
LibraryReadError. A missing key isNone. Do not catch a read error and carry on with an empty list: skip the item, count it, and say so.pyzotero and the raw client stay in
zot.py,library.py, andattach.py. A test enforces it. Nobackend.zlin command code.Whole-library reads happen in
sync.pyand nowhere else. If a feature seems to need a library listing, it needsbackend.items_in_scope(None), which is the mirror.Nothing under
out/is deleted. An item that left is marked, or moved toout/_trash/. A folder the item no longer belongs in is folded into one it does (mirror.fold_folder).Bytes from the manager go into the item folder, not a side cache (
state/pdf-cache/is only for[mirror].pdfs = "none").Sources never write
manifestorout/. The pipeline does.--applyis explicit and dry-run is the default on every verb that writes to the manager.
Module map¶
Module |
Job |
May import |
|---|---|---|
|
Zotero client, |
|
|
Authorize and upload |
|
|
|
|
|
Other adapters (seeking testers) |
|
|
Manifest, filenames, record IO |
|
|
Atomic text / bytes / JSON writes (unique |
|
|
Folders by key, records → |
|
|
Write one item’s folders from payloads ( |
|
|
The refresh: delta or full, version last |
|
|
|
|
|
Collection, year, type selection |
|
|
Identifier, hygiene, and corpus-frequency logic. Take a backend; never name a manager |
the protocol |
|
House expansions ( |
|
|
Apply-from-peer-review ( |
|
|
Local manuscript pack ( |
|
|
Nested TOML sections applied onto |
|
|
|
|
|
Systematic review: protocol, screening ledger, PRISMA counts, CSV/RIS exchange under |
|
|
One fetch lane each. Return bytes or a miss |
|
|
Opt-in Camoufox REST recover (before |
|
|
Order the lanes, save, attach, write the manifest |
most things |
|
|
|
|
OA parallel and serial fetch phases |
|
|
EZProxy recovery, handoff, dry-run rows for |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Completeness verbs after flags |
domain modules via |
|
Re-export shim for the four verbs (keep |
the four |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Typer wrappers via |
|
Connect, scope, progress, agent emit, source-list helpers. |
|
|
|
rag, |
|
|
|
|
|
|
|
|
ingest |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CLI |
|
|
|
|
|
Firefox page → mirror identity, blank-field merge, staged PDF/HTML, snapshot, capture note |
|
|
Native-messaging stdio host and |
|
|
|
config, optional live ping |
|
Operator verbs (doctor, collections, session/ezproxy/scholar, mirrors, pack, cache clean) |
|
|
The Typer app tree and exits. Re-exports |
everything |
|
Command signatures, one module per verb family. A body is a call into its |
|
|
Per-item lanes; owns |
|
|
|
none |
|
Shared builders for CLI JSON and MCP ( |
|
|
Mirror-first interchange records for a scoped library export. Agent/MCP |
|
|
BibTeX/RIS from snowball / authorwatch proposal JSONL on disk |
|
|
First-line prefixes + |
none |
|
Classify and trash Paperful-owned notes |
|
|
Cited-in-PDF works missing from the library fingerprint |
|
|
Briefing/note/file DOI list vs |
|
|
Optional |
|
|
Drop-folder watch/drain, match ladder, gated create, collection routing |
|
|
Missing-PDF sort: refs-gap cites × miss severity |
|
|
Contact-only missing-PDF rows (metadata / Twenty emails, CSV). No fetch |
|
|
Twenty People lookup (local cache) and |
httpx |
|
Optional stdio MCP: read-only gaps, snowball preview / trends, export, proposal_export, refs_gap, ask (optional |
|
|
Localhost FastAPI: JSON capability API + mounts |
|
|
Server-rendered workbench (Jinja). |
CLI / MCP builders |
|
People lists → OpenAlex new works; |
OpenAlex client, |
|
ORCID ego co-authorship SNA ( |
OpenAlex |
|
Web grey search ( |
|
|
Corpus / cited / coauthor / mix suggestions → |
|
|
Parse operator-saved RG / LinkedIn / Academia HTML or CSV (no network) |
stdlib HTML/CSV |
|
Alert loop job ledger ( |
|
|
Crawl, hops, watch ( |
OpenAlex; library protocol only on apply |
|
IMRaD field extract ( |
|
|
Thin httpx client for an operator-owned GROBID REST server |
|
The refresh¶
run_sync (sync.py):
backend.changes(since)— rows changed after the stored library version (all rows on a first or--fullrefresh), the keys now in the library, the trash, the collections. Zotero’s local API leaves trashed items out of listings and has no/deleted; a removal is a key that stopped being listed.Work out which parents are affected: changed themselves, a child changed, or a child key the index knew is gone.
Rewrite each one with
snapshot.write_item(exact=True: the item’s whole collection membership is known, so folders move and fold).Mark or move parents that left (
mirror.retire). Refused when more than half the mirror would go: that is a different library.Write
out/_sync.json. Last. If any item could not be read, the version does not move and the next refresh covers the same ground.With
[mirror].pdfs = "all", copy PDFs (copy_pdfs). Whole library until it has completed once, then changed items only.
Every step can be repeated. A crash leaves valid records and an old version.
Disk schemas¶
Tier policy (1.0 contract):
Tier |
Policy |
|---|---|
T0 Trust |
Required keys frozen in code ( |
T1 Agent packs |
Same for top-level keys used by scripts |
T2 Additive |
Schema string stable; keys may grow; no frozenset required |
T3 Cache |
Layout may change any release; rebuild with |
Schema |
Location |
Writer |
Tier |
Frozenset / golden |
|---|---|---|---|---|
|
|
|
T0 |
|
|
|
|
T0 |
|
|
stdout |
|
T0 |
|
|
HTML comment in child notes |
|
T0 |
|
|
|
|
T1 |
Additive |
|
|
|
T1 |
|
|
|
|
T1 |
|
|
|
|
T1 |
|
|
optional |
|
T2 |
additive; not in |
|
|
|
T1 |
|
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
item history sidecar |
|
T2 |
— |
|
standalone catalogue |
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
hand-edited; |
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
reachout / request ledger |
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
Additive through 1.x |
|
snowball watch cursor |
|
T2 |
— |
|
|
|
T2 |
Drift classes |
|
|
|
T2 |
Alert loop / what-cites; see keepup.md |
|
co-author graph |
|
T2 |
— |
|
|
|
T2 |
ORCID ego graph, phase slices, metrics, |
|
|
|
T2 |
SearXNG grey query, ranked hits, probe candidates. Metadata apply only. |
|
|
|
T2 |
URL seen set (not DOI). |
|
|
|
T2 |
Holdings rows and healed misses; golden under |
|
|
|
T2 |
Frozen required keys ( |
|
|
|
T2 |
Frozen required keys ( |
|
|
|
T2 |
Stopping-rule scores per hop |
|
|
|
T2 |
Discover map. Rebuilt from the queue. Nodes carry |
|
|
|
T2 |
— |
|
synthesize sidecar |
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
— |
|
|
|
T2 |
Required: |
|
|
|
T3 |
Rebuildable cache ( |
|
|
|
T1 |
|
|
|
|
T1 |
Frozen keys: |
|
|
|
T1 |
Frozen keys: |
|
|
|
T1 |
Compact investigation log: summary, retrieve rounds, novelty search, Q&A. No passage text. Written only when that lane ran |
|
|
|
T2 |
Edit plan plus pack metadata. Never overwrites the source manuscript |
|
|
|
T2 |
— |
|
extracted text cache |
|
T3 |
Rebuildable |
|
LanceDB meta |
|
T3 |
Not a promise |
(no schema) |
|
|
T3 |
Advanced Ask summary cache; keyed by chunk, question, model |
|
e2e stack reports |
|
T2 |
Internal / CI |
Consumers: recover --from-last-run, GUI Activity, and agent_ops read paperful.run_report.v1 (state/last-run.json). restore requires paperful.item.v1. Batch verbs and optional paperful mcp emit paperful.agent.json.v1.
The catalogue rebuilds an Item from a record. The test
test_item_from_record_matches_the_live_listing holds the two equal field
for field. A new Item field needs a home in the record and a case there.
Contract tests: tests/test_schema_freeze.py.
Adding things¶
A read verb. backend = _connect(cfg), _load_scope(backend, …), do
the work, write a run report. Add it to READ_VERBS. Disk-only verbs such as
authorwatch save and extract-sections still belong there so a closed
manager is not an accident.
A write verb. Same, dry-run by default. Before applying:
if not backend.supports_write(): _exit_env(_no_write(backend), cfg).
A source. Subclass in paperful/sources/, register it, return a
PageResult. It gets a Context; it does not get the manifest or out/.
An adapter method. Ask first whether the mirror can serve it. If it is a
read, add it to MirrorCatalogue. If it is a write, add it to the adapter,
to MirroredBackend (refresh the item after), and to MirrorFirstBackend
(pass through, refuse offline).
A manager. Implement LibraryBackend and submit it through the
adapter SDK (conformance kit + field report). With a
changes(since) method it gets the mirror-first path for free. Zotero,
Mendeley, and EndNote all expose one. Without one, reads stay live. Promotion
still requires a real-library report; the kit alone does not.
Tests¶
uv run pytest runs offline. tests/conftest.py refuses every request a
real Zotero client makes, so a Zotero running on your machine is never read
by a test. The socket gate is local until it returns to CI
(rebuild step 3):
uv run pytest --disable-socket --allow-unix-socket --allow-hosts=127.0.0.1,::1,localhost
(tests/conftest.py re-enables sockets for the grey_live /
e2e_live markers). Tests that need Crossref/OpenAlex-shaped answers stub
them; a test that dials out is a bug, not a fixture.
Fake |
Use |
|---|---|
|
A library with versions, a trash, and call counts. For the refresh and the catalogue |
|
Mixin for a stub client that lists |
|
A manager with write calls. For |
Count requests when the point of a change is fewer of them: FakeZotero.calls.
CI and local pitfalls¶
GitHub Actions (.github/workflows/ci.yml) runs one job on Ubuntu, Python
3.12: uv run pytest -m smoke (CLI version, shell pages, workbench command
paths). Lint, the full offline suite, audit, the socket gate, fresh-install,
docker, browser, and the other OS/Python cells are not on the gate. The order
for putting them back is CI gate, cut back to smoke.
Run the rest locally before a release:
lint:
make lint—ruff check,ruff format --check, andmypyon the modules under[tool.mypy] filesinpyproject.toml.socket:
uv run pytest -m "not docs" --disable-socket --allow-unix-socket --allow-hosts=127.0.0.1,::1,localhost.suite:
uv run pytest(82% coverage gate inpyproject.toml; 85 is deferred).
The smoke marker is still the copy-and-layout check. A tab or command-path
change should keep uv run pytest -m smoke green.
Atomic writes. JSON and text under state/ and out/ go through
paperful.fsio (atomic_write_text / atomic_write_json: unique
.part temp file, then os.replace). Cross-process sections take
fsio.file_lock(state_dir, name) (a filelock under state/.locks/).
Use these instead of Path.write_text for anything another thread or
process may read mid-write (run reports, last-run.json, mirror records).
CLI help assertions. On CI, CI / GITHUB_ACTIONS is set and Typer/Rich
style option names with ANSI codes. A flag like --apply is often split across
escape sequences, so assert "--apply" in result.stdout fails even though help
is correct. Strip SGR codes with tests.textutil.plain_text before matching
tokens (see the comment in that module). For table layout, several CLI test
modules widen the shared cli.console (width=250) so Rich does not ellipsize
cells — follow tests/test_cli.py when adding help or table assertions.
Dev sync and the workbench. uv sync --group dev installs Jinja2 and
python-multipart as well as FastAPI, so uv run pytest can render the
workbench. CI still passes --extra serve (the operator extra). The same
sync pulls lancedb for index/RAG tests. PyPI wheels cover Linux
x86_64/arm64, Windows, and macOS arm64; there
is no wheel for every macOS x86_64 / OS combo. If sync fails with “no wheel for
the current platform”, use native arm64 Python on Apple Silicon, run pytest
inside the Linux dev container / CI image, or temporarily sync without the dev
group only when you are not touching RAG tests.
Pytest inside Compose. The runtime image is for operators (paperful …), not
the full dev test suite. Reproduce CI with host uv run pytest or a
python:3.12-slim container plus uv sync --group dev --extra serve. Do not
expect host-only tests (for example default Zotero endpoint URLs) to pass when
PAPERFUL_ZOTERO_HOST is set for container → host networking.
Docs CI. docs.yml builds the guide on every push and PR but is
advisory (continue-on-error, warnings allowed); pages.yml deploys on
main pushes that touch docs/, website/, or the Sphinx test. Neither
sets DOCS_STRICT. Run DOCS_STRICT=1 make docs locally before pushing
guide changes; new guide pages must be linked from docs/index.md
(tests/test_sphinx_docs.py).
PyPI releases¶
Wheels are built with Hatchling (uv build → dist/). Publishing uses
trusted publishing from
.github/workflows/publish.yml when a GitHub Release is published or a
v* tag is pushed. Configure the pending publisher on pypi.org
once:
Field |
Value |
|---|---|
PyPI project |
|
Owner |
|
Repository |
|
Workflow |
|
Environment |
|
Add a GitHub environment named pypi on the repo (Settings → Environments)
if you want approval gates; the workflow references environment: pypi.
First upload before trusted publishing is wired: build locally, then upload
with an API token for the glenwwright account (PyPI → Account settings →
API tokens). Do not commit the token.
make pre-release
uv build
bash scripts/release/pre_release.sh --dist-only
UV_PUBLISH_TOKEN=pypi-… uv publish dist/paperful-$(python3 -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")*
If a local assessments/*-full-assessment.md exists, rows marked Not done
or NEEDS FIXES block the tag until you close them out. Emergency patches:
PAPERFUL_SKIP_ASSESSMENT=1 (document why in CHANGELOG.md).
GitHub publish still runs the version, changelog, and website checks; the
assessment gate runs only on the maintainer machine (make pre-release
before the tag). Weekly since packs you open on your own collections stay
off this script.
uv publish uploads every file in dist/ unless you pass explicit paths.
pre_release.sh fails if dist/ contains wheels or sdists for an older
version than pyproject.toml.
Confirm: pip install paperful==<version> and paperful --help.