πŸ— Architecture

Status: reference.

What runs, what each part writes, and which parts are optional. Written for someone who has the pipeline working and wants to change something. Every flag is in CLI.md, every setting in CONFIG.md, and the design rationale in DESIGN.md.

🧩 The four layers

A deterministic corpus layer, a generative drafting layer, an optional enrichment layer that deepens the corpus, and an advisory review layer you run over a finished draft. The numbers are the order you meet them, not a dependency rank. Every edge is one layer reading a file another wrote; no layer calls into another:

corpus (sync) ──ledger, parsed/──▢ drafting (skills + gate chain) ──draft──▢ review
     β”‚                                    β–²                                    β”‚
     └──▢ enrichment (-m chitragupta.enrich) ─docling/, chroma/, passagesβ”€β”€β”˜              β”‚
                        └───────────────── passages β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Diagram: architecture layers

Two properties carry the safety argument:

πŸ“¦ Package commands beside the layers

chitragupta init, doctor, install <stage> and figure sync|check|new|look sit on the package rather than in a layer. None of them reads or writes the ledger or takes the write lock. figure works on one figure file rather than a draft, so it is not a draft verb (figure-checks/README.md). Its code lives in chitragupta/core/figure/ and its parser in chitragupta/cli/figure/; chitragupta/figure.py is a shim that only delegates to the parser, so python -m chitragupta.figure keeps working. init, doctor and install are split the same way: their code in chitragupta/core/, beside the modules more than one layer reads, and their parsers in chitragupta/cli/, behind the shims chitragupta/init.py, doctor.py and install.py.

πŸ—‚ Where the code lives

The top level of chitragupta/ holds the entry points and nothing else; every module behind them sits in core/, grouped by layer, or in cli/ if it is a command's front end. tests/core/test_top_level.py pins the list, and tests/ mirrors it (tests/core/<layer>/, tests/cli/<layer>/, tests/webapp/).

Path under chitragupta/ What it holds
__init__.py the package
__main__.py the shim the chitragupta and cg console scripts and python -m chitragupta run: it delegates to cli/main.py
corpus.py, sync.py, draft.py, review.py, enrich.py, figure.py, doctor.py, init.py, install.py shims: each delegates to its front end in cli/, so python -m chitragupta.<name> keeps working; sync.py only refuses (exit 64)
cli/main.py the chitragupta/cg command tree: parses the command name and forwards the rest
cli/command_help.py, cli/help_format.py the help index and the ClickParser every --help uses
cli/corpus/ the corpus layer's dispatcher (__init__.py) and its sync, ledger, topics and discover verbs
cli/draft/ the drafting layer's dispatcher (__init__.py), each of its thirteen verbs (gate, dossier, retrieve, references, evidence, render, style, spec, unit, registry, tldr, figures and diff), the three private modules that run and print spec, unit and registry, and the twelve _dossier_*.py modules that print every dossier subcommand
cli/review/ the review layer's dispatcher (__init__.py), which hangs each aid's own parser off one parser; _registry.py, which names each aid's module; every aid's parser and text, and _emit.py, which prints them
cli/enrich.py the enrichment layer's parser, and the printer of the run core/corpus/enrich/run.py holds
cli/figure/ the figure command's dispatcher (__init__.py) and its sync, new, look and check verbs, each with its parser and text; their builders are core/figure/_commands.py and _look_command.py
cli/doctor.py, cli/init.py, cli/install.py the package commands' parsers and text, over core/doctor.py, core/init.py and core/install.py
cli/webapp.py the webapp command's parser, which imports webapp/ only once it has parsed, and prints webapp --json's document from core/webapp_runtime.py
cli/_run.py the end every split command's main shares: call the builder, print its text or JSON, print a refusal, exit with the verdict; and the sink that prints the core's notices. For corpus sync and enrich under --json, the JSON Lines stream: a start line, each event, one terminal line
core/corpus/, core/draft/, core/review/, core/figure/ each layer's code; enrichment is core/corpus/enrich/
core/draft/paper_passages.py the webapp reader's paper: the passage ladder's passages for one citekey, with its title and status, read from the ledger read-only
core/ what more than one layer reads: config.py with config_load.py, config_enrich.py and config_path.py, the ledger paths, the lock, the overlap index, the installed version (version.py), and init, doctor and install
core/envelope.py, core/results.py, core/invocation.py what every --json document carries (#1275): the verb, command and version envelope and its version reader; the command() decorator, which registers a builder under its verb, hands it the envelope and collects the run's notes into notes; the types a command's canonical invocation is declared with, and the rule that writes command from them
core/webapp_runtime.py the webapp's private runtime folder outside the project, one per project under the per-user state directory (server.json, its lock and open.html), and webapp --json's document naming it
core/refusals.py, core/events.py, core/verdicts.py how a command's core reports without print or sys.exit: a refusal is a raised Refusal, carrying its exit code and HTTP status; a note or progress line is an event emitted to the sink the caller installed; a verdict is a value the payload holds, turned into the exit code by verdicts.exit_code
core/policy/ the approval model's policy (APPROVAL-MODEL.md): rows.py, the tier table as data, one row per command and per mode a flag selects, and matching, the rows a builder's arguments select; lines.py, which reads a command line; sequence.py, which splits a line of plain commands joined by ; or && into the commands decide_all judges; decide.py, whose decide answers allow, deny or ask for one tool call, and actions.py, the actions, layout and decision it judges and answers with; several.py, whose decide_all gives one answer for a request that makes several; homes.py, the variables, the person's Codex home and the root's instruction files that decide denies on every harness; opencode.py, the OpenCode server's password and the root's config files, which decide keeps from the agent; private.py, the one list of private directories every path rule reads, the runtime folders among them; reach.py, which file paths and words of a line reach one; network.py, the programs and git subcommands that reach the network; search_options.py, the read-only options of each recursive search program; state_home.py, the state variables and the state/chitragupta paths that reach any project's webapp runtime folder; cards.py, the text of each reason, the answers a card offers and the sign-off card; scope.py, the scope file's format and load(); draft_paths.py, the bound draft's dossier, figures and mirror paths by path arithmetic; binding.py, which arguments of each draft-scope write row say where it writes; guard.py, the scope guard results.command runs before every builder; terminal.py, which turns decide_all's verdict into a terminal harness's answer, and terminal_rows.py, the terminal scope's listing for whichever draft a row names; claude_calls.py, codex_calls.py and opencode_calls.py, which turn each harness's tool call into the actions decide judges. It imports only the standard library and core/refusals.py, since a hook pays its imports on every call
core/terminal_hook.py, cli/terminal_hook.py, terminal_hook.py the terminal policy hook (#1332): the core turns one harness call into the policy's answer in that harness's shape, and refuses a write into the package that runs it; the cli/ module reads the payload, keeps the hook's deadline and exits 2 on any failure; the top-level shim is the module the hook command runs
core/terminal_profile.py, core/terminal_plugin.js what chitragupta init and the release zip write into .claude/settings.json, .codex/hooks.json and .opencode/opencode.json: the hook command and the static deny rules; and the OpenCode plugin that runs the hook from tool.execute.before
core/terminal_policy_check.py doctor's report of the terminal policy: a harness config without it, a hook interpreter that cannot start, and a Codex hook that is not trusted
core/agent_layout.py the Layout the policy reads, for the webapp and the terminal hook
webapp/ the loopback-only webapp: serve.py refuses or starts the server, the rest is the server and its app; _executor.py, the one single-thread executor every in-process core call runs on; paper.py, the read-only /api/paper route over core/draft/paper_passages.py, and /api/draft/tldr/show and /api/draft/figures over draft tldr show's and draft figures' builders; drafts.py, the read-only /api/draft/dossier/list route the draft selector lists, /api/draft/dossier/status over draft dossier status's builder, and /api/draft/dossier/outline and /api/draft/gate; review.py, /api/review/synthesis, never filed; book.py, /api/draft/spec/status, /api/draft/spec/show and /api/draft/unit/status; _paths.py, the bounds each of those routes checks before the core runs, and confined() with its areas (the project, the two output mirrors, the rendered mirror, the dossiers); corpus.py, the /api/corpus/ledger and /api/draft/retrieve/search routes over corpus ledger's and draft retrieve search's builders; _jobs.py, the one-slot job runner (#1271), which starts corpus sync --json or enrich --json as a child in its own process group on the event loop, never the core executor, relays its JSON Lines and stops it with the server; _jobs_process.py, how that group is started, interrupted, terminated and killed on POSIX and on Windows; _jobs_buffer.py, the replay buffer and each reader's queue; _jobs_events.py, the runner's own events and the job's state
webapp/_routes/ the read views (#1269): _reads.py, ReadRoute and the one handler every one of them shares, which refuses an undeclared query key, bounds each value and calls the command's builder on the core executor under the read scope; draft_reads.py, review_reads.py and project_reads.py, each layer's routes as data, the review aids that always file running with filing off; read_views.py, VIEWS, every read view the page lists (its route, its CLI leaf and each query field's parameter), which scripts/gen_schemas.py writes to assets/schemas/webapp/read-views.json for the page's Commands screen. The tier-2 write routes (#1270): _writes.py, WriteRoute, the one POST handler every one of them shares, which refuses any body field it does not declare, confines each path, answers 409 while the same output is still being produced, and calls the command's builder on the core executor as a person's click; draft_writes.py, review_writes.py and project_writes.py, each layer's routes as data, every one fixing the mode its row of the tier table selects; output_files.py, GET /api/output, which serves a file a write produced from content/rendered/, content/review/ or the root's dossier archive, behind the token; write_views.py, VIEWS, every write route the page offers (its route, leaf, body fields, button and the payload keys naming its files), which scripts/gen_schemas.py writes to assets/schemas/webapp/write-views.json. The tier-3 job routes (#1271): jobs.py, POST /api/corpus/sync and POST /api/enrich, whose bodies become the child's arguments and refuse a destructive option the page did not confirm, and the current job, its event stream and its cancel
webapp/agent/ the agent session: harness.py chooses the harness and checks it is installed; adapter.py, the interface each harness's adapter implements; claude.py, the Claude Code process and its control protocol; _claude_messages.py, which reads its stream-json into events, with core/policy/claude_calls.py turning a tool call into decide's Action; _ask_hook.py, the PreToolUse hook that answers ask; opencode.py, the OpenCode adapter over one opencode serve, with _opencode_server.py, the process, its password and start-up checks, _opencode_checks.py, the session's ruleset and the config check, _opencode_messages.py and _opencode_items.py, which read its event stream into events and requests, _local_http.py, its standard-library HTTP client, and opencode_home.py, the webapp's OpenCode home, sharing _auth_link.py with Codex's; opencode_plugin.js, the webapp's OpenCode plugin, which refuses what decide denies through _opencode_hook.py and keeps the server's password out of the shell, and _opencode_plugin_files.py, the settings and layout it reads beside the scope file; events.py, the stream's event types; scope_files.py, the private scope directory and each session's scope file; session.py, one tab's session, and _session_kit.py, its stream's subscriber and the refusals its routes answer with; _approvals.py, which answers every call with decide_all, and _approval.py and _signoff.py, its approvals' events and a sign-off's card; draft_binding.py, the bound draft: the one-tab lock, the bind snapshot and the rollback; draft_watch.py, which runs draft gate whenever the bound draft's bytes change; sessions.py, every tab's session, the draft locks and the grace period; routes.py, the seven /api/agent/ routes, and replies.py, the bodies four of them return

Every argparse front end is in cli/.

Every command but webapp is split into a core and its printing (#1280; webapp --json reports through core/webapp_runtime.py and serves nothing): a build_<verb> in the core returns a payload, and its cli/ module prints it through cli/_run.py. The core never prints, exits or writes a standard stream; it raises a Refusal, emits events and returns. Every cli/ entry point (cli/main.py, the four layer dispatchers, enrich, figure, webapp, doctor, init and install) runs the command inside the sink, so a note the core emits reaches the terminal on the stream it used before. tests/test_import_direction_scan.py holds those rules with no allowlist, and tests/cli/test_census.py fails on a command that is not split.

πŸ“š Layer 1: the corpus layer

One entry point, python -m chitragupta.corpus, with four verbs: sync does the work, and ledger, topics and discover read what it recorded. The layer's code lives in chitragupta/core/corpus/; chitragupta/cli/corpus/__init__.py dispatches the verbs, chitragupta/core/corpus/sync.py holds the run itself and chitragupta/cli/corpus/sync.py prints it.

sync reads papers/bibliography.bib, updates one ledger row per citekey, resolves each PDF from the entry's file field, and extracts text to content/parsed/<citekey>.txt. It is incremental: a PDF whose bytes have not changed is not re-parsed. It also reports near-duplicate citekeys, a backend that starts losing word boundaries, and stale citekeys (deleted only under --remove-stale). Exit codes are 0 clean, 1 a parse failed, 2 another writer holds the lock, 3 the bibliography has a hole (CLI.md).

ledger is read-only, takes no lock and runs on bare python, so it answers "what does the corpus hold?" while a sync runs.

✍ Layer 2: the drafting layer

Twelve user-facing skills in .claude/skills/: six write a new draft, three revise an existing one, book-assembler composes a book from accepted units, figure-drawer draws the figures the others ask for, and ai-images makes a picture from a prompt, drafts nothing and runs none of the chain below. GENRE.md says what each produces. The layer's code lives in chitragupta/core/draft/, its front ends in chitragupta/cli/draft/, and chitragupta/draft.py is its one entry point.

Each skill retrieves from the corpus layer, drafts into content/drafts/, then runs the same chain on its own output:

  1. python -m chitragupta.draft gate <draft>: the hard gate. The skill loops until it exits 0 and presents nothing before that.
  2. python -m chitragupta.draft references <draft>: an IEEE reference list from exactly the citekeys cited (skipped for thesis .tex fragments, whose surrounding LaTeX owns the bibliography).
  3. python -m chitragupta.draft render <draft> --format pdf.

The gate runs at three points, and only one depends on the skill. A hook runs it on every write under content/drafts/, the skill runs it before presenting, and draft render runs it before producing any format, so a draft written around the hook still cannot become a document. HARNESS.md has what each harness enforces and HOOKS.md the hooks themselves.

The skills only read the corpus. They never run sync or the enrichment layer: both take the write lock and can run for tens of minutes, so starting one is your decision. Only sync writes the ledger, through ledger.connect(); every reader opens it with ledger.read_connection(), which creates nothing and refuses a missing or outdated ledger. The gate is the exception: with no ledger it still runs and fails every citekey closed. On an empty ledger the citation-grounded genres stop, and the two teaching genres ask whether to continue uncited.

🧠 Layer 3: the enrichment layer

This layer extends the corpus layer. Nothing in it is generative, no skill runs it, and it takes the same write lock as sync. Its one entry point is python -m chitragupta.enrich, a shim that only delegates to chitragupta/cli/enrich.py, which prints the run chitragupta/core/corpus/enrich/run.py holds:

.venv-full/bin/python -m chitragupta.enrich --stages docling,embed
.venv-full/bin/python -m chitragupta.enrich --for-draft content/drafts/digital-twins.md
Stage Writes
docling content/docling/<doc>.md and a .passages.json sidecar of quotable passages; the only stage --for-draft scopes
embed content/chroma/: a vector per 200-word chunk
bertopic content/topics.json: a cluster per document
extract-keywords content/keywords.toml: the papers' own declared keywords
seed-topics content/topic_seeds.json: citekeys matching the seed phrases
converge content/topic_set.json: emergent and named topics joined
topic-graph content/topic_graph.json (TOPIC-DISCOVERY.md)

A review report and a render are deliberately not stages: hosting them here would make this layer import the review and drafting layers, and make them wait on a running sync. Each stage reports ok, partial, skipped or error instead of crashing on a missing dependency, and none needs an LLM API key. What the stages are for is in RETRIEVAL.md; scoping is in LADDERS.md.

A skill reads what this layer produced (content/chroma/, content/docling/) when it exists and falls back to the lightweight default when it does not. Reading an artefact is not calling a layer.

πŸ” Layer 4: the review layer

Eleven aids behind one command, run over a finished draft (or, for union, a book). REVIEW.md covers what each answers and how to read its report; this section is the layer's boundary only:

Output lands in content/review/, mirroring the draft's path, with chitragupta/core/review/__init__.py owning that contract. The layer's code, and the seven modules only it imports, live in chitragupta/core/review/, and its dispatcher in chitragupta/cli/review/; chitragupta/review.py is a shim that only delegates to the dispatcher, so python -m chitragupta.review keeps working. The layer is called review, not verification, because the gate is the verification and lives in the drafting layer.

Which side a check falls on is decided by what it is measured against, not by how decidable its answer is. The gate compares a citekey to the ledger, which is ground truth, so an absolute verdict is available. A check measured against a recorded preference or against a parse can be wrong for reasons outside the draft. quotation is the hard case: its answer is binary, but it is measured against today's parse, which a re-parse or a switched backend can change, so it needs a third outcome, unverifiable. Such a check reports and never blocks, whichever layer it lives in. A harness may guarantee that it runs and that its findings are seen, never that they were obeyed, which is why DEVELOPER-AGENTS.md bars promoting any new check into a gate beside chitragupta/core/draft/citation_gate.py.

verbatim scan is the gate's complement: the gate proves each citekey is real, and the scan reports what wording came with it. It stays a review aid (SOUL.md, PLAGIARISM.md).

β™» Incremental by default, honest about failure

Nothing is recomputed without a reason. sync, the embedding index, the topic model and the Docling stage each skip input that has not changed, so a second run over an unchanged corpus costs close to nothing and sync is safe on a schedule. A stage that cannot run says so, with missing-binary or skipped, rather than crashing or silently succeeding.

πŸ” What is reproducible, and what is not

Run the pipeline twice over an unchanged bibliography and some artifacts come back byte-identical, some equivalent, and one genuinely different.

Artifact Stable across a re-run on unchanged input?
content/ledger.sqlite rows Yes, except last_synced, which is wall-clock. Paths are stored relative, so moving the project re-parses nothing
pdf_size, pdf_mtime_ns Only while the file is untouched; a fresh mtime causes a re-hash, not a re-parse
content/parsed/<citekey>.txt, pdftotext Yes: byte-identical, measured
content/parsed/<citekey>.txt, docling No, under a worker pool: about 1 in 300 differed
content/parsed/<citekey>.passages.json No, and this is the one that matters (below)
content/rendered/*.md, *.tex Yes: byte-identical, measured
content/rendered/*.pdf, content/review/*.pdf No: the TeX engine embeds a timestamp and /ID
content/review/*.md and .json Yes: no wall-clock line, so they diff against the next revision. A re-parse that moved a quoted span moves them too
content/topics.json Yes, but a topic id is not a stable identifier: adding a document can renumber every topic
content/retrieval_index.json, retrieval_passage_index.json, content/overlap/ Caches: delete them and the next run rebuilds them
content/chroma/ Persistent and incremental; inherits its input text's instability

The passage sidecar. Docling groups elements slightly differently under load, and chitragupta/core/draft/passages.py writes one passage per element, so a bibliography entry can split in two or two can merge. About 1% of across-configuration comparisons changed a passage's text. So:

Docling exposes no determinism setting, and torch's use_deterministic_algorithms raises rather than degrades. bench/RESULTS.md has the measurements.

🚫 What this architecture does not do

It also does not sandbox a PDF, a TeX run or Pandoc; SECURITY.md lists what it does and does not protect.

πŸ”§ What each capability requires

Capability What it needs
Parse the bib file bibtexparser (venv)
Extract PDF text pdftotext (os-deps stage), or docling (CONFIG.md)
Ledger, BM25 retrieval, gate, references, md render stdlib only
Prose conformance (draft style) stdlib, plus vale on PATH
Docling, embeddings, BERTopic, review support's model, verbatim scan's embedding tier venv, enrich group
tex/pdf render pandoc, LuaLaTeX, latexmk and the fonts in chitragupta/core/pdf_fonts.py
draft diff --format pdf latexdiff and bibtexu, plus the above

🐍 Which interpreter, and why

Tier Needs Commands
1 bare python, stdlib only chitragupta.draft (all thirteen commands), chitragupta.corpus ledger, chitragupta.review (all eleven aids)
2 venv + bibtexparser chitragupta.corpus sync
3 venv + the enrich group python -m chitragupta.enrich; the embedding search (embed_index.search()) that deep-research's agents and draft-reviser may use

The gate chain is deliberately in tier 1, so the pipeline's one safety guarantee cannot be blocked by a broken or missing virtual environment (PEP 668 makes that a slow fix on most distributions). CLI.md lists each command's tier. Two review aids reach past tier 1 for one optional part (review support's model, verbatim scan's embedding tier) and report that part as not run without it.

One entry point per layer, one level deep. The command surface is chitragupta <layer> <verb>, with python -m chitragupta.<layer> <verb> alongside it for the hooks and skills (PACKAGING.md). A layer's code may nest as deep as it likes; its command surface does not. The submodules inside chitragupta/core/corpus/enrich/ and chitragupta/core/review/ carry no __main__ block, so python -m chitragupta.core.corpus.enrich.docling_parse imports the module and exits 0 having done nothing, a silent trap for which the price is exactly one --help per layer. Under the enrichment and review layers' own names the same spelling is an error instead: chitragupta/enrich.py and chitragupta/review.py are one-file shims, not packages, so python -m chitragupta.enrich.<module> and python -m chitragupta.review.<aid> exit 1. The drafting layer's modules sit in chitragupta/core/draft/ and chitragupta/cli/draft/ behind chitragupta/draft.py and carry no __main__ block either. The one module that refuses instead is chitragupta/sync.py, because it is the spelling that sits in a crontab: it prints python -m chitragupta.corpus sync and exits 64. tests/cli/review/test_review_entrypoint.py, tests/cli/draft/test_draft_entrypoint.py, tests/cli/corpus/test_corpus_entrypoint.py and tests/test_command_depth_scan.py pin the rule in code and prose.

Every --help uses ClickParser from chitragupta/cli/help_format.py: argparse laid out the way click prints it, with no new dependency.

πŸͺœ Ladders and tiers

A ladder is a chain the code walks automatically, falling to the next rung when one cannot answer: evidence passages, the enrichment text source, and the accelerator. A tier is a menu you choose from, with no automatic descent: the parser backend, the interpreter, the render format. A ladder degrades silently; a tier fails loudly and says what is missing. LADDERS.md has each one and what its bottom rung costs.

The detection tiers of verbatim scan are the exception: all that can run do, and each finding is labelled exact, skip-gram or embedding. A tier that could not run says so, so a clean run means "nothing found by the tiers that ran" (PLAGIARISM.md).

πŸ”’ One writer at a time

sync and the enrichment layer take the same lock, content/pipeline.lock.db. The second writer to start exits 2, and the lock releases itself if its holder is killed. Readers are never blocked: corpus ledger, the gate, retrieval and the review layer all run during a sync. DESIGN.md has the reasoning.