Repository navigation
financial model
This page is generated from
docs/financial-model.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 before "Module reference" are written for readers; "Module reference" and what follows were moved from
CLAUDE.mdor the README, unchanged apart from the fixes in the move ledger.
The figures a CAM reports, how the framework decides whether a covenant passes, and what a draft must contain, explained from first principles with worked numbers. Why it is built this way: design decisions D2, D4, D5 and D6.
This page explains the figures a CAM reports and how the framework decides what a draft must say about them. It
assumes no credit background. Figures are in whatever currency units you supply (the framework labels no currency);
the examples use the synthetic deal from Workflows, in "synthetic units". The definitions here
describe scripts/spreading_builder.py, which is authoritative. Every figure is also specified entry by entry —
formula, unit, edge rules, implementation reference and status, under a stable id — in the
formula register.
Each is computed from the raw line items you supply for a period (revenue, cost_of_sales, and so on; the field
list is in the command reference). A missing line item counts as 0; it is never invented.
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. (Decision D-c of issue #504.) The names are retained for compatibility; these inputs do not describe cash payment timing.
| Term | How it is computed | Plain meaning |
|---|---|---|
| Gross profit | revenue - cost of sales | What is left after the direct cost of what was sold |
| Operating profit (EBIT) | gross profit - admin expenses - depreciation - amortisation + other income | Profit from running the business, before interest and tax. A house convention: before exceptional items (deducted only in profit before tax) and including other income, so every ratio and covenant on it is on that basis (F-004) |
| EBITDA (before exceptionals, incl. other income) | operating profit + depreciation + amortisation | Operating profit before the non-cash charges; the usual measure of cash earnings. Like operating profit, before exceptional items and including other income, so every EBITDA-based ratio and covenant is on that basis (F-006) |
| Profit before tax | operating profit - interest paid + interest received - exceptional costs | Where exceptional costs are deducted; operating profit and EBITDA are before them |
| Net profit | profit before tax - tax paid | |
| Free cash flow (FCF), before working capital | EBITDA - capex - tax paid - interest paid + interest received | Cash generated after investment, tax and net interest, before any change in working capital (the working-capital-adjusted measure is the next row; the stored key stays fcf). Scheduled principal repayments are not deducted: they are financing, and DSCR already covers them |
FCF after working capital (fcf_after_working_capital) |
FCF - (operating working capital - the prior period's operating working capital); operating working capital = trade debtors + stock + other current assets - trade creditors - other current liabilities | FCF adjusted for the cash absorbed by (or released from) working capital. The operating working capital level is an intermediate, not stored on its own. The earliest period and any period with no recorded prior (including a prior period that records none of the five working capital lines) are N/A, never zero (F-064) |
| Current assets / liabilities | assets: cash + trade debtors + stock + other current assets. Liabilities: trade creditors + current debt + overdraft + other current liabilities | What is expected to turn into cash, or fall due, within a year |
| Total debt | current debt + overdraft + long-term debt + loan notes | Interest-bearing borrowing. The combined Loan Notes / Preference Shares line counts fully as debt, whatever the instrument's terms (F-020). Provisions and trade creditors are deliberately excluded |
| Total equity | share capital + retained profit | The owners' stake. Retained profit includes all reserves and share premium; there is no separate line for them (F-017) |
| Tangible net worth (TNW) | total equity - intangible assets | Net worth that does not rely on intangibles such as goodwill |
| Ratio (state key) | Formula | Reading |
|---|---|---|
DSCR (EBITDA-based), debt service cover (dscr) |
EBITDA / (interest paid + scheduled principal) | EBITDA-based: times EBITDA covers the year's debt service, not a cash-flow measure (the cash-flow-based DSCR is cash_flow_dscr, the next row). Above 1 means earnings cover it; a minimum covenant is typically set above 1 (here 1.25) |
DSCR (Cash Flow) (cash_flow_dscr) |
(FCF after working capital + interest paid - interest received) / (interest paid + scheduled principal) | Cash flow available for debt service (after tax, capex and the working-capital movement; interest added back so it is deducted once) over the same debt service. N/A for the earliest period or any period with no recorded prior, and when debt service is zero or negative (issue #521) |
Gross leverage (gross_leverage) |
total debt / EBITDA | Years of EBITDA needed to repay the debt; lower is stronger |
Net debt / EBITDA (net_debt_to_ebitda) |
(total debt - cash) / EBITDA | Leverage after counting cash. Negative when cash exceeds debt (net cash) |
Gearing (gearing) |
total debt / total equity | Debt relative to the owners' stake; see Percent-type ratios are stored as fractions |
Current ratio (current_ratio) |
current assets / current liabilities | Short-term liquidity; above 1 means current assets cover current liabilities |
EBIT interest cover (ebit_interest_cover, alias EBIT/Interest) |
operating profit / interest paid | Times profit covers interest |
EBITDA interest cover (ebitda_interest_cover, alias EBITDA/Interest) |
EBITDA / interest paid | The same on EBITDA |
FCF conversion (fcf_conversion_pct; workbook row "FCF Conversion % (before working capital)") |
FCF / EBITDA | The share of EBITDA that becomes free cash; see the percent-type ratio convention |
Trade debtor days (trade_debtor_days) |
trade debtors / revenue x 365 | How long customers take to pay |
Stock days (stock_days) |
stock / cost of sales x 365 | How long stock sits |
Trade creditor days (trade_creditor_days) |
trade creditors / cost of sales x 365 | How long the company takes to pay suppliers |
Working capital cycle (working_capital_cycle_days) |
debtor days + stock days - creditor days | Days of operating cash tied up |
gearing and fcf_conversion_pct are the two percent-type ratios. Both ratio values and any covenant threshold on
either metric use the fraction convention: 0.87 represents 87%. In image transcription, an explicit trailing
percent sign on one of these ratios is converted to its fraction while the source text remains visible in the
read-back; a trailing x or % on other ratios keeps its existing behavior. A bare number is never automatically divided
by 100.
For supplied_forecast.py and transcription_check.py, a percent-type value whose absolute magnitude is greater
than 10 emits one aggregated warning to stderr and is retained as supplied, so the analyst can check its unit rather
than having the framework guess. The covenant policy engine returns UNRESOLVABLE if the absolute value of either
the recorded actual ratio or its threshold exceeds 10, because it looks like a percentage rather than a stored
fraction. It does not compare that likely unit mismatch as a PASS or FAIL. Existing N/A rules take precedence:
a ratio with a zero or negative denominator remains N/A and its covenant remains UNRESOLVABLE for that reason.
The valid raw line-item names are the keys of scripts/spreading_builder.py's FIELD_LABELS (for example
revenue, cost_of_sales, admin_expenses, interest_paid — not cost_of_goods_sold, admin_expense or
interest). A payload carrying a name that is not one of them is refused before anything is written: one
error: line names the period and each unknown key and, when a close match exists, suggests the nearest valid name, and nothing is written
to state.json (issue #596, rule R-SPREAD-008). No underscore-prefixed or other metadata keys are allowed —
every name in a payload must be a known field name. An omitted known field still reads as zero, as before; only
the name is checked, never the value's presence.
A deal that already has an unknown name on file in multi_period_financials — recorded before this rule existed —
is not locked out: the call still computes. Every path that reads the stored lines to compute prints one stderr
warning per unknown key naming the period and the key, so the analyst can correct it: a spreading run
(--financials or --spread), a transcription commit (once, not once per preflight), the headless orchestrator
(with new figures or stress-only), the covenant cushion report, the supplied-forecast path that derives a downside from stored analyst-supplied lines, a covenant policy read that
recomputes a stored guarantor spread, and the guarantor --entity-id spread (which also names a misspelt key in the analyst-supplied
store, names only, never computing it). The same refusal applies to a new guarantor entity record at registration,
and the stored name stays on file until it is corrected. One refusal names the unknown keys of every affected period
and of both raw stores, not only the first.
FY-Current of the synthetic deal (financials_input.json):
revenue 5000, cost of sales 3000, admin expenses 1000, depreciation 300, interest paid 150, scheduled principal 350,
capex 400, tax paid 100, cash 250, trade debtors 600, stock 400, trade creditors 450, other current liabilities 100,
current debt 350, long-term debt 1650, intangible assets 100, share capital 500, retained profit 1800.
- Gross profit = 5000 - 3000 = 2000. Operating profit = 2000 - 1000 - 300 = 700. EBITDA = 700 + 300 = 1000.
- Profit before tax = 700 - 150 = 550; net profit = 550 - 100 = 450. FCF = 1000 - 400 - 100 - 150 = 350.
- Operating working capital = 600 + 400 - 450 - 100 = 450 (FY-1's is 420); FCF after working capital = 350 - (450 - 420) = 320.
- Total debt = 350 + 1650 = 2000. Total equity = 500 + 1800 = 2300. TNW = 2300 - 100 = 2200.
- Current assets = 250 + 600 + 400 = 1250; current liabilities = 450 + 350 + 100 = 900.
- DSCR = 1000 / (150 + 350) = 2.0. Gross leverage = 2000 / 1000 = 2.0. Net debt / EBITDA = (2000 - 250) / 1000 = 1.75. Current ratio = 1250 / 900 = 1.3889. Gearing = 2000 / 2300 = 0.8696. EBIT interest cover = 700 / 150 = 4.6667. FCF conversion = 350 / 1000 = 0.35.
- Debtor days = 600 / 5000 x 365 = 43.8; creditor days = 450 / 3000 x 365 = 54.75; stock days = 400 / 3000 x 365 = 48.6667; working capital cycle = 43.8 + 48.6667 - 54.75 = 37.7167.
spreading_check.py produces exactly these values, and the workbook's formulas produce them too.
A ratio is only meaningful when its denominator is positive. If the denominator is zero or negative the ratio is
N/A: null in state.json, the text N/A in the workbook. The denominators are EBITDA (gross leverage, net debt
/ EBITDA, FCF conversion, EBITDA interest cover), interest paid plus scheduled principal (DSCR), total equity
(gearing), interest paid (EBIT interest cover), current liabilities (current ratio), revenue (debtor days) and cost of
sales (stock and creditor days).
Why: dividing by a negative EBITDA gives a finite negative leverage, which sits below every maximum covenant threshold, so a loss-making borrower would appear to pass "leverage must not exceed 3.5x". Zero is genuinely undefined (no interest expense is infinite cover, not zero cover). Only the denominator is tested: a negative numerator over a positive denominator is a real number and is kept (an EBITDA of -100 over debt service of 490 gives a DSCR of -0.204, a real shortfall that fails a minimum-DSCR covenant; net cash gives a negative net debt / EBITDA).
Non-finite and non-numeric values are invalid input, not financial results. At the framework-computed
entry points, recognised raw line-item fields must be finite JSON numbers or null. Strings (including numeric
strings), booleans, lists and objects are refused rather than coerced, with one error: line naming the period and
field, exit status 1, and no state write. null keeps the existing unavailable-input behavior for an individual
raw line item, and omitted fields still default to zero. Each period supplied in --financials or --spread must
itself map to an object of raw line items; a period mapped to a string, number, null, list or other non-object
value is refused by the command-line entry points with one period-naming error: line and no state write. For
supplied_forecast.py, non-object values in the forecast or downside.periods map are refused with one error: line
naming the period and saying it must be an object of line items, also before any state write. Stress assumption values
follow a stricter rule: every supplied shock must be a finite JSON number. Strings (including
numeric strings), booleans, null, lists and objects are refused with one error: line naming the stress key,
exit status 1, before any state write. The shared rule is used by spreading, supplied-forecast and headless
orchestrator paths; formulas and valid-input outputs are unchanged. The spreading and stress paths also reject
NaN, Infinity and -Infinity in raw figures or stress assumptions before evaluating them. Non-finite values already present in persisted state, supplied as
covenant thresholds/ratios, or produced by arithmetic overflow are also rejected before the state changes or a
policy result is returned. They are never coerced to zero, N/A or a large finite substitute. The same guard covers
the collateral and security_package figures in state and the --collateral input of the headless run (one
error: line, exit status 1, nothing written). This does not change the rule above: finite negative numerators
remain valid figures, while ratios with zero or negative denominators remain N/A.
Collateral cover percentage. The aggregate collateral_cover_pct is expressed on a 0–100 percentage scale, unlike
fraction-stored percent-type ratios. It is N/A (omitted from ground truth as None) if aggregate exposure is zero or
negative, or if any asset has a negative or non-finite exposure or collateral value. A negative asset is invalid input;
it must not reduce or offset positive exposure from another asset. The workbook's per-asset and total CV % of Exposure
cells apply the same strictly positive exposure rule and show N/A otherwise. For valid, non-negative collateral inputs
with a positive exposure, the existing collateral-value / exposure calculation and percentage scale are unchanged.
Divergence closed at input (issue #378). The exported workbook's total row sums the per-asset cells, so it could
net a negative asset into a positive total and show a percentage, while compute_collateral_cover_pct returns None for
the same input. Rather than guard the sheet a second time, a negative on any monetary collateral field
(exposure, cap_value, non_recovery, costs, collateral_value) is now refused where the input is recorded:
the headless --collateral route calls the shared validate_collateral_inputs() validator with one error: line,
exit 1 and nothing written. compute_collateral_cover_pct()'s None-on-negative branch is kept as defence in depth.
The interactive /collateral refusal is prompt-observance only until PR C wires the validator into it.
A covenant on an N/A ratio is UNRESOLVABLE: it cannot be tested. That is neither a pass nor a fail, and it is the
same for a minimum and a maximum covenant. A covenant is also UNRESOLVABLE if its type is not minimum/maximum, its
threshold is missing or not a number, or its metric is not one of the computed ratios. Every covenant result carries
a reason, empty for a pass or fail and one sentence for UNRESOLVABLE, for example gross leverage not meaningful: EBITDA is negative. If a stored ratio sits next to a recorded denominator that is zero or negative (an older
checkpoint, or an analyst-supplied ratio), the covenant is still UNRESOLVABLE and the stored number is ignored.
A covenant is tested only on its own basis: borrower, consolidated or guarantor_group (an absent or null
basis means borrower, which is what every covenant recorded before the field existed meant). The deal's recorded
figures are one view: the borrower's, or, when the deal records group_basis (borrower-supplied consolidated group
accounts), the consolidated group's. A borrower or consolidated covenant on a different basis than the recorded view is UNRESOLVABLE, with a
reason that says so, and so is a covenant whose basis is not one of the three: the engine never tests it against the
figures that happen to be recorded. A guarantor_group covenant is the exception: it is never tested against the recorded view but resolved per covenant against its own named entity (see "The financial basis is selected per covenant" in the Covenants section below). Example: a deal that records consolidated group accounts and a covenant on the
borrower's own DSCR (the default, because the covenant states no basis) is UNRESOLVABLE until the covenant states its
basis or borrower figures are recorded. Nothing is refused; the engine computes and reports the result. The
decided next step, delivered by a separate change and not yet in the commands, is that the interactive steps will
stop and ask the analyst to confirm any UNRESOLVABLE result (decision of 2026-10-22 on #48).
A covenant is a condition in the facility: a minimum (the ratio must be at least the threshold) or a maximum
(it must be at most the threshold), recorded as {"metric": "dscr", "type": "minimum", "threshold": 1.25}; a covenant may equally name the cash-flow DSCR, cash_flow_dscr (issue #521). Equality
passes. Results: PASS, FAIL or UNRESOLVABLE, with actual and a headroom as a fraction of the threshold's
absolute value: for a minimum (actual - threshold) / abs(threshold), for a maximum (threshold - actual) / abs(threshold), so the headroom is positive when the covenant passes and negative when it fails whatever the
threshold's sign. In the example, DSCR 2.0 against a minimum of 1.25 has headroom 0.6; gross leverage 2.0 against a
maximum of 3.5 has 0.4286. A threshold of exactly 0 has no percentage headroom (it is null), but the status is
still decided by comparison.
The financial basis is selected per covenant. An absent or null basis means borrower and retains the existing deal-level behaviour. consolidated uses the borrower-supplied view recorded in group_basis. guarantor_group requires a non-blank basis_entity_id and resolves exactly one registered guarantor by that ID, with an explicit guarantee_id link to the deal's guarantees. Its figures come only from that entity's current C3 framework-computed spread. A missing/invalid entity ID, wrong role, missing or ambiguous link, unspread record, stale fingerprint/output or analyst-supplied-only period yields UNRESOLVABLE. When the entity is identified but fails the role, link or spread check, each period it records (labels only; no figure is exposed) is still reported UNRESOLVABLE with that reason, never silently omitted. A guarantor result carries both basis: "guarantor_group" and basis_entity_id; a missing ID is reported as null. The borrower and case-A result shapes are unchanged, and no borrower or other-guarantor figures are used as fallback.
A consolidated covenant can read a credit aggregation (issue #472, B3). When the deal records a credit_aggregation and no case-A group_basis, the one shared resolver (resolve_covenant_view()) routes a consolidated covenant to the aggregation: only a period whose recorded inputs still reproduce their fingerprint and that carries a well-shaped computed object supplies figures. A period that is stale, invalid, absent or recorded but not calculated (B2b has not computed it) is UNRESOLVABLE with that period's reason, never replaced by the borrower's figures. If both a group_basis and a credit_aggregation are recorded, a consolidated covenant is UNRESOLVABLE (exactly one source is allowed; D22). A covenant with no basis or basis: "borrower" never reads aggregation values. The result then carries view_source: "credit_aggregation" and the period's input_fingerprint beside basis: "consolidated"; a deal with no credit_aggregation keeps its earlier result shape exactly. A non-positive denominator stays N/A and the covenant UNRESOLVABLE (D5). Aggregated figures reach the draft check's ground truth only under an explicit identity, as credit_aggregation::<metric> (with _<period> for a non-current period), and are never flattened into the borrower's bare metric name. Forward-year and downside testing of an aggregation is not part of B3: such a covenant stays UNRESOLVABLE there (the recorded view is not the covenant's basis) until the accounting-gated work provides forward figures.
Covenants are tested in three places, with three different consequences:
| Where | Which period | A FAIL or UNRESOLVABLE... |
|---|---|---|
covenant_results |
FY-Current |
rejects the draft by code until the figures or the covenant record change |
downside_covenant_breaches |
each forward year, only where the base case passes and the stressed case fails or cannot be tested |
rejects the draft unless it addresses the breach by id (downside_breaches_acknowledged); each record carries basis and basis_entity_id only when present on the base-case result |
forward_covenant_results |
each projected forward year's own base case |
never rejects; it is recorded, and the non-passing entries are shown to the model as plain data; guarantor rows identify their basis_entity_id
|
Each downside_covenant_breaches record carries basis and basis_entity_id only when the corresponding base-case result has those keys, copied without re-deriving the rule. For a guarantor covenant, C3 supplies the base/forward spread but no guarantor-specific downside. Where its base-period covenant passes and a matching deal downside period exists, C4 records an UNRESOLVABLE downside item with downside_actual: null and the guarantor identity; it never compares the borrower's downside ratios with guarantor actuals. A base-case FAIL or UNRESOLVABLE is not also a downside breach. An ordinary borrower covenant with no stated basis keeps the key absent (not null). On consolidated-view figures, an unstated basis defaults to borrower and is UNRESOLVABLE, so it cannot produce a downside breach.
A forward year with no projection recorded is not tested, and the state carries no covenant tenor, so a covenant that really ends earlier is still reported for later projected years. For a guarantor covenant, each recorded forward period on the selected entity is evaluated against that entity's own current spread; a recorded but stale, analyst-supplied-only or otherwise unavailable period is disclosed as UNRESOLVABLE with its entity identity. A period not recorded for that entity is not invented from the borrower's projection.
FY+1, FY+2 and FY+3 are management's own forecast: raw figures you supply, in the same shape as a historical
year, computed by the same formulas (or, in the analyst-supplied mode, the analyst's own figures recorded as given: see
Analyst-supplied forecasts). Nothing is extrapolated. In the example, FY+1 has EBITDA 550 and total debt
1650 (DSCR 1.1, gross leverage 3.0), and FY+2 has EBITDA -100, so its gross leverage is N/A and its DSCR
is -0.204. Against the covenants (minimum DSCR 1.25, maximum leverage 3.5): FY+1 DSCR fails, FY+1 leverage
passes, FY+2 DSCR fails and FY+2 leverage is UNRESOLVABLE. All four are disclosed in forward_covenant_results
(ids FORWARD-FY-1-DSCR, FORWARD-FY-1-GROSS-LEVERAGE, FORWARD-FY-2-DSCR, FORWARD-FY-2-GROSS-LEVERAGE) without
rejecting the draft.
A downside case is a forward year re-run under three deterministic shocks, all optional (each defaults to no shock):
shocked_revenue = revenue x (1 - revenue_haircut_pct / 100)-
shocked_admin_expenses = admin_expenses x (1 + opex_increase_pct / 100)(admin expenses only, never cost of sales) shocked_interest_paid = interest_paid + total_debt x interest_rate_bump_bps / 10000
Stress-assumption units and bounds. All three assumptions must be non-negative. A
revenue_haircut_pct of 100 or more is refused because it would make revenue zero or negative;
it must be less than 100. revenue_haircut_pct and opex_increase_pct are percentages, so 10 means
10%. A positive value strictly between 0 and 1 for either percentage field is accepted as written but
prints a warning to stderr because it may be a fraction/percent unit slip; there is no confirmation
flow and the value is not converted. interest_rate_bump_bps is measured in basis points, not
percent. No other upper bounds are imposed on operating-expense increases or interest-rate basis points.
The same validation is used by spreading_check.py, the analyst-supplied supplied_forecast.py
path, and the headless orchestrator, before any state write or model call.
Every other raw figure carries through unchanged. For the example's FY+1 with a 5% revenue haircut and a 200 basis
point interest rise: revenue 4600 becomes 4370, interest 150 becomes 150 + 1650 x 200 / 10000 = 183, EBITDA falls from
550 to 320, DSCR falls from 1.1 to 0.600 and gross leverage rises from 3.0 to 5.15625, which breaches the
3.5 maximum. Because the base case passed, that is a downside breach (DOWNSIDE-FY-1-GROSS-LEVERAGE) and the draft
must address it. The FY+1 DSCR already failed in the base case, so it is reported once, as a forward result, not
again as a downside breach.
Each downside breach has its own stable breach_id. If two covenants use the same metric in the same year, the
IDs are disambiguated with numeric suffixes (DOWNSIDE-FY-1-DSCR, DOWNSIDE-FY-1-DSCR-2). A single covenant keeps
the existing unsuffixed ID. The draft must acknowledge each breach separately; acknowledging one does not acknowledge
the other.
scripts/covenant_cushion.py (issue #470; read-only, JSON on stdout) reports the mechanical distance between each
recorded covenant's PASS and its first non-PASS result. It computes nothing the policy engine owns: every covenant
row is the engine's own result, reused through policy_engine.evaluate_single_covenant(), and every shock point
re-runs the recorded raw line items through apply_stress_shocks() and evaluate_financial_model().
Exact EBITDA break-evens exist for the four EBITDA-driven covenants, per period, from that period's raw lines:
EBITDA* = threshold x (interest_paid + scheduled_principal) for the DSCR,
EBITDA* = total_debt / threshold for gross leverage,
EBITDA* = (total_debt - cash) / threshold for net debt / EBITDA and
EBITDA* = threshold x interest_paid for EBITDA / interest cover, each with the side that satisfies the covenant,
derived from the covenant's recorded type exactly as the policy engine evaluates it (a minimum covenant passes when
the ratio is at or above the threshold, a maximum when it is at or below) combined with the ratio's direction as
EBITDA rises: the rising ratios (DSCR, EBITDA / interest cover) pass a minimum covenant at-or-above and a maximum
at-or-below; the leverage ratios fall over positive debt and rise over net cash, mirroring the two; a boundary at
or below zero EBITDA or a zero numerator is reported with a note saying whether the covenant passes at every
testable EBITDA or at none, never as a fabricated crossing. The EBITDA basis is the one the model computes: before exceptional items and
including other income (decision D-a, issue #504); the DSCR is the EBITDA-based DSCR (decision D-d; the cash-flow
DSCR, cash_flow_dscr, is not one of the report's break-even covenants). A zero or negative ratio denominator (debt service or interest paid) leaves the ratio N/A and the
covenant UNRESOLVABLE, and no break-even is reported for it; a leverage covenant with a zero threshold has no
boundary. A boundary at or below zero EBITDA means the ratio is N/A there, so the covenant is UNRESOLVABLE at
EBITDA <= 0 before it can FAIL (and the report's note says whether it passes at every testable EBITDA or at none)
rather than fabricating a crossing.
Reverse stress moves one shock at a time over the three recorded shocks only (there is no cost-of-sales shock):
the base scenario starts from zero shock, the downside scenario from the recorded stress vector, reporting both the
cumulative crossing and the additional cushion beyond the recorded setting. Each search brackets the first non-PASS
point (FAIL or UNRESOLVABLE alike) by geometric expansion then bisection and reports the pass/non-pass bracket and
its tolerance — never a point of false precision. A ratio the shock cannot move (for example gross leverage under
the interest bump) is reported "not moved"; a non-monotone driver, a point the spreading builder refuses, or a
crossing outside the documented bounds (revenue haircut 0–100%; opex increase and interest bump up to 10,000) is
reported with its reason instead of a cushion. A baseline already FAIL or UNRESOLVABLE reports zero remaining
cushion, and no search pretends an adverse shock first caused it. The recorded stress vector must pass the shared
domain validator (numeric_validation.validate_stress_assumptions(), the write path's own contract): a present
malformed or negative assumption refuses the whole report with its reason rather than being read as a zero shock;
only an absent shock key defaults to zero.
Because the searches re-evaluate the raw line items, a period whose figures are analyst-supplied
(financials_source for FY-Current, forecast_source for a forward year) or absent from
multi_period_financials reports its break-even and searches as unavailable with the reason; a recorded ratio that
disagrees with a re-evaluation of the raw lines is flagged as a caveat. For guarantor_group, the baseline result
uses the same exact-entity resolver as policy evaluation. C4 deliberately reports guarantor EBITDA break-even and
reverse-stress searches as unavailable: the framework has no guarantor-specific stress basis, and borrower raw lines
and stress assumptions must not be applied to a guarantor. Forward-year rows are disclosure only, exactly as the
policy engine records them. The formulas are register entries
F-059..F-063; the report is not a credit decision, and policy_check.py remains
authoritative.
Case B aggregates the borrower and selected registered entities. B2a records and validates the inputs
only: credit_aggregation.py persists, under the top-level credit_aggregation key, each
requested period's manifest (participants, the common period end and its evidence, per-entity confirmed
scope) and one SHA-256 input fingerprint over the canonical input payload. B2a computes nothing:
no elimination, subtotal, ratio or covenant result. The accounting-gated B2b step will later fill each
period's optional computed object (financials and ratios in the same shape as the borrower's
top-level financials[period] and ratios[period]); until it exists no period has computed, and
every covenant consumer treats a missing, stale or untrusted computed as UNRESOLVABLE with a reason (the
B4 outputs label such a period not calculated, stale or invalid with the reason and show no figures). The full key contract
is documented in the data model.
The participants are the reserved token @borrower (the existing legacy borrower stores, never an
entity record) plus explicit entity_records IDs whose perimeter is included and confirmed; nothing is
inferred. Every participant must carry the same period label and exactly the same ISO date per period,
with the borrower's date supplied in the request with an evidence reference; a missing date or any
mismatch refuses the whole aggregation before any write. Intercompany counterparties resolve by exact ID
to a selected participant of that line's own period, or to @borrower; a dangling, unselected,
out-of-perimeter or unconfirmed reference is a named hard error, and an unconfirmed line is refused.
Analyst-supplied-only figures are refused rather than silently reconciled (D4 is not overridden), a deal
that already carries a case-A group_basis is refused fail-closed, and non-finite or boolean numbers
are refused. This is a credit aggregation, never a statutory consolidation: it does not describe
the aggregation as a consolidation, and it creates no elimination logic, adjusted raw line, new formula
or register entry — those belong to the gated B2b step and the formula register's own change control.
spreading_check.py --entity-id <entity ID> is the script-level path for one registered guarantor. It selects one
entity_records entry and calls the existing evaluate_financial_model() with only that entry's
multi_period_financials. The existing borrower computation and its formulas are not changed or reused as a
fallback. Returned financials and ratios are stored inside the selected entity record with
figures_basis: "recomputed"; the borrower-level financial stores and financials_source are left unchanged.
Case C remains standalone; this is not a credit aggregation or consolidation, and the spread adds no
top-level state key of its own.
The entity record stores one SHA-256 input fingerprint per computed period. Each canonical JSON payload includes the contract tag, entity ID, period label and end date, full source metadata, raw-figure source, selected raw store name and complete raw period. It uses sorted compact UTF-8 JSON, preserves non-ASCII text and refuses non-finite JSON values. The calculated values and display/perimeter/guarantee metadata are not inputs to that hash. A missing or mismatched digest or malformed payload makes the period stale. The display helper also compares stored financials/ratios with the existing evaluator's current output, so a dependent later period is withheld when a changed prior-period working-capital input changes its FCF-after-working-capital or cash-flow DSCR. No evaluator formula is duplicated or changed.
Only multi_period_financials is evaluated. A period present only in analyst_supplied_financials stays
uncomputed and unavailable; there is no blending or fallback. Every stored and user-visible C3 result carries
analyst_review_status: "not yet reviewed by an analyst" until a credit reviewer signs off. C3 does not
change covenant routing, legal CP/CS, or CAM/workbook presentation.
By default every subtotal and ratio is recomputed from raw line items. An institution may instead supply its own
already-spread figures (its template may treat a line differently, for example depreciation inside cost of goods
sold). The framework then records them exactly as given, sets financials_source to "analyst-supplied", and the
CAM must carry an explicit caveat that those figures were not independently recomputed. It never reconciles them to
its own schema. One limit: a stored ratio whose denominator is not recorded (an analyst-supplied DSCR, say) cannot be
cross-checked, so the N/A rule can only be applied where the denominator is on file.
One basis per deal. If financials_source is already "analyst-supplied", the default framework-computed
spreading_check.py path refuses to recompute and relabel the deal. Use /spread's analyst-supplied mode to record
further figures; one deal never mixes the two modes. A historical period is refused on an analyst-supplied deal whatever
--no-update-financials-source says (one error: line, exit status 1, nothing written); only a forward-year-only call, as
/project makes, is accepted.
/project has the same opt-in alternative as /spread (issue #124): when an institution's forecast convention does not
fit the framework's raw schema, the analyst supplies already-computed forward-year subtotals and ratios and
scripts/supplied_forecast.py records them exactly as given (financials[FY+n], ratios[FY+n], and an optional
raw breakdown in analyst_supplied_financials). They are never passed through the framework's formulas to produce a
recorded value. The default, framework-computed mode is unchanged.
Labelling. forecast_source: "analyst-supplied" says the forward years were supplied (absent means
framework-computed, which is every deal that existed before this mode), and the deal-wide financials_source is
"analyst-supplied" so the CAM must carry the caveat; the analyst's description of their forecast convention is added
to financials_source_note, which that caveat quotes. One basis: a deal whose forward years were computed from raw
lines, or whose historical years were computed by the framework (or have no recorded basis), is refused rather than
blended, because one deal-wide flag and one set of workbook raw inputs cannot describe two bases; and once an
analyst-supplied forecast is on file, the framework-computed path refuses to overwrite its forward years or relabel the
deal.
The downside, decided conservatively. The three stress shocks are defined on the framework's raw field names and an interest-bearing-debt aggregate, so they cannot be assumed to mean anything for an analyst's own forecast. For each forward year:
- If the analyst supplied their own stressed forecast for it (subtotals and/or ratios plus a description of the
scenario), that is recorded as
analyst-suppliedand is what covenants are tested against under stress. - Otherwise, if stress shocks were requested, they are applied only if they genuinely meet their assumptions: the
year's raw lines were supplied; every line a requested shock acts on is present; every line the covenant ratios read
is present (the calculation reads an omitted line as zero, and an omitted line is not a zero the analyst confirmed,
so each is given, as an explicit
0where it is nil); and the framework's formulas reproduce the subtotals and ratios the analyst gave for that year to two decimal places. Then the downside is derived by the existing calculation, labelledframework-derived from reconciled analyst-supplied lines, and holds only the figures every one of whose lines was supplied (no profit before tax unless exceptional costs were given, no total assets unless the fixed-asset lines were). A year that fails any of this is not stressed with the framework's shocks. - Otherwise, if a downside was wanted at all (shocks requested, or an own scenario given for another year), the year is
recorded under
downside_case["unavailable"]with the reason. The policy engine then treats any covenant that passes in that year's base case as UNRESOLVABLE under stress, exactly as it already does when a stress drives a ratio to N/A: adownside_covenant_breachesentry withdownside_statusUNRESOLVABLE,downside_actualnulland a reason beginningdownside analysis unavailable for FY+n:. The draft must address it (the existing "Undisclosed Downside Breach" rejection), so the absence of a downside is disclosed, never silent and never a pass. - If neither shocks nor a scenario were supplied, no downside was asked for and none is recorded, as for any deal.
downside_case keeps its financials and ratios, and for these deals also carries basis (which source each year's
downside came from), unavailable and the scenario's description. There is one description per case and it
describes every analyst-supplied year in it: supplying a scenario with a different description while earlier
analyst-supplied years are not restated is refused (nothing is written), and restating them all with the new
description is accepted. The headless orchestrator.py can neither recompute nor originate such a downside, so it
keeps the recorded stress assumptions and refuses a --stress-assumptions that differs from them (repeating them is a
no-op); change them by re-running /project's analyst-supplied mode. In the workbook, supplied forward and downside
columns show the supplied values, unavailable downside columns are blank, and each is labelled
(outputs). A worked example is in
Workflows.
Figures a session reads out of a screenshot, a photo or a scanned page go through scripts/transcription_check.py
before they are recorded (issue #132; the procedure is in Workflows). The
rules it applies are described here.
Signs: what the source writes versus what the framework is given. The framework reads raw lines with fixed
semantics (evaluate_financial_model()): costs and cash outflows are entered as positive amounts and subtracted,
liabilities are entered as positive amounts, and a negative cost is a credit or reversal. A source often presents them
differently: costs or creditors in brackets, which is only presentation. So each figure is kept exactly as written
and a separate value is recorded:
- The staged file declares, per class of line, how the source writes an amount of that kind:
cost_sign(cost of sales, admin expenses, depreciation, amortisation, interest paid, exceptional costs, tax),outflow_sign(scheduled principal, capex) andliability_sign(every liability line)."positive": written as a positive number, so recorded as written, and a negative is a credit or reversal."negative": written in brackets or with a minus sign, so recorded with its sign reversed, and a positive is a credit or reversal. A declaration is required wherever a line of its class is transcribed; it is never inferred, and if the image does not make it plain the analyst is asked. - Income, assets and equity lines are recorded as written. Subtotals and ratios are results with a sign of their own
(a loss is
(120)) and are recorded as written. - The read-back shows both values, the interpretation of each line ("as written" or "sign reversed: ...") and each convention in words, and the digest covers the declarations, so changing one is a new confirmation. It lists every figure that will be recorded as negative so a genuine credit or deficit is seen, not assumed, and warns when every line of a class contradicts its declaration.
- The cross-foot uses the recorded values, so it checks what the framework will actually be given. If a mismatch
would disappear were a class read with the opposite sign, it is reported as a doubt about the declaration
(
matches if costs were read with the opposite sign) and cannot be acknowledged: it blocks until the declaration or the figures are corrected. For example, revenue1,200, cost of sales(700)and a stated gross profit of500mismatch if costs are declared positive (-700is recorded, gross profit1,900) and match if they are declared negative (700).
What is compared. For every subtotal the source itself states (gross_profit, operating_profit, ebitda,
profit_before_tax, net_profit, fcf, current_assets, current_liabilities, total_assets, total_liabilities,
total_equity, total_debt, tangible_net_worth), the stated figure is compared with the same subtotal derived from
the recorded raw lines by evaluate_financial_model(), the framework's own formulas. Which lines feed a subtotal, and
with which sign, is discovered from that function (a line's weight is the subtotal's value when that line alone is
1), so the mapping is not written down a second time and cannot drift from the formulas. A test confirms the weights
reproduce the framework's subtotals exactly. In addition, when balance sheet lines are present, total assets less total
liabilities less total equity must come to zero (the balance_sheet_balances check).
Rounding. A presented statement is rounded, so its parts rarely add up exactly. The tolerance is the rounding the
figures as written allow: half a unit of the last written digit of the stated subtotal plus half a unit of the last
written digit of each line that feeds it, weighted by its sign. Lines shown to one decimal and a total shown to none:
100.4 + 200.4 = 300.8 against a stated 301, with two zero lines written as 0, tolerates 0.5 x (0.1 + 0.1 + 1 + 1 + 1) = 1.6. The same amounts written to two decimals tolerate only 0.025. Digits count as written, which is why
the transcription keeps trailing zeros.
When no check is made. A check needs every feeding line to have been transcribed; an explicit 0 counts, an
omitted line is unknown, not zero (the framework otherwise reads an omitted line as 0, which is the wrong default for
a check). A check that cannot be made is reported as NOT ASSESSED with the missing lines, never as a pass. Ratios are
never cross-footed: the rounding of their inputs cannot be bounded, so any tolerance would be invented. If the image
states no subtotal and no balance sheet, the read-back says there is nothing to compare.
A discrepancy. It is shown with the stated figure, the sum of the lines, the difference and the tolerance, and the commit is refused until it is resolved. Resolving means correcting the transcription (or the sign declaration) where the image shows it is wrong, or, for a difference no sign reading explains, recording the analyst's reason in their words as an acknowledgement for that period and check (a source can define a subtotal differently, for example an equity line the raw schema has no field for). An acknowledgement is part of what the analyst confirms. Nothing is ever amended on its own.
By mode. In framework-computed mode the stated subtotals are used only for the cross-foot; every recorded
subtotal and ratio is recomputed from the lines. In analyst-supplied mode the stated subtotals and ratios are recorded
as supplied, subject to the percent-type ratio convention. Any raw
lines go to analyst_supplied_financials, and the cross-foot still compares the stated subtotals with those lines when both are
present. Stated differences between an institution's subtotal and the framework's definition are exactly what an
acknowledgement is for in either mode.
One basis per deal. financials_source is a whole-deal flag, and a commit never changes it or mixes the two
modes in one deal. Before the image is copied or anything is written, an existing financials_source that differs
from the staged mode refuses the commit with one message. A state that records financial figures but no
financials_source (an older or hand-edited file) has an unknown basis and is refused the same way; it is not assumed
to be either mode. A deal with no figures yet, or one already in the same mode (a second screenshot for another
period), is accepted.
Checked before anything is saved. A refused commit leaves no copied image, manifest entry or state change, so everything about the deal that can be known in advance is checked first, with state_manager's own logic rather than a second copy of it: the state is readable and each key this mode reads and rewrites has the right shape (in framework-computed mode that includes spreading_check's keys, such as stress_assumptions); it is not recorded as a newer schema version than this checkout supports, which write_state() would refuse (a version that cannot be compared is refused too); financials_transcriptions is a list; sources/manifest.json, if present, is a readable list; and in framework-computed mode the computation itself, run without writing (spreading_check.plan_fields(), the same merge, formulas and downside case compute() uses), succeeds against what the deal already holds. What no preflight can know is a failure at write time: a full disk, a lock that times out, or another session changing the state in between.
One state update. The figures, the provenance record and the completed spread step are written together in a single state update, in both modes: in framework-computed mode the figures are planned with spreading_check.plan_fields() (the same merge, formulas and downside case compute() uses) and written with the record, never by a separate earlier write. The deal is looked at once more immediately before that update, and planned from that fresh read; if it can no longer take the transcription (another basis, a newer schema) the commit is refused. The image and its manifest entry, however, are saved before the state update, and the two cannot be committed atomically: if the update fails, or the deal changed in between, the verified image and its manifest entry remain with no figures, record or step recorded. A failed update (an OSError such as a lock timeout, or a state_manager error) is reported as one error line that names the saved file, says its sources/manifest.json entry remains and is not removed automatically, says what is known about state.json (compared with its bytes before the update: checked and unchanged, changed during the failed update and may already hold this transcription when an error came after the atomic replacement, or could not be checked), and tells the operator to inspect before retrying; the original exception is kept as its cause. The other I/O steps of a commit are reported the same way and never as a traceback: a failure copying the image for verification or creating the scratch folder (nothing was saved), a failure inside save_source() (the line lists the new files left in sources/, such as a copied image or a manifest.json.tmp, and whether the manifest changed, found by comparing the folder before and after; no figures were recorded and state.json was not touched), a saved copy that cannot be read back (the image and its manifest entry exist), and a state that cannot be re-read after the image was saved. Nothing is deleted or retried automatically. state_manager serialises writes but not a read-plan-write sequence, so another session changing the same keys in the instant between that last look and the write is not detected; the ordinary spreading_check path has the same limit.
The image. The read-back shows the SHA-256 fingerprint of the image file and the digest covers it, so replacing the file after the read-back makes the confirmation stale. At commit the file is copied aside and the copy checked against the confirmed fingerprint before it becomes the saved source, and the saved copy is checked again; the state record keeps the fingerprint and never the image.
Limits. The check finds transcription slips that break a subtotal or the balance sheet. It cannot find an error
in a figure no subtotal depends on, two offsetting errors, a figure misread the same way in a line and in its total,
or a sign convention declared wrongly where the source states no subtotal to test it against (the notices and the
analyst's reading of the read-back are then all that stand between the declaration and the record). A source that
mixes conventions within one class of line cannot be expressed and has to be corrected with the analyst. It reads
commas as thousands separators and a point as the decimal mark, refuses anything else (1,5), and cannot tell 1,234
in a European statement from one thousand two hundred thirty-four; the unit and the read-back exist for the analyst to
catch exactly that.
From the recorded structure alone (no model), policy_state holds:
-
Conditions precedent (CPs), things that must happen before drawdown, each with a stable
cp_id.KYC-AMLandFACILITY-EXECUTIONare always required. A charge that is not exactly"Perfected"addsSEC-PERFECT-<asset>; one that does not rank exactly"First"addsSEC-PRIORITY-<asset>; each guarantee addsGUARANTEE-<provider>. -
Conditions subsequent (CSs), ongoing obligations after drawdown, each with a
cs_id:MI-REPORTINGalways,CS-COVENANT-COMPLIANCEwhen there are covenants,CS-SEC-REPERFECT-<asset>for each charge, andCS-GUARANTEE-<provider>for each guarantee. - Security gaps: an uncharged asset, an unperfected charge, or a subordinate ranking.
- Covenant results, downside breaches and forward covenant results as above.
A draft must carry every required CP and CS, every downside breach, and a source for its narrative, state only
figures that match the computed ones, and cover the risk taxonomy; policy_checks.py checks all of that and the
reasons are listed in Troubleshooting. A passing check shows the draft is
consistent with the computed facts and complete against the deal's own structure. It does not show the narrative is
sound; that is the Risk Reviewer's and a person's job.
The sections from here on are the module-level reference, moved from CLAUDE.md (ledger).
scripts/policy_engine.py — no anthropic dependency. evaluate_deal_policy(state_dict)
is the deterministic governance core: covenant PASS/FAIL/UNRESOLVABLE evaluation against
covenants, security perfection/ranking gap detection against security_package, Condition
Precedent (cp_id) and Condition Subsequent (cs_id) generation from the deal's own structure
(KYC/AML and facility-execution CPs always required; security-mapping/perfection/priority CPs
and guarantee CPs only when the underlying gap/guarantee actually exists), and downside covenant
breach detection (a covenant that PASSes in the base case but FAILs, or becomes UNRESOLVABLE, under stress).
Returns policy_state: {"required_conditions_precedent", "required_conditions_subsequent", "covenant_results", "security_gaps", "downside_covenant_breaches", "forward_covenant_results"}. A ratio with a zero or negative
denominator is N/A, and its covenant is UNRESOLVABLE (issue #169). spreading_builder returns None for any
ratio whose denominator (EBITDA, total equity, interest paid, debt service, current liabilities, revenue, cost of
sales) is not positive -- before this, negative EBITDA or equity gave a finite negative leverage/gearing that sat
below every maximum threshold, so a loss-making borrower PASSED "leverage <= 3.5x". Only the denominator is tested
(a negative numerator over a positive denominator, e.g. DSCR below zero, is a real figure and a minimum-DSCR
covenant correctly FAILs on it). A covenant on an N/A ratio is UNRESOLVABLE for minimum and maximum alike --
never PASS, never a false FAIL -- and every covenant_results entry now has a reason (None when resolved; for
an N/A ratio one sentence naming the metric and denominator, e.g. "gross leverage not meaningful: EBITDA is
negative" / "gearing not defined: total equity is zero"; spreading_builder.describe_undefined_ratio(), which
only speaks about a RECORDED denominator: a subtotal that is absent or not a number, or an analyst-supplied
deal's missing raw block, gives the generic "has no computed value for this period", never "is zero"). Defence
in depth: if the period's recorded denominator is zero or negative, the covenant is UNRESOLVABLE even when a
number is stored next to it (analyst-supplied ratios are recorded as given, and a state checkpointed before this
fix may hold a negative leverage); the stored value is ignored and the reason says so. What it cannot catch: a
stored ratio whose denominator is not recorded in financials (e.g. an analyst-supplied DSCR, which has no raw
block to check against), and a state checkpointed before the fix whose stored negative ratio still reaches the
grounding figures (re-run /spread to refresh it; only the covenant status is protected). The
reason reaches the Maker in covenant_results and the code-enforced rejection text (UNRESOLVABLE has always been
a code-enforced reject reason). A covenant that PASSes in the base case but is FAIL or UNRESOLVABLE in a downside
year is a downside_covenant_breaches entry (new keys downside_status and reason), so a stress that wipes out
EBITDA is disclosed, not silently dropped (the code-enforced rejection text for one reads "cannot be tested in
FY+1 under stress (reason)", not "breaches threshold"). The exported workbook's ratio cells use the same rule
(IF(denominator>0, ..., "N/A"), not just IFERROR; the working capital cycle row wraps its sum in IFERROR
so an "N/A" day row gives "N/A", not #VALUE!), so it agrees with state.json cell for cell. The margin rows use the same guard but have no state.json
counterpart, and the collateral cover cells use the same positive-denominator guard as the ratio cells; neither is a covenant metric. Forward years
(issue #176): a covenant applies to every forward base-case year (FY+1..FY+3) that has a recorded,
non-empty ratio set; a year with nothing recorded is not evaluated, and state.json carries no covenant tenor, so
a covenant that really ends earlier is still reported for later projected years. forward_covenant_results is
the complete record -- one entry per year and covenant, PASS included -- each being _evaluate_covenant()'s
result (same #169 rules, reason for UNRESOLVABLE) plus year and a stable forward_id
(FORWARD-FY-1-GROSS-LEVERAGE, numeric suffix for two covenants on one metric). It is a separate list rather
than a year dimension on covenant_results because every consumer of that list (the reject reasons, the
orchestrator context, the eval contexts) assumes one FY-Current entry per covenant, and policy_checks.py turns
any FAIL/UNRESOLVABLE in it into a rejection. Disclosure only: no code-enforced reason reads
forward_covenant_results, so a forward-year FAIL or UNRESOLVABLE never rejects a deal by itself, and it cannot
go unrecorded. orchestrator.py shows the model only the non-PASS entries, as neutral data (no instruction; the
wording for the Maker and Reviewer is post-baseline prompt work); the full list is persisted with policy_state
in state.json. It never repeats downside_covenant_breaches (which still reports only base PASS -> stressed
non-PASS): a year already failing in the base case appears only in the forward list. This is
what both
orchestrator.py (headless) and scripts/policy_check.py (slash-command interface, below) call
to get the exact same code-enforced structural facts regardless of which interface a deal runs
through -- agents/risk_reviewer_agent.md's own preamble treats policy_state's presence in a
prompt as the signal that this deterministic layer is active for that run.
scripts/policy_checks.py — no anthropic dependency. parse_underwriter_output(draft_text)
extracts the Underwriter's trailing structured JSON block (cp_ids_included,
risk_categories_covered, reported_figures, sources, financials_source_disclosed,
credit_policy_considered, etc. -- see agents/underwriter_agent.md's Structured Output
guideline); ground_truth_figures(financials, ratios, collateral, downside_case, collateral_analysis) flattens the
deal's actual computed figures into one lookup dict. FY-Current retains plain metric keys (for example,
ebitda and dscr); every other base-case period uses {metric}_{period} (for example,
ebitda_FY-1 and dscr_FY+1). A stored, current collateral_analysis (stored_analysis_is_current(): same calculator version, input
digest intact, and recalculating its stored inputs reproduces its stored results) adds collateral_<asset_id>_<metric> per asset and collateral_max_lgd_pct and
collateral_avg_lgd_pct, copied from the calculator's results; a stale or N/A result is omitted, never
defaulted. A per-asset coverage_pct and lgd_pct are fractions (0.75 = 75%), unlike the aggregate
collateral_cover_pct, which is on a 0 to 100 scale. The asset ids max and avg are reserved (the calculator
refuses them) because collateral_max_lgd_pct and collateral_avg_lgd_pct would otherwise collide with an
asset's lgd_pct. Downside keys retain their distinct {metric}_{period}_downside suffix; check_draft_compliance(draft_text, policy_state, ground_truth_figures_dict, financials_source=None, credit_policy_present=None) is
the single source of truth for "why would this draft be code-enforced-REJECTED" -- covenant/
security/CP/CS completeness, risk-taxonomy coverage (REQUIRED_RISK_TAXONOMY), narrative-vs-
ground-truth figure mismatches, and the self-declared-field presence checks (analyst-supplied
disclosure, credit-policy consideration). Returns a plain list of human-readable reason strings,
empty if compliant -- callers (orchestrator.py's _apply_deterministic_policy_checks(),
.claude/commands/review.md's prose) decide what a non-empty list means for their own verdict.
scripts/policy_check.py — no anthropic dependency, same "importable or standalone" duality
as deal_export.py. compute(company, proposal, draft_path=None) wraps policy_engine.py/
policy_checks.py into one call: without draft_path, returns just policy_state (e.g. for
/assemble building its own drafting context, before a draft exists); with draft_path, also
runs the full check_draft_compliance() audit against that file's trailing structured JSON
block. This is what gives the slash-command interface (/assemble's and /review's own Bash
steps) the identical code-enforced governance orchestrator.py's headless pipeline already has,
without either interface reimplementing the logic in prose:
python scripts/policy_check.py --company "Acme Corp" --proposal "Fleet Loan" --draft "deals/Acme Corp/Fleet Loan_draft.md"
scripts/spreading_check.py — no anthropic dependency, same "importable or standalone"
duality as policy_check.py/deal_export.py. compute(company, proposal, multi_period_financials=None, stress_assumptions=None, update_financials_source=True) wraps
spreading_builder.py's evaluate_financial_model()/evaluate_downside_case(): merges
freshly-given raw periods into whatever this deal's state.json already has on file (never a
blind replace -- /spread and /project each supply only the periods they're responsible for,
in separate calls), recomputes financials/ratios for the affected periods, and -- when
stress assumptions (freshly given or already on file) and at least one forward period exist --
derives downside_case too. The merge is two levels deep for both inputs: a period's raw
figures are merged field-by-field into whatever that period already had on file (a correction to
just revenue doesn't discard the period's other already-recorded fields), and fresh
stress_assumptions are merged key-by-key the same way (re-confirming one shock doesn't drop
another already-confirmed one left unmentioned) -- caught in post-merge review of the PR that
introduced this script, where the first version replaced each wholesale instead. This is what
gives the slash-command interface (/spread's and
/project's own Bash steps) the identical code-enforced formula evaluation orchestrator.py's
headless pipeline already has, instead of Claude recalculating the same subtotals/ratios by
hand in prose (see issue #98). Deliberately not used by /spread's analyst-supplied mode, which
skips independent recomputation entirely (see issue #55):
python scripts/spreading_check.py --company "Acme Corp" --proposal "Fleet Loan" --financials "deals/Acme Corp/Fleet Loan_financials_input.json"
Which periods are evaluated (issue #597). A call evaluates the periods it touches plus the
period that follows each of them, when that successor is on file and framework-computed, with the
prior-working-capital map built from the merged store — so a forward-only call reads the prior
period already on file (its fcf_after_working_capital and cash_flow_dscr are recorded from the
whole deal, not as N/A), and a correction to one period recomputes the next. No formula changes: a
forward year whose previous period is analyst-supplied stays N/A with a reason, never a figure
blended from the other store (on a deal whose financials_source is analyst-supplied, a leftover framework
historical period is never read as the prior, in the base case, the downside case and the workbook alike: the
exported FCF after working capital for the first forward year reads N/A), a null period is "not recorded" and
is never evaluated as a successor or shocked as a downside year (and a year that is later recorded as null
drops the base and downside figures calculated for it earlier, so they cannot stay live as current), the five working-capital lines it reads go through
the same raw-input contract as incoming figures (a boolean, a string or an oversized number is one error: line,
while an unrelated bad line in a comparator-only period does not block the update), the stress run reads only the
shocked periods and the period before each, and older periods are not recomputed on every call. See the note on
F-064 in the formula register.
update_financials_source (CLI: --no-update-financials-source to disable) gates whether a
fresh computation stamps financials_source: "framework-computed" -- financials_source is a
whole-deal flag /spread owns the decision for, not per-period, so /project's own call always
passes this flag: without it, /project supplying forward-year figures on a deal whose
historicals were recorded via /spread's analyst-supplied mode would silently flip the deal's
flag back to "framework-computed", dropping the Guideline 9 caveat requirement for figures
that were never actually independently recomputed.
The collateral entries F-049–F-057 and F-066 define origination proxies, not a later-date exposure or a complete lease-accounting net-investment calculation. The residual value is a risk-team input and sits inside the financed amount on the book covered by the recorded maintainer decision. It is split out of the financed share and counted once: non-RV funded exposure plus RV exposure equals total exposure. The non-RV component is derived on the explicit assumption that the rental schedule amortises the non-RV slice without finance charges or profit margin; an analyst should challenge that assumption if the underlying contracts do not support it.
Net exposure deducts only non-asset mitigants explicitly declared available on default and not already netted in the financing. It is floored at zero, with excess disclosed separately. Gross uncovered risk (F-055) remains before mitigants; net uncovered risk (F-066) is the distinct post-mitigant shortfall, with eligible mitigants allocated pro rata to each asset's total exposure (F-052, F-066). Average LGD (F-057) is weighted by total exposure, the gross exposure-at-default proxy at origination. Max and average LGD are N/A if the asset set is empty, no LGDs are recorded, or any asset's LGD is missing.
These figures exclude accrued interest, arrears and late charges. F-053's costs means enforcement/recovery costs only. Residual realisability, security/title, valuation provenance and cross-collateralisation remain narrative credit judgement, not calculated outputs. Full precision is retained in storage; rounding is for display only. Percent-type collateral ratios F-054 are fractions, while aggregate F-047 remains on its existing 0–100 scale (KD-2).
The calculator is implemented in scripts/collateral_check.py (collateral_check.py --company ... --proposal ... --input-file ...): it validates the complete payload before writing anything, computes the per-asset and deal-level figures, and records them as the collateral_analysis state object — per-asset inputs and results, the separate mitigants list, deal-level results, the input_digest (SHA-256 of the canonical inputs) and calculator_version — together with the backward-compatible collateral projection refreshed from the same results, marking the collateral step complete only on success. Any refusal prints one error: line, exits 1 and writes nothing. The register entries F-049–F-057 and F-066 are the entry-by-entry specification; the worked example is a valuation of 100,000 with a 20% down payment and 40% RV: financed exposure 80,000, split 40,000 non-RV and 40,000 RV, collateral value 60,000, coverage 0.75, gross uncovered risk 20,000.
A deal may carry one explicit residual-realisation scenario: stress_assumptions.rv_realisation_pct, a finite number from 0 to 100 (100 = full realisation; absent means no stressed output). Only the residual part of an asset's collateral value is stressed: the residual part is the lower of the F-053 collateral value and the F-050 RV exposure, and the rest is non-residual. The stressed collateral value is the non-residual part plus (rv_realisation_pct ÷ 100) × the residual part, floored at zero. Stressed variants exist for F-053, F-054, F-055 and F-066 only — collateral value, coverage, gross uncovered risk and net uncovered risk — computed on the unchanged F-051/F-052 exposures. The figures are report-only: the assumption is stored in stress_assumptions as with the other stress keys, and the stressed outputs appear in the calculator's JSON output only; nothing derived is persisted. The worked example at 50% realisation: collateral value 60,000 splits 40,000 residual (the RV exposure) and 20,000 non-residual; the stressed collateral value is 20,000 + 0.5 × 40,000 = 40,000, stressed coverage 0.5, stressed gross uncovered risk 40,000 against the base 20,000, and the same 40,000 for net uncovered risk with no mitigants. An out-of-range or malformed stored assumption is refused with one error: line and nothing written; a sub-1 value means sub-1 percent (0.5 = 0.5%), per the shared stress-assumption warning rule.
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