Skip to content

data model

github-actions[bot] edited this page Nov 13, 2026 · 17 revisions

This page is generated from docs/data-model.md in the repository -- docs/ is the canonical documentation. Direct wiki edits here are overwritten on the next publish; make changes in docs/ by pull request.

Data model

The sections before "Module reference" are written for readers; "Module reference" and what follows were moved from CLAUDE.md or the README, unchanged apart from the fixes in the move ledger.

How a deal's state is stored and guarded: the state.json file, its keys, the two raw-figure stores, resuming a deal, schema versions, saved sources and the persisted-convention stores. The normative protocol and the state-file schema example stay in CLAUDE.md.

state.json at a glance

Each deal has one state file, deals/<Company>/<Proposal>_<YYYY-MM-DD>/state.json, plus a sources/ folder beside it. It is the record of the deal: every step reads it first and writes its results back when it finishes, so a resumed session or a compacted conversation never has to reconstruct a figure from memory. (The rules are in CLAUDE.md, "Context Window & State Management Protocol"; the reasons in Design decisions, D3.) deals/ is git-ignored, so state never reaches version control.

An annotated fragment of the synthetic deal's state after /spread, /project and the structure steps (values shortened):

{
  "company": "Synthetic Co",
  "proposal": "Synthetic Fleet Loan",
  "date": "2026-10-04",
  "schema_version": "1.3.0",
  "deal_type": "asset_finance",
  "inputs": {"pd": "0.20%", "lgd": "LGD 3 (15%)"},
  "steps_completed": ["spread", "project"],
  "financials_source": "framework-computed",
  "multi_period_financials": {"FY-Current": {"revenue": 5000, "cost_of_sales": 3000, "...": "..."}},
  "financials": {"FY-Current": {"raw": {"...": "..."}, "ebitda": 1000, "tangible_net_worth": 2200, "fcf_after_working_capital": 320, "...": "..."}},
  "ratios": {"FY-Current": {"dscr": 2.0, "gross_leverage": 2.0, "...": "..."},
             "FY+2": {"dscr": -0.20408163265306123, "gross_leverage": null, "...": "..."}},
  "stress_assumptions": {"revenue_haircut_pct": 5, "interest_rate_bump_bps": 200},
  "downside_case": {"financials": {"FY+1": {"...": "..."}}, "ratios": {"FY+1": {"gross_leverage": 5.15625, "...": "..."}}},
  "covenants": [{"metric": "dscr", "type": "minimum", "threshold": 1.25}],
  "collateral": [{"asset_id": "AST-001", "exposure": 1200, "collateral_value": 1500, "...": "..."}],
  "security_package": [{"secures_asset_id": "AST-001", "perfection_status": "Perfected", "ranking": "First"}],
  "guarantees": [{"provider": "Synthetic Parent Holdings", "type": "Corporate Guarantee", "amount": 500}]
}

The keys

