# Latris

> Latris is an evidence-native modelling workbench — a Python CLI plus a
> FastAPI/WebSocket server backend — where every project is a git repo,
> evidence and provenance are first-class data, and AI assistance produces
> human-approved structured proposals. This file maps the documentation
> for AI agents; humans start at README.md.

Install: `pip install "latris[data,quant]"` (Python 3.11+, git; the extras add SD integration and Bayesian inference). The guide for AI agents ships with the package — `latris docs` prints it with no network — and `latris capabilities` lists what Latris can do. Source: https://github.com/Shannon-Bengtson/latris (Apache-2.0).

Working in a chat app (Claude, ChatGPT) rather than a shell? Use the Latris connector at https://mcp.latris.app/mcp instead of the CLI — see https://latris.app/ai/.

## Project

- [README.md](README.md): what Latris is, install, quickstart, and an "For AI agents" quickstart section.
- [latris.app](https://latris.app): the product website. The Latris app (app.latris.app — the GUI, hosted report links, Word / review-pack / story exports) is built on this open library.
- [docs/README.md](docs/README.md): documentation index.
- [docs/FOUNDATIONS.md](docs/FOUNDATIONS.md): the methods Latris implements and the literature behind each — a work is cited only where Latris implements it, with limits stated. The report's "Methods and foundations" section, `latris foundations`, and the capability manifest's `foundations` block are generated from the same registry (`src/latris/operations/foundations.py`).
- [CONTRIBUTING.md](CONTRIBUTING.md): how to set up a dev environment and submit changes.
- [LICENSE](LICENSE): Apache-2.0.

## Engineering docs (source of truth for how the system works)

- [docs/engineering/ARCHITECTURE.md](docs/engineering/ARCHITECTURE.md): three-layer architecture (substrate → conceptual → formal views), module layout, the five chokepoint files, CLI↔server boundary contract.
- [docs/engineering/SCHEMA_NOTES.md](docs/engineering/SCHEMA_NOTES.md): pydantic models ↔ YAML mapping, provenance axes, the on-disk project format.
- [docs/engineering/GIT_INTEGRATION.md](docs/engineering/GIT_INTEGRATION.md): auto-commit model, identity enforcement, semantic diffs, collaboration model.
- [docs/engineering/AI_LAYER.md](docs/engineering/AI_LAYER.md): LLM wiring (litellm + instructor + keyring), the closed prompt library, call flow, mock mode (LATRIS_AI_MOCK), delegated invocation for external agents (`ai task emit`/`ai task apply` — no API key).
- [docs/engineering/CLI_REFERENCE.md](docs/engineering/CLI_REFERENCE.md): the full `latris` command catalogue.
- [docs/engineering/TESTING.md](docs/engineering/TESTING.md): test layers, hermetic test contract, coverage policy.

## The worked example (acceptance test, always current)

- [worked_example/worked_example_output.md](worked_example/worked_example_output.md): generated transcript of every CLI command, end to end — the fastest way to learn the tool's actual behaviour.
- [worked_example/worked_example.py](worked_example/worked_example.py): the generator; any new user-facing feature must extend it.

## Building a model with the CLI (start here)

- No network? `latris docs` prints the README's "For AI agents" section from the installed package (`latris docs readme`, `latris docs llms` for this file).

- The README's "For AI agents" section has a complete causal-loop-diagram session: git identity, nodes, links by label, polarity with a rationale (`latris view set cld <edge> polarity + --rationale "..."`), sources and evidence, coherence and loop checks, findings (`latris finding add`), and the client report with a Mermaid diagram (`latris export md --pack client --no-ai`).
- `latris --json <command>` gives machine-readable output for the core commands, analyses (loops, paths, adjustment sets), BN/SD/FCM parameters, inference and simulation.
- Ask before you build: unless the request already says, ask the person (one message, at most three short questions) for the background and the decision it informs, who will read it, and what they expect the answer to be. Record it with `context:` in a build spec (`background`, `audience`, `boundary`, `intuition`) or `latris project set background|audience|boundary|predictions "..."`; the report opens with it. If they'd rather you just build, record each unanswered point with `latris question add` or `latris assumption add`.
- Ask at each phase too: `latris checkpoint show` (printed after `build` and `check handover` when you're an agent) gives the next checkpoint — framing, structure, values, surprise, audience — with questions built from the model (named factors, the least-supported link, the values sensitivity ranks highest). Ask them in one message and end your turn; record the person's words with `latris checkpoint record <checkpoint> --answers "..."`. Nothing is refused: to carry on without them, `latris checkpoint skip <checkpoint> --reason "..."`, or `latris checkpoint pace just-build` if they said to just build. The report's "What the person reviewed" section shows each one answered, skipped or never asked.
- Keep what you read: `extract:` on a source in a build spec (or `latris ref snapshot <key> --url ... --extract "..."`) stores the abstract or passage you read, so a check of that source is grounded in visible text.
- One model, several views: `latris project select-models cld fcm` (or `bn`, `dag`) adds a quantitative view of the same factors and links — set weights or probability tables on the diagram you have instead of starting again.
- Who did what: Latris recognises an AI agent from its shell (Claude Code sets `CLAUDECODE`; other agents set `AI_AGENT`). Then the nodes, links, evidence and findings you create are recorded as AI-proposed, `--by` / `--verified-by` default to `ai`, and every commit carries a `Recorded-by-agent:` line. Commits stay in the person's git name — they're responsible for the project. If your shell doesn't say you're an agent, `export LATRIS_AGENT=<your name>` first.
- Approvals are the person's. `mature approve`, `mature review`, `signoff record`, `mapping approve`, `challenge resolve`, and a check or prose `--by human`, ask an agent for `--confirmed-by-person`. Pass it only when the person has looked at the thing themselves and asked you to record their decision — e.g. they read the model in the chat and said "approve the Workload → Burnout link", or "I checked smith2021 — it supports that". The commit then says you recorded it on their instruction. Don't pass it to approve your own work or to clear `check handover`; tell the person what's waiting for their review instead.
- Build a whole model in one step: `latris build --spec model.yaml` (YAML or JSON; `-` reads stdin) adds factors, links with polarity and reasons, sources, citations, assumptions (with target and rationale), questions, proposed findings, challenges, interpretation prose and the outcome as one commit, after checking the whole spec — `latris build --help` lists every key. Mark the outcome with `outcome:` (or `latris view role cld "<factor>" outcome`) so it isn't suggested as an intervention point.
- Quantify and stress-test: system dynamics scenarios (`latris sd set-scenario NAME --set "Var=value"`, compared by `sd simulate --scenario NAME`), uncertainty ranges (`sd set-uncertainty <node> triangular --min --mode --max`) feeding `sd monte-carlo` (percentile bands, seeded) and `sd sensitivity <variable>` (tornado, unreviewed values flagged), and `sd loops` (which feedback loop dominates, when). Results — and `bn query` posteriors — are recorded; the client report shows the latest of each with charts in the hosted report, and they become interpretation claims. A `latris link` carries the parameters and analyses and recomputes them on opening; `latris build --spec` takes `sd:`, `bn:` and `analyses:` blocks.
- Bayesian networks: soft evidence `latris bn query -s "Node=state:0.8"` (afterwards the node is 80% that state; `--likelihood` for likelihood ratios), the most likely explanation `latris bn explain -e "Node=state"` (MPE; `--over` for MAP), and probabilistic sensitivity — `latris bn set-uncertainty <node> --n 20` ("worth 20 observations") then `latris bn monte-carlo <target>` (point estimate with 50%/95% intervals and which tables drive them). All recorded for the report and carried by `latris link`.
- Links true by definition or accounting (departures reduce active volunteers): `confidence: by-definition` in a build spec, or `latris attr set <link> confidence by-definition`. They need no source, don't count against coverage, and the figure draws them solid, not as unproven.
- Checking a source: `latris evidence check "<from> -> <to>" polarity <bibkey> supports|against|off-topic --rationale "..."` records whether the source supports the claim (`--by ai` when an agent runs it; `--by human --confirmed-by-person` when the person read it and told you what it says). Until then reports say "not yet checked against the source".
- Quotes are looked up, not trusted: an agent's `supports` needs `--quote` copied from text Latris holds for the source (a saved `extract` / `ref snapshot`, `ref fetch`, or the abstract; whitespace, quote marks and case are forgiven, `...` marks a gap). A paraphrase is refused, so save the passage you read first. The report says what each check rests on (an extract of the full text, or the abstract or a summary).
- Before handing over: `latris check handover` lists what's left (unsourced links, unchecked citations, sources with nothing on file showing they were read, quotes not found in the stored text, unapproved findings, sections without prose or out of date, contradictions, broken references between files) with a fix for each; exits 1 until clear. `latris check integrity` lists broken references (a link or citation pointing at something that isn't there, duplicate labels or links); `--fix` removes rows left by deleted nodes and links.
- Evidence against a link: `latris evidence add <link> polarity <bibkey> --contradicts` (or `contradicts: [<bibkey>]` on a link in a build spec). It stays on the same link as the supporting sources; reports show both sides under "Contested links" and it doesn't count toward coverage. It is still unchecked until someone reads it (`evidence check ... against`).
- Correct the record with commands, not by editing YAML: `latris ref edit <key> --doi|--url|--title ...` (`""` clears), `latris ref remove <key> [--with-citations]`, `latris evidence remove <link> <attribute> <key>`. Give only identifiers you have seen; a source read only as described in another takes `--cited-via <key>` (`cited_via:` in a spec) and the report says it was read second-hand.
- Prose goes out of date: when the model changes after a section was written, `interpret list`/`show`, `check handover` and the report flag it; `latris interpret refresh-claims`, then rewrite it.
- With the Latris connector available (mcp.latris.app chat tools: `create_model`, `get_report`, ...), use it instead of the CLI: its `report_url` is a short link to share. `latris link` is for when there is no connector.
- What you get where: the open-source library (`pip install "latris[data,quant]"`) is the engine and CLI — every analysis, a Markdown report with a Mermaid sketch, and `latris link`. The Latris app (app.latris.app — free account, nothing to install) adds the hosted interactive report (typeset figure, result charts, interpretation — what a board reads), the visual editor, Word reports, review packs reviewers fill in, the scrollytelling story, and saved models with short links. A `latris link` link IS the shareable report: send it as it is — don't build a wrapper page or a separate document around it.
- Giving the model to a person: `latris link` prints a link that opens it in the Latris app (app.latris.app) as a hosted report with the full figure, which they can share or save to a free account (editor, Word). Making it needs no network — the model travels inside the link — so it works from sandboxes with no network to latris.app; opening it needs app.latris.app. The link never stops working; the short report address it opens lasts 30 days unless the model is saved, and saving gives a short link that doesn't expire. Known issue: the copy keeps interpretation prose but drops source checks, quotes, extracts and approvals, so don't send a link whose prose says sources were checked or findings approved; see [docs/engineering/SHARE_LINK.md](docs/engineering/SHARE_LINK.md).
- Reports: five packs for different readers (client, publication, review, workshop, audit) — `latris capabilities` describes them. The board-ready version is the `client` pack (answer first, then the diagram, findings and evidence) with its interpretation sections written: `latris interpret initialise`, then `interpret show <section>` and `interpret set-prose <section> "..." --by ai` (no API key needed).

## Choosing a model type (for the person you're helping)

People rarely know which formalism fits their question. Guide the choice by the kind of answer needed, not the drawing:

- "How does this work — what feeds back on what?" → CLD. Start here by default: cheapest honest answer, and every other formalism builds on it.
- "Can this effect actually be estimated, and from what data?" → DAG. Adjustment sets; then, with a dataset (`latris data add file.csv`), `latris analyse estimate <treatment> <outcome> --dataset <name>` picks the smallest valid adjustment set the data measures, fits linear (robust SEs) or logistic regression, shows the unadjusted association beside it, and refuses — naming what to measure — when the DAG says the data can't support it. Causal only under the DAG's assumptions; no counterfactuals.
- "How likely is each outcome, and what would change my mind?" → BN. Discrete states and probabilities; CPTs elicited, learned, or mixed.
- "Which forces dominate, roughly?" → FCM. Signed, weighted links; steady-state tendencies.
- "How will it behave over time if we intervene?" → SD. Stocks, flows, units, scenarios — the most commitment; build the CLD first.
- "How is this programme supposed to work, and which steps are we taking on trust?" → Theory of Change. Levels from activity to impact (`latris toc level <factor> <level>`); `latris toc check` lays out every pathway from an activity to an impact and, link by link, whether it is checked, cited, untested or contested, with its stated assumptions. Process tracing weighs the evidence: `latris toc prior "A -> B" 0.6`, `latris toc test "A -> B" <name> --if-true 0.9 --if-false 0.3 --found` (hoop, smoking gun, doubly decisive, straw in the wind), then `latris toc trace` for each link's posterior, each pathway's confidence and the most informative test still to run. With data over time, `latris toc impact <outcome> --dataset D --time COL --at T` gives an interrupted time series (add `--group COL --treated V` for difference-in-differences), with a caution for each validity check that fails.
- "What combinations of failures cause this, and how likely is it?" → Fault Tree. `latris ft event <factor> top_event|intermediate_event|basic_event|undeveloped_event`, link inputs to the event they feed (`edge add <input> <event> --kind logical`), `ft gate <event> and|or|vote --k K`, `ft probability <event> <p> --source <where>`; `ft analyse` gives minimal cut sets, single points of failure, the exact top-event probability and importance (Fussell–Vesely, Birnbaum, RAW), flagging important values nobody has verified. Assumes independent basic events. How sure: `ft uncertainty <event> --median 1e-3 --error-factor 3` on uncertain probabilities, then `ft monte-carlo` (percentiles, mean vs point estimate, which ranges drive the spread; the same `uncertainty`/`monte-carlo` pair exists for `bowtie` and `et`).
- "What stands between this hazard and harm, and where is it thin?" → Bow-Tie. `latris bowtie element <factor> hazard|top_event|threat|consequence|barrier|escalation_factor`; draw lines with ordinary links (threat → barrier → … → top event → barrier → … → consequence; escalation factor → control → barrier it degrades); `bowtie barrier <b> --type --status --owner --pfd --source`, `bowtie frequency <threat> <per year>`; `bowtie analyse` flags lines with no or one effective barrier, shared barriers, uncontrolled escalation and unowned barriers, and with the numbers gives LOPA frequencies.
- "Once this happens, how does it play out, and how often does it end badly?" → Event Tree. `latris et element <factor> initiating_event|functional_event|end_state`, `et order <heading> …`, `et sequence <end state> "Heading=yes" "Heading=no" …` for each path (the tree must be complete; `et check`), `et probability <heading> <p_yes> [--given "Heading=no"]`, `et frequency <initiator> <per year>`; `et analyse` gives each sequence's probability and frequency, end-state totals and the dominant sequences.
- "Which option should we choose, given what we care about?" → MCDA. `latris mcda element <factor> option|criterion`, `mcda criterion <c> --weight W --direction higher|lower [--worst --best --units --source]`, `mcda score <option> <criterion> <value> --source`; `mcda analyse` ranks the options (each criterion's contribution), names dominated options, and says how far each weight would have to move before the top choice changes, flagging unverified scores the margin rests on.
- "Which explanation does the evidence fail to rule out?" → ACH (analysis of competing hypotheses). `latris ach element <factor> hypothesis|evidence_item`, `ach item <item> --credibility --relevance`, `ach rate <item> <hypothesis> CC|C|N|I|II --rationale`; `ach analyse` ranks hypotheses by weighted evidence against them, flags items that don't discriminate, and names linchpins with whether their sources (ordinary citations on the item) were checked.
- "What should we do, given what we don't know — and is it worth finding out more first?" → Decision tree. `latris dt element <factor> decision|chance|terminal`, link parent → child, `dt branch "Parent -> Child" --label L [-p P] [--value V]`, `dt payoff <terminal> <value>`, `dt uncertainty <chance node> <name>` (same name = same uncertainty under different choices), `dt settings --objective maximise|minimise --units`; `dt analyse` gives the best strategy, the expected value of perfect information per uncertainty, and the probabilities at which the choice flips. How sure: `dt range <terminal | "Parent -> Child" | chance node> beta|gamma|normal|dirichlet --mean M --sd S` (or `--n N`), then `dt psa` (spread per option, how often each is best, EVPI over the parameters, partial EVPI per input, drivers); `dt correlate A B 0.6` samples two ranges together.
- "What does each option cost and achieve over years, and is the better one worth its price?" → Markov cohort model. `latris markov element <factor> state|strategy`, link states, `markov transition "From -> To" <p> [--strategy S]`, `markov reward <state> --cost C --utility U [--strategy S]`, `markov start <state> 1`, `markov settings --cycles N --discount 0.035 --wtp 20000 --cost-units £ --outcome-units QALY`; `markov analyse` gives discounted costs and outcomes per strategy and the incremental analysis (ICERs, dominance, extended dominance, the strategy to choose at the WTP). How sure: `markov range "From -> To" beta --mean 0.1 --sd 0.02 [--strategy S]`, `markov range <state> gamma --quantity cost --mean M --sd S` (utility, or `leaving dirichlet --n N`), then `markov psa` (probabilistic ICERs, acceptability curve, EVPI and partial EVPI per input, drivers); `markov correlate A B 0.8 [--other-strategy S]` samples two ranges together. With two or more ranges on any of these types (or SD): `latris analyse global-sensitivity <model type> [--method sobol|morris]` — each input's share of the result's variance, alone and with interactions.
- "Does the case hold up, and what does it rest on?" → Argument map. `latris argument element <factor> conclusion|claim|question`, link premise → claim, `argument link "Premise -> Claim" --relation supports|attacks [--reason NAME] [--warrant W] [--qualifier probably]` (premises sharing a reason only work together; an objection to an objection answers it), sources on claims as usual (`evidence add <claim> description <key>`), `challenge open "Premise -> Claim" ...` to object to an inference, `argument claim <claim> accepted|rejected`; `argument analyse` says whether the conclusion stands, its linchpins, unanswered objections and which premises have no checked source.
- "What do the equations give for these inputs, and how far can I trust it?" → Equation model: sourced formulas with units and no clock (a physical law, a published parameterisation). `latris eq input <factor> <value> <units> [--min --max]`, `eq parameter <factor> <value> <units> --source <key> [--min --max]`, `eq formula <factor> "<formula>" <units> [--output] --source <key>` (formulas name other quantities by slugified label and add the links they read; units are checked, so a dimensionally wrong formula is refused), `eq check`; `eq evaluate` works out every quantity at the reference values and under each saved scenario (`eq scenario <name> --set "Quantity=value units"`), flagging values outside their stated valid range; `eq sweep --input <factor>` gives an output's response curve; `eq uncertainty <factor> triangular --min --mode --max` then `eq monte-carlo` gives the spread and what drives it.

## Using a model outside Latris (contract and predict)

- A model declares a contract: named inputs (units, default, valid range) and named outputs. `latris contract init <equation_model|sd|bn>` drafts it from the model; `contract input|output|remove` edit it; `contract show` prints it; `contract check` says whether it still fits the model.
- `latris predict --set name=value [--ref <milestone or commit>]` (JSON: `latris --json predict …` — `--json` goes before the command) runs the model on those inputs and records nothing (an analysis is recorded for the report; a prediction is a throwaway call). The result has `outputs`, the `inputs` used, `warnings` (an input outside its valid range: the result is an extrapolation) and `provenance` (the commit, the contract's hash, the review state). Always pass on the warnings and the commit.
- From Python: `import latris; model = latris.load(path, ref="Signed off"); model.predict({"flow_depth": 2.5})`. `latris contract diff <old> <new>` says whether a newer version breaks a caller (exit 1 if so).
- Declare a contract only when the person wants the model used elsewhere. Never invent an input name or widen a valid range to silence a warning. Design: [docs/engineering/PREDICT.md](docs/engineering/PREDICT.md).

Same substrate throughout: factors and links stay, evidence and challenges stay, and quantifying a CLD as FCM/BN/SD later never means redrawing (`project select-models` records the choice + rationale). Triangulating (CLD + DAG on one substrate) is a strength, not a mistake. Human-facing guide: https://latris.app/formalisms/.

## Delegated AI invocation (no API key in this environment?)

- Any of the 45 closed prompts can be answered by you, the agent, instead of a vendor API: `latris ai task emit <PromptName> --inputs '<json>'` writes a self-contained task package (system + user context + response JSON schema). Answer with JSON matching `response_schema`, then have the human run `latris ai task apply --task task.json --from response.json`. Validation, approval gates, and provenance are identical to API calls; the interaction logs `model_id` as `external-agent[:name]`. See [docs/engineering/AI_LAYER.md](docs/engineering/AI_LAYER.md) § "Delegated calls (bring your own agent)".

## Working rules for agents in this repo

- Read [CLAUDE.md](CLAUDE.md) and [src/latris/CLAUDE.md](src/latris/CLAUDE.md) before editing code.
- The per-project state directory is `.graph-tooling` — a frozen data-format constant; never rename it.
- Run tests with `python -m pytest` (parallel by default); regenerate the worked-example transcript with `pytest tests/test_worked_example.py --slow` after changing CLI behaviour.
