Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
feat(control): add exact cross-statement tie-outs across BS IS EQ CF and trial balance
davoodmehraban89 committed
Oct 31, 2026 at 08:32 UTC
67a4dc7669446662e74b74c9e5aef603e7aec277
1 file changed
+360
backend/src/aram_backend/cross_statement_reconciliation.py
new
+360
@@ -0,0 +1,360 @@
1
+"""Cross-statement arithmetic and provenance gate for unsigned ARAM candidates.
2
+
3
+Consumes only the typed, nonofficial candidate objects produced by the earlier
4
+read-only engines. Exact matches are necessary, not sufficient, for approval.
5
+"""
6
+from __future__ import annotations
7
+
8
+from dataclasses import asdict, dataclass
9
+from decimal import Decimal
10
+from hashlib import sha256
11
+import json
12
+import re
13
+from typing import Any, Sequence
14
+
15
+from aram_backend.balance_sheet_candidate import BalanceSheetCandidate
16
+from aram_backend.cash_flow_direct_candidate import DirectCashFlowCandidate
17
+from aram_backend.coverage_preview import CoverageError
18
+from aram_backend.equity_changes_candidate import EquityChangesCandidate
19
+from aram_backend.income_statement_candidate import IncomeStatementCandidate
20
+from aram_backend.reconciliation_review import _money, _sum_exact
21
+from aram_backend.trial_balance_diagnostic import TrialBalanceDiagnostic
22
+
23
+EXPECTED_KINDS = {
24
+ "balance_sheet": "UNAPPROVED_BALANCE_SHEET_PRESENTATION_CANDIDATE",
25
+ "income_statement": "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE",
26
+ "equity_changes": "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE",
27
+ "cash_flow": "UNAPPROVED_DIRECT_CASH_FLOW_CANDIDATE",
28
+ "trial_balance": "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC",
29
+}
30
+
31
+
32
+@dataclass(frozen=True)
33
+class CashBalanceNoteSelection:
34
+ statement_section: str
35
+ note_number: str
36
+ subnote_code: str
37
+ evidence_ref: str
38
+
39
+
40
+@dataclass(frozen=True)
41
+class SelectedCashBalanceNote:
42
+ statement_section: str
43
+ note_number: str
44
+ subnote_code: str
45
+ presentation_amount: str
46
+ evidence_ref: str
47
+
48
+
49
+@dataclass(frozen=True)
50
+class CrossStatementReconciliation:
51
+ company_code: str
52
+ fiscal_year: int
53
+ source_sha256: str
54
+ cash_flow_transaction_ledger_sha256: str
55
+ cash_note_selection_sha256: str
56
+ same_source_snapshot: bool
57
+ trial_balance_opening_debit_net_total: str
58
+ trial_balance_movement_difference: str
59
+ trial_balance_closing_debit_net_total: str
60
+ trial_balance_rollforward_difference: str
61
+ balance_sheet_difference: str
62
+ balance_sheet_equity_total: str
63
+ equity_statement_closing_total: str
64
+ balance_sheet_equity_difference: str
65
+ income_statement_net_result: str
66
+ equity_net_profit_loss_movements: str
67
+ net_profit_equity_difference: str
68
+ balance_sheet_cash_total: str
69
+ cash_flow_closing_cash: str
70
+ balance_sheet_cash_difference: str
71
+ income_statement_bridge_valid: bool
72
+ cash_flow_bridge_valid: bool
73
+ equity_rollforward_valid: bool
74
+ trial_balance_arithmetic_valid: bool
75
+ selected_cash_notes: tuple[SelectedCashBalanceNote, ...]
76
+ findings: tuple[str, ...]
77
+ eligible_for_analyst_review: bool
78
+ kind: str = "UNAPPROVED_CROSS_STATEMENT_RECONCILIATION"
79
+ source_ledger_completeness_verified: bool = False
80
+ accounting_policy_authorized: bool = False
81
+ independently_reviewed: bool = False
82
+ trusted_approvals: bool = False
83
+ official_financial_statement: bool = False
84
+ export_authorized: bool = False
85
+ releasable: bool = False
86
+
87
+ def to_dict(self) -> dict[str, Any]:
88
+ return asdict(self)
89
+
90
+
91
+def _hash(value: object, label: str) -> str:
92
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
93
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label)
94
+ return value
95
+
96
+
97
+def _text(value: object, label: str, *, blank_ok: bool = False) -> str:
98
+ if (not isinstance(value, str) or len(value) > 256
99
+ or value != value.strip() or (not value and not blank_ok)
100
+ or any(ord(char) < 32 or ord(char) == 127 for char in value)):
101
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label)
102
+ return value
103
+
104
+
105
+def _validate_candidate(candidate: object, label: str, expected_type: type) -> None:
106
+ if type(candidate) is not expected_type:
107
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label + "_OBJECT")
108
+ if getattr(candidate, "kind", None) != EXPECTED_KINDS[label]:
109
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label + "_KIND")
110
+ forbidden = (
111
+ "official_financial_statement", "independently_reviewed",
112
+ "export_authorized", "releasable", "accounting_policy_authorized",
113
+ "trusted_approvals",
114
+ )
115
+ if any(getattr(candidate, flag, False) for flag in forbidden):
116
+ raise CoverageError("CROSS_STATEMENT_APPROVAL_PROVENANCE_INVALID")
117
+ _hash(candidate.source_sha256, label.upper() + "_SOURCE_HASH")
118
+ _text(candidate.company_code, label.upper() + "_COMPANY")
119
+ if type(candidate.fiscal_year) is not int or candidate.fiscal_year <= 0:
120
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_YEAR")
121
+
122
+
123
+def _income_bridge(income: IncomeStatementCandidate) -> bool:
124
+ revenue = _money(income.revenue_total)
125
+ cost = _money(income.cost_of_revenue_total)
126
+ gross = _money(income.gross_profit)
127
+ operating_expense = _money(income.operating_expense_total)
128
+ operating = _money(income.operating_profit)
129
+ other_income = _money(income.other_income_total)
130
+ other_expense = _money(income.other_expense_total)
131
+ pretax = _money(income.profit_before_tax)
132
+ tax = _money(income.tax_expense_total)
133
+ net = _money(income.net_result)
134
+ return (
135
+ _sum_exact([revenue, -cost, -gross]) == 0
136
+ and _sum_exact([gross, -operating_expense, -operating]) == 0
137
+ and _sum_exact([operating, other_income, -other_expense, -pretax]) == 0
138
+ and _sum_exact([pretax, -tax, -net]) == 0
139
+ )
140
+
141
+
142
+def _cash_flow_bridge(cash: DirectCashFlowCandidate) -> bool:
143
+ operating = _sum_exact([
144
+ _money(cash.operating_inflows), -_money(cash.operating_outflows),
145
+ ])
146
+ investing = _sum_exact([
147
+ _money(cash.investing_inflows), -_money(cash.investing_outflows),
148
+ ])
149
+ financing = _sum_exact([
150
+ _money(cash.financing_inflows), -_money(cash.financing_outflows),
151
+ ])
152
+ net_change = _money(cash.net_change_in_cash)
153
+ rollforward = _sum_exact([
154
+ _money(cash.opening_cash_and_equivalents), net_change,
155
+ -_money(cash.closing_cash_and_equivalents),
156
+ ])
157
+ return (
158
+ operating == _money(cash.operating_net_cash_flow)
159
+ and investing == _money(cash.investing_net_cash_flow)
160
+ and financing == _money(cash.financing_net_cash_flow)
161
+ and _sum_exact([operating, investing, financing, -net_change]) == 0
162
+ and rollforward == _money(cash.rollforward_difference) == 0
163
+ )
164
+
165
+
166
+def _trial_balance_bridge(trial: TrialBalanceDiagnostic) -> bool:
167
+ opening = _money(trial.opening_debit_net_total)
168
+ debit_credit = _money(trial.movement_difference)
169
+ closing = _money(trial.closing_debit_net_total)
170
+ rollforward = _money(trial.opening_to_closing_difference)
171
+ return (
172
+ trial.balanced_for_analyst_review
173
+ and opening == 0 and debit_credit == 0 and closing == 0 and rollforward == 0
174
+ )
175
+
176
+
177
+def reconcile_cross_statements(
178
+ *, balance_sheet: BalanceSheetCandidate,
179
+ income_statement: IncomeStatementCandidate,
180
+ equity_changes: EquityChangesCandidate,
181
+ cash_flow: DirectCashFlowCandidate,
182
+ trial_balance: TrialBalanceDiagnostic,
183
+ cash_balance_notes: Sequence[CashBalanceNoteSelection],
184
+) -> CrossStatementReconciliation:
185
+ """Reconcile BS/IS/EQ/CF/TB candidates without granting financial approval.
186
+
187
+ The caller must explicitly select the BS asset notes that represent cash
188
+ and cash equivalents. This policy is evidence-bearing and untrusted. Exact
189
+ Decimal comparison uses zero tolerance; any scope/hash mismatch or blocked
190
+ upstream candidate prevents analyst eligibility.
191
+ """
192
+ candidates = (
193
+ ("balance_sheet", balance_sheet, BalanceSheetCandidate),
194
+ ("income_statement", income_statement, IncomeStatementCandidate),
195
+ ("equity_changes", equity_changes, EquityChangesCandidate),
196
+ ("cash_flow", cash_flow, DirectCashFlowCandidate),
197
+ ("trial_balance", trial_balance, TrialBalanceDiagnostic),
198
+ )
199
+ for label, candidate, expected_type in candidates:
200
+ _validate_candidate(candidate, label, expected_type)
201
+
202
+ if not isinstance(cash_balance_notes, (list, tuple)) or not 0 < len(cash_balance_notes) <= 5_000:
203
+ raise CoverageError("INVALID_CASH_BALANCE_NOTE_SELECTION")
204
+
205
+ selected: dict[tuple[str, str, str], CashBalanceNoteSelection] = {}
206
+ for item in cash_balance_notes:
207
+ if not isinstance(item, CashBalanceNoteSelection):
208
+ raise CoverageError("INVALID_CASH_BALANCE_NOTE_SELECTION")
209
+ key = (
210
+ _text(item.statement_section, "CASH_NOTE_SECTION"),
211
+ _text(item.note_number, "CASH_NOTE_NUMBER"),
212
+ _text(item.subnote_code, "CASH_NOTE_SUBNOTE", blank_ok=True),
213
+ )
214
+ _text(item.evidence_ref, "CASH_NOTE_EVIDENCE")
215
+ if key in selected:
216
+ raise CoverageError("DUPLICATE_CASH_BALANCE_NOTE_SELECTION")
217
+ selected[key] = item
218
+ selection_hash = sha256(json.dumps(
219
+ [asdict(selected[key]) for key in sorted(selected)],
220
+ ensure_ascii=True, sort_keys=True, separators=(",", ":"),
221
+ ).encode("utf-8")).hexdigest()
222
+
223
+ findings: list[str] = []
224
+ base = balance_sheet
225
+ if any(
226
+ candidate.company_code != base.company_code
227
+ or candidate.fiscal_year != base.fiscal_year
228
+ for _, candidate, _ in candidates
229
+ ):
230
+ findings.append("CROSS_STATEMENT_COMPANY_YEAR_MISMATCH")
231
+
232
+ hashes = {candidate.source_sha256 for _, candidate, _ in candidates}
233
+ same_snapshot = len(hashes) == 1
234
+ if not same_snapshot:
235
+ findings.append("CROSS_STATEMENT_SOURCE_SNAPSHOT_MISMATCH")
236
+ source_hash = base.source_sha256
237
+
238
+ for label, candidate, _ in candidates:
239
+ eligible = (
240
+ getattr(candidate, "eligible_for_analyst_review", None)
241
+ if label != "trial_balance"
242
+ else candidate.balanced_for_analyst_review
243
+ )
244
+ if not eligible:
245
+ findings.append(label.upper() + "_CANDIDATE_BLOCKED")
246
+
247
+ bs_computed_difference = _sum_exact([
248
+ _money(balance_sheet.assets_total),
249
+ -_money(balance_sheet.liabilities_total),
250
+ -_money(balance_sheet.equity_total),
251
+ ])
252
+ bs_reported_difference = _money(balance_sheet.balance_difference)
253
+ if (bs_computed_difference != bs_reported_difference
254
+ or bs_reported_difference != 0
255
+ or not balance_sheet.arithmetically_balanced):
256
+ findings.append("BALANCE_SHEET_EQUATION_INVALID")
257
+
258
+ equity_difference = _sum_exact([
259
+ _money(balance_sheet.equity_total),
260
+ -_money(equity_changes.closing_equity_total),
261
+ ])
262
+ if equity_difference != 0:
263
+ findings.append("BALANCE_SHEET_EQUITY_CLOSING_MISMATCH")
264
+
265
+ profit_difference = _sum_exact([
266
+ _money(income_statement.net_result),
267
+ -_money(equity_changes.net_profit_loss_movements),
268
+ ])
269
+ if profit_difference != 0:
270
+ findings.append("INCOME_RESULT_EQUITY_MOVEMENT_MISMATCH")
271
+
272
+ income_valid = _income_bridge(income_statement)
273
+ if not income_valid:
274
+ findings.append("INCOME_STATEMENT_BRIDGE_INVALID")
275
+
276
+ equity_rollforward = _sum_exact([
277
+ _money(equity_changes.opening_equity_total),
278
+ _money(equity_changes.total_movement),
279
+ -_money(equity_changes.closing_equity_total),
280
+ ])
281
+ equity_rollforward_valid = (
282
+ equity_rollforward == 0
283
+ and _money(equity_changes.rollforward_difference) == 0
284
+ )
285
+ if not equity_rollforward_valid:
286
+ findings.append("EQUITY_STATEMENT_ROLLFORWARD_INVALID")
287
+
288
+ bs_lines = {
289
+ (line.statement_section, line.note_number, line.subnote_code): line
290
+ for line in balance_sheet.lines
291
+ }
292
+ selected_lines: list[SelectedCashBalanceNote] = []
293
+ cash_amounts: list[Decimal] = []
294
+ for key in sorted(selected):
295
+ line = bs_lines.get(key)
296
+ if line is None:
297
+ findings.append("CASH_BALANCE_NOTE_NOT_FOUND_IN_BALANCE_SHEET")
298
+ continue
299
+ if line.category != "ASSETS":
300
+ findings.append("CASH_BALANCE_NOTE_NOT_ASSET")
301
+ continue
302
+ amount = _money(line.presentation_amount)
303
+ cash_amounts.append(amount)
304
+ selected_lines.append(SelectedCashBalanceNote(
305
+ statement_section=key[0], note_number=key[1],
306
+ subnote_code=key[2], presentation_amount=str(amount),
307
+ evidence_ref=selected[key].evidence_ref,
308
+ ))
309
+ if len(selected_lines) != len(selected):
310
+ findings.append("CASH_BALANCE_NOTE_SELECTION_INCOMPLETE")
311
+ bs_cash_total = _sum_exact(cash_amounts)
312
+ cash_difference = _sum_exact([
313
+ bs_cash_total, -_money(cash_flow.closing_cash_and_equivalents),
314
+ ])
315
+ if cash_difference != 0:
316
+ findings.append("BALANCE_SHEET_CASH_FLOW_CLOSING_MISMATCH")
317
+
318
+ cash_valid = _cash_flow_bridge(cash_flow)
319
+ if not cash_valid:
320
+ findings.append("CASH_FLOW_BRIDGE_INVALID")
321
+
322
+ trial_valid = _trial_balance_bridge(trial_balance)
323
+ if not trial_valid:
324
+ findings.append("TRIAL_BALANCE_ARITHMETIC_INVALID")
325
+
326
+ tb_opening = _money(trial_balance.opening_debit_net_total)
327
+ tb_movement = _money(trial_balance.movement_difference)
328
+ tb_closing = _money(trial_balance.closing_debit_net_total)
329
+ tb_rollforward = _money(trial_balance.opening_to_closing_difference)
330
+
331
+ return CrossStatementReconciliation(
332
+ company_code=base.company_code, fiscal_year=base.fiscal_year,
333
+ source_sha256=source_hash,
334
+ cash_flow_transaction_ledger_sha256=_hash(
335
+ cash_flow.transaction_ledger_sha256, "CASH_FLOW_TRANSACTION_HASH",
336
+ ),
337
+ cash_note_selection_sha256=selection_hash,
338
+ same_source_snapshot=same_snapshot,
339
+ trial_balance_opening_debit_net_total=str(tb_opening),
340
+ trial_balance_movement_difference=str(tb_movement),
341
+ trial_balance_closing_debit_net_total=str(tb_closing),
342
+ trial_balance_rollforward_difference=str(tb_rollforward),
343
+ balance_sheet_difference=str(bs_reported_difference),
344
+ balance_sheet_equity_total=str(_money(balance_sheet.equity_total)),
345
+ equity_statement_closing_total=str(_money(equity_changes.closing_equity_total)),
346
+ balance_sheet_equity_difference=str(equity_difference),
347
+ income_statement_net_result=str(_money(income_statement.net_result)),
348
+ equity_net_profit_loss_movements=str(_money(equity_changes.net_profit_loss_movements)),
349
+ net_profit_equity_difference=str(profit_difference),
350
+ balance_sheet_cash_total=str(bs_cash_total),
351
+ cash_flow_closing_cash=str(_money(cash_flow.closing_cash_and_equivalents)),
352
+ balance_sheet_cash_difference=str(cash_difference),
353
+ income_statement_bridge_valid=income_valid,
354
+ cash_flow_bridge_valid=cash_valid,
355
+ equity_rollforward_valid=equity_rollforward_valid,
356
+ trial_balance_arithmetic_valid=trial_valid,
357
+ selected_cash_notes=tuple(selected_lines),
358
+ findings=tuple(sorted(set(findings))),
359
+ eligible_for_analyst_review=not findings,
360
+ )