Repository navigation
cli reference
This page is generated from
docs/cli-reference.mdin the repository --docs/is the canonical documentation. Direct wiki edits here are overwritten on the next publish; make changes indocs/by pull request.
The sections "Calibrate", "Orchestrator" and "Export" were moved from
CLAUDE.md(unchanged apart from the fixes in the move ledger); the rest of the page is written for readers.
Usage reference for every script in scripts/ that has a command line: what it does, its flags, what it prints, how it exits and whether it needs ANTHROPIC_API_KEY. The slash commands are described in the command reference; how the scripts fit together in the workflows and the architecture. python scripts/<name>.py --help is authoritative for flags.
| Script | Does | Needs ANTHROPIC_API_KEY
|
Detail |
|---|---|---|---|
calibrate.py |
Derives a style guide and a template from your sample PDFs | Yes, unless --mock (automatic without a key) |
Calibrate |
orchestrator.py |
The whole deal pipeline in one process: draft, audit, checks, export | Yes | Orchestrator |
deal_export.py |
Exports a drafted CAM to .docx and .xlsx
|
No | Export |
draft_lint.py |
Lints a CAM or research brief for internal framework vocabulary and unfinished scaffolding | No | Draft lint |
committee_summary.py |
Writes a short committee summary (Markdown and Word) from a deal's recorded state and the policy check | No | Committee summary |
export_readback.py |
Compares a deal's exported .xlsx and .docx with what its record regenerates; read-only |
No | Export read-back |
covenant_cushion.py |
Prints the covenant cushion report: exact EBITDA break-evens and single-shock reverse-stress brackets from a deal's recorded state; read-only | No | Covenant cushion |
research_export.py |
Exports a research brief to .docx
|
No | Research export |
spreading_check.py |
Computes subtotals, ratios and the downside case; checkpoints them | No | Spreading check |
collateral_check.py |
Computes the per-asset and deal-level collateral figures and records them as collateral_analysis plus the collateral projection |
No | Collateral check |
supplied_forecast.py |
Records analyst-supplied forward-year figures for /project as given, with an explicit downside treatment |
No | Supplied forecast |
transcription_check.py |
Reads back figures transcribed from an image, cross-foots them, and records them only after a confirmed digest | No | Transcription check |
policy_check.py |
Computes policy_state; audits a draft |
No | Policy check |
state_manager.py |
Finds deals read-only, lists prior-review candidates, starts a clean review state, checks completed steps, exports Reviewer-view files, and records borrower-supplied consolidated group-basis metadata | No | State manager |
review_compare.py |
Compares two exact dated states of the same deal; optionally checks historical-period restatements | No | Review comparison |
check_model_freshness.py |
Reports newer, deprecated and unknown model IDs using the installed SDK's metadata tables | No | Model freshness check |
source_manifest.py |
Saves a source document; checks sources were saved | No | Source manifest |
conventions.py |
Reads and writes persisted spreading conventions | No | Conventions |
pii_scan.py |
Scans a template for likely-real data | No | PII scan |
check_coverage.py, check_test_count.py, mutation_report.py
|
Test and CI tooling | No | Test tooling |
wiki_publish.py |
Generates the GitHub Wiki page tree from docs/, and publishes it to the wiki with --publish
|
No | Wiki publish |
pr_scope_check.py |
Compares changed paths with the PR's declared file scope; advisory only | No | PR scope check |
pr_base_fail_check.py |
Reports whether the tests a PR adds or changes fail on the base commit; advisory only | No | New tests on the base commit |
run_evals.py |
The local live-model evaluation harness | Only for --live
|
Evaluation harness |
Only the first, second and last scripts can reach the Anthropic API; every other script is deterministic and makes no
network call -- the one exception is wiki_publish.py's --publish mode, whose git clone and push over HTTPS are
the wiki publish -- and is what the slash commands run in their Bash steps.
-
Run from the repository root. Paths such as
deals/,config/,templates/andagents/are relative to the working directory. -
A deal is named by
--companyand--proposal. Together they selectdeals/<Company>/<Proposal>_<Date>/; the dated folder is found automatically (the most recent one), so a deal resumed on another day finds its own state. -
Output. Scripts that return data print JSON to standard output; export scripts print one
Done!line with the path. Progress and warnings go to standard error. -
Exit status.
0on success.1for a failure the script reports itself, including an unusablestate.json(printed as oneerror: ...line, never a traceback; see Troubleshooting).2for a command-line usage error (an unknown flag or a missing required one). A few checks have their own rules, noted per script;--check-stepsand--check-sourcesexit0whatever their result, because the calling command decides what a missing step or source means. - Text. Everything is read and written as UTF-8 and the output streams are made UTF-8 even when redirected, so a non-ASCII name survives a pipe on Windows.
-
--helpis authoritative. The flags below are checked against it by the test suite.
scripts/calibrate.py --type <deal_type> (headless; needs ANTHROPIC_API_KEY) — reads historical CAM PDFs from
inputs/calibration_samples/ (in sorted filename order) and makes two Claude calls against that
text (more when the samples overflow one call's limit -- see "Sample length" below): one extracts
writing style/tone into config/style_guide.md; the other derives a genericized CAM template
(explicitly instructed to strip all real data to [placeholder]s) written to
templates/local/cam/<deal_type>_cam.md. <deal_type> defaults to corporate_credit and
should match the value later passed to orchestrator.py --type.
Each PDF is checked for extractable non-whitespace text. A PDF with none (often an image-only scan) is named in a warning and skipped; if no sample PDF contains extractable text, calibration exits with an error before any model call or output write. Use /calibrate, which reads PDFs natively, or OCR the scans first.
python scripts/calibrate.py --type asset_finance
--mock: skips both Anthropic calls and writes deterministic placeholder output instead
(clearly labeled (MOCK) in the file content) -- for smoke-testing the PDF-reading and
file-writing plumbing without an API key or network access. It never fabricates anything
domain-specific (no invented PD/LGD/rating figures -- that would contradict the grounding rule
and isn't this script's job in the first place); it only proves the pipeline runs end to end.
Triggers automatically, with a printed notice, whenever ANTHROPIC_API_KEY isn't set:
python scripts/calibrate.py --mock --type asset_finance
Sample length (issue #109): each Claude call takes at most CHUNK_CHAR_LIMIT (12,000)
characters of sample text, and the combined text of every PDF in inputs/calibration_samples/
routinely exceeds that. The length check is the run's first decision point -- after the PDFs
are read (local only) but before any API call or file write -- and offers two choices: ignore
(use only the first 12,000 characters, discarding the rest, now stated explicitly) or split
(split the text in memory at paragraph/line boundaries into parts, run the style/template prompt
on each, then merge the per-part results with one consolidation call, hierarchically if there
are very many parts; the merge prompts restate the "zero real data, bracketed placeholders"
and editorial-judgment rules). --on-overflow {ask,split,ignore} (default ask) pre-answers it;
ask prompts on a terminal and falls back to split when there's no TTY, since silently losing
material is the failure this exists to prevent and splitting only costs extra API calls.
--mock makes no calls, so it only reports how many parts a real run would use (it ignores
--on-overflow). Whitespace-only parts (e.g. a lone trailing newline) are dropped before
counting or calling, and if only one non-blank part remains nothing is lost, so there's no
prompt. The original sample PDFs are only ever read, never written or split on disk. Both result
files are computed in memory first, with no API call between the two writes at the end, so an API
failure partway through a long split run leaves any existing config/style_guide.md/template
untouched. A response cut off at its output-token limit prints a [WARN] rather than flowing on
silently. /calibrate has no such cap (native PDF reading) and is unaffected.
scripts/orchestrator.py (headless; needs ANTHROPIC_API_KEY) — the main pipeline. For a
given --company, --proposal, --pd, --lgd and --type, it: loads the Maker/Checker
prompts and style guide, resolves the CAM template for --type via
template_resolver.cam_template_path and includes it in the drafting prompt if one exists,
runs the Underwriter draft and then the Risk Reviewer audit, checkpointing to state.json via
state_manager.write_state after each of those two agent calls (see the state management protocol in CLAUDE.md), then calls deal_export.export_deal (see below) to do the
folder-creation/template-auto-save/export work:
python scripts/orchestrator.py --company "Acme Corp" --proposal "Fleet Loan" --type "asset_finance"
scripts/orchestrator.py --company <name> --proposal <name> [--pd <PD>] [--lgd <LGD>] [--type <deal_type>] [--financials <json>] [--spread <json>] [--collateral <json>] [--stress-assumptions <json>] [--new-review]
-
--companyand--proposalare required and name the deal. A read-onlystate_manager.py --findlookup is used at the single state-resolution point. When no exact record exists but a normalized near match is present, the orchestrator prints one warning line to standard error naming the candidate proposal/date, then continues with today's behavior; it does not refuse the run or select the candidate. No warning is printed when no normalized candidate exists. If the company folder cannot be listed (for example a permission error), the advisory is skipped and the run continues exactly as it did before the lookup existed. See State manager. -
--pd(default0.20%) and--lgd(defaultLGD 3 (15%)) are user-supplied risk inputs and are used exactly as given. The defaults are example values: if you omit the flags they flow into the CAM as if you had supplied them, so always pass your own. -
--typeselects the template and defaults tocorporate_credit. -
A model reply that ends at its output-token limit (
stop_reasonmax_tokens: 4000 for the Maker draft and revision, 2000 for the Checker audit) stops the run with oneerror:line and exit status 1. The partial text is not parsed, saved, audited, recorded as a verdict or exported, and nothing from that call is checkpointed; see Troubleshooting. -
--financialsis a JSON file of raw line items per period (FY-2,FY-1,FY-Current,FY+1,FY+2,FY+3, any subset);--spreadhas the same shape and takes precedence if both are given. Forward years are management's own forecast, never derived by the tool. Periods are merged into the deal's recordedmulti_period_financialsrather than replacing the whole history. Within a period, supplied fields update the recorded fields and any omitted fields remain; computedfinancialsandratiosfor touched periods are recomputed and merged with the other recorded periods. This matches the interactivespreading_check.pybehavior, so a forward-only file does not erase FY-1/FY-Current. Each period key must be one of the framework's period labels (FY-2,FY-1,FY-Current,FY+1,FY+2,FY+3): any other key, for example an entity name such asHoldCo, is refused with oneerror:line naming the key before a model call or write (D19 in decisions). Each period value must be an object of raw line items; a string, number, null, list or other non-object period is refused with oneerror:line naming the period. For recognised raw line-item fields, each non-null value must be a finite JSON number: numeric strings are not coerced and booleans are not numbers. Invalid values (including JSON overflow values such as1e999) are refused with oneerror:line naming the period and field, exit status 1, before a model call or state write. Null raw line-item values retain the evaluator's existing behavior and are not rejected; missing fields keep their existing behavior too. Each supplied stress value must also be a finite JSON number; strings, booleans, null, lists and objects are refused with a key-namingerror:line before a model call or state write. Analyst-supplied history safeguard: a run on an analyst-supplied deal that supplies any historical period (FY-2,FY-1,FY-Current) is refused with oneerror:line and exit status 1, before a model call, with nothing written andfinancials_sourceunchanged; record historical figures with/spread's analyst-supplied mode. Forward-year-only input is refused the same way:financials_sourceis a deal-level flag, and a headless run never recomputes or relabels an analyst-supplied deal, whether or not raw line items exist for its preserved periods (oneerror:line, exit status 1, nothing written,financials_sourceunchanged). Record changes to supplied figures with/spread's analyst-supplied mode; an interactive, forward-only/projectcall is the one allowed way to add framework-computed forward years to such a deal (data model). -
--collateralis a JSON file in one of two shapes (issue #266). An object withassetsand optionalmitigantsis the collateral calculator payload: it is validated and calculated by the same pure code as/collateral, and the run recordscollateral_analysisplus thecollateralprojection, so the workbook's result columns and the policy ground truth see the same figures as the interactive route. A refused payload is oneerror:line before anything is written. A flat list of asset objects (an empty list too, which clears the recorded collateral) is the legacy shape: it is recorded as thecollaterallist only, with no calculator results, and it discards any earliercollateral_analysis(that analysis described the assets the list replaces). A file that holds JSONnullis refused with oneerror:line before anything is written, as is one given to--stress-assumptions:nullwould read as "not supplied" and silently keep the old record (CG563-2); omit the flag to keep it. Without--collaterala run keeps what the deal already has, and its policy ground truth uses a stored analysis only while it is current. -
--stress-assumptions(for a deal whose forecast is analyst-supplied: it must equal what is recorded, or the run is refused with oneerror:line before anything is written) is a JSON file of the downside shocks (revenue_haircut_pct,opex_increase_pct,interest_rate_bump_bps), applied to the forward years only and ignored if there are none. Each supplied value must be a finite JSON number; strings, booleans, nulls, lists and objects are refused with one key-namingerror:line. -
--new-reviewtargets today's dated folder. If it already contains astate.json, the pipeline resumes that review as a rerun after a failure and leaves its existingprior_review_dateunchanged. If the dated folder does not exist, the orchestrator creates a minimal fresh state throughstate_manager.start_review(), linking it to the nearest earlier state-bearing review for the exact same company and proposal; if none exists, it starts unlinked. The link is a date only: no earlier-review inputs or results are inherited. Subsequent pipeline checkpoints preserveprior_review_date. If a dated folder already exists without astate.json, it is refused rather than overwritten (and is refused before any model call, with the folder left untouched). A refusal (including when today's date is not later than the newest existing state-bearing review) exits with oneerror:line and status 1 before a model call or write. A single[INFO]line on standard error says whether the new review was linked and to which date, or started unlinked. A company that has no deal folder yet is the exception: the headless run keeps its earlier behaviour for it, with no link, no refusal and no[INFO]line (a company name typed on a command line is deliberate; the interactive/start-reviewandstate_manager.py --start-revieware the paths that refuse an unknown company), and the near-miss warning described above still applies.
Headless execution needs ANTHROPIC_API_KEY (or other credentials the SDK accepts); without any, it exits with one
error: no Anthropic credentials were found... line and status 1 before a model call. Ordinary runs do not write
state before that credential check. A successful --new-review start may already have created the minimal state and
its optional prior_review_date link; without credentials, no financial/model checkpoint or generated documents are
written, and a same-day rerun resumes that minimal state without relinking. See
Troubleshooting.
scripts/deal_export.py — no anthropic dependency, so it's callable two ways: imported
directly by orchestrator.py (export_deal(...)), or run standalone as
python scripts/deal_export.py --company ... --proposal ... --type ... --draft <path> from
/assemble's Bash step, since Claude has already produced the draft itself by that point and
just needs it turned into deal output files. export_deal() creates the dated
deals/[Company]/[Proposal]_[Date]/ folder, auto-saves the draft as a new
templates/local/cam/<type>_cam.md if that deal type had no template at all yet (never into
the git-tracked templates/cam/ -- see the confidentiality rule in CLAUDE.md), and exports
.docx/.xlsx. Which dated folder and state: an explicit date_str selects both the output
folder and the state.json read for the workbook, so an older review cannot be populated from a newer
review's figures. orchestrator.py passes the date_str it resolved at the start of its run; the CLI takes an
optional --date-str. Without it, state_manager.resolve_export_date_str() prefers the latest state-bearing
folder, then reuses the latest date-shaped output folder if no state exists yet, else uses today.
State auto-resume remains separate: state_manager.resolve_date_str() selects only the latest
folder containing state.json, so an explicit export-only folder cannot hijack later state reads.
A present malformed state.json remains selected so its existing corruption error is surfaced.
Only a folder named exactly <proposal>_<YYYY-MM-DD> counts, so proposal Fleet never claims
another deal's Fleet_Q2_2026-05-01, and --date-str must be a real calendar date in YYYY-MM-DD format, so an
impossible date such as 2026-02-31 is rejected with one error: line and exit status 1. An explicit date that names a dated folder with no state.json is an error (one error: line, exit status 1, nothing
written) when the deal has state in another dated folder; a deal with no state anywhere still exports into the named
folder. A bare library call that
omits date_str retains its existing state auto-discovery, while its output folder still defaults to today.
Without this a deal
finished days after it started exported into a new folder, disconnected from its own
state.json/sources//draft_v*.md (issue #97) -- /assemble no longer needs a prose
patch to re-home state.json.
Before the export runs, each citation that will not be a clickable link in the .docx is
reported as an advisory [deal_export] Citation link warning: ... line on standard error
(a bare URL in a Sources entry, or an in-text [Key] whose source has a URL); the export
then carries on with the same exit status and files, and a source with no URL never warns.
A CAM draft with no populated Sources or References section (issue #583) is reported the same
advisory way: one [deal_export] Sources section warning: ... line on standard error, and the export
continues with the same exit status and files. The check reuses the section finder research_export.py
applies to research briefs -- an ATX heading titled Sources or References (case-insensitive, any
level, not inside a fenced code block or an HTML comment, and not a numbered title such as ## 15. Sources) whose section
contains a list item or an http:///https:// URL, ending at the next heading of the same or a higher
level. A populated section produces no warning.
scripts/committee_summary.py --company ... --proposal ... [--date-str YYYY-MM-DD] writes a one-to-two-page meeting aid
for one deal: <Company>_<Proposal>_Committee_Summary.md and .docx in the deal's dated folder. Without --date-str
it uses the newest dated folder that has a state.json; with it, that exact folder, and the policy check runs on that
same state (policy_check.compute_from_state()), never on a different one.
-
Content: the record and financial basis; the group-accounts disclosure when
group_basisis recorded; the recorded inputs, deal type and guarantees (facility amount, tenor and pricing say "not recorded", because state holds no such key); recorded subtotals and ratios by period, exactly as stored (nullprintsN/A); covenant results now (FY-Current), per forward year (disclosure only) and downside breaches; the required conditions precedent and subsequent; recorded collateral, the security package and the policy check's security gaps; open gaps (a missingspreadstep, steps not recorded,UNRESOLVABLEcounts, saved-source status); the recorded review verdict and iteration count, labelled historical; and a fixed limits section. -
Covenant basis: a current or forward table adds a
basiscolumn only when at least one result row carries the key. Rows without the key showborrowerwhen the column is present; tables with no such row retain their existing layout exactly. The renderer applies the same conditional rule to downside-breach rows if they carrybasis, but currentpolicy_engine.pybreach records do not include that field, so the ordinary engine-generated downside table retains its legacy layout. Exposing basis on those breach records is deferred to a separate policy-engine change. -
Recorded text is shown literally: a value, a key or a table header that holds a pipe, a line break or text that
the Word builder reads as markup (
*, a backtick,[,]) cannot reshape the document or pass itself off as a heading or emphasis:|becomes/, line breaks and runs of spaces become one space, and a value with markup characters (asterisk, backtick, square or angle brackets, or underscore emphasis such as_x_; names likesnake_caseare untouched) is shown as a code span (a backtick inside it becomes an apostrophe). The report title's company and proposal names get the same treatment. -
Nothing new is computed or judged: every figure is a recorded value or a policy-check output, an unrecorded term
says "not recorded", and there is no verdict, grade or recommendation. The policy check runs without a draft, so
draft-level audit findings are "not assessed";
/reviewowns them. -
Writes: only the two report files, each through a temporary file and an atomic replace. A Word failure after the
Markdown was written is reported as exactly that. It never writes
state.json,steps_completed,review_trail, a draft, the source manifest or a template. Running it again replaces both reports. -
Output and exit codes: one JSON object on stdout (
status,selected_folder,markdown_path,docx_path,included_sections,policy_scope). A missing deal or dated folder, a malformed state key (includinggroup_basis) or an unusable source manifest gives oneerror:line on stderr and exit1, with nothing written. A usage error exits2.
python scripts/committee_summary.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan"scripts/export_readback.py --company ... --proposal ... [--date-str YYYY-MM-DD] checks that a deal's exported files
still match its record. Without --date-str it uses the deal's newest dated folder that has a state.json; with it,
that exact folder. It regenerates the expected workbook from the folder's state.json (through the same input
selection deal_export.py uses) and the expected document from the approved Markdown draft that state.json names in
approved_draft_path (which /assemble records), writes both to a temporary directory, and compares them with
<Company>_<Proposal>_Spreading.xlsx and <Company>_<Proposal>_CAM.docx in the dated folder.
-
Workbook: sheet names, order and visibility; defined names; every cell's value (formulas as text, numbers within
1e-9, so an overwritten formula or an edited input is found; a formula where the export wrote the same characters as
text is reported as a
formuladifference, without evaluating either) and its number format, font (name, size, colour, bold, italic, underline, strike), fill, borders and alignment; row and column visibility, row heights and column widths; merged cells, freeze panes, sheet protection; each chart's type, position and the cell ranges it plots; and how many data validations and conditional formats a sheet has. Cached formula results are not evaluated, and a sheet whose used range is larger than 1,000,000 positions (one stray cell in the far corner does that) is refused rather than compared. - Document: the body blocks in order: each paragraph's style, alignment and spacing, every run's text, bold, italic, underline, strike, font, size, colour, highlight, superscript, subscript and capitals, hyperlink targets with the formatting of the link text, embedded image hashes, sizes and alt text; the definition (font, size, colour, spacing) of every style both documents use; each table's style, direct layout (shading, borders, cell and column widths, vertical alignment, spanning) and, per cell, the same paragraph detail; and each section's page size, orientation, margins and its headers and footers (including first-page and even-page ones, and whether each is inherited), compared with the same paragraph, table and image detail as the body. Comments, footnotes, text boxes, themes and file properties are not compared.
-
Output: one JSON object on stdout:
status(matchormismatch),selected_folder, the two artifacts' paths and counts,mismatch_count, up to 200findings(eachartifact,location,kind,expected,actual;truncatedistruewhen there were more) andlimits. Exit0on a match and1on a mismatch. -
Refusals: a missing state, workbook, document or draft, an
approved_draft_paththat is not a relative path to a file inside the dated folder, a damaged file, or a stategroup_basisorfinancials_sourcethat is malformed gives oneerror:line on stderr and exit1, with nothing compared. A usage error exits2. - Read-only: the only files it writes are temporary comparison files, removed on exit. It never edits the deal.
It detects edits made after export and exports that are stale against a changed record. It does not prove the
exporter itself is right (the expected files come from the same builders), does not read CAM prose, and does not
replace policy_check.py or /review. Run it from the directory the export was run from, because a draft's image
paths resolve against the working directory.
python scripts/export_readback.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan"scripts/covenant_cushion.py --company ... --proposal ... [--date-str YYYY-MM-DD] prints the covenant cushion
report for one deal as JSON on stdout. Without --date-str it uses the deal's newest dated folder that has a
state.json; with it, that exact folder. It is read-only: it writes no deal file, state, draft, manifest or
output file, and it makes no network call and needs no ANTHROPIC_API_KEY.
-
Content: for each recorded covenant and each period the policy engine also tests (
FY-Currentplus the forward years with recorded ratios; forward years are disclosure only), the report carries: the covenant row exactly as the policy engine records it (metric, type, threshold, actual, status, headroom, reason, basis when present); the exact EBITDA break-even for the four EBITDA-driven covenants (DSCR, gross leverage, net debt / EBITDA, EBITDA / interest cover) with the side that satisfies the covenant, or the reason no boundary exists; and, for each of the three recorded shocks (revenue haircut, opex increase, interest-rate bump; there is no cost-of-sales shock), two single-shock reverse-stress searches — the base scenario (all shocks at zero) and the downside scenario (the other shocks held at their recorded settings, the searched shock starting from its recorded setting, reporting both the cumulative crossing and the additional cushion beyond that setting). - Searches return brackets, not points: each search brackets the first non-PASS point (FAIL or UNRESOLVABLE alike) by geometric expansion then bisection, and reports the pass/non-pass bracket with its tolerance and the status beyond it. A covenant whose ratio a shock cannot move is reported "not moved"; a non-monotone driver, a point the spreading builder refuses, or a crossing outside the documented bound (revenue haircut 0–100%; opex increase and interest bump up to 10,000) is reported with its reason instead of a cushion. A baseline that is already FAIL or UNRESOLVABLE reports zero remaining cushion with no search.
-
Availability: the searches re-evaluate the recorded raw line items through the spreading builder's own
shock and model functions, so a period whose figures are analyst-supplied (financials_source for FY-Current,
forecast_source for a forward year) or absent from
multi_period_financialsreports its break-even and searches as unavailable with the reason; nothing is invented. Forguarantor_group, the baseline follows the selected entity's fresh spread, while C4's guarantor break-even and reverse-stress searches are explicitly unavailable; borrower raw inputs and shocks are never reused. - Nothing is judged: the report is the mechanical distance to a covenant's first non-PASS result under one shock at a time; it is not a credit decision, and the policy check remains authoritative. A recorded ratio that disagrees with a re-evaluation of the raw lines is flagged as a caveat rather than silently trusted.
-
Output and exit codes: one JSON object on stdout. A missing deal or dated folder, a malformed state key or
an unusable input gives one
error:line on stderr and exit1; a usage error exits2.
python scripts/covenant_cushion.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan"scripts/research_export.py --company ... --proposal ... --brief <path> runs the framework-vocabulary and obvious-placeholder lint on the user-supplied text before resolving its dated output path or creating a folder. It then requires an ATX heading named Sources or References (case-insensitive, any level, not inside a fenced code block) whose section contains a list item or an http:///https:// URL. The section ends at the next heading of the same or a higher level. A missing or empty section exits with one error: line and status 1; nothing is written. Before the export runs, each citation that will not be a clickable link in the .docx is reported as an advisory [research_export] Citation link warning: ... line on standard error (a bare URL in a Sources entry, or an in-text [Key] whose source has a URL); the export then carries on with the same exit status and files, and a source with no URL never warns.
An analyst may explicitly authorise an export without sources. Only then pass --analyst-override-no-sources "<reason>"; the reason must contain non-whitespace text. The brief's .docx gets a final paragraph such as Footnote: No sources list is included in this brief. Exported under analyst override on 2026-10-14: analyst-authorised reason. The reason is not persisted in state.json. The slash command must never offer or infer this override. If the brief already has a populated source section, the flag adds no footnote.
An explicitly authorised release of a brief the Reviewer did not approve uses --analyst-release-unapproved "<reason>". The non-empty reason is collapsed to one line. The flag is refused, with one error: line, exit status 1 and nothing written, when the saved review_trail has no trailing REJECTED entry (no review yet, or the latest verdict is not REJECTED). The exporter counts consecutive trailing REJECTED entries in the saved review_trail, inserts a Review status: Not approved by the independent Risk Reviewer... paragraph immediately after the first document heading, and, after writing the DOCX, appends one {date, passes, reason} record to the review_stopped_by_analyst list in state.json. The list is append-only: no release clears or overwrites an earlier record, a later approved export leaves it untouched, and review_verdict keeps carrying the current verdict. A review_stopped_by_analyst that is already present but is not a list is refused with one error: line before anything is written. This is not an automatic fallback: the slash-command session may pass the flag only after the analyst explicitly chooses the disclosed manual-review option. When both release flags are used, the review status remains near the top and the missing-sources footnote remains last.
scripts/research_export.py --company ... --proposal ... --brief <path> exports a drafted research brief (Markdown)
to <Company>_<Proposal>_Research_Brief.docx in the deal's dated folder, reusing the folder that exists or creating
one. It is deliberately separate from deal_export.py, so a research-only deal never triggers a CAM's side effects
(no workbook, no template auto-save). It has no Anthropic dependency.
python scripts/research_export.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan" \
--brief "deals/Synthetic Co/Synthetic Fleet Loan_brief.md"Done! Research brief exported to deals/Synthetic Co/Synthetic Fleet Loan_2026-10-04/Synthetic Co_Synthetic Fleet Loan_Research_Brief.docx
scripts/research_export.py --company ... --proposal ... --brief <path> runs the framework-vocabulary and obvious-placeholder lint on the user-supplied text before resolving its dated output path or creating a folder. It then requires an ATX heading named Sources or References (case-insensitive, any level, not inside a fenced code block) whose section contains a list item or an http:///https:// URL. The section ends at the next heading of the same or a higher level. A missing or empty section exits with one error: line and status 1; nothing is written.
An analyst may explicitly authorise an export without sources. Only then pass --analyst-override-no-sources "<reason>"; the reason must contain non-whitespace text. The brief's .docx gets a final paragraph such as Footnote: No sources list is included in this brief. Exported under analyst override on 2026-10-14: analyst-authorised reason. The reason is not persisted in state.json. The slash command must never offer or infer this override. If the brief already has a populated source section, the flag adds no footnote.
scripts/spreading_check.py --company ... --proposal ... [--financials <json>] [--stress-assumptions <json>] [--no-update-financials-source] recomputes the borrower-level financials and ratios from raw line items, derives the downside case
when stress assumptions and at least one forward year exist, checkpoints everything to state.json and prints the
updated state (financials, ratios, downside_case, financials_source) as one JSON object, indented two spaces and
ending in one newline (read it as JSON; the order of its members is not a contract). It merges what it is given into what
the deal already has, two levels deep: a correction to one period's revenue keeps that period's other fields, and
re-confirming one stress shock keeps the others. Give --financials for new periods and omit it to recompute from
what is already on file. --no-update-financials-source stops the call stamping framework-computed; /project
always passes it. The keys must be the framework's period labels (FY-2, FY-1, FY-Current, FY+1, FY+2, FY+3): any other key, for example an entity name such as HoldCo, is refused with one error: line naming the key and listing the valid labels, exit status 1, and no state write (the evaluator has no entity dimension; D19 in decisions). Each supplied period must be an object of line items; a string, scalar, null or list period is refused with one
error: line naming the period, exit status 1, and no state write. For recognised raw line-item fields, non-null values
must be finite JSON numbers; numeric strings and booleans are refused rather than coerced. Each stress value must also be
a finite JSON number (not a string, boolean, null, list or object). Invalid input produces one key/period-naming
error: line and leaves state.json byte-identical. A null raw line-item value retains the evaluator's existing
behavior; omitted fields are also unchanged. An unknown raw line-item name — for example
cost_of_goods_sold, admin_expense or interest where the valid names are cost_of_sales,
admin_expenses and interest_paid — is refused with one error: line naming the period and each
unknown key and, when a close match exists, suggesting the nearest valid name, exit status 1, and no state write; no underscore-prefixed
or other metadata keys are allowed (issue #596). A deal with an unknown name already on file still computes
and prints one stderr warning per unknown key naming the period and the key. The same rules apply to the orchestrator's --financials and --spread inputs. The slash
commands /spread and /project run it; see Workflows.
Standalone guarantor (case C3). To spread the already-registered guarantor identified by its stable entity ID,
run python scripts/spreading_check.py --company ... --proposal ... --entity-id <entity ID>. The script reads
only that entity record's multi_period_financials, calls the same evaluate_financial_model(), and stores the
financials, ratios and one source-bound SHA-256 fingerprint per computed period inside the entity record. The
borrower's top-level financial stores and financials_source are unchanged. Entity mode cannot be combined with
--financials, --stress-assumptions or --no-update-financials-source. A period held only in
analyst_supplied_financials is listed as unavailable and is never recomputed. Every result carries
analyst_review_status: "not yet reviewed by an analyst"; missing/mismatched fingerprints or stored results
that no longer match the evaluator are stale and are not printed as current.
python scripts/spreading_check.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan" \
--financials "deals/Synthetic Co/Synthetic Fleet Loan_financials_input.json"scripts/collateral_check.py --company ... --proposal ... --input-file <path> computes the collateral
exposure analysis of issue #266 (register F-049 to F-057 and F-066) from a JSON payload of assets and
non-asset mitigants, and records it atomically: the full analysis goes to the collateral_analysis state
object (per-asset inputs and results, the separate mitigants list, deal-level results, the input_digest
and calculator_version), the backward-compatible collateral projection is refreshed from the same
results, and the collateral step is marked complete only on success. --input-file - reads the payload
from stdin. The whole payload is validated before anything is written; on any refusal the script prints
exactly one error: line to stderr, exits 1 and leaves state.json byte-identical. On success it prints
the analysis as one JSON object to stdout. The pure calculation is importable
(calculate_collateral_analysis()); the CLI does I/O only.
Per asset the payload requires asset_id (matching [A-Za-z0-9-]{1,32}, unique), valuation,
down_payment_pct and est_rv_pct; cap_or_model_value, non_recovery, costs and number_of_units
default to zero when omitted, and lgd_pct is optional (a missing LGD makes max and average LGD N/A,
never zero). Percentages are fractions in [0, 1]; est_rv_pct above the financed share
(1 − down_payment_pct) is refused. Each mitigant requires amount (non-negative) and the boolean
eligible_for_netting — a missing eligibility flag is refused; mitigant_id is optional. See
financial-model.md for the formulas and data-model.md for the
stored shape.
If the deal's stored stress_assumptions carries rv_realisation_pct (issue #549; F-067), the printed
JSON also carries a top-level stressed object with the residual-only stress figures — per-asset
stressed_collateral_value, stressed_coverage_pct, stressed_uncovered_risk and
stressed_net_uncovered_risk, and deal-level stressed_total_collateral_value, stressed_coverage_pct,
stressed_gross_uncovered_risk and stressed_net_uncovered_risk. These are report-only: nothing
derived is written to state.json, and the stored assumption is untouched. An out-of-range or malformed
stored assumption is refused with one error: line and nothing written.
python scripts/collateral_check.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan" \
--input-file "deals/Synthetic Co/Synthetic Fleet Loan_collateral_input.json"scripts/supplied_forecast.py --company ... --proposal ... --forecast <json> [--stress-assumptions <json>] --note <text>
is /project's analyst-supplied mode (issue #124). --forecast holds {"forecast": {"FY+1": {"subtotals": {...}, "ratios": {...}, "lines": {...}}}, "downside": {"description": "...", "periods": {"FY+1": {"subtotals": {...}, "ratios": {...}}}}}: numbers as the analyst gave them, a ratio that is N/A as null, lines (the /spread raw field
names) and downside optional. It validates strictly (unknown names, non-numbers, any forecast/downside period whose value is not an object
of line items, a year with only raw lines, a stressed forecast without a description, and stress values that are not
finite JSON numbers), checks the deal (the state is readable and writable by this checkout, the
basis is compatible: no framework-computed forward years, no framework-computed or unknown-basis history), and then
writes financials, ratios, the optional analyst_supplied_financials, forecast_source, financials_source, the
note and the downside treatment in one state update, printing a summary of which forward years are analyst-supplied
and which downside years are framework-derived or unavailable. Any refusal is one error: line, exit status 1, and
nothing is written. A state that cannot be read or written (a lock that cannot be taken, a full disk) and a malformed
shock already stored in stress_assumptions are also one error: line. When the file is shown to be as it was, it says
so and that nothing was recorded; when a failure came after the file may have been replaced (for example the lock file
could not be removed), or the file cannot be read back, it says the update did not complete cleanly and to inspect
state.json before retrying. --note is required; it
is added to financials_source_note. It never uses the framework's formulas to produce a recorded value; the formulas
are used only to test whether the stress shocks may be applied, which needs every line the covenant ratios read. The
rules are in the financial model.
python scripts/supplied_forecast.py --company "Synthetic Co" --proposal "Synthetic Budget Loan" \
--forecast docs/examples/synthetic_co/forecast_supplied.json \
--stress-assumptions docs/examples/synthetic_co/forecast_stress.json \
--note "Management budget; depreciation is within cost of sales"scripts/transcription_check.py --transcription <json> [--json] reads back figures that /spread transcribed from
an image (a screenshot, a photo, a scanned page) and writes nothing: no deal is read or changed. It prints the image's
SHA-256 fingerprint; the sign conventions in words; the figures grouped by period and statement, each as written
beside the value that would be recorded and how one was read as the other; every figure that will be recorded as
negative; a cross-foot of every subtotal the source states against the sum of the recorded lines that feed it; and a
digest of exactly what it showed (including the declarations and the image's bytes). --json prints the same as
{digest, source_sha256, report, text}.
scripts/transcription_check.py --transcription <json> --commit --confirm <digest> --company ... --proposal ... [--source-note <text>] records the transcription, but only if --confirm is the digest of these figures and this
image as they are now, no cross-foot discrepancy is unresolved, the deal's existing financials_source is the
same mode and the deal's state can be written by this checkout (readable, correctly shaped, not a newer schema
version, a readable sources/manifest.json, and in framework-computed mode a computation that succeeds against what
is stored); otherwise it exits 1 with one error: refused: ... line and writes nothing (no source copied, no state
changed). On success it saves the image as the source of record after checking it against the confirmed fingerprint
(the manifest claim says the figures were transcribed from an image and carries the digest and a fingerprint prefix),
then, in one state update, records the figures, appends spread to steps_completed and appends a record to
financials_transcriptions (holding the fingerprint, never the image). The image is saved before that update and
the two cannot be committed atomically: if the update fails, the verified image and its manifest entry remain with
no figures recorded. In framework-computed mode it recomputes exactly as spreading_check.py
does; in analyst-supplied mode it records subtotals, ratios and any lines exactly as given and needs --source-note,
the confirmed convention, to which it appends a sentence saying the figures were transcribed from an image (stored as
financials_source_note, which the CAM caveat quotes). What it enforces and what it cannot is in
Figures read from an image and
AI assurance.
The staged file holds every figure as text exactly as it appears, plus the unit and how the source writes the signs of costs, cash outflows and liabilities; a worked example is in Workflows.
python scripts/transcription_check.py --transcription "deals/Synthetic Co/Synthetic Fleet Loan_transcription.json"scripts/draft_lint.py --draft <path> --kind {cam,research-brief} [--template <path>] checks a saved Markdown draft without a model call or network access. It prints a JSON object containing findings and exits 0 when none are found, 1 when findings or invalid input require rejection, and 2 for command-line usage errors. For a CAM, pass the exact resolved template to check copied guidance comments and unfilled template tokens. The shared CAM compliance path resolves the template from the recorded deal type, preferring a fork's templates/local/cam/ override. Research briefs have no CAM template, so they use vocabulary and bounded obvious-placeholder checks.
Only the final complete ```json block, with nothing but blank lines after it, is excluded from CAM checks, because it is the structured output and not client-facing narrative; an earlier JSON example, and any prose around it, is still linted. A placeholder is reported in the spelling the draft uses, and a bracketed label followed by a link destination is a link, not a placeholder. A draft with an unterminated HTML comment cannot be linted: the CLI prints one error: line and exits 1, while the shared CAM compliance path reports it as a rejection reason (Draft lint could not run: ...) so a headless run sends it back for revision rather than stopping. A comment problem in the selected template is not the drafter's to fix and still raises: the headless orchestrator reads and checks the template before its first model call and stops with one error: line. A deal type that is not a plain template name (for example Asset Finance) has no template to compare with, so only the vocabulary and obvious-placeholder checks run, as they do when no type is known. HTML comments that the DOCX exporter strips are ignored; comments inside complete fenced code blocks remain visible.
Example:
python scripts/draft_lint.py --draft "deals/Synthetic Co/Fleet Loan_draft.md" --kind cam --template templates/cam/corporate_credit_cam.mdscripts/policy_check.py --company ... --proposal ... [--draft <path>] [--deal-type <type>] prints JSON: policy_state (required
conditions precedent and subsequent, covenant results, security gaps, downside breaches, forward covenant results),
reasons (every reason the draft is code-enforced rejected, empty without --draft unless the recorded structure
itself forces one), compliant, and cam_data_present (false for a deal with no financials, ratios, covenants or
security recorded, i.e. nothing was actually checked, as for a research-only deal). With --draft it audits that
file's trailing structured JSON block and client-facing prose. The optional --deal-type is for legacy state without a
recorded type; when supplied alongside a recorded type it must match. Otherwise the recorded type selects the shipped
CAM template or local override for Rule B. It exits 0 whether or not reasons is empty (an unusable state.json is
the exception: one error: line, exit 1); the caller decides what a non-empty reasons means.
The policy engine resolves each covenant's basis independently. A guarantor_group covenant must name a registered
basis_entity_id whose record has role guarantor, an explicit unique guarantee_id link and a current C3 spread.
The covenant_results and forward_covenant_results identify that entity with basis and basis_entity_id;
missing IDs are shown as null. Missing/ambiguous links, wrong roles, stale or unavailable periods are
UNRESOLVABLE, never tested against borrower or another entity's figures. The command and its flags are unchanged.
python scripts/policy_check.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan" \
--draft "deals/Synthetic Co/Synthetic Fleet Loan_draft.md"scripts/review_compare.py --company ... --proposal ... --current-date YYYY-MM-DD [--prior-date YYYY-MM-DD] [--format json|markdown] [--periods-rolled-one-year] is a read-only, deterministic comparison of two
state.json snapshots belonging to the exact same company and proposal. It uses state_manager.state_path()
for the normal deals/<Company>/<Proposal>_<Date>/state.json layout, reads both files as UTF-8 JSON, and
never creates a folder, changes state, or calls a model.
-
--companyand--proposalare exact identity matches; fuzzy or normalized matching is never used. -
--current-dateis the current review's real calendar date and dated folder. -
--prior-dateexplicitly names an earlier review. When omitted, the current state must recordprior_review_date; otherwise the command refuses rather than guessing from the other folders. -
--format json|markdownselects the output shape (JSON is the default). JSON mode prints exactly one JSON object. Both renderers order changes deterministically and include the number of changed paths, unchanged categories, and categories not recorded in either state. -
--periods-rolled-one-yearis explicit analyst confirmation that historical period labels moved forward by exactly one year. It adds a separate restatement check after the standard by-label comparison; forward periods are excluded. Without the flag the output has norestatement_checkkey.
A missing, unreadable, corrupt, non-object, wrong-identity, impossible-date, non-finite, or too deeply nested (more than 100
levels of objects and lists; real states are a few levels deep) state is one
error: ... line on standard error and exit status 1, with no traceback. A prior date must be strictly earlier
than the current date. Legacy states without schema_version and newer-schema states are read without rewriting
them. Numeric equality uses exact decimal values; delta is present only when both sides record a number. If
financials_source changes, the report warns that movement may not be like-for-like.
python scripts/review_compare.py --company "Synthetic Co" --proposal "Asset Facility" --current-date 2026-10-20 --prior-date 2025-10-20 --format markdown
python scripts/review_compare.py --company "Synthetic Co" --proposal "Asset Facility" --current-date 2026-10-20 --periods-rolled-one-yearscripts/state_manager.py has seven mutually exclusive modes:
-
--find --company ... --proposal ...is a read-only lookup. It prints one JSON object. An exact existing record yields{"record_found": true, "state_path": "...", "date": "YYYY-MM-DD"}, using the newest valid dated folder with astate.json. A present but corruptstate.jsonstill counts as a record; reading it through the normal mode continues to raise the established corruption error. If no exact record exists, the object hasrecord_found: false,company_folder_exists, andnear_misses. Suggestions normalize case and runs of whitespace/hyphens only; they never select a different proposal. The mode creates no files or directories. -
--review-candidates --company ... --proposal ... [--date YYYY-MM-DD]is read-only and prints one JSON object:{"company": "...", "proposal": "...", "date": "...", "candidates": [...], "default_prior_date": "..."|null, "skipped": [...]}.--datedefaults to today, using the same clock source as state-date resolution. Candidates are folders for the exact same company and proposal that have a readable, structurally validstate.jsonand a valid calendar date strictly earlier than the requested date. The array is sorted newest first; each entry containsdateandstate_path;default_prior_dateis the nearest eligible date ornull. Export-only folders, invalid dates, other proposals, and case/spacing/hyphen near-matches are excluded. An earlier dated folder whosestate.jsoncannot be read is not offered as a link, but it is listed inskipped(dateand a one-linereason) so that "no earlier review" is never reported when one exists. The mode applies the same refusals as--start-review(below): an unknown company, or a date that is not strictly later than the newest existing review, is oneerror:line and exit status1. No selection or filesystem write occurs. -
--start-review --company ... --proposal ... [--date YYYY-MM-DD] [--prior-date YYYY-MM-DD | --no-prior]creates a genuinely fresh review.--datedefaults to today. With neither prior option it links to the nearest earlier candidate, or starts unlinked and says plainly that no eligible earlier review was found.--prior-dateselects an explicit eligible earlier candidate; if it is not eligible, the command refuses.--no-priordeliberately starts unlinked even when candidates exist;--prior-dateand--no-priortogether are an argparse usage error (exit2). A successful run prints one JSON object withstarted,state_path,date,prior_review_date(ornull),linked, and a human-readablemessage. The newstate.jsoncontains onlycompany,proposal,date,schema_version, and optionalprior_review_date. No prior review fields, source files, drafts, inputs, or calculations are copied. The target dated folder is never reused or overwritten. The start date must be strictly later than the newest existing state-bearing folder for this company/proposal so existing automatic resume commands find the new review as active; backdating is refused. The company must already have a deal folder: a company with no folder is refused (oneerror:line, exit status1, nothing created) so that a mistyped company name cannot quietly become a new deal; a deal that has never been reviewed starts with/triageor/spread. An existing company with a proposal that has no earlier review may start an unlinked review (the renamed-proposal case). The decision and the creation run under one lock per company and proposal, so two concurrent starts cannot both pass the date check, and the creation is all-or-nothing: if writing fails, the temporary file and the folder that this call created are removed and the error is oneerror:line. An empty or blank--companyor--proposalis refused by everystate_manager.pymode. -
--check-steps --company ... --proposal ... --required <step,step>checks every named step againststeps_completedand prints{"missing_steps": [...], "ok": true|false}. A valid result always exits0; an unreadable or malformed state is oneerror:line and exit1. Its JSON output is unchanged. -
--export-reviewer-view --company ... --proposal ...validates the saved state and writesreview_view/state_for_review.json(the record withoutreview_trailorreview_verdict) andreview_view/review_trail.json(the history list, or[]when absent) into the deal's dated folder. A successful run overwrites both derived files and prints one JSON object with their paths. Invalid state, or a newer or malformed schema version, produces oneerror:line, exit1, and writes nothing. -
--record-group-basis --company ... --proposal ... --group-basis-file <json file> --perimeter-confirmed [--date YYYY-MM-DD]records optional case-A metadata on an exact existing deal only. The UTF-8 JSON file suppliesbasis,reporting_entity,entities_covered,source(document,accounting_basis, documentdate),period_end,periodsandfigures_basis; it does not hold financial figures. The command refuses unless the explicit--perimeter-confirmedflag is present, then recordsperimeter_confirmed: trueandperimeter_confirmed_onfrom--dateor today. Here--dateis the confirmation date; the source document has its ownsource.date. Supplied figures needfinancials_source: "analyst-supplied"recorded; recomputed figures must agree with"framework-computed", and an unrecorded source is read as"framework-computed", the default the exporter assumes. A contradiction is refused, at recording and at export. No deal is created and no existing financial/raw-figure key other thangroup_basisis changed; the ordinarywrite_stateschema-version policy still applies. Success prints one JSON line withrecorded,state_pathandfigures_basis; a file, field, date or existing-state refusal prints oneerror:line, exits1, and writes nothing. The workbook describes this as a credit aggregation, never a statutory consolidation. -
--register-entity-record --company ... --proposal ... --entity-record-file <json file> --perimeter-confirmed [--date YYYY-MM-DD]registers one subsidiary, parent or guarantor record on an exact existing deal only. The UTF-8 JSON file supplies one record object containingentity_id,legal_name, the single primaryrole(subsidiary,parentorguarantor),source(document,accounting_basis, real ISOdate), period-keyedperiod_ends,perimeter,raw_figures_source, the period-keyedmulti_period_financialsandanalyst_supplied_financialsmaps,spread_status: "not-spread",intercompany_linesandguarantee_ids. The borrower is not an entity-record role and its figures stay in the existing deal-level stores. The command refuses unless the explicit--perimeter-confirmedflag is present; as with--record-group-basis, it recordsperimeter.confirmed: trueand setsperimeter.confirmed_onfrom--date(today by default), whilesource.dateremains the source document date. It validates the complete registry under the per-deal lock before one atomic write. IDs may not be replaced. At registration, eachcounterparty_entity_idmust be a non-empty string and must not equal that record's own ID; resolution to another registered entity is deferred to the aggregation step, which checks references among the entities it uses.guarantee_idsmay be empty forsubsidiaryandparentrecords, but aguarantormust list at least one ID; each listed ID must resolve to exactly one explicitguarantee_idin the deal'sguaranteeslist. Provider names are not used as links. Each entity-period may hold figures in at most one raw store. Each record's period maps must use framework labels and real calendar dates; matching period ends across records is deferred to the later aggregation step, so a standalone guarantor may have a different year-end. Raw line values follow the existing finite-number-or-null contract (null means unavailable); every intercompany amount must be a finite number (not null, boolean, string or non-finite value). A successful command prints one JSON line withrecorded,entity_id,state_pathandspread_status; any missing/corrupt deal, invalid input or duplicate ID produces oneerror:line, exits1, and writes nothing. The command never creates a missing deal. Step 1 computes no spread, subtotal, ratio, elimination, aggregate or covenant result.
The two review-view files are derived copies for the interactive Reviewer, not records of the deal; no other script may
read them as a record. The source of truth remains the real state.json, which /review updates in its State: write
stage. See the data model. Script-reported refusals use exit status 1, exactly one
error: ... line on standard error, no stdout and no traceback; malformed CLI usage exits 2.
python scripts/state_manager.py --find --company "Synthetic Co" --proposal "Synthetic Fleet Loan"
python scripts/state_manager.py --review-candidates --company "Synthetic Co" --proposal "Synthetic Fleet Loan" --date 2026-10-21
python scripts/state_manager.py --start-review --company "Synthetic Co" --proposal "Synthetic Fleet Loan" --date 2026-10-21
python scripts/state_manager.py --start-review --company "Synthetic Co" --proposal "Synthetic Fleet Loan" --date 2026-10-21 --prior-date 2025-10-21
python scripts/state_manager.py --start-review --company "Synthetic Co" --proposal "Synthetic Fleet Loan" --date 2026-10-21 --no-prior
python scripts/state_manager.py --check-steps --company "Synthetic Co" --proposal "Synthetic Fleet Loan" --required spread,collateral
python scripts/state_manager.py --export-reviewer-view --company "Synthetic Co" --proposal "Synthetic Fleet Loan"
python scripts/state_manager.py --record-group-basis --company "Synthetic Group Ltd" --proposal "Synthetic Group Facility" --group-basis-file group-basis.json --perimeter-confirmed --date 2026-10-21scripts/credit_aggregation.py --company ... --proposal ... --request-file <json file> records case-B
credit aggregation inputs (step B2a) on an exact existing deal only. The UTF-8 JSON file supplies
{"periods": {"<period>": {"participants": [...], "borrower_period_end": "YYYY-MM-DD", "borrower_period_end_evidence": "...", "scope_confirmed": true}}}:
the participants are the reserved @borrower token plus explicit entity_records IDs whose perimeter is
included and confirmed, never inferred; every participant must carry the same period label and exactly the
same ISO date per period, and every intercompany counterparty on a selected participant's lines for that period must resolve to a
selected participant of that period or to @borrower (lines of other periods are not inputs of this period). The command validates the whole request
against the live state under the per-deal lock before one atomic write, and persists each period's manifest
and SHA-256 input fingerprint under the top-level credit_aggregation key (schema version 1.3.0). It
computes nothing — eliminations and calculation are the separately gated B2b step, whose optional
computed object this contract reserves — and it never touches borrower figures, either raw store,
entity_records or group_basis. Refusals include: a missing or false scope_confirmed, a missing
@borrower token, duplicate, unknown or out-of-perimeter participants, missing or mismatched period
ends, dangling, unselected, out-of-perimeter or unconfirmed counterparties, unconfirmed lines,
analyst-supplied-only figures, a deal that already carries a case-A group_basis, non-finite or boolean
numbers, and unknown keys. A successful command prints one JSON object (pretty-printed, so several lines) with recorded, periods and
state_path; any refusal prints one error: line, exits 1, and leaves state.json byte-for-byte
unchanged (no deal is ever created). See the
data model for the full contract.
scripts/source_manifest.py --company ... --proposal ... --step <step> --claim <text> --file <path> [--url <url>] [--filename <name>] copies an already-downloaded document into the deal's sources/ folder and appends an entry
(filename, url, step, claim, fetched_date) to sources/manifest.json; it never fetches anything. With
--check-sources instead prints {"missing_saved_sources": true|false, "sources_declared": "declared"|"not_declared"|"unknown"}.
The existing missing_saved_sources key remains boolean: true when declared, non-empty citations have no saved material,
or when the consumed completion/declaration shape is unknown. steps_completed, when present, must be a list of strings;
absence remains valid for new/incomplete historical states. sources_declared is "unknown" for malformed consumed
completion metadata, any invalid declaration, or a completed source-bearing step without a list[str] declaration.
Nulls, mappings, scalars and lists containing non-strings are invalid; a nonempty manifest cannot conceal them.
It is "declared" when at least one valid triage.sources or commercial.sources list exists and the completed
relevant steps have valid lists; explicit [] declares no citations. Otherwise it is "not_declared".
A calling command must stop and request a corrected state shape on "unknown" rather than treating it
as proof that no citations were used. The command exits 0 for any check result. A sources/manifest.json that cannot
be used (unreadable, a link whose target does not exist, not UTF-8, not JSON, not a list, or a list with an entry that
is not an object), and a company or proposal that is not a safe folder name, are errors: each is one error: line, exit
status 1, no traceback and no JSON on stdout, and the file is never modified. Saving checks the manifest before copying
anything, so a refusal leaves no copied document behind.
python scripts/source_manifest.py --company "Synthetic Co" --proposal "Synthetic Fleet Loan" --step research \
--claim "Synthetic legal identity extract" --file registry_extract.txt --url https://example.invalid/registry
python scripts/source_manifest.py --check-sources --company "Synthetic Co" --proposal "Synthetic Fleet Loan"scripts/conventions.py (--company <name> | --enterprise) (--read | --write) [--financials-source <value>] [--note <text>] [--confirmed-date <date>] [--proposal <name>] reads or writes a persisted, analyst-confirmed spreading
convention: borrower-specific (--company, stored at deals/<Company>/_conventions.json) or enterprise-wide
(--enterprise, config/spreading_conventions.json). --write requires --financials-source; it overwrites the
current fields and appends to a history. --read prints {"found": true|false, "convention": ...}. It is run by
/spread only; the headless pipeline never calls it, because nothing may be persisted without a person's explicit
confirmation. See the data model.
python scripts/conventions.py --enterprise --readscripts/pii_scan.py <path> scans one template file for likely-real data (currency figures, emails, phone numbers,
dates, company names, registration numbers) and prints JSON findings. An empty list means only that nothing obvious
was found; it is not a guarantee, and a human review is still required before a local template is promoted into
templates/cam/. See Security.
python scripts/pii_scan.py templates/local/cam/asset_finance_cam.md-
scripts/check_coverage.py <coverage.json> [--config <pyproject.toml>] [--report-only]compares coverage.py's JSON report with the floors inpyproject.toml; exit0when met,1when not,2for an unreadable report or configuration;--report-onlyprints the table and always exits0. -
scripts/check_test_count.py <pytest_output> [--badge-path <path>] [--write]compares pytest's passed count withbadges/test-count.json(exit1on a mismatch);--writeupdates the file from a complete green run (never used in CI). -
scripts/check_model_freshness.py [--json PATH]reports configured-model freshness from local SDK tables; findings never fail the report. -
scripts/mutation_report.py <results> [--config <pyproject.toml>] [--top <n>] [--json <path>]prints the per-module mutation score frommutmut results --all true; exit0whenever a report is produced,2for an unreadable file.
Their rules and the reasoning are in Testing.
scripts/pr_scope_check.py is a standard-library-only, deterministic CLI. It makes no network request
and does not call a model. The separate .github/workflows/scope-check.yml workflow reads the PR body
as data, collects the changed file names with Git, and appends this report to the job summary. It is
advisory only, not a required check.
The script accepts these flags (also shown by --help):
| Flag | Meaning |
|---|---|
--changed-files PATH |
Required UTF-8, NUL-delimited changed-file list, as produced by git diff --name-only --no-renames -z. An empty list is valid. |
--scope-body PATH |
Required UTF-8 Markdown body extracted from the GitHub event JSON. The script never fetches the PR or executes body text. |
--summary-file PATH |
Optional Markdown file to append the same report to; the report is also printed to standard output. |
In the body, a single ## Declared file scope section may contain one repo-relative path or glob per
bullet, written exactly as - path/or/glob``. Blank lines and full-line HTML comments are ignored.
Duplicate sections, unexpected nonblank text, malformed patterns and unsafe paths are errors. If the
section is missing or has no patterns, the report includes SCOPE NOT DECLARED and the command exits
`0`, so legacy PRs and an intentionally empty scope remain warning-only.
Paths and patterns use forward slashes for comparison on every operating system. Backslashes are
normalized to slashes; repeated separators, leading ./ and internal . components are collapsed.
Absolute, UNC and drive-prefixed paths, any .. component, control characters, duplicate changed paths,
and invalid UTF-8 are refused. Matching is case-sensitive: *, ? and character classes match within
one path component; ** is supported as a whole component and matches zero or more components
(tests/**/*.py matches Python files directly under tests/ and in nested subdirectories). A trailing slash pattern
matches files below that directory.
Protected paths are always reported, even if declared: agents/*.md, .github/workflows/**,
pyproject.toml, config/**, badges/test-count.json, .claude/** and
diff_cover_critical.toml. Each changed path appears in exactly one category:
IN_SCOPE, OUT_OF_SCOPE, PROTECTED_DECLARED or PROTECTED_UNDECLARED. A protected file that
is not declared is listed as PROTECTED_UNDECLARED, not counted again as an ordinary out-of-scope file.
Only declarations that are exactly *, ** or **/* produce the additional BROAD_SCOPE advisory;
it never changes the exit status. Counts are exact, rows are sorted deterministically, and at most 100
path rows are shown before a deterministic omitted-row count.
Exit 0 means the input is valid, regardless of scope mismatches or a missing/empty scope. Exit 2
means a CLI, file, encoding, body or path/pattern input error. The status is deliberately advisory: the
report does not prove that declared scope is correct, that every relevant file was declared, or that a
change is safe to merge.
python scripts/pr_scope_check.py --changed-files changed-files.nul --scope-body scope-body.md
python scripts/pr_scope_check.py --changed-files changed-files.nul --scope-body scope-body.md --summary-file summary.mdpython scripts/pr_base_fail_check.py --base-sha SHA --head-sha SHA --changed-files changed-files.nul [--summary-file PATH] is the advisory check behind issue #475's option C: it answers, for a pull
request that adds or changes tests, whether those tests fail on the base commit — the red-first
evidence a reviewer otherwise re-derives by hand. Run it from a checkout at the head commit (the
workflow checks out the PR's own merge commit); --changed-files is the NUL-delimited
git diff --name-only -z base...head output.
It selects the top-level test* functions and Test* class methods that are new or changed between
base and head (an AST comparison, decorators included, so a changed parametrization counts; an edit
confined to non-test code selects nothing), overlays the PR's changed tests/ paths — test files,
fixtures and conftest.py alike — onto a git worktree of the base commit, and runs exactly those
node IDs there with pytest --junitxml. Only tests/ paths are ever overlaid or run. Parametrized
tests are reported by function with their run counts.
Each selected unit is classified RED_ON_BASE (a failing run, kind assertion), PASSES_ON_BASE
(all runs passed), or CANNOT_RUN (kind import when its file failed collection on the base, the
expected outcome when a PR adds a module; kind skipped when any run was skipped and none failed, because a skipped run never executed); a PR that changes no test function is NO_TESTS_SELECTED.
The report is Markdown — verdict line, one row per unit, the legend — appended to --summary-file
and printed. PASSES_ON_BASE appears in the summary only.
Exit 0 for every verdict, including RED_ON_BASE: a red result is the check working, not a failure,
and the check is never a gate. Exit 2 means the check itself is broken — malformed input, a HEAD
that is not --head-sha, a git or worktree failure, a pytest internal error, or a missing JUnit
file — and then the summary says CHECK MALFUNCTION rather than anything verdict-shaped.
python scripts/pr_base_fail_check.py --base-sha "$BASE_SHA" --head-sha "$GITHUB_SHA" --changed-files changed-files.nul --summary-file "$GITHUB_STEP_SUMMARY"python scripts/check_model_freshness.py [--json PATH] prints a Markdown report of model IDs configured in
config/settings.json (maker_model, checker_model, and calibrate_model when set) and the string literal
_DEFAULT_MODEL in scripts/calibrate.py. The default is read with ast, not by importing calibrate.py.
The installed anthropic.types.Model and
anthropic.resources.messages.messages.DEPRECATED_MODELS tables supply known IDs and deprecation dates.
The report suggests a newer stable ID only from the same family. Dated variants, -latest and -preview aliases are
not used for version comparison. An ID that cannot be parsed or found is marked unknown; a missing or reshaped SDK
table is reported as SDK table not found without a guess. With --json PATH, report data is written as JSON
(report_version, sdk_version, freshness_note, sdk_tables, models, findings and summary).
Exit 0 whenever a report is produced, including when it contains findings; exit 2 for unreadable configuration.
It does not read an API key, call the API, or make a model call. It is only as fresh as the installed Anthropic SDK.
A model change remains a separate reviewed PR with an evaluation statement; the script never upgrades one automatically.
See Model freshness report.
scripts/run_evals.py validates the synthetic dataset (--validate, --list), plans and self-checks with zero model
calls (--dry-run), and, only with --live and your own ANTHROPIC_API_KEY, runs the cases under a hard call cap
(--max-calls, default 80, never above 250; --repeats, --cases, --yes, --keep-work, --out), exporting and
comparing baselines (--export-baseline, --allow-partial, --compare). See Evaluation.
python scripts/run_evals.py --dry-runpython scripts/wiki_publish.py --repo <owner/name> [--root <repo root>] (--out <dir> | --check | --publish --source-sha <sha>) (no ANTHROPIC_API_KEY) generates the GitHub Wiki page tree for the docs/ corpus.
--out writes the tree into a directory (which may not be the repository root, docs/, a directory inside
docs/ or an ancestor of docs/: the paths are resolved first and such an output is one error: line, exit
1, nothing written, so the source pages can never be overwritten); --check builds and validates in memory
and writes nothing; --publish (with --source-sha, the commit it publishes from) clones the repository's
wiki, fully replaces its content with the generated set, makes one commit carrying the source sha -- or none,
when nothing changed -- and pushes it back to the wiki's default branch. The token is read only from the
GITHUB_TOKEN environment variable and reaches git only as an HTTP header: never a URL, a log line, a file or
a git process's environment (the variable is removed from every git child's environment). Generation and validation run before anything is cloned or pushed, so a broken corpus publishes
nothing; a failed push, an unreachable wiki and a missing token are each one error: line, exit 1. It runs
on every push to main that changes docs/ (the wiki-publish workflow; see
Operations).
Only the allowlisted pages (docs/*.md, dotfiles excluded, and the example pages under docs/examples/synthetic_co/)
are read; linked repository files are checked and rewritten to URLs, never copied. Page names come
from the file names (docs/README.md becomes Home, the example pages are flattened with an
examples-synthetic_co- prefix); links are rewritten to wiki, blob, tree or raw-blob URLs; every
page starts with a generated-source notice saying docs/ is canonical; Home is the docs index and
_Sidebar is its reading order. A missing target, a broken anchor, a symlinked page or a target
outside the repository is one error: line naming the file and line, exit 1, and nothing is
written. Deterministic: the same docs/ tree always gives byte-identical output. See
issue #192.
This page is generated from
docs/README.mdin the repository --docs/is the canonical documentation. Direct wiki edits here are overwritten on the next publish; make changes indocs/by pull request.
- Home
- Architecture
- Workflows
- Slash command reference
- Collateral analysis
- Skills
- Skill design
- Financial model and policy engine
- Formula register
- Rules register
- Shared glossary
- Data model
- CLI reference
- Outputs and templates
- Configuration
- Testing and CI
- Security and confidentiality
- AI assurance
- Evaluation harness
- Contributing
- Agent ledger
- Operations runbook
- Troubleshooting
- Design decisions
- OpenCAM MVP v1 — product requirements document (reconstructed)
- Move ledger
Examples