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:

  1. Refresh the mirror. One listing of what changed.

  2. Write back when asked. Attach, --apply, a note. Always explicit.

  3. 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

collections, resolve_collection, subtree_keys, collection_counts

out/_collections.json and the item folders

items_in_scope, get_item, items_lacking_pdf

record.json

raw_item, children, find_child_note_keys, read_child_note

record.json and notes/

preview_merge

record.json and annotations.json

export_pdf

the item folder; the manager only when the folder has no PDF

apply_patch, attach, merge_into, trash_item, trash_note, note and tag writers, create_parent

the manager, then that item is re-read into its folder. trash_note never marks the parent _gone

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_VERBS in tests/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 is None. 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, and attach.py. A test enforces it. No backend.zl in command code.

  • Whole-library reads happen in sync.py and nowhere else. If a feature seems to need a library listing, it needs backend.items_in_scope(None), which is the mirror.

  • Nothing under out/ is deleted. An item that left is marked, or moved to out/_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 manifest or out/. The pipeline does.

  • --apply is explicit and dry-run is the default on every verb that writes to the manager.

Module map

Module

Job

May import

zot.py

Zotero client, Item, pure helpers

resolve

attach.py

Authorize and upload

zot

library.py

LibraryBackend protocol, ZoteroBackend, MirroredBackend, ChangeSet

zot, attach

mendeley.py, endnote.py

Other adapters (seeking testers)

library types

store.py

Manifest, filenames, record IO

zot, attach, fsio

fsio.py

Atomic text / bytes / JSON writes (unique .part + os.replace) and file_lock under state/.locks/

filelock

mirror.py

Folders by key, records → Item, PDFs on disk, gone policy. Calls no manager

store, zot

snapshot.py

Write one item’s folders from payloads (write_item); scoped full refresh

mirror, library

sync.py

The refresh: delta or full, version last

snapshot, mirror, library

catalogue.py

MirrorCatalogue, MirrorFirstBackend, open_library

sync, mirror, library

scope.py

Collection, year, type selection

library errors

resolve/ (ids.py, enrich.py), lint.py, acronyms.py, authors_report.py, metadata.py, dedupe.py, pdfid.py

Identifier, hygiene, and corpus-frequency logic. Take a backend; never name a manager

the protocol

glossary.py / glossary_cmd.py

House expansions (paperful.glossary.v1 in state/glossary/). Peer review fuzzy-match + Vale alias export

config

rewrite.py, rewrite_areas.py, rewrite_align.py, rewrite_plan.py, rewrite_llm.py, rewrite_render.py, rewrite_docx.py, rewrite_office.py, rewrite_pdf.py, rewrite_openxml.py

Apply-from-peer-review (paperful.rewrite.plan.v1). Pack required; never overwrites the source; stdlib tracked-changes OOXML (Word), in-place pptx/odt copy or ODF/PDF spines; optional openxml-audit extra

peer-review pack + gated llm

peer_review.py, peer_review_lanes.py, peer_review_checks/ (run, structure, biblio, floats, style, overlap), peer_review_extract.py, peer_review_llm.py (suggested_from_llm dispatches _run_reviewers / _run_optional_lane), peer_review_marg.py, peer_review_adversary.py, peer_review_outline.py, peer_review_claims.py, peer_review_verify.py, peer_review_units.py, peer_review_context.py, peer_review_metrics.py, peer_review_ai_tells.py, peer_review_ai_model.py, peer_review_vale.py, peer_review_overlap.py, peer_review_stats.py

Local manuscript pack (paperful.peer_review.pack.v1). Checkers always; composable suggested review lanes (reviewers, MARG-S, adversary, outline, claims, verify, ScholarPeer-inspired context / context-web with three-round retrieve and context.json; no vendor); optional GROBID TEI chunks for marg / claims / verify; claims cited-source locators from state/rag/text when -C is set; optional Binoculars extra (git overlay; no torch at import); optional Vale house-style pass (no vale at import); glossary expansions when state/glossary/ has entries

cli_runtime, gated llm, optional grobid_client

config_tables.py

Nested TOML sections applied onto Config

