codex/aram-windows-five-statement-pilot-20261031
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 919 lines 39.3 KB
Raw
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 (
16 CATEGORIES as BALANCE_SHEET_CATEGORIES,
17 BalanceSheetCandidate, CandidateBalanceSheetLine,
18 )
19 from aram_backend.cash_flow_direct_candidate import (
20 CashAccountReconciliation, CashFlowLine, DirectCashFlowCandidate,
21 )
22 from aram_backend.coverage_preview import CoverageError
23 from aram_backend.equity_changes_candidate import (
24 EQUITY_COMPONENTS, MOVEMENT_CATEGORIES, EquityAccountMovement,
25 EquityChangesCandidate, EquityComponentTotal, EquityNoteMovement,
26 )
27 from aram_backend.income_statement_candidate import (
28 CATEGORIES as INCOME_STATEMENT_CATEGORIES,
29 CandidateIncomeStatementLine, IncomeStatementCandidate,
30 )
31 from aram_backend.reconciliation_review import _money, _sum_exact
32 from aram_backend.trial_balance_diagnostic import (
33 TrialBalanceAccount, TrialBalanceDiagnostic,
34 )
35
36 EXPECTED_KINDS = {
37 "balance_sheet": "UNAPPROVED_BALANCE_SHEET_PRESENTATION_CANDIDATE",
38 "income_statement": "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE",
39 "equity_changes": "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE",
40 "cash_flow": "UNAPPROVED_DIRECT_CASH_FLOW_CANDIDATE",
41 "trial_balance": "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC",
42 }
43
44
45 @dataclass(frozen=True)
46 class CashBalanceNoteSelection:
47 statement_section: str
48 note_number: str
49 subnote_code: str
50 evidence_ref: str
51
52
53 @dataclass(frozen=True)
54 class SelectedCashBalanceNote:
55 statement_section: str
56 note_number: str
57 subnote_code: str
58 presentation_amount: str
59 evidence_ref: str
60
61
62 @dataclass(frozen=True)
63 class CrossStatementReconciliation:
64 company_code: str
65 fiscal_year: int
66 source_sha256: str
67 cash_flow_transaction_ledger_sha256: str
68 cash_note_selection_sha256: str
69 same_source_snapshot: bool
70 trial_balance_opening_debit_net_total: str
71 trial_balance_movement_difference: str
72 trial_balance_closing_debit_net_total: str
73 trial_balance_rollforward_difference: str
74 balance_sheet_difference: str
75 balance_sheet_equity_total: str
76 equity_statement_closing_total: str
77 balance_sheet_equity_difference: str
78 income_statement_net_result: str
79 equity_net_profit_loss_movements: str
80 net_profit_equity_difference: str
81 balance_sheet_cash_total: str
82 cash_flow_closing_cash: str
83 balance_sheet_cash_difference: str
84 income_statement_bridge_valid: bool
85 cash_flow_bridge_valid: bool
86 equity_rollforward_valid: bool
87 trial_balance_arithmetic_valid: bool
88 cash_accounts_match_trial_balance: bool
89 cash_account_totals_valid: bool
90 selected_cash_notes: tuple[SelectedCashBalanceNote, ...]
91 findings: tuple[str, ...]
92 eligible_for_analyst_review: bool
93 kind: str = "UNAPPROVED_CROSS_STATEMENT_RECONCILIATION"
94 source_ledger_completeness_verified: bool = False
95 accounting_policy_authorized: bool = False
96 independently_reviewed: bool = False
97 trusted_approvals: bool = False
98 official_financial_statement: bool = False
99 export_authorized: bool = False
100 releasable: bool = False
101
102 def to_dict(self) -> dict[str, Any]:
103 return asdict(self)
104
105
106 def _hash(value: object, label: str) -> str:
107 if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
108 raise CoverageError("INVALID_CROSS_STATEMENT_" + label)
109 return value
110
111
112 def _text(value: object, label: str, *, blank_ok: bool = False) -> str:
113 if (not isinstance(value, str) or len(value) > 256
114 or value != value.strip() or (not value and not blank_ok)
115 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
116 raise CoverageError("INVALID_CROSS_STATEMENT_" + label)
117 return value
118
119
120 def _validate_candidate(candidate: object, label: str, expected_type: type) -> None:
121 if type(candidate) is not expected_type:
122 raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_OBJECT")
123 if getattr(candidate, "kind", None) != EXPECTED_KINDS[label]:
124 raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_KIND")
125 forbidden = (
126 "official_financial_statement", "independently_reviewed",
127 "export_authorized", "releasable", "accounting_policy_authorized",
128 "trusted_approvals", "source_ledger_completeness_verified",
129 "cash_account_scope_owner_approved",
130 "transaction_ledger_completeness_verified",
131 "accounting_policies_verified",
132 )
133 for flag in forbidden:
134 if hasattr(candidate, flag):
135 value = getattr(candidate, flag)
136 if type(value) is not bool or value:
137 raise CoverageError("CROSS_STATEMENT_APPROVAL_PROVENANCE_INVALID")
138 eligible_field = (
139 "balanced_for_analyst_review" if label == "trial_balance"
140 else "eligible_for_analyst_review"
141 )
142 eligible = getattr(candidate, eligible_field, None)
143 if type(eligible) is not bool:
144 raise CoverageError("CROSS_STATEMENT_CANDIDATE_ELIGIBILITY_INVALID")
145 findings = getattr(candidate, "findings", None)
146 if (not isinstance(findings, tuple)
147 or any(not isinstance(item, str) or not item for item in findings)
148 or (eligible and findings)):
149 raise CoverageError("CROSS_STATEMENT_CANDIDATE_FINDINGS_INVALID")
150 _hash(candidate.source_sha256, label.upper() + "_SOURCE_HASH")
151 for hash_field in (
152 "note_references_sha256", "presentation_policies_sha256",
153 "transaction_ledger_sha256", "classification_policies_sha256",
154 ):
155 if hasattr(candidate, hash_field):
156 _hash(getattr(candidate, hash_field), label.upper() + "_" + hash_field.upper())
157 _text(candidate.company_code, label.upper() + "_COMPANY")
158 if type(candidate.fiscal_year) is not int or candidate.fiscal_year <= 0:
159 raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_YEAR")
160
161
162 def _balance_sheet_detail_bridge(balance: BalanceSheetCandidate) -> bool:
163 if not isinstance(balance.lines, tuple) or not balance.lines:
164 return False
165 buckets: dict[str, list[Decimal]] = {
166 category: [] for category in BALANCE_SHEET_CATEGORIES
167 }
168 seen: set[tuple[str, str, str]] = set()
169 for line in balance.lines:
170 if not isinstance(line, CandidateBalanceSheetLine):
171 return False
172 key = (
173 _text(line.statement_section, "BS_DETAIL_SECTION"),
174 _text(line.note_number, "BS_DETAIL_NOTE"),
175 _text(line.subnote_code, "BS_DETAIL_SUBNOTE", blank_ok=True),
176 )
177 if (key in seen or not isinstance(line.category, str)
178 or line.category not in BALANCE_SHEET_CATEGORIES):
179 return False
180 seen.add(key)
181 if type(line.sign_multiplier) is not int or line.sign_multiplier not in (-1, 1):
182 return False
183 source = _money(line.source_closing_exposure)
184 amount = _money(line.presentation_amount)
185 if amount != source * line.sign_multiplier or amount < 0:
186 return False
187 _text(line.line_label, "BS_DETAIL_LABEL")
188 _text(line.note_reference_evidence, "BS_DETAIL_REFERENCE")
189 _text(line.policy_evidence_ref, "BS_DETAIL_POLICY")
190 buckets[line.category].append(amount)
191 totals = {key: _sum_exact(values) for key, values in buckets.items()}
192 return (
193 all(buckets[key] for key in BALANCE_SHEET_CATEGORIES)
194 and totals["ASSETS"] == _money(balance.assets_total)
195 and totals["LIABILITIES"] == _money(balance.liabilities_total)
196 and totals["EQUITY"] == _money(balance.equity_total)
197 and _sum_exact([
198 totals["ASSETS"], -totals["LIABILITIES"], -totals["EQUITY"],
199 ]) == _money(balance.balance_difference) == 0
200 and balance.arithmetically_balanced is True
201 )
202
203
204 def _income_detail_bridge(income: IncomeStatementCandidate) -> bool:
205 if not isinstance(income.lines, tuple) or not income.lines:
206 return False
207 buckets: dict[str, list[Decimal]] = {
208 category: [] for category in INCOME_STATEMENT_CATEGORIES
209 }
210 seen: set[tuple[str, str, str]] = set()
211 for line in income.lines:
212 if not isinstance(line, CandidateIncomeStatementLine):
213 return False
214 key = (
215 _text(line.statement_section, "IS_DETAIL_SECTION"),
216 _text(line.note_number, "IS_DETAIL_NOTE"),
217 _text(line.subnote_code, "IS_DETAIL_SUBNOTE", blank_ok=True),
218 )
219 if (key in seen or not isinstance(line.category, str)
220 or line.category not in INCOME_STATEMENT_CATEGORIES):
221 return False
222 seen.add(key)
223 if type(line.sign_multiplier) is not int or line.sign_multiplier not in (-1, 1):
224 return False
225 source = _money(line.source_closing_exposure)
226 amount = _money(line.presentation_amount)
227 if amount != source * line.sign_multiplier or amount < 0:
228 return False
229 _text(line.line_label, "IS_DETAIL_LABEL")
230 _text(line.note_reference_evidence, "IS_DETAIL_REFERENCE")
231 _text(line.policy_evidence_ref, "IS_DETAIL_POLICY")
232 buckets[line.category].append(amount)
233 totals = {key: _sum_exact(values) for key, values in buckets.items()}
234 revenue = totals["REVENUE"]
235 cost = totals["COST_OF_REVENUE"]
236 gross = _sum_exact([revenue, -cost])
237 operating = _sum_exact([gross, -totals["OPERATING_EXPENSE"]])
238 pretax = _sum_exact([
239 operating, totals["OTHER_INCOME"], -totals["OTHER_EXPENSE"],
240 ])
241 net = _sum_exact([pretax, -totals["TAX_EXPENSE"]])
242 return (
243 bool(buckets["REVENUE"])
244 and any(buckets[key] for key in (
245 "COST_OF_REVENUE", "OPERATING_EXPENSE",
246 "OTHER_EXPENSE", "TAX_EXPENSE",
247 ))
248 and revenue == _money(income.revenue_total)
249 and cost == _money(income.cost_of_revenue_total)
250 and gross == _money(income.gross_profit)
251 and totals["OPERATING_EXPENSE"] == _money(income.operating_expense_total)
252 and operating == _money(income.operating_profit)
253 and totals["OTHER_INCOME"] == _money(income.other_income_total)
254 and totals["OTHER_EXPENSE"] == _money(income.other_expense_total)
255 and pretax == _money(income.profit_before_tax)
256 and totals["TAX_EXPENSE"] == _money(income.tax_expense_total)
257 and net == _money(income.net_result)
258 )
259
260
261 def _equity_detail_bridge(
262 equity: EquityChangesCandidate, trial: TrialBalanceDiagnostic,
263 ) -> bool:
264 if (not isinstance(trial.accounts, tuple)
265 or not isinstance(equity.note_movements, tuple) or not equity.note_movements
266 or not isinstance(equity.account_movements, tuple)
267 or not equity.account_movements
268 or not isinstance(equity.component_totals, tuple)):
269 return False
270 trial_by_code = {
271 account.account_code: account
272 for account in trial.accounts
273 if isinstance(account, TrialBalanceAccount)
274 }
275 if len(trial_by_code) != len(trial.accounts):
276 return False
277 accounts_by_note: dict[tuple[str, str, str], list[EquityAccountMovement]] = {}
278 seen_accounts: set[str] = set()
279 for account in equity.account_movements:
280 if not isinstance(account, EquityAccountMovement):
281 return False
282 code = _text(account.account_code, "EQ_DETAIL_ACCOUNT")
283 if code in seen_accounts:
284 return False
285 seen_accounts.add(code)
286 key = (
287 _text(account.statement_section, "EQ_DETAIL_SECTION"),
288 _text(account.note_number, "EQ_DETAIL_NOTE"),
289 _text(account.subnote_code, "EQ_DETAIL_SUBNOTE", blank_ok=True),
290 )
291 if (not isinstance(account.equity_component, str)
292 or account.equity_component not in EQUITY_COMPONENTS
293 or not isinstance(account.movement_category, str)
294 or account.movement_category not in MOVEMENT_CATEGORIES
295 or type(account.sign_multiplier) is not int
296 or account.sign_multiplier not in (-1, 1)
297 or type(account.source_excel_row) is not int
298 or account.source_excel_row < 2
299 or type(account.source_row) is not int
300 or account.source_row <= 0):
301 return False
302 opening = _money(account.opening_balance)
303 debit = _money(account.debit_turnover)
304 credit = _money(account.credit_turnover)
305 movement = _money(account.movement_amount)
306 closing = _money(account.closing_balance)
307 source = trial_by_code.get(code)
308 if (source is None
309 or account.account_name != source.account_name
310 or account.source_excel_row != source.excel_row
311 or account.source_row != source.source_row
312 or opening * account.sign_multiplier != _money(source.opening)
313 or debit != _money(source.debit)
314 or credit != _money(source.credit)
315 or closing * account.sign_multiplier != _money(source.closing)
316 or debit < 0 or credit < 0
317 or movement != _sum_exact([debit, -credit]) * account.sign_multiplier
318 or _sum_exact([opening, movement, -closing]) != 0):
319 return False
320 _text(account.account_name, "EQ_DETAIL_ACCOUNT_NAME")
321 _text(account.policy_evidence_ref, "EQ_DETAIL_POLICY")
322 accounts_by_note.setdefault(key, []).append(account)
323
324 note_by_key: dict[tuple[str, str, str], EquityNoteMovement] = {}
325 category_movements: dict[str, list[Decimal]] = {
326 category: [] for category in MOVEMENT_CATEGORIES
327 }
328 component_values: dict[str, dict[str, list[Decimal]]] = {}
329 opening_values: list[Decimal] = []
330 movement_values: list[Decimal] = []
331 closing_values: list[Decimal] = []
332 for note in equity.note_movements:
333 if not isinstance(note, EquityNoteMovement):
334 return False
335 key = (
336 _text(note.statement_section, "EQ_DETAIL_SECTION"),
337 _text(note.note_number, "EQ_DETAIL_NOTE"),
338 _text(note.subnote_code, "EQ_DETAIL_SUBNOTE", blank_ok=True),
339 )
340 if key in note_by_key or key not in accounts_by_note:
341 return False
342 if (not isinstance(note.equity_component, str)
343 or note.equity_component not in EQUITY_COMPONENTS
344 or not isinstance(note.movement_category, str)
345 or note.movement_category not in MOVEMENT_CATEGORIES):
346 return False
347 _text(note.line_label, "EQ_DETAIL_LABEL")
348 _text(note.note_reference_evidence, "EQ_DETAIL_REFERENCE")
349 _text(note.policy_evidence_ref, "EQ_DETAIL_POLICY")
350 rows = accounts_by_note[key]
351 if any(
352 row.equity_component != note.equity_component
353 or row.movement_category != note.movement_category
354 for row in rows
355 ):
356 return False
357 opening = _sum_exact([_money(row.opening_balance) for row in rows])
358 movement = _sum_exact([_money(row.movement_amount) for row in rows])
359 closing = _sum_exact([_money(row.closing_balance) for row in rows])
360 raw_closing = _sum_exact([
361 _money(row.closing_balance) * row.sign_multiplier for row in rows
362 ])
363 note_opening = _money(note.opening_balance)
364 note_movement = _money(note.movement_amount)
365 note_closing = _money(note.closing_balance)
366 if (
367 opening != note_opening or movement != note_movement
368 or closing != note_closing
369 or raw_closing != _money(note.source_closing_exposure)
370 or _sum_exact([note_opening, note_movement, -note_closing]) != 0
371 ):
372 return False
373 note_by_key[key] = note
374 opening_values.append(note_opening)
375 movement_values.append(note_movement)
376 closing_values.append(note_closing)
377 category_movements[note.movement_category].append(note_movement)
378 group = component_values.setdefault(note.equity_component, {
379 "opening": [], "movement": [], "closing": [],
380 })
381 group["opening"].append(note_opening)
382 group["movement"].append(note_movement)
383 group["closing"].append(note_closing)
384 if set(accounts_by_note) != set(note_by_key):
385 return False
386
387 component_by_key: dict[str, EquityComponentTotal] = {}
388 for item in equity.component_totals:
389 if not isinstance(item, EquityComponentTotal):
390 return False
391 if (not isinstance(item.equity_component, str)
392 or item.equity_component not in EQUITY_COMPONENTS
393 or item.equity_component in component_by_key):
394 return False
395 component_by_key[item.equity_component] = item
396 if set(component_by_key) != set(component_values):
397 return False
398 for component, group in component_values.items():
399 item = component_by_key[component]
400 if (
401 _money(item.opening_balance) != _sum_exact(group["opening"])
402 or _money(item.movement_amount) != _sum_exact(group["movement"])
403 or _money(item.closing_balance) != _sum_exact(group["closing"])
404 ):
405 return False
406
407 summary_categories = {
408 "CAPITAL_CONTRIBUTION": equity.capital_contributions,
409 "NET_PROFIT_LOSS": equity.net_profit_loss_movements,
410 "DIVIDENDS": equity.dividends,
411 "OTHER_COMPREHENSIVE_INCOME": equity.other_comprehensive_income,
412 "TRANSFER": equity.transfers,
413 "PRIOR_PERIOD_ADJUSTMENT": equity.prior_period_adjustments,
414 "OTHER_MOVEMENT": equity.other_movements,
415 }
416 return (
417 _sum_exact(opening_values) == _money(equity.opening_equity_total)
418 and _sum_exact(movement_values) == _money(equity.total_movement)
419 and _sum_exact(closing_values) == _money(equity.closing_equity_total)
420 and _sum_exact([
421 _money(equity.opening_equity_total),
422 _money(equity.total_movement),
423 -_money(equity.closing_equity_total),
424 ]) == _money(equity.rollforward_difference) == 0
425 and all(
426 _sum_exact(category_movements[category]) == _money(amount)
427 for category, amount in summary_categories.items()
428 )
429 )
430
431
432 def _income_bridge(income: IncomeStatementCandidate) -> bool:
433 revenue = _money(income.revenue_total)
434 cost = _money(income.cost_of_revenue_total)
435 gross = _money(income.gross_profit)
436 operating_expense = _money(income.operating_expense_total)
437 operating = _money(income.operating_profit)
438 other_income = _money(income.other_income_total)
439 other_expense = _money(income.other_expense_total)
440 pretax = _money(income.profit_before_tax)
441 tax = _money(income.tax_expense_total)
442 net = _money(income.net_result)
443 return (
444 _income_detail_bridge(income)
445 and _sum_exact([revenue, -cost, -gross]) == 0
446 and _sum_exact([gross, -operating_expense, -operating]) == 0
447 and _sum_exact([operating, other_income, -other_expense, -pretax]) == 0
448 and _sum_exact([pretax, -tax, -net]) == 0
449 )
450
451
452 def _cash_flow_bridge(cash: DirectCashFlowCandidate) -> bool:
453 categories = {
454 activity: {"inflows": [], "outflows": []}
455 for activity in ("OPERATING", "INVESTING", "FINANCING")
456 }
457 line_ids: set[str] = set()
458 transfer_values: list[Decimal] = []
459 if (type(cash.transaction_count) is not int
460 or not isinstance(cash.cash_flow_lines, tuple)
461 or cash.transaction_count != len(cash.cash_flow_lines)):
462 return False
463 for line in cash.cash_flow_lines:
464 if not isinstance(line, CashFlowLine):
465 return False
466 line_id = _text(line.line_id, "CASH_FLOW_LINE_ID")
467 _text(line.transaction_id, "CASH_FLOW_TRANSACTION_ID")
468 _text(line.posting_date, "CASH_FLOW_POSTING_DATE")
469 cash_code = _text(line.cash_account_code, "CASH_FLOW_CASH_ACCOUNT")
470 counterpart_code = _text(line.counterpart_account_code, "CASH_FLOW_COUNTERPART")
471 activity = _text(line.activity, "CASH_FLOW_ACTIVITY")
472 _text(line.source_evidence_ref, "CASH_FLOW_SOURCE_EVIDENCE")
473 _text(line.classification_evidence_ref, "CASH_FLOW_CLASSIFICATION_EVIDENCE")
474 if line_id in line_ids or cash_code == counterpart_code:
475 return False
476 line_ids.add(line_id)
477 inflow = _money(line.cash_inflow)
478 outflow = _money(line.cash_outflow)
479 if inflow < 0 or outflow < 0 or not ((inflow > 0) ^ (outflow > 0)):
480 return False
481 if activity in categories:
482 categories[activity]["inflows"].append(inflow)
483 categories[activity]["outflows"].append(outflow)
484 elif activity == "CASH_TRANSFER":
485 transfer_values.append(_sum_exact([inflow, outflow]))
486 else:
487 return False
488
489 operating = _sum_exact([
490 _sum_exact(categories["OPERATING"]["inflows"]),
491 -_sum_exact(categories["OPERATING"]["outflows"]),
492 ])
493 investing = _sum_exact([
494 _sum_exact(categories["INVESTING"]["inflows"]),
495 -_sum_exact(categories["INVESTING"]["outflows"]),
496 ])
497 financing = _sum_exact([
498 _sum_exact(categories["FINANCING"]["inflows"]),
499 -_sum_exact(categories["FINANCING"]["outflows"]),
500 ])
501 net_change = _money(cash.net_change_in_cash)
502 transfer_total = _sum_exact(transfer_values)
503 rollforward = _sum_exact([
504 _money(cash.opening_cash_and_equivalents), net_change,
505 -_money(cash.closing_cash_and_equivalents),
506 ])
507 return (
508 _sum_exact(categories["OPERATING"]["inflows"]) == _money(cash.operating_inflows)
509 and _sum_exact(categories["OPERATING"]["outflows"]) == _money(cash.operating_outflows)
510 and operating == _money(cash.operating_net_cash_flow)
511 and _sum_exact(categories["INVESTING"]["inflows"]) == _money(cash.investing_inflows)
512 and _sum_exact(categories["INVESTING"]["outflows"]) == _money(cash.investing_outflows)
513 and investing == _money(cash.investing_net_cash_flow)
514 and _sum_exact(categories["FINANCING"]["inflows"]) == _money(cash.financing_inflows)
515 and _sum_exact(categories["FINANCING"]["outflows"]) == _money(cash.financing_outflows)
516 and financing == _money(cash.financing_net_cash_flow)
517 and _sum_exact([operating, investing, financing, -net_change]) == 0
518 and _money(cash.internal_transfer_inflows) == transfer_total
519 and _money(cash.internal_transfer_outflows) == transfer_total
520 and rollforward == _money(cash.rollforward_difference) == 0
521 )
522
523
524 def _trial_balance_bridge(trial: TrialBalanceDiagnostic) -> bool:
525 if (type(trial.account_count) is not int
526 or not isinstance(trial.accounts, tuple)
527 or trial.account_count != len(trial.accounts) or not trial.accounts
528 or type(trial.balanced_for_analyst_review) is not bool):
529 return False
530 seen: set[str] = set()
531 openings: list[Decimal] = []
532 debits: list[Decimal] = []
533 credits: list[Decimal] = []
534 closings: list[Decimal] = []
535 source_rows: set[int] = set()
536 for account in trial.accounts:
537 if not isinstance(account, TrialBalanceAccount):
538 return False
539 code = _text(account.account_code, "TRIAL_BALANCE_ACCOUNT_CODE")
540 if code in seen:
541 return False
542 seen.add(code)
543 if (type(account.source_row) is not int or account.source_row <= 0
544 or account.source_row in source_rows):
545 return False
546 source_rows.add(account.source_row)
547 _text(account.account_name, "TRIAL_BALANCE_ACCOUNT_NAME")
548 opening = _money(account.opening)
549 debit = _money(account.debit)
550 credit = _money(account.credit)
551 closing = _money(account.closing)
552 if (debit < 0 or credit < 0
553 or _sum_exact([debit, -credit]) != _money(account.debit_net_movement)
554 or _sum_exact([opening, debit, -credit, -closing]) != 0):
555 return False
556 openings.append(opening)
557 debits.append(debit)
558 credits.append(credit)
559 closings.append(closing)
560 opening_total = _sum_exact(openings)
561 debit_total = _sum_exact(debits)
562 credit_total = _sum_exact(credits)
563 closing_total = _sum_exact(closings)
564 movement = _sum_exact([debit_total, -credit_total])
565 rollforward = _sum_exact([opening_total, movement, -closing_total])
566 return (
567 trial.balanced_for_analyst_review
568 and opening_total == _money(trial.opening_debit_net_total)
569 and debit_total == _money(trial.debit_turnover_total)
570 and credit_total == _money(trial.credit_turnover_total)
571 and closing_total == _money(trial.closing_debit_net_total)
572 and movement == _money(trial.movement_difference) == 0
573 and opening_total == 0 and closing_total == 0
574 and rollforward == _money(trial.opening_to_closing_difference) == 0
575 )
576
577
578 def _cash_accounts_match_trial_balance(
579 cash: DirectCashFlowCandidate, trial: TrialBalanceDiagnostic,
580 ) -> tuple[bool, bool]:
581 findings_valid = True
582 totals_valid = True
583 if (not isinstance(trial.accounts, tuple)
584 or not isinstance(cash.account_reconciliations, tuple)
585 or not isinstance(cash.cash_flow_lines, tuple)):
586 return False, False
587 if (type(trial.account_count) is not int
588 or trial.account_count != len(trial.accounts)
589 or type(cash.cash_account_count) is not int
590 or cash.cash_account_count != len(cash.account_reconciliations)
591 or cash.cash_account_count < 1):
592 findings_valid = False
593
594 trial_by_code: dict[str, TrialBalanceAccount] = {}
595 for account in trial.accounts:
596 if (not isinstance(account, TrialBalanceAccount)
597 or not isinstance(account.account_code, str)
598 or account.account_code != account.account_code.strip()
599 or not account.account_code
600 or account.account_code in trial_by_code):
601 findings_valid = False
602 continue
603 trial_by_code[account.account_code] = account
604
605 cash_by_code: dict[str, CashAccountReconciliation] = {}
606 for item in cash.account_reconciliations:
607 if (not isinstance(item, CashAccountReconciliation)
608 or not isinstance(item.account_code, str)
609 or item.account_code != item.account_code.strip()
610 or not item.account_code or item.account_code in cash_by_code):
611 findings_valid = False
612 continue
613 cash_by_code[item.account_code] = item
614
615 line_debits: dict[str, list[Decimal]] = {
616 code: [] for code in cash_by_code
617 }
618 line_credits: dict[str, list[Decimal]] = {
619 code: [] for code in cash_by_code
620 }
621 for line in cash.cash_flow_lines:
622 if not isinstance(line, CashFlowLine):
623 findings_valid = False
624 continue
625 cash_code = line.cash_account_code
626 counterpart_code = line.counterpart_account_code
627 if (not isinstance(cash_code, str) or cash_code not in cash_by_code
628 or not isinstance(counterpart_code, str)
629 or counterpart_code not in trial_by_code):
630 findings_valid = False
631 continue
632 inflow = _money(line.cash_inflow)
633 outflow = _money(line.cash_outflow)
634 if inflow > 0:
635 line_debits[cash_code].append(inflow)
636 if outflow > 0:
637 line_credits[cash_code].append(outflow)
638 if line.activity == "CASH_TRANSFER":
639 if counterpart_code not in cash_by_code:
640 findings_valid = False
641 continue
642 if inflow > 0:
643 line_credits[counterpart_code].append(inflow)
644 elif outflow > 0:
645 line_debits[counterpart_code].append(outflow)
646 else:
647 findings_valid = False
648 elif counterpart_code in cash_by_code:
649 findings_valid = False
650
651 seen: set[str] = set()
652 opening_values: list[Decimal] = []
653 closing_values: list[Decimal] = []
654 for code, item in cash_by_code.items():
655 if code in seen:
656 findings_valid = False
657 continue
658 seen.add(code)
659 trial_account = trial_by_code.get(code)
660 if trial_account is None:
661 findings_valid = False
662 continue
663 if (type(item.source_row) is not int or item.source_row <= 0
664 or item.source_row != trial_account.source_row
665 or item.account_name != trial_account.account_name):
666 findings_valid = False
667 _text(item.policy_evidence_ref, "CASH_ACCOUNT_POLICY_EVIDENCE")
668 source_values = (
669 _money(item.opening_balance), _money(item.source_debit_turnover),
670 _money(item.source_credit_turnover), _money(item.closing_balance),
671 )
672 trial_values = (
673 _money(trial_account.opening), _money(trial_account.debit),
674 _money(trial_account.credit), _money(trial_account.closing),
675 )
676 if source_values != trial_values:
677 findings_valid = False
678 transaction_debit = _sum_exact(line_debits[code])
679 transaction_credit = _sum_exact(line_credits[code])
680 if (
681 transaction_debit != _money(item.transaction_debit_turnover)
682 or transaction_credit != _money(item.transaction_credit_turnover)
683 ):
684 totals_valid = False
685 debit_difference = _sum_exact([
686 transaction_debit, -_money(item.source_debit_turnover),
687 ])
688 credit_difference = _sum_exact([
689 transaction_credit, -_money(item.source_credit_turnover),
690 ])
691 rollforward = _sum_exact([
692 source_values[0], source_values[1], -source_values[2], -source_values[3],
693 ])
694 if (debit_difference != 0 or credit_difference != 0 or rollforward != 0
695 or _money(item.debit_difference) != debit_difference
696 or _money(item.credit_difference) != credit_difference
697 or _money(item.rollforward_difference) != rollforward):
698 totals_valid = False
699 opening_values.append(source_values[0])
700 closing_values.append(source_values[3])
701
702 if (_sum_exact(opening_values) != _money(cash.opening_cash_and_equivalents)
703 or _sum_exact(closing_values) != _money(cash.closing_cash_and_equivalents)):
704 totals_valid = False
705 return findings_valid, totals_valid
706
707
708 def reconcile_cross_statements(
709 *, balance_sheet: BalanceSheetCandidate,
710 income_statement: IncomeStatementCandidate,
711 equity_changes: EquityChangesCandidate,
712 cash_flow: DirectCashFlowCandidate,
713 trial_balance: TrialBalanceDiagnostic,
714 cash_balance_notes: Sequence[CashBalanceNoteSelection],
715 ) -> CrossStatementReconciliation:
716 """Reconcile BS/IS/EQ/CF/TB candidates without granting financial approval.
717
718 The caller must explicitly select the BS asset notes that represent cash
719 and cash equivalents. This policy is evidence-bearing and untrusted. Exact
720 Decimal comparison uses zero tolerance; any scope/hash mismatch or blocked
721 upstream candidate prevents analyst eligibility.
722 """
723 candidates = (
724 ("balance_sheet", balance_sheet, BalanceSheetCandidate),
725 ("income_statement", income_statement, IncomeStatementCandidate),
726 ("equity_changes", equity_changes, EquityChangesCandidate),
727 ("cash_flow", cash_flow, DirectCashFlowCandidate),
728 ("trial_balance", trial_balance, TrialBalanceDiagnostic),
729 )
730 for label, candidate, expected_type in candidates:
731 _validate_candidate(candidate, label, expected_type)
732
733 if not isinstance(cash_balance_notes, (list, tuple)) or not 0 < len(cash_balance_notes) <= 5_000:
734 raise CoverageError("INVALID_CASH_BALANCE_NOTE_SELECTION")
735
736 selected: dict[tuple[str, str, str], CashBalanceNoteSelection] = {}
737 for item in cash_balance_notes:
738 if not isinstance(item, CashBalanceNoteSelection):
739 raise CoverageError("INVALID_CASH_BALANCE_NOTE_SELECTION")
740 key = (
741 _text(item.statement_section, "CASH_NOTE_SECTION"),
742 _text(item.note_number, "CASH_NOTE_NUMBER"),
743 _text(item.subnote_code, "CASH_NOTE_SUBNOTE", blank_ok=True),
744 )
745 _text(item.evidence_ref, "CASH_NOTE_EVIDENCE")
746 if key in selected:
747 raise CoverageError("DUPLICATE_CASH_BALANCE_NOTE_SELECTION")
748 selected[key] = item
749 selection_hash = sha256(json.dumps(
750 [asdict(selected[key]) for key in sorted(selected)],
751 ensure_ascii=True, sort_keys=True, separators=(",", ":"),
752 ).encode("utf-8")).hexdigest()
753
754 findings: list[str] = []
755 base = balance_sheet
756 if any(
757 candidate.company_code != base.company_code
758 or candidate.fiscal_year != base.fiscal_year
759 for _, candidate, _ in candidates
760 ):
761 findings.append("CROSS_STATEMENT_COMPANY_YEAR_MISMATCH")
762
763 hashes = {candidate.source_sha256 for _, candidate, _ in candidates}
764 same_snapshot = len(hashes) == 1
765 if not same_snapshot:
766 findings.append("CROSS_STATEMENT_SOURCE_SNAPSHOT_MISMATCH")
767 reference_hashes = {
768 balance_sheet.note_references_sha256,
769 income_statement.note_references_sha256,
770 equity_changes.note_references_sha256,
771 }
772 if len(reference_hashes) != 1:
773 findings.append("CROSS_STATEMENT_NOTE_REFERENCE_SNAPSHOT_MISMATCH")
774 source_hash = base.source_sha256
775
776 for label, candidate, _ in candidates:
777 eligible = (
778 getattr(candidate, "eligible_for_analyst_review", None)
779 if label != "trial_balance"
780 else candidate.balanced_for_analyst_review
781 )
782 if not eligible:
783 findings.append(label.upper() + "_CANDIDATE_BLOCKED")
784
785 if not _balance_sheet_detail_bridge(balance_sheet):
786 findings.append("BALANCE_SHEET_DETAIL_INVALID")
787
788 bs_computed_difference = _sum_exact([
789 _money(balance_sheet.assets_total),
790 -_money(balance_sheet.liabilities_total),
791 -_money(balance_sheet.equity_total),
792 ])
793 bs_reported_difference = _money(balance_sheet.balance_difference)
794 if (bs_computed_difference != bs_reported_difference
795 or bs_reported_difference != 0
796 or not balance_sheet.arithmetically_balanced):
797 findings.append("BALANCE_SHEET_EQUATION_INVALID")
798
799 equity_difference = _sum_exact([
800 _money(balance_sheet.equity_total),
801 -_money(equity_changes.closing_equity_total),
802 ])
803 if equity_difference != 0:
804 findings.append("BALANCE_SHEET_EQUITY_CLOSING_MISMATCH")
805
806 profit_difference = _sum_exact([
807 _money(income_statement.net_result),
808 -_money(equity_changes.net_profit_loss_movements),
809 ])
810 if profit_difference != 0:
811 findings.append("INCOME_RESULT_EQUITY_MOVEMENT_MISMATCH")
812
813 income_valid = _income_bridge(income_statement)
814 if not income_valid:
815 findings.append("INCOME_STATEMENT_BRIDGE_INVALID")
816
817 equity_rollforward = _sum_exact([
818 _money(equity_changes.opening_equity_total),
819 _money(equity_changes.total_movement),
820 -_money(equity_changes.closing_equity_total),
821 ])
822 equity_rollforward_valid = (
823 _equity_detail_bridge(equity_changes, trial_balance)
824 and equity_rollforward == 0
825 and _money(equity_changes.rollforward_difference) == 0
826 )
827 if not equity_rollforward_valid:
828 findings.append("EQUITY_STATEMENT_ROLLFORWARD_INVALID")
829
830 bs_lines = {}
831 for line in (
832 balance_sheet.lines if isinstance(balance_sheet.lines, (tuple, list)) else ()
833 ):
834 if not isinstance(line, CandidateBalanceSheetLine):
835 continue
836 key = (line.statement_section, line.note_number, line.subnote_code)
837 if key in bs_lines:
838 findings.append("DUPLICATE_BALANCE_SHEET_NOTE_LINE")
839 else:
840 bs_lines[key] = line
841 selected_lines: list[SelectedCashBalanceNote] = []
842 cash_amounts: list[Decimal] = []
843 for key in sorted(selected):
844 line = bs_lines.get(key)
845 if line is None:
846 findings.append("CASH_BALANCE_NOTE_NOT_FOUND_IN_BALANCE_SHEET")
847 continue
848 if line.category != "ASSETS":
849 findings.append("CASH_BALANCE_NOTE_NOT_ASSET")
850 continue
851 amount = _money(line.presentation_amount)
852 cash_amounts.append(amount)
853 selected_lines.append(SelectedCashBalanceNote(
854 statement_section=key[0], note_number=key[1],
855 subnote_code=key[2], presentation_amount=str(amount),
856 evidence_ref=selected[key].evidence_ref,
857 ))
858 if len(selected_lines) != len(selected):
859 findings.append("CASH_BALANCE_NOTE_SELECTION_INCOMPLETE")
860 bs_cash_total = _sum_exact(cash_amounts)
861 cash_difference = _sum_exact([
862 bs_cash_total, -_money(cash_flow.closing_cash_and_equivalents),
863 ])
864 if cash_difference != 0:
865 findings.append("BALANCE_SHEET_CASH_FLOW_CLOSING_MISMATCH")
866
867 cash_valid = _cash_flow_bridge(cash_flow)
868 if not cash_valid:
869 findings.append("CASH_FLOW_BRIDGE_INVALID")
870
871 cash_accounts_match_tb, cash_account_totals_valid = (
872 _cash_accounts_match_trial_balance(cash_flow, trial_balance)
873 )
874 if not cash_accounts_match_tb:
875 findings.append("CASH_ACCOUNTS_TRIAL_BALANCE_MISMATCH")
876 if not cash_account_totals_valid:
877 findings.append("CASH_ACCOUNT_TURNOVER_OR_TOTALS_INVALID")
878
879 trial_valid = _trial_balance_bridge(trial_balance)
880 if not trial_valid:
881 findings.append("TRIAL_BALANCE_ARITHMETIC_INVALID")
882
883 tb_opening = _money(trial_balance.opening_debit_net_total)
884 tb_movement = _money(trial_balance.movement_difference)
885 tb_closing = _money(trial_balance.closing_debit_net_total)
886 tb_rollforward = _money(trial_balance.opening_to_closing_difference)
887
888 return CrossStatementReconciliation(
889 company_code=base.company_code, fiscal_year=base.fiscal_year,
890 source_sha256=source_hash,
891 cash_flow_transaction_ledger_sha256=_hash(
892 cash_flow.transaction_ledger_sha256, "CASH_FLOW_TRANSACTION_HASH",
893 ),
894 cash_note_selection_sha256=selection_hash,
895 same_source_snapshot=same_snapshot,
896 trial_balance_opening_debit_net_total=str(tb_opening),
897 trial_balance_movement_difference=str(tb_movement),
898 trial_balance_closing_debit_net_total=str(tb_closing),
899 trial_balance_rollforward_difference=str(tb_rollforward),
900 balance_sheet_difference=str(bs_reported_difference),
901 balance_sheet_equity_total=str(_money(balance_sheet.equity_total)),
902 equity_statement_closing_total=str(_money(equity_changes.closing_equity_total)),
903 balance_sheet_equity_difference=str(equity_difference),
904 income_statement_net_result=str(_money(income_statement.net_result)),
905 equity_net_profit_loss_movements=str(_money(equity_changes.net_profit_loss_movements)),
906 net_profit_equity_difference=str(profit_difference),
907 balance_sheet_cash_total=str(bs_cash_total),
908 cash_flow_closing_cash=str(_money(cash_flow.closing_cash_and_equivalents)),
909 balance_sheet_cash_difference=str(cash_difference),
910 income_statement_bridge_valid=income_valid,
911 cash_flow_bridge_valid=cash_valid,
912 equity_rollforward_valid=equity_rollforward_valid,
913 trial_balance_arithmetic_valid=trial_valid,
914 cash_accounts_match_trial_balance=cash_accounts_match_tb,
915 cash_account_totals_valid=cash_account_totals_valid,
916 selected_cash_notes=tuple(selected_lines),
917 findings=tuple(sorted(set(findings))),
918 eligible_for_analyst_review=not findings,
919 )