Key Written by Holds
company, proposal, date, schema_version every write Deal identity, kept in sync on every write; the schema version of the writing framework
deal_type, inputs /triage, /collateral, /assemble, the orchestrator The CAM type; pd, lgd (user-supplied, never adjusted) and experian_score or another bureau score
steps_completed every step The names of steps that have finished (triage, spread, ...); /assemble hard-gates on spread
triage, commercial /triage, /commercial, /research The Go/No-Go verdict and rationale; the company and sector sections. Each section's sources field is a list of citation strings, including [] when no citations were used
financials, ratios, multi_period_financials, financials_source spreading_check.py for computed periods; supplied_forecast.py for analyst-supplied forward values Computed per-period subtotals/ratios with raw inputs under financials[period]["raw"]; multi_period_financials records computed raw input lines, while financials_source remains the deal-wide historical-basis label
analyst_supplied_financials, financials_source_note /spread, analyst-supplied mode; supplied_forecast.py for forward raw breakdowns when provided The analyst's raw breakdown (if given); the convention note the CAM caveat quotes (for figures read from an image, with a sentence saying so)
group_basis state_manager.py --record-group-basis, after explicit analyst confirmation Optional metadata describing borrower-supplied consolidated accounts: basis, reporting entity, covered entities, source/date/accounting basis, common period end, period labels, supplied/recomputed basis and confirmed perimeter. It contains no figures and never changes either raw store.
entity_records state_manager.py --register-entity-record, after explicit perimeter confirmation Optional registry keyed by stable entity ID. Each record captures one subsidiary, parent or guarantor, its source, period ends, confirmed perimeter, exactly one raw store per entity-period, intercompany references and explicit guarantee IDs. Step 1 records inputs only; no spread or aggregation is computed.
credit_aggregation credit_aggregation.py, after explicit analyst scope confirmation Optional case-B record keyed by period label. Each period holds the manifest (participants, the common period end and its evidence, per-entity confirmed scope) and one SHA-256 input fingerprint; the optional computed object is the accounting-gated B2b step's output. It is metadata and fingerprints only: no figures are stored by B2a, and borrower figures are never touched.
financials_transcriptions transcription_check.py --commit (/spread, figures read from an image) A list with one record per confirmed transcription: the kind of image, the mode, the saved source file and its SHA-256 fingerprint (never the image), the unit, the declared sign conventions, the periods, the confirmed digest and date, and the cross-foot outcome (matched, acknowledged with the analyst's reason, not assessed). Absent for figures read from text. One deal holds only one basis: a transcription in the other /spread mode is refused
stress_assumptions, downside_case spreading_check.py (run by /project) The three stress shocks; the stressed forward-year figures and ratios
forecast_source supplied_forecast.py (/project, analyst-supplied mode) "analyst-supplied" when the forward years were supplied by the analyst and are recorded as given; absent means framework-computed (every deal that predates the mode). Such a deal also has financials_source: "analyst-supplied", and its downside_case carries basis, unavailable and description besides financials and ratios (one description for all of its analyst-supplied years)
collateral, security_package /collateral One entry per asset; one per charge
collateral_analysis collateral_check.py (issue #266 PR B) The full recorded collateral analysis: assets (one record per asset — asset_id, the validated inputs and the computed results), mitigants (the validated list, each with amount, eligible_for_netting and optional mitigant_id), deal-level results (total exposure, total collateral value, coverage, gross and net uncovered risk, excess mitigant, collateral_max_lgd_pct, collateral_avg_lgd_pct), input_digest (SHA-256 of the canonical inputs) and calculator_version. A reader (the workbook, the policy ground truth) uses it only while it is current: same calculator_version, input_digest intact, and recalculating the stored inputs and mitigants reproduces the stored results exactly; an edited result, another version or a changed input is stale and omitted, never repaired. Written atomically with the legacy collateral projection refreshed from the same results; a missing per-asset LGD makes max and average LGD null, never zero
covenants, guarantees /project {"metric", "type", "threshold"} entries, each optionally with a basis (borrower, consolidated or guarantor_group; absent or null means borrower) and basis_entity_id (required and non-blank for guarantor_group); {"provider", "type", "amount"} guarantee entries may carry an explicit guarantee_id for entity-record linkage
policy_state /assemble, the orchestrator The computed conditions, covenant results, security gaps, downside breaches and forward covenant results, stored whole
review_trail, review_verdict /review, the orchestrator's audit The append-only history of verdicts and notes; the latest verdict
deal_structure_notes.review_cap /research review checkpoint, when the analyst sets a lower maximum Optional lower per-deal REJECTED-pass threshold; it takes precedence over the default third-pass checkpoint and is recorded when set. This is an optional nested deal note, not a schema-version bump
review_stopped_by_analyst research_export.py --analyst-release-unapproved (/research, after explicit analyst choice) An append-only list of {"date": "YYYY-MM-DD", "passes": N, "reason": "..."} records, one per release: the date, the trailing consecutive REJECTED review count and the analyst's reason for releasing the brief for manual review. No record is cleared or overwritten, and a later approved export leaves the list as it is; review_verdict carries the current verdict
analyst_terms /research and /assemble, when the analyst defines a term A list of {term, meaning, date} records checkpointed immediately so the definition is not lost if the conversation is compacted; entries become learning candidates only on explicit confirmation
draft_path, model_provenance /assemble; the orchestrator The exported .docx path; which models and which prompt versions (content hashes) drafted and audited this deal
approved_draft_path /assemble Repository-relative path to the approved Markdown draft retained as draft_approved.md in the same dated deal folder

financials_source is a deal-wide label and audit caveat, not the exporter's routing key for every period. When it is "analyst-supplied", framework-computed mode refuses historical-period recomputation and /project leaves the label unchanged. The one allowed exception to the normal one-raw-store-per-deal rule is an interactive, forward-only /project call: its forward-year raw lines are framework-computed, recorded under financials[period]["raw"] and exported from that store, while the historical lines remain in analyst_supplied_financials. No historical period is recomputed, financials_source stays "analyst-supplied", and the two stores are never blended within a period. A forecast explicitly marked analyst-supplied is not recomputed. The headless orchestrator.py does not get this exception; it refuses a run that would recompute an analyst-supplied deal, even if the supplied input is forward-only.

Ratios that cannot be computed are null, never 0. The units for gearing, fcf_conversion_pct and their covenant thresholds follow the percent-type ratio fraction convention. A step may add keys of its own; this table is a floor.

analyst_terms is an additive step-specific key, not a closed schema field. Its entries use the analyst's wording and a date; state_manager.py leaves unknown keys alone, so this addition does not require a schema_version bump. The commands still own the prompt-level rule to merge entries without dropping existing ones. The fresh Reviewer is not given analyst_terms; if a definition matters to the audit, write it plainly in the brief.

Consolidated group-basis metadata (case A)

group_basis is optional and remains absent from legacy deals unless an analyst records it with python scripts/state_manager.py --record-group-basis. It is metadata only: no amounts, ratios or entity-level financial lines are stored there, and it does not replace, edit or blend financials, ratios, multi_period_financials or analyst_supplied_financials. Those two raw-figure stores remain separate; financials_source remains a plain deal-wide value.

When present, all fields are required: basis must be supplied_consolidated; reporting_entity is the borrower or parent presenting the accounts; entities_covered is a non-empty list of distinct entity names including the reporting entity; source contains non-empty document and accounting_basis strings plus the document's real ISO date; period_end is one real ISO calendar date common to the perimeter, without per-entity overrides; periods is a non-empty list of distinct framework labels (FY-2, FY-1, FY-Current, FY+1, FY+2, FY+3); and figures_basis is supplied or recomputed. Supplied subtotals/ratios are kept as given and require financials_source: "analyst-supplied"; recomputed figures use the framework's existing calculations over supplied consolidated raw lines and require financials_source: "framework-computed". If that deal-wide source label already exists and contradicts the metadata, recording is refused. An absent financials_source is read as framework-computed, the default the exporter assumes, so recomputed figures may be registered but supplied figures need an explicit analyst-supplied (run /spread in its analyst-supplied mode first). The command sets perimeter_confirmed: true and the real ISO perimeter_confirmed_on date only after the analyst passes the explicit --perimeter-confirmed flag.

This describes a credit aggregation of consolidated accounts supplied by the borrower, not a statutory consolidation prepared by the framework. Case A introduces no eliminations, new formulas or entity-level arithmetic, and does not infer control from ownership percentages. The optional, metadata-only field preserves compatibility for states without the key. The original optional group_basis metadata did not itself require a schema bump. Schema version 1.2.0 recorded the addition of the separate entity_records contract; 1.3.0 records the addition of the separate credit_aggregation contract. A state without entity_records remains unchanged when read; it is not migrated or populated from borrower data. The next normal write applies the current schema version. Unknown future fields within group_basis are ignored; a null value means not recorded, as for every other key; a malformed value that is present is refused by consumers that read it, with an error naming group_basis.

Shared entity records (cases B and C, step 1)

entity_records is an optional top-level object keyed by stable entity ID. It is shared by case B's credit aggregation and case C's standalone guarantor spread; there is no separate guarantor-only record. A state without this key means no entities have been recorded. Reading a legacy state does not synthesize entities or migrate borrower figures. The reserved token @borrower is never a valid registry key: it maps only to the existing legacy borrower stores.

Each registry value is one entity record with:

  • entity_id, which must equal the key, and a non-empty legal_name;
  • exactly one primary role: subsidiary, parent or guarantor. borrower is intentionally not a role here: borrower figures remain in the existing deal-level stores;
  • source.document, source.accounting_basis and real ISO source.date;
  • period_ends, a mapping from the framework period label (FY-2, FY-1, FY-Current, FY+1, FY+2, FY+3) to a real ISO calendar date;
  • perimeter.included, control_basis, scope_rationale, confirmed: true and a real ISO confirmed_on;
  • a non-empty raw_figures_source, two raw maps named multi_period_financials and analyst_supplied_financials, and spread_status: "not-spread";
  • intercompany_lines, each naming a framework period, existing evaluator line_key, explicit counterparty_entity_id, direction, finite numeric amount and confirmation flag;
  • guarantee_ids, which may be empty for subsidiary and parent roles; a guarantor must list at least one. Each listed ID must resolve to exactly one explicit guarantee_id in the deal's existing guarantees list. A provider name is never used to guess a link.

Every nested raw map remains period-keyed. The validator rejects an entity ID where a period label is expected, impossible dates, a mismatched entity key, empty or self-referential counterparty IDs, missing or false perimeter confirmation, duplicate/unresolved guarantee IDs, raw-line values outside the existing validator's finite-number-or-null contract (null denotes unavailable), or non-finite/non-numeric intercompany amounts, and figures present in both raw stores for one entity-period. Each record validates its own framework labels and real calendar dates. Counterparty resolution and matching period ends across records are deferred to the later aggregation step, which checks references and date agreement only among the entities it actually uses; a standalone guarantor may have a different year-end. Dates are never aligned or rolled automatically. Extra record fields are preserved for forward compatibility.

Registration uses python scripts/state_manager.py --register-entity-record --company ... --proposal ... --entity-record-file <json file> --perimeter-confirmed [--date YYYY-MM-DD]. The JSON file contains one record object. The explicit flag records analyst confirmation; --date is the confirmation date (or today), distinct from source.date. The command requires an exact existing deal, refuses duplicate IDs, validates the whole registry while holding the deal lock, and writes once through the atomic state manager path. A refusal leaves state.json byte-for-byte unchanged.

Step 1 is recording and validation only. It computes no subtotals, ratios, spread, eliminations, aggregate view or covenant result, and does not change borrower figures, workbook/CAM presentation, policy routing or legal guarantee conditions. Later work must define and review those behaviours separately.

Credit aggregation inputs (case B, step B2a)

credit_aggregation is an optional top-level object keyed by framework period label, recorded with python scripts/credit_aggregation.py --company ... --proposal ... --request-file <json file>. It is the contract the accounting-gated B2b step (eliminations and calculation) will later fill; B2a itself computes nothing and never touches financials, ratios, multi_period_financials, analyst_supplied_financials, entity_records or group_basis. Schema version 1.3.0 records the key's addition.

Each requested period resolves to one entry:

"credit_aggregation": {
  "FY-Current": {
    "manifest": {
      "participants": ["@borrower", "synthetic-opco"],
      "period_end": "2025-12-31",
      "period_end_evidence": "Synthetic audited accounts FY2025",
      "scope_confirmations": {"synthetic-opco": {"included": true, "...": "..."}}
    },
    "input_fingerprint": "<64-character lowercase SHA-256 hex>",
    "computed": {"financials": {"ebitda": 500.0}, "ratios": {"gross_leverage": 1.8}, "output_digest": "<64-character lowercase SHA-256 hex>"}
  }
}

participants always includes the reserved token @borrower, which maps only to the existing legacy borrower stores (the framework-computed financials[period]["raw"] line the exporter would select) and never creates an entity record; state_manager.py refuses @borrower as an entity_records key. Every other participant is an explicit entity_records ID whose perimeter.included is true and whose perimeter is confirmed. Participants are never inferred. Every participant must carry the same period label and exactly the same ISO date per period: entity dates come from entity_records[id].period_ends[period], and the borrower's date arrives in the request with an evidence reference. A missing date or period, or any mismatch, refuses the whole aggregation before any write; nothing is rolled, aligned or inferred. Every counterparty_entity_id of a selected participant resolves to a selected participant of that line's own period, or to the borrower view through @borrower; dangling, unselected, out-of-perimeter or unconfirmed references are named hard errors, never assumed external and never matched by name. An unconfirmed intercompany line is refused. The request also refuses: analyst-supplied-only figures (D4's as-given rule is not overridden), a deal that already carries a case-A group_basis (fail closed, no winner by insertion order), non-finite or boolean numbers, and unknown keys.

The B2b contract. Each period's optional computed object carries financials and ratios in the same shape as the borrower's top-level financials[period] and ratios[period]. Until B2b exists no period has computed; every consumer treats a missing or stale computed as UNRESOLVABLE with a reason (credit_aggregation.aggregation_period_status() reports current, not_calculated, stale, invalid or absent). The shape is flat and per period, for example {"financials": {"ebitda": 500.0}, "ratios": {"gross_leverage": 1.8}, "output_digest": "<sha-256>"}: each metric maps to a finite number or null (an integer too large for a float counts as non-finite), never to a nested per-period object or a boolean; a nested or non-numeric computed is invalid and the state validator refuses it. Output integrity: output_digest is the SHA-256 returned by credit_aggregation.computed_output_digest(input_fingerprint, financials, ratios), which binds the figures to the exact input fingerprint they were calculated from. A computed object with no digest, or whose digest does not match, is invalid and is never read as current, so an accidental or uncoordinated edit is caught. The digest is a consistency checksum, not proof of origin: the helper is public and unkeyed, so someone who edits state.json and recomputes the digest can still make a forged period current. Proving that only approved B2b figures are consumed needs the deterministic recompute on read that the B2b design must provide (maintainer decision, issue #472). The B2b writer must fill computed through that helper. The recorded manifest, including each confirmed scope snapshot, must also equal the manifest the current inputs produce, or the period is stale. B3 and B4 read this contract only.

Per-period fingerprint. One SHA-256 per period over canonical JSON tagged open-cam-credit-aggregation-input/v1, serialised as json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8"), lowercase hex. The payload covers the contract tag and version, the period label and its end date, the sorted participant IDs, each participant's raw-store name and raw period object, source and perimeter confirmation, the borrower's period-end evidence, the confirmed scope, and each entity participant's intercompany lines for that period (sorted, so a reordering is not a change; an amount, direction or line-key change makes the period stale); computed outputs are excluded. An absent financials_source is fingerprinted as framework-computed, the meaning it has everywhere else. Any change to a participant, source, period, scope or the contract version makes the stored fingerprint stale.

Recording merges per period under the deal lock in one atomic write after full validation; any refusal leaves state.json byte-for-byte unchanged. Recording a period replaces that period's entry and drops any earlier computed for it (the new inputs have invalidated it); periods not named in the request are preserved. Re-recording identical inputs reproduces the identical fingerprint.

Reviewer view files

For an interactive /review, state_manager.py --export-reviewer-view derives two files under deals/<Company>/<Proposal>_<Date>/review_view/: state_for_review.json is a copy of the deal record without review_trail and review_verdict, while review_trail.json contains the history list (or [] when absent). Each successful export overwrites both derived copies. They are not records; state.json remains the source of truth and is the file /review updates in its State: write stage. No other script may consume these view files as a deal record. This removes the default path to earlier verdicts during the Reviewer's first pass, but it does not prevent a determined Reviewer from globbing to the combined state.json; see AI assurance.

Two raw-figure stores, never blended within a period

Raw figures have two separate stores. The correct source is selected for each period; having both stores in the same deal is permitted when history was analyst-supplied and /project later computed forward years.

Under decision D-c of issue #504, interest_paid is the period's P&L charge: interest payable and similar charges, not cash interest paid in the period. tax_paid is the period's P&L charge: tax on profit, not cash tax paid in the period. These definitions apply to raw figures in either store; store selection does not change the line's accounting basis.

Period Raw figures the exporter reads Written by
Historical period when financials_source is "framework-computed" financials[period]["raw"] (the raw lines are also tracked in multi_period_financials) spreading_check.py
Historical period when financials_source is "analyst-supplied" analyst_supplied_financials[period] /spread, analyst-supplied mode
Forward period when forecast_source is "analyst-supplied" analyst_supplied_financials[period], when a raw breakdown was supplied; recorded subtotals/ratios remain in financials/ratios as given supplied_forecast.py (/project)
Forward period when the forecast is framework-computed (forecast_source absent or not "analyst-supplied") financials[period]["raw"], including when historical financials_source remains "analyst-supplied" spreading_check.py (/project)

The workbook exporter, scripts/deal_export.py, follows these per-period rules. It never assumes a single store is universal, never falls back to the other store when a period's selected store is missing, and never blends raw fields from both stores within one period. An analyst-supplied period can have no raw breakdown at all; its recorded subtotals and ratios are still preserved rather than reconstructed from incomplete raw figures.

Resuming a deal

A step begins by finding the deal's state (the most recent dated folder for that company and proposal; a bare library call or a brand-new deal gets today's date) and treats everything recorded there as true. With orchestrator.py --new-review, today's dated folder is created through the shared fresh-review state manager only when that dated folder does not exist and the company already has a deal folder (for a company with no folder the headless run keeps its earlier behaviour: nothing to link, nothing refused). That minimal state links to the nearest earlier state-bearing review for the exact same company and proposal using prior_review_date, or starts unlinked when no eligible earlier review exists. The link is only a date; prior inputs and results are never inherited. Later pipeline checkpoints merge into the state and preserve prior_review_date. If today's dated folder already has a state.json, --new-review resumes it unchanged as a rerun after failure: it does not create another state or change the existing link. A pre-existing dated folder without state.json is refused rather than overwritten. A refusal (for example, when today's date is not later than the newest state-bearing review) exits with one error: line before a model call or write. The orchestrator checkpoints its current grounded figures and policy_state before it calls either agent, so a failure at the first model call can still leave the current review's figures on disk. If credentials are missing, the run stops before any model call. If fresh-review creation succeeds but credential resolution then fails, the minimal new state and its optional prior-review link remain on disk, but no financial checkpoint, model output, or generated document has been written. A fresh-review refusal is reported before credential resolution and causes no write.

Starting a new review

Use python scripts/state_manager.py --review-candidates to inspect valid earlier state-bearing folders for the exact company and proposal; the nearest earlier review is the default. --start-review creates a new date folder containing only company, proposal, date, and the current schema_version, plus the optional scalar prior_review_date when linked. This value is the exact YYYY-MM-DD of a previous review for the same company and proposal. Keep the proposal name exactly the same across years: a renamed proposal cannot be linked or compared. With no eligible prior, the new review is explicitly unlinked; --no-prior can request this even when candidates exist, and --prior-date can select any eligible earlier candidate. The start refuses an existing dated folder and, to keep the newest-folder resume rule reliable, refuses dates not strictly later than the newest existing state-bearing folder. It also refuses a company that has no deal folder yet (a mistyped company name must not quietly become a new deal; use /triage or /spread for a deal that has never been reviewed), while an existing company with a new proposal name may start unlinked. Earlier folders whose state.json cannot be read are reported as skipped, never silently ignored, and a start that fails part-way leaves no folder or file behind.

A started review inherits nothing from its prior: no inputs, financials, ratios, policy state, completed steps, review trail, covenants, downside, collateral, security package, facility terms, guarantees, drafts, or source manifest. The prior review is linked by date only. Company-level conventions and learnings stay in their existing stores and are neither copied into the new review nor modified by starting it. No schema-version bump is required for this optional key.

Comparing two reviews

scripts/review_compare.py compares two exact dated state.json snapshots read-only. Both must identify the exact same company and proposal; the explicit --prior-date must be earlier than --current-date, or the current state must record that prior date in its optional prior_review_date field. The comparator does not search other dated folders to guess a predecessor. It accepts legacy unversioned states and reads newer schema versions without writing either file or normalizing persisted data.

The by-label comparison covers recorded financials, ratios, multi-period and analyst-supplied figures, forecast and stress inputs, downside, the financial-source label and note, covenants and the recorded policy results, collateral, security package, guarantees, and optional structured ownership / facility_terms. Missing optional keys mean "not recorded", not zero. Changes are ordered deterministically. Decimal values are compared exactly; a delta is reported only where both sides are numeric. Covenants and covenant results are keyed by metric, type, and occurrence; forward covenant results use forward_id, downside breaches breach_id, conditions precedent/subsequent cp_id/cs_id, collateral asset_id, and guarantees guarantee_id when every record has a non-blank explicit ID. Lists without a reliable identifier (including security packages, security gaps, and guarantees without guarantee_id) are compared as exact ordered values. Changes in financials_source carry a clear comparability warning. This output reports stored facts and transitions, not an explanation or credit verdict.

The opt-in --periods-rolled-one-year check is a separate section after the by-label result. It compares historical periods in the prior review with their next-older labels in the current review, reports exact recorded values and differences, marks pairs consistent, restated, or not_comparable, and never includes forward periods. The flag records the analyst's confirmation; period roll-forward is never inferred.

Standalone guarantor spread (case C step 3)

C3 spreads one registered guarantor by stable entity_id, not by its legal name or a borrower-level alias. The script selects exactly one entity_records[entity_id] whose role is guarantor, passes only that record's multi_period_financials map to the existing evaluate_financial_model(), and stores the returned financials and ratios inside that same record. It never combines entity records, reads the borrower's raw figures as a fallback, or changes the borrower's top-level financials, ratios, multi_period_financials, analyst_supplied_financials or financials_source. The state schema is unchanged: the spread adds no top-level state key of its own.

A record is either spread_status: "not-spread" with no spread payload, or spread_status: "spread" with all of the following nested fields: figures_basis: "recomputed", spread_timestamp (timezone-aware ISO-8601), spread_source (the script provenance reference), financials, ratios, spread_fingerprints (one 64-character lowercase SHA-256 digest per computed period), and analyst_review_status: "not yet reviewed by an analyst". The latter is a stored disclosure and appears in every user-visible spread result: C3 does not imply that a credit reviewer has signed it off.

Only periods held in multi_period_financials are computed. A period held only in analyst_supplied_financials remains preserved as supplied input and is listed as unavailable; it is not recomputed, blended with the other store or replaced with borrower data. A guarantor with no framework-computed periods has no C3 spread.

Per-period fingerprint. For each computed period, the canonical payload contains only: contract tag open-cam-entity-spread-input/v1, entity_id, the period label, that period's end date, the full source object, raw_figures_source, selected store name multi_period_financials, and that period's complete raw-line object. It is encoded as json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") and hashed with SHA-256. Calculated outputs, display name, perimeter and guarantee_ids are excluded. The digest fingerprints values recorded in state; it does not prove the source document's authenticity. A raw-line or period-end correction changes that period's digest; changing the shared source object or raw_figures_source changes every period digest because those complete values appear in every period payload.

A missing/mismatched digest or malformed payload is stale, never current. Before a period is exposed, its digest is recomputed and its stored financials/ratios are compared with the existing evaluator's current output. That second check preserves the evaluator's existing prior-period working-capital dependency: if a prior period changes and consequently changes a later period's FCF-after-working-capital or cash-flow DSCR, the later stored result is also withheld as stale even though its own raw-input digest did not change. Unaffected periods remain available. Re-spreading writes the new period results and fingerprints through one locked, atomic state update.

Use python scripts/spreading_check.py --company ... --proposal ... --entity-id <entity ID> for this script-level operation. It takes the input already recorded in the selected entity record; it does not accept --financials or stress assumptions in entity mode. No multi-entity downside, aggregation, elimination, covenant routing, CAM presentation or legal guarantee condition is added by C3.

Guarantor-group covenant routing (case C step C4)

A covenant with basis: "guarantor_group" names exactly one entity in its non-blank basis_entity_id. The resolver selects entity_records[basis_entity_id] by exact ID; the registry key must equal the record's entity_id, the record role must be guarantor, and each guarantee_ids value on that record must match exactly one explicit guarantee_id in the deal's guarantees list. Legal names and provider names are never lookup keys or fallbacks. A missing, malformed, ambiguous or mismatched link makes that covenant UNRESOLVABLE.

The selected record must have spread_status: "spread". C4 reuses C3's entity_spread_view(): only periods whose input fingerprint and stored evaluator outputs are current are available. A stale, missing, analyst-supplied-only or otherwise unavailable recorded period is UNRESOLVABLE for that covenant and period. The same holds when the entity is identified but fails the role, guarantee-link or spread-status check: its recorded period labels (never its figures) are kept, so each recorded period is still reported UNRESOLVABLE with the global reason. The engine never substitutes borrower figures or another entity's figures. Current and forward guarantor results carry basis: "guarantor_group" and the selected basis_entity_id; when the ID itself is absent, the result carries basis_entity_id: null and an explicit reason. Borrower and case-A result shapes remain unchanged.

The selected-record check is per covenant so a broken link is reported as UNRESOLVABLE rather than silently changing the basis or using a different entity. Registration and state-write validation remain strict. C4 adds no top-level state key, migration or schema-version change; entity_records and the C3 fingerprint contract are unchanged.

Schema versions and validation

schema_version is MAJOR.MINOR.PATCH. A state written by an older or unversioned framework is read and upgraded on the next write; a newer or malformed version is refused on write (the file is left unchanged), because writing would silently drop fields. Reading a newer file still works. Each step validates only the keys it reads, so a deal is never rejected for a key a step does not use; the types it checks are: financials, ratios, multi_period_financials and analyst_supplied_financials are objects keyed by period; inputs and stress_assumptions and collateral_analysis are objects; covenants, collateral, security_package, guarantees, steps_completed and review_trail are lists; financials_source is framework-computed or analyst-supplied. A null value is "not recorded". The messages and fixes are in Troubleshooting.

Saved sources

sources/manifest.json is a list with one entry per saved document: filename, url (if it came from the web), step, claim (what it backs) and fetched_date. The document itself sits beside it. triage.sources and commercial.sources are lists of citation strings (list[str]); use an empty list when a step used no citations rather than omitting the key. Nulls, mappings, scalars and lists containing non-strings are invalid declarations; arbitrary elements are never converted into citation strings. steps_completed, if present, must be a list of strings; an absent field remains valid for new/incomplete historical states. Malformed consumed completion metadata, any invalid source declaration, or a completed source-bearing step without a declaration reports sources_declared: "unknown" and missing_saved_sources: true, even with a nonempty manifest.

Persisted conventions and learnings

Three small stores keep analyst-confirmed knowledge between deals, each written only on an explicit yes, always disclosed where it is applied, and none ever created by the headless pipeline:

Store Scope Written by Used by
deals/<Company>/_conventions.json, config/spreading_conventions.json one borrower, or every borrower /spread (via conventions.py) /spread surfaces it; the CAM caveat quotes the note
config/credit_policy_notes.md the fork /review both agents; mandatory for the Risk Reviewer
deals/<Company>/_learnings.md, config/deal_learnings.md one borrower, or every borrower /assemble, /research the Underwriter, advisory only

The convention file looks like the example in Workflows. These are plain local files, not a trained model.

Module reference

The sections from here on are the module-level reference, moved from CLAUDE.md (ledger).

State manager and state.json

scripts/state_manager.py — no anthropic dependency, same testability pattern as template_resolver.py. Its mutually exclusive --find mode calls find_deal(company, proposal) and prints one JSON object without creating files or directories. An exact match returns record_found: true, the resolved state_path and newest date for the exact proposal's valid dated folder containing state.json; a corrupt-but-present state file still counts as found so the regular reader can report the established corruption error. If no exact record exists, the result has record_found: false, company_folder_exists and near_misses. The latter is advisory only and contains only valid dated folders with state.json whose proposal names exactly match after case-folding and collapsing runs of whitespace/hyphens. No fuzzy/prefix selection is performed. The --check-steps mode keeps its existing output; --export-reviewer-view validates state and writes the history-free first-pass copy and separate history copy described above, refusing invalid, newer-schema or malformed-schema state before writing. state_path(company, proposal, date_str=None, base_dir=None) resolves deals/<Company>/<Proposal>_<Date>/state.json; when date_str isn't given, it auto-discovers an existing dated folder for that company/proposal (most recent wins) instead of defaulting to today, so a deal resumed on a later calendar day still finds its original file. An explicit date_str supplied to state_path(), read_state(), write_state() or append_review_trail() must be a real calendar date in exact YYYY-MM-DD form; malformed or impossible values raise StateError before any deal folder is created. Passing date_str=None retains the existing auto-discovery/today behavior. (This is deliberately different from the bare deal_export.export_deal() default, which is still today -- so callers resolve the date themselves via resolve_date_str(), see that script's entry in the CLI reference and issue #97.) read_state(company, proposal, keys=()) returns the parsed dict or None; it raises StateShapeError for a corrupt or non-UTF-8 file, a top level that is not an object, or (when keys names them) a wrongly-typed key -- see "Malformed state fails clearly" below. write_state(company, proposal, **fields) shallow-merges fields into the existing state (if any), always keeps company/proposal/date in sync, creates the deal directory if needed (reusing an existing one per the auto-discovery above), and returns the full merged state. write_state() and append_review_trail() never downgrade a state (issue #170). Before touching anything, they compare the file's recorded schema_version with this code's SCHEMA_VERSION, numerically per MAJOR.MINOR.PATCH part (1.10.0 is newer than 1.9.0; parse_schema_version()). Equal, older, and absent (read back as LEGACY_SCHEMA_VERSION, 0.0.0) are written and upgraded to SCHEMA_VERSION as before, unknown fields preserved. A newer version raises SchemaVersionError (a ValueError) naming both versions and the file, and a malformed one (not a string, or not exactly MAJOR.MINOR.PATCH digits: null, 1.2, v1.1.0, ...) raises it too, since it cannot be shown to be older -- in both cases the file is left byte-for-byte unchanged and no temp file is left behind. Reading such a file is unaffected. The fix for a newer file is to update this checkout of the framework, never to edit the version by hand. Limits: the guard covers only those two functions, i.e. spreading_check.py (the /spread and /project Bash steps) and orchestrator.py; the slash commands that record their step by writing state.json directly with Claude's file tools (/triage, /research, /commercial, /collateral, /review, /assemble) bypass it. Every CLI shows the refusal as one error: line and exit status 1 (see the next paragraph; orchestrator.py refuses at its first write_state, before any model call). A caller that passes schema_version= explicitly still overrides the stamp (unchanged behaviour). A read-only state_manager.py --find lookup is advisory. At the headless orchestrator's single state-resolution point, when no exact record exists and normalized candidates are present, it prints one stderr warning naming the candidate proposal/date and carries on with the existing resolution behavior. A missing record with no normalized near match produces no warning; the lookup does not change policy_check.py or source_manifest.py JSON output.

Malformed state fails clearly (issue #171). StateError (a ValueError) is the base for "this state.json's content cannot be used": SchemaVersionError (above) and StateShapeError (corrupt JSON, a top level that is not an object, or a key of the wrong type). validate_state(state, keys=None, path=...) checks the container types in STATE_SHAPES -- financials, ratios, multi_period_financials, analyst_supplied_financials are objects keyed by period whose values are objects; inputs, stress_assumptions are objects; downside_case is an object whose optional financials/ratios are period objects; collateral, covenants, security_package, guarantees, steps_completed, review_trail are lists (their elements are not inspected); financials_source is "framework-computed" or "analyst-supplied" -- and raises one StateShapeError naming every offending key, its required type and what was found, and the file. Each consumer validates the keys it reads, via read_state(..., keys=...): spreading_check.STATE_KEYS_READ, policy_check.STATE_KEYS_READ, deal_export.STATE_KEYS_READ, orchestrator.STATE_KEYS_READ, --check-steps (steps_completed), append_review_trail (review_trail); a deal is never rejected for a key that step does not use, and unknown keys are never inspected (a newer framework's fields survive). The top level is checked on every read. Deliberate tolerances, kept: a null value is "not recorded" for every key (a null period is empty); deal_export treats a non-object period inside financials/analyst_supplied_financials as empty, a non-list collateral as no collateral (one blank row) and a non-object downside_case as no downside case, as it always has, and so validates only that those two raw-figure keys are objects, that an object downside_case's inner financials/ratios are objects, and that financials_source is a known value (it routes historical raw-input selection; forward-period workbook selection also follows forecast_source, as described above). An empty value of the wrong container type (financials: [], covenants: {}) is rejected like any other: earlier code silently read it as empty. export_deal() reads and validates state before it creates the output folder or auto-saves a template, so a refusal leaves nothing behind; for a bare call with no date_str this also means a bare call still finds the deal's existing state before creating today's output folder. When an explicit date is supplied, that same date selects the state read as well as the output folder; this is how the CLI and orchestrator keep export figures tied to the selected review. Every CLI that reads state (spreading_check, policy_check, deal_export, orchestrator, state_manager --check-steps, source_manifest --check-sources) catches StateError and prints one error: ... line to stderr with exit status 1, never a traceback; the "always exits 0" of the two --check-* modes is about their results (a missing step or source is not an error), not about a state.json they cannot read.

Source manifest

scripts/source_manifest.py — no anthropic dependency, same testability pattern as state_manager.py (reuses its date-resolution/locking/sanitization directly rather than duplicating it). save_source(company, proposal, *, step, claim, source_path, url=None, filename=None) copies an already-downloaded/saved file into deals/<Company>/<Proposal>_<Date>/sources/ and appends an entry to sources/manifest.json; read_manifest(company, proposal) returns that manifest as a list ([] if nothing's been saved yet). See "Source material persistence" in CLAUDE.md. Callable from a slash command's Bash step:

python scripts/source_manifest.py --company "Acme Corp" --proposal "Fleet Loan" --step triage \
    --claim "Legal identity and PSC filing" --file /path/to/downloaded.pdf --url https://...

sources_declared(state) reports the declaration shape as "declared", "not_declared", or "unknown". A completed triage or commercial step without a list[str] declaration is "unknown", as is any malformed declared list or malformed consumed steps_completed; saved material cannot make that unknown shape valid. Absent completion metadata alone is not invalid, and an explicit empty list is a valid declaration of no citations. missing_saved_sources(state, manifest) remains a boolean check: it returns true when any declared non-empty citation has no saved manifest material, or when the consumed declaration/completion shape is unknown. It remains deal-level (not matched against an exact triage/commercial/research manifest step tag — /research tags its entries "research") and floor-level (at least one source saved, not an exhaustive 1:1 match to every citation because some sources are legitimately unsaveable, e.g. a bot-blocked page). The --check-sources CLI prints both missing_saved_sources and sources_declared and exits 0 for a check result; a state or manifest it cannot read is still an error, exit 1. The calling command must not silently continue when sources_declared is "unknown".

Persisted-convention stores

scripts/conventions.py — see "Persisted conventions" in CLAUDE.md for its full behavior; briefly, read_company_convention/write_company_convention/read_enterprise_convention/ write_enterprise_convention back the borrower-specific and enterprise-wide spreading-convention stores, callable from /spread's own Bash steps (--company/--enterprise × --read/--write).

Clone this wiki locally