config parsers

config_check.py

config check: unknown top-level keys and sections (did-you-mean), secrets that belong in the environment

config

sr/ (protocol.py, screen.py, identify.py, prisma.py, exchange.py) / sr_cmd.py

Systematic review: protocol, screening ledger, PRISMA counts, CSV/RIS exchange under state/sr/<slug>/; sr init / screen / status / export / import

fsio, store

sources/

One fetch lane each. Return bytes or a miss

sources.base

camofox_client.py / camofox_recover.py

Opt-in Camoufox REST recover (before browser_agent)

sources.camofox, camofox.md

pipeline.py

Order the lanes, save, attach, write the manifest

most things

pipeline_save.py

try_download (bytes/URL + license gate) then commit_download (save, manifest, attach)

store, pdfid

pipeline_phases.py

OA parallel and serial fetch phases

pipeline helpers

run_hooks.py

EZProxy recovery, handoff, dry-run rows for run

pipeline, handoff

gaps_cmd.py

gaps body after the CLI parses flags

handoff, run_hooks

run_cmd.py

run body after the CLI parses flags

pipeline, run_hooks, catalogue (PDF-todo helpers; not zot)

ask_cmd.py

ask body after the CLI parses flags

agent_ops, rag, claim_check

claim_check.py

ask --claim-check pack (paperful.claim_check.v1). Sentence split from stuff; labels from peer_review_claims overlap; no LLM

stuff, peer_review_claims, rag retrieve

evidence.py / evidence_cmd.py

paperful evidence pack (paperful.evidence.v1). Heading split / extract-sections; quote or check this; no LLM

sections.extract, peer_review_claims.quote_in_text

dedupe_cmd.py / attachments_cmd.py / summarize_cmd.py / synthesize_cmd.py

Completeness verbs after flags

domain modules via cli_runtime

completeness_cmd.py

Re-export shim for the four verbs (keep cli imports and monkeypatches stable)

the four *_cmd modules

lint_cmd.py

lint after flags

lint

since.py / since_cmd.py

since: read the earlier run / screen / versions / urls reports, probe the open-access metadata lanes, and write the paperful.since.v1 pack. Always dry-run; no manager writes

sources, urls, versions, handoff_rank, fsio; since_cmd adds screen and cli_runtime

screen_cmd.py

screen after flags

screen

peer_review_cmd.py

peer-review after flags

peer-review

rewrite_cmd.py

rewrite after flags

rewrite

glossary_cmd.py

glossary validate / export-vale after flags

glossary

fix_metadata_cmd.py

fix-metadata after flags

metadata

ocr_cmd.py

ocr after flags

ocr

recover_cmd.py

recover after flags

pipeline, browser_agent

reachout_cmd.py

reachout after flags

reachout, handoff

notes_delete_cmd.py

notes delete after flags

notes

authors_cmd.py

authors after flags

authors_report

acronyms_cmd.py

acronyms after flags

acronyms

all_cmd.py

all chain + step dispatch after flags

Typer wrappers via cli; helpers via cli_runtime

cli_runtime.py

Connect, scope, progress, agent emit, source-list helpers. _bind_scoped / _connect_scope are the shared collection/year/type ladder used by command modules

catalogue, library, scope, run_hooks (not cli)

rag_cmd.py

rag ingest/status/search/questions/answered after flags

rag, cli_runtime

sections_cmd.py

extract-sections after flags

sections.command, grobid, llm

twenty_cmd.py

twenty lookup/sync after flags

twenty

ingest_cmd.py

ingest-dois after flags

ingest

sync_cmd.py

sync, import, openalex-store build-cites after flags

sync, snapshot

report_cmd.py

report, export-proposals, run-report-count helpers after flags

store, runreport

playbooks_cmd.py

playbooks probe/propose/promote after flags

playbooks

profile_cmd.py

profile list/show/save after flags

run_config

snowball_cmd.py

snowball verbs and request helpers after flags

snowball.command

authorwatch_cmd.py

authorwatch verbs after flags

authorwatch

keepup_cmd.py

keepup verbs after flags

keepup

attach_cmd.py

