Skip to content

πŸ— 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:

1
2
3
4
corpus (sync) ──ledger, parsed/──▢ drafting (skills + gate chain) ──draft──▢ review
     β”‚                                    β–²                                    β”‚
     └──▢ enrichment (-m chitragupta.enrich) ─docling/, chroma/, passagesβ”€β”€β”˜              β”‚
                        └───────────────── passages β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
%%{init: {
  "theme": "base",
  "themeVariables": {
    "fontSize": "14px",
    "primaryColor": "#E6F1F7",
    "primaryBorderColor": "#0072B2",
    "primaryTextColor": "#1A1A1A",
    "lineColor": "#0072B2",
    "secondaryColor": "#E6F5F1",
    "secondaryBorderColor": "#009E73",
    "tertiaryColor": "#FBEFE6",
    "tertiaryBorderColor": "#D55E00"
  }
}}%%
flowchart TB

  subgraph J1["<b>LAYER 1 Β· CORPUS</b>: deterministic, no LLM"]
    direction TB
    SYNC["<code>chitragupta corpus sync</code><br/>needs the venv Β· takes the write lock"]
    OUT1[/"<b>ledger.sqlite</b> Β· <b>parsed/</b>"/]
    SYNC --> OUT1
  end

  subgraph PKG["<b>PACKAGE COMMANDS</b>: beside the layers"]
    direction TB
    P["<code>init</code> Β· <code>doctor</code> Β· <code>install</code> Β· <code>figure</code><br/>bare python Β· no lock"]
  end

  subgraph J2["<b>LAYER 2 Β· DRAFTING</b>: generative, on demand"]
    direction TB
    SKILL["<b>genre skills</b><br/>read the corpus, never write the ledger"]
    CHAIN["<code>draft gate</code>: the hard gate<br/><code>draft references</code> Β· <code>draft render</code><br/>bare python, no venv"]
    SKILL --> CHAIN
  end

  subgraph JH["<b>LAYER 3 Β· ENRICHMENT</b>: optional, you run it"]
    direction TB
    FULL["<code>chitragupta enrich</code><br/>venv + enrich group Β· same write lock"]
    OUT3[/"docling/ Β· chroma/ Β· topic files"/]
    FULL --> OUT3
  end

  subgraph AID["<b>LAYER 4 Β· REVIEW</b>: advisory, no lock"]
    direction TB
    A["<code>chitragupta review &lt;aid&gt;</code><br/>bare python Β· runs during a sync"]
    OUT4[/"<b>content/review/</b>"/]
    A --> OUT4
  end

  OUT1 == "the only evidence" ==> SKILL
  OUT1 == "the only authority" ==> CHAIN
  OUT3 -. "read if present" .-> SKILL
  OUT3 -. "quotable passages" .-> A
  CHAIN --> A
  OUT1 ~~~ FULL
  OUT4 ~~~ P


  class SYNC flow
  class SKILL,CHAIN alt
  class FULL absent
  class OUT1,OUT3,OUT4 alt
  class A absent
  class P absent

  %% house roles: generated by scripts/render_diagrams.py --sync
  classDef flow fill:#E6F1F7,stroke:#0072B2,stroke-width:1.4px,color:#1A1A1A
  classDef alt fill:#E6F5F1,stroke:#009E73,stroke-width:1.4px,color:#1A1A1A
  classDef key fill:#FBEFE6,stroke:#D55E00,stroke-width:2px,color:#1A1A1A
  classDef absent fill:#FFFFFF,stroke:#8C8C8C,stroke-width:1.2px,stroke-dasharray:4 3,color:#1A1A1A

Two properties carry the safety argument:

  • The bibliography is the only entrance. Citekeys come from your own BibTeX export. The pipeline never fetches a paper, never invents a citekey, and never renames one.
  • The gate is the only exit. chitragupta.draft gate consults content/ledger.sqlite and nothing else, so a citekey no sync ever put there cannot survive into a rendered draft.

πŸ“¦ 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
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
core/corpus/, core/draft/, core/review/, core/figure/ each layer's code; enrichment is core/corpus/enrich/
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/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
webapp/ the loopback-only webapp: serve.py refuses or starts the server, the rest is the server and its app

Every argparse front end is in cli/.

Every command but webapp is split into a core and its printing (#1280): 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:

1
2
.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:

  • A skill runs one only where its SKILL.md says so. A genre skill runs verbatim scan before presenting, and agenda-reviser reads review agenda when asked. The rest are yours to run.
  • They take no lock, so they keep working during a sync.
  • None of them gates anything, and none may be promoted to one.

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:

  • A previously quoted span is not guaranteed to survive a re-parse. If a reviewed quotation matters, the reviewed text is the artifact, not its offset.
  • Serial parsing is the stable configuration. [parser].workers = 1 (the default) has not been observed to vary. A pool on one quiet GPU kept passage text stable over 1,200 comparisons; a contended GPU did not.

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 does not fetch papers or write back to your reference manager.
  • It does not verify claims. The gate guarantees a citekey is real, not that its sentence is right; the review aids help you check that.
  • It takes an outline only if you write one (spec.md for a book, outline.md in a draft's dossier, DOSSIER.md).
  • It notices a hand edit but does not adapt to it on its own (USER-EDITS.md).
  • It does not record who wrote a sentence, and will not. An authorship marker would go stale while still looking authoritative (DESIGN.md).

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