attach after flags

attach, handoff, pipeline

versions_cmd.py

versions after flags

versions

refs_gap_cmd.py

refs gap after flags

refs_gap, agent_ops

coverage_cmd.py

coverage after flags

coverage, agent_ops

export_cmd.py

CLI export (RIS/BibTeX/EndNote XML + --pdfs) after flags

interop, store, mirror

inbox_cmd.py

inbox watch/drain/proposals after flags

inbox, inbox_match, inbox_route

capture.py

Firefox page → mirror identity, blank-field merge, staged PDF/HTML, snapshot, capture note

store, mirror, snapshot, run_cmd, notehtml

capture_host.py

Native-messaging stdio host and install-host

capture

doctor.py

run_checks orchestrates domain helpers (_manager_checks, _disk_checks, _session_checks, _fetch_lane_checks, _tool_path_checks, _corpus_checks)

config, optional live ping

doctor_cmd.py / collections_cmd.py / session_cmd.py / mirrors_cmd.py / pack_cmd.py / cache_cmd.py

Operator verbs (doctor, collections, session/ezproxy/scholar, mirrors, pack, cache clean)

cli_runtime, domain modules

cli.py

The Typer app tree and exits. Re-exports cli_runtime and cli_bind names

everything

cli_bind/ (core, tidy, find, mirror, ask, snowball, watch; _shared holds the option objects)

Command signatures, one module per verb family. A body is a call into its *_cmd module. Modules load in a fixed order so --help keeps its order

cli, the *_cmd modules

routing.py

Per-item lanes; owns SERIAL_SOURCES (Sci-Hub and other serial phases)

config, zot

agent_json.py

--format json envelope (paperful.agent.json.v1) and exit 3

none

agent_ops.py

Shared builders for CLI JSON and MCP (gaps, snowball dry-run / trends, export, refs-gap, ask) plus CLI coverage_envelope

agent_json, catalogue, rag, export_build, pack_bib, snowball.trends, coverage

export_build.py

Mirror-first interchange records for a scoped library export. Agent/MCP export calls this with notes off and no PDF directory. CLI export overlays the same records in export_cmd.py (EndNote XML bundle and --pdfs live there)

interop, store, mirror, library protocol

pack_bib.py

BibTeX/RIS from snowball / authorwatch proposal JSONL on disk

interop, snowball

notehtml.py

First-line prefixes + paperful.note.v1 comment

none

notes.py

Classify and trash Paperful-owned notes

notehtml, library protocol

refs_gap.py

Cited-in-PDF works missing from the library fingerprint

identity, bibliography parse

coverage.py

Briefing/note/file DOI list vs -C membership

identity, resolve

witness.py

Optional paperful.witness.v1 on run reports

config, rag status tip

inbox.py / inbox_match.py / inbox_route.py

Drop-folder watch/drain, match ladder, gated create, collection routing

handoff, library, optional llm

handoff_rank.py

Missing-PDF sort: refs-gap cites × miss severity

handoff

reachout.py

Contact-only missing-PDF rows (metadata / Twenty emails, CSV). No fetch

handoff, twenty

twenty.py

Twenty People lookup (local cache) and sync (CRM create/enrich). User guide: Twenty and SearXNG

httpx

mcp_server.py

Optional stdio MCP: read-only gaps, snowball preview / trends, export, proposal_export, refs_gap, ask (optional ask_mode)

agent_ops

serve.py

Localhost FastAPI: JSON capability API + mounts ui when the serve extra is installed

agent_ops, ui

ui/

Server-rendered workbench (Jinja). origin_guard.py (OriginGuardMiddleware, added in serve.create_app) returns 403 on non-GET requests whose Sec-Fetch-Site / Origin / Referer is cross-origin. app.py owns shared helpers + mount_ui; routes live in wanted_routes / discover_routes (binder + snowball page; tab handlers in discover_graph_routes / discover_search_routes / discover_people_routes) / shell_routes / repair_routes / index_routes / peer_review_routes / rewrite_routes (each register_*). Desk HTTP bodies are module-level handle_* functions; each register_* only binds them. Row builders: pages.py re-exports wanted_rows / discover_rows / ask_rows plus page_common (pagination, dest, fingerprints). Long jobs: jobs.py re-exports wanted_jobs / discover_jobs / repair_jobs / index_jobs (RAG, ask, summarize, synthesize) and defines peer-review / rewrite. Ordinary pages do not run doctor (System does). Handlers resolve doctor_payload / collections_tree via paperful.ui.app so tests can monkeypatch there

CLI / MCP builders

authorwatch.py

People lists → OpenAlex new works; gather_briefing / write_briefing / write_digest; apply creates parents + ingested.md; accept / delete

OpenAlex client, identity, snowball.ingest, authorwatch_suggest

network/

ORCID ego co-authorship SNA (paperful.network.v1 under state/network/<run-id>/); phase slices; optional NetworkX metrics

OpenAlex works_by_author, AuthorRecord; extra paperful[network]

search/

Web grey search (paperful.search.v1 under state/search/<run-id>/); SearXNG JSON; metadata apply

snowball.searxng, playbooks, greyid

authorwatch_suggest.py

Corpus / cited / coauthor / mix suggestions → suggestions.jsonl; shared co-author accumulation for briefing

authors_report, OpenAlex, promoted packs

authorwatch_social.py

Parse operator-saved RG / LinkedIn / Academia HTML or CSV (no network)

stdlib HTML/CSV

keepup.py / keepup_cites.py

Alert loop job ledger (paperful.keepup.v1); poll watch / authorwatch / collection citers; interval gate; apply + dismiss

snowball.watch, authorwatch, OpenAlex works_citing

snowball/

Crawl, hops, watch (watch apply from inbox), thin briefing, frontier digest, trends (OpenAlex group_by year counts). command.py is the public run_* surface; _execute / gate / create-and-fill live in execute.py, continue/resume/apply in apply.py. watch run does not create library items. Citation-map categories live in map_categories.py; library annotate/add/remove in graph_library.py

OpenAlex; library protocol only on apply

sections/

IMRaD field extract (extract-sections): deterministic split + optional GROBID TEI + optional LLM fill

rag.extract text cache, rag.chunk / sections.headings, grobid_client, gated llm

grobid_client.py

Thin httpx client for an operator-owned GROBID REST server

sections.grobid, rag.extract.GrobidParser, doctor

The refresh

run_sync (sync.py):

  1. backend.changes(since) — rows changed after the stored library version (all rows on a first or --full refresh), 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.

  2. Work out which parents are affected: changed themselves, a child changed, or a child key the index knew is gone.

  3. Rewrite each one with snapshot.write_item (exact=True: the item’s whole collection membership is known, so folders move and fold).

  4. Mark or move parents that left (mirror.retire). Refused when more than half the mirror would go: that is a different library.

  5. 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.

  6. 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 (*_KEYS); rename/remove is a break; extras additive. Golden fixtures under tests/fixtures/

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 rag ingest

Schema

Location

Writer

Tier

Frozenset / golden

paperful.item.v1

out/.../record.json

store / snapshot

T0

ITEM_RECORD_KEYS; tests/fixtures/item_v1/

paperful.run_report.v1

state/runs/*.json, state/last-run.json

runreport

T0

RUN_REPORT_*_KEYS; tests/fixtures/run_report_v1/

paperful.agent.json.v1

stdout --format json

agent_json

T0

REQUIRED_KEYS; tests/fixtures/agent_json*

paperful.note.v1

HTML comment in child notes

notehtml

T0

NOTE_BLOCK_KEYS; tests/fixtures/note_v1/

paperful.refs_gap.pack.v1

state/refs-gaps/<stamp>/pack.json

refs_gap

T1

Additive memory counts and per-row delta / first_seen from state/refs-gaps/memory.jsonl. REFS_GAP_PACK_KEYS; tests/fixtures/refs_gap_pack_v1/

paperful.coverage.pack.v1

state/coverage/<stamp>/pack.json

coverage

T1

COVERAGE_PACK_KEYS; tests/fixtures/coverage_pack_v1/

paperful.precedent.pack.v1

state/precedent/<stamp>/pack.json

precedent

T1

PRECEDENT_PACK_KEYS; tests/fixtures/precedent_pack_v1/

paperful.stuff.pack.v1

state/stuff/<id>/<stamp>/pack.json

stuff

T1

STUFF_PACK_KEYS; tests/fixtures/stuff_pack_v1/

paperful.witness.v1

optional witness on run reports

witness

T2

additive; not in RUN_REPORT_KEYS

paperful.inbox.proposal.v1

state/inbox/proposals/*.json

inbox_match

T1

INBOX_PROPOSAL_KEYS; extra route_* keys allowed; tests/fixtures/inbox_proposal_v1/

paperful.sync.v1

out/_sync.json

sync

T2

—

paperful.annotations.v1

annotations.json

snapshot

T2

—

paperful.collections.v1

out/_collections.json

store

T2

—

paperful.history.v1

item history sidecar

store

T2

—

paperful.standalone.v1

standalone catalogue

sync

T2

—

paperful.pack.v1

state/packs/<id>.json

pack

T2

—

paperful.dedupe_pack.v1

state/dedupe-packs/

dedupe

T2

—

paperful.version_pack.v1

state/version-packs/

versions

T2

—

paperful.ingest_dois.v1

state/ingest/<stamp>/

ingest_dois

T2

—

paperful.collections_add.v1

state/collections-add/<stamp>/

collections_add

T2

—

paperful.acronyms.v1

state/acronyms/<scope>.json

acronyms

T2

—

paperful.glossary.v1

state/glossary/<scope>.json

hand-edited; glossary CLI

T2

—

paperful.authors_report.v1

state/reports/<slug>-authors.json

authors_report

T2

—

paperful.author_pack.v1

state/author-packs/

snowball.authors

T2

—

paperful.author_contact.v1

state/author-contacts/

twenty

T2

—

paperful.author_request.v1

reachout / request ledger

author_request

T2

—

paperful.authorwatch.v1

state/authorwatch/<name>/watch.json

authorwatch

T2

—

paperful.authorwatch.person.v1

state/authorwatch/<name>/people.jsonl

authorwatch

T2

—

paperful.authorwatch.suggestion.v1

state/authorwatch/<name>/suggestions.jsonl

authorwatch_suggest

T2

—

paperful.snowball.candidate.v1

state/snowball/<run-id>/

snowball.candidate

T2

Additive through 1.x

paperful.snowball.watch.v1

snowball watch cursor

snowball.watch

T2

—

paperful.snowball.watch.responses.v1

state/snowball/watches/<name>/responses.json

snowball.response_cache

T2

Drift classes new / unchanged / metadata_changed / reassigned_id. Additive prisma / watch_drift on queue summary.json and snowball watch run reports; not frozen RUN_REPORT_SUMMARY_KEYS

paperful.keepup.v1

state/keepup/<name>/job.json

keepup

T2

Alert loop / what-cites; see keepup.md

paperful.snowball.coauthors.v1

co-author graph

snowball.authors

T2

—

paperful.network.v1

state/network/<run-id>/

network

T2

ORCID ego graph, phase slices, metrics, attributes.csv. Distinct from snowball coauthors.v1.

paperful.search.v1

state/search/<run-id>/

search

T2

SearXNG grey query, ranked hits, probe candidates. Metadata apply only.

paperful.search.watch.v1

state/search/watches/<name>/watch.json

search.watch

T2

URL seen set (not DOI). interval_days is a due-date hint; Paperful does not schedule.

paperful.since.v1

state/since/<stamp>-<scope>/since.json

since

T2

Holdings rows and healed misses; golden under tests/fixtures/since_pack_v1/. See since.md

paperful.sr.protocol.v1

state/sr/<slug>/protocol.json

sr.protocol

T2

Frozen required keys (PROTOCOL_KEYS). Title, question, exclude reasons. No scheduler

paperful.sr.screen.v1

state/sr/<slug>/screening.jsonl

sr.screen

T2

Frozen required keys (SCREEN_KEYS). One decision per line (include / exclude / maybe, reason, reviewer)

paperful.snowball.stop.v1

state/snowball/<run-id>/stop.json

snowball.stop

T2

Stopping-rule scores per hop

paperful.citation_graph.v1

state/snowball/<run-id>/citation_graph.json

snowball.citation_graph

T2

Discover map. Rebuilt from the queue. Nodes carry role, in_library, item_key, has_pdf, optional operator staging (tags / note / target_collection / staged), optional watch_new / compare_new, thresholds, and triage (read-first list). Library actions: paperful.snowball.graph_library.

paperful.htmlpdf.proposal.v1

state/htmlpdf/proposals/

sources.htmlpdf

T2

—

paperful.synthesis.v1

synthesize sidecar

synthesize

T2

—

paperful.ask_batch.v1

state/ask-batch/<stamp>/

rag.batch

T2

—

paperful.rag.thread.v1

state/rag/threads/*.json

rag.thread

T2

—

paperful.rag.questions.v1

state/rag/questions/

rag.questions

T2

—

paperful.sections.v1

state/sections/<key>.json

extract-sections

T2

Required: schema, item_key, title, year, source, fields, missing. Optional: sections, engine (grobid|rule), pdf_sha256, notes (scan skip / GROBID failure). Each fields.<name>: text, provenance (rule|grobid|llm), optional heading, pages

paperful.grobid.tei.v1

state/grobid/<sha256>.json next to .tei.xml

sections.grobid

T3

Rebuildable cache (extract-sections, [rag].parser = "grobid", peer-review --lane marg / claims / verify)

paperful.peer_review.pack.v1

state/peer-reviews/<id>/<stamp>/pack.json

peer-review

T1

PEER_REVIEW_PACK_KEYS (findings, overlap, metrics, llm, …). llm may be null. When set: mode default|marg|both|adversary|outline|claims|verify|context|context-web, optional marg.parser / claims / verify / outline. Optional top-level outline skeleton and claims ledger (intra-doc status / support_quote / loc; optional sources[] with item_key, cited-source status, quote, loc when -C ran). Optional ai_model / vale / forensics only when those extras ran. Context / context-web may add llm.context.investigation plus log / log_path

paperful.claim_check.v1

state/ask-claims/<stamp>/

ask --claim-check

T1

Frozen keys: schema, claim_check_id, created_at, scope, k, input, counts, rows, skips. Row status is supported|mixed|unsupported. Supported quotes occur in the indexed chunk. No LLM

paperful.evidence.v1

state/evidence/<stamp>/

evidence

T1

Frozen keys: schema, evidence_id, created_at, scope, rows, counts, skips. Cell is a quote in the held PDF or the literal check this. No LLM

paperful.peer_review.context.v1

state/peer-reviews/<id>/<stamp>/context.json

peer-review (context / context-web)

T1

Compact investigation log: summary, retrieve rounds, novelty search, Q&A. No passage text. Written only when that lane ran

paperful.rewrite.plan.v1 / paperful.rewrite.pack.v1

state/rewrites/<id>/<stamp>/

rewrite

T2

Edit plan plus pack metadata. Never overwrites the source manuscript

paperful.rq_answered.v1

state/rq-answered/

rag.answered

T2

—

paperful.rag.text.v1

extracted text cache

rag.extract

T3

Rebuildable

paperful.rag.index.v1

LanceDB meta

rag.index

T3

Not a promise

(no schema)

state/rag/evidence/

rag.evidence

T3

Advanced Ask summary cache; keyed by chunk, question, model

paperful.e2e_stack.report.v1

e2e stack reports

e2e_nba

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

tests/test_sync.py::FakeZotero

A library with versions, a trash, and call counts. For the refresh and the catalogue

tests/conftest.py::FakeListing

Mixin for a stub client that lists Item objects. For CLI tests

tests/test_write_through.py::FakeLibrary

A manager with write calls. For MirroredBackend

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, and mypy on the modules under [tool.mypy] files in pyproject.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 in pyproject.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

paperful (created on first successful upload)

Owner

glen-w

Repository

Paperful

Workflow

publish.yml

Environment

pypi

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.