@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 18:15 UTC

codex/aram-account-note-source-trace-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 313 lines 16.7 KB
Raw
1 """Fail-closed provenance and tie-out checks for desktop-only previews."""
2 from __future__ import annotations
3
4 import re
5
6 from aram_backend.coverage_preview import (
7 AccountTrace, CoverageError, CoveragePreview, MappingTrace,
8 )
9 from aram_backend.reconciliation_review import _money, _sum_exact
10 from aram_backend.balance_sheet_candidate import BalanceSheetCandidate
11 from aram_backend.cash_flow_direct_candidate import DirectCashFlowCandidate
12 from aram_backend.cross_statement_reconciliation import CrossStatementReconciliation
13 from aram_backend.equity_changes_candidate import EquityChangesCandidate
14 from aram_backend.five_statement_pipeline import FiveStatementPipelineResult
15 from aram_backend.income_statement_candidate import IncomeStatementCandidate
16 from aram_backend.trial_balance_diagnostic import TrialBalanceDiagnostic
17
18
19 def _require_false(obj: object, fields: tuple[str, ...]) -> None:
20 for field in fields:
21 value = getattr(obj, field)
22 if type(value) is not bool or value:
23 raise CoverageError("DESKTOP_PREVIEW_PROVENANCE_INVALID")
24
25
26 def _require_bool(obj: object, field: str) -> bool:
27 value = getattr(obj, field)
28 if type(value) is not bool:
29 raise CoverageError("DESKTOP_PREVIEW_BOOLEAN_INVALID")
30 return value
31
32
33 def validate_desktop_pipeline_result(result: FiveStatementPipelineResult) -> None:
34 """Verify the exact typed orchestration result before rendering any data."""
35 if type(result) is not FiveStatementPipelineResult:
36 raise CoverageError("DESKTOP_PREVIEW_PIPELINE_TYPE_INVALID")
37 candidates = (
38 (result.balance_sheet, BalanceSheetCandidate, "UNAPPROVED_BALANCE_SHEET_PRESENTATION_CANDIDATE"),
39 (result.income_statement, IncomeStatementCandidate, "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE"),
40 (result.equity_changes, EquityChangesCandidate, "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE"),
41 (result.cash_flow, DirectCashFlowCandidate, "UNAPPROVED_DIRECT_CASH_FLOW_CANDIDATE"),
42 (result.trial_balance, TrialBalanceDiagnostic, "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC"),
43 )
44 if result.kind != "UNAPPROVED_FIVE_STATEMENT_PIPELINE_CANDIDATE":
45 raise CoverageError("DESKTOP_PREVIEW_PIPELINE_KIND_INVALID")
46 if type(result.reconciliation) is not CrossStatementReconciliation:
47 raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_TYPE_INVALID")
48 if result.reconciliation.kind != "UNAPPROVED_CROSS_STATEMENT_RECONCILIATION":
49 raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_KIND_INVALID")
50 _require_false(result, (
51 "source_ledger_completeness_verified", "accounting_policy_authorized",
52 "independently_reviewed", "trusted_approvals",
53 "official_financial_statement", "export_authorized", "releasable",
54 ))
55 _require_false(result.reconciliation, (
56 "source_ledger_completeness_verified", "accounting_policy_authorized",
57 "independently_reviewed", "trusted_approvals",
58 "official_financial_statement", "export_authorized", "releasable",
59 ))
60 source_hashes: set[str] = set()
61 companies: set[str] = set()
62 years: set[int] = set()
63 eligibility: list[bool] = []
64 for candidate, expected_type, expected_kind in candidates:
65 if type(candidate) is not expected_type or candidate.kind != expected_kind:
66 raise CoverageError("DESKTOP_PREVIEW_CANDIDATE_TYPE_INVALID")
67 if (not isinstance(candidate.source_sha256, str)
68 or not re.fullmatch(r"[0-9a-f]{64}", candidate.source_sha256)):
69 raise CoverageError("DESKTOP_PREVIEW_SOURCE_HASH_INVALID")
70 source_hashes.add(candidate.source_sha256)
71 if (not isinstance(candidate.company_code, str)
72 or not candidate.company_code
73 or candidate.company_code != candidate.company_code.strip()
74 or type(candidate.fiscal_year) is not int
75 or candidate.fiscal_year <= 0):
76 raise CoverageError("DESKTOP_PREVIEW_SCOPE_INVALID")
77 companies.add(candidate.company_code)
78 years.add(candidate.fiscal_year)
79 for hash_field in (
80 "note_references_sha256", "presentation_policies_sha256",
81 "transaction_ledger_sha256", "classification_policies_sha256",
82 ):
83 if hasattr(candidate, hash_field):
84 digest = getattr(candidate, hash_field)
85 if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
86 raise CoverageError("DESKTOP_PREVIEW_PROVENANCE_HASH_INVALID")
87 eligible_field = (
88 "balanced_for_analyst_review" if isinstance(candidate, TrialBalanceDiagnostic)
89 else "eligible_for_analyst_review"
90 )
91 eligibility.append(_require_bool(candidate, eligible_field))
92 findings = candidate.findings
93 if not isinstance(findings, tuple) or any(
94 not isinstance(item, str) or not item for item in findings
95 ):
96 raise CoverageError("DESKTOP_PREVIEW_FINDINGS_INVALID")
97 if isinstance(candidate, BalanceSheetCandidate):
98 flags = ("official_financial_statement", "accounting_policy_authorized",
99 "independently_reviewed", "export_authorized", "releasable")
100 elif isinstance(candidate, IncomeStatementCandidate):
101 flags = ("official_financial_statement", "accounting_policy_authorized",
102 "independently_reviewed", "export_authorized", "releasable")
103 elif isinstance(candidate, EquityChangesCandidate):
104 flags = ("official_financial_statement", "accounting_policy_authorized",
105 "source_ledger_completeness_verified", "independently_reviewed",
106 "export_authorized", "releasable")
107 elif isinstance(candidate, DirectCashFlowCandidate):
108 flags = ("cash_account_scope_owner_approved",
109 "transaction_ledger_completeness_verified",
110 "accounting_policy_authorized", "official_financial_statement",
111 "independently_reviewed", "export_authorized", "releasable")
112 else:
113 flags = ("source_ledger_completeness_verified",
114 "accounting_policies_verified", "official_financial_statement",
115 "independently_reviewed", "releasable")
116 _require_false(candidate, flags)
117 reconciliation = result.reconciliation
118 if (len(source_hashes) != 1
119 or reconciliation.source_sha256 not in source_hashes
120 or not isinstance(reconciliation.source_sha256, str)
121 or not re.fullmatch(r"[0-9a-f]{64}", reconciliation.source_sha256)
122 or reconciliation.same_source_snapshot is not True):
123 raise CoverageError("DESKTOP_PREVIEW_SOURCE_SNAPSHOT_MISMATCH")
124 if (not isinstance(reconciliation.cash_flow_transaction_ledger_sha256, str)
125 or not re.fullmatch(r"[0-9a-f]{64}", reconciliation.cash_flow_transaction_ledger_sha256)
126 or not isinstance(reconciliation.cash_note_selection_sha256, str)
127 or not re.fullmatch(r"[0-9a-f]{64}", reconciliation.cash_note_selection_sha256)):
128 raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_HASH_INVALID")
129 if (not isinstance(reconciliation.findings, tuple)
130 or any(not isinstance(item, str) or not item for item in reconciliation.findings)):
131 raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_FINDINGS_INVALID")
132 if companies != {reconciliation.company_code} or years != {reconciliation.fiscal_year}:
133 raise CoverageError("DESKTOP_PREVIEW_SCOPE_MISMATCH")
134 if (result.balance_sheet.note_references_sha256
135 != result.income_statement.note_references_sha256
136 or result.balance_sheet.note_references_sha256
137 != result.equity_changes.note_references_sha256):
138 raise CoverageError("DESKTOP_PREVIEW_REFERENCE_SNAPSHOT_MISMATCH")
139 ties = (
140 (result.balance_sheet.equity_total, reconciliation.balance_sheet_equity_total),
141 (result.balance_sheet.balance_difference, reconciliation.balance_sheet_difference),
142 (result.income_statement.net_result, reconciliation.income_statement_net_result),
143 (result.equity_changes.closing_equity_total, reconciliation.equity_statement_closing_total),
144 (result.equity_changes.net_profit_loss_movements, reconciliation.equity_net_profit_loss_movements),
145 (result.cash_flow.closing_cash_and_equivalents, reconciliation.cash_flow_closing_cash),
146 (result.trial_balance.opening_debit_net_total, reconciliation.trial_balance_opening_debit_net_total),
147 (result.trial_balance.movement_difference, reconciliation.trial_balance_movement_difference),
148 (result.trial_balance.closing_debit_net_total, reconciliation.trial_balance_closing_debit_net_total),
149 (result.cash_flow.transaction_ledger_sha256, reconciliation.cash_flow_transaction_ledger_sha256),
150 )
151 if any(left != right for left, right in ties):
152 raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_MISMATCH")
153 # The mapping trace is generated from the same immutable XLSX bytes as
154 # the five statements. Do not render account-to-note lineage if it lacks
155 # the exact company, year, source hash, account rows or debit-net figures.
156 coverage = result.mapping_coverage
157 if type(coverage) is not CoveragePreview:
158 raise CoverageError("DESKTOP_PREVIEW_MAPPING_TYPE_INVALID")
159 if (
160 coverage.kind != "UNAPPROVED_MAPPING_COVERAGE_PREVIEW"
161 or type(coverage.financial_statement) is not bool
162 or type(coverage.trusted_approvals) is not bool
163 or type(coverage.releasable) is not bool
164 or coverage.financial_statement or coverage.trusted_approvals
165 or coverage.releasable
166 or coverage.company_code != reconciliation.company_code
167 or coverage.fiscal_year != reconciliation.fiscal_year
168 or coverage.source_sha256 != reconciliation.source_sha256
169 ):
170 raise CoverageError("DESKTOP_PREVIEW_MAPPING_PROVENANCE_INVALID")
171 if (type(coverage.accounts) is not tuple
172 or type(coverage.mappings) is not tuple
173 or type(coverage.notes) is not tuple
174 or type(coverage.account_count) is not int
175 or coverage.account_count != len(coverage.accounts)):
176 raise CoverageError("DESKTOP_PREVIEW_MAPPING_COUNT_INVALID")
177 tb_by_code = {
178 row.account_code: row for row in result.trial_balance.accounts
179 }
180 if len(tb_by_code) != len(result.trial_balance.accounts):
181 raise CoverageError("DESKTOP_PREVIEW_TB_DUPLICATE_ACCOUNT")
182 by_account: dict[str, AccountTrace] = {}
183 for account in coverage.accounts:
184 if type(account) is not AccountTrace or account.account_code in by_account:
185 raise CoverageError("DESKTOP_PREVIEW_MAPPING_ACCOUNT_INVALID")
186 tb_account = tb_by_code.get(account.account_code)
187 if (
188 tb_account is None or account.account_name != tb_account.account_name
189 or account.account_excel_row != tb_account.excel_row
190 or account.source_row != tb_account.source_row
191 or _money(account.closing_exposure) != _money(tb_account.closing)
192 ):
193 raise CoverageError("DESKTOP_PREVIEW_MAPPING_SOURCE_MISMATCH")
194 by_account[account.account_code] = account
195 if set(by_account) != set(tb_by_code):
196 raise CoverageError("DESKTOP_PREVIEW_MAPPING_SOURCE_MISMATCH")
197
198 mapping_counts: dict[str, int] = {}
199 included_accounts: set[str] = set()
200 seen_mapping_rows: set[int] = set()
201 seen_mapping_ids: set[str] = set()
202 note_amounts: dict[tuple[str, str, str, str], list] = {}
203 note_codes: dict[tuple[str, str, str, str], list[str]] = {}
204 seen_account_statement: set[tuple[str, str]] = set()
205 for mapping in coverage.mappings:
206 if type(mapping) is not MappingTrace:
207 raise CoverageError("DESKTOP_PREVIEW_MAPPING_ROW_INVALID")
208 account = by_account.get(mapping.account_code)
209 if (
210 account is None or type(mapping.included) is not bool
211 or mapping.account_name != account.account_name
212 or mapping.account_excel_row != account.account_excel_row
213 or mapping.source_row != account.source_row
214 or _money(mapping.closing_exposure) != _money(account.closing_exposure)
215 or type(mapping.mapping_excel_row) is not int
216 or mapping.mapping_excel_row < 2
217 or mapping.mapping_excel_row in seen_mapping_rows
218 or not isinstance(mapping.mapping_id, str)
219 or not mapping.mapping_id
220 or mapping.mapping_id in seen_mapping_ids
221 ):
222 raise CoverageError("DESKTOP_PREVIEW_MAPPING_ROW_INVALID")
223 seen_mapping_rows.add(mapping.mapping_excel_row)
224 seen_mapping_ids.add(mapping.mapping_id)
225 mapping_counts[mapping.account_code] = (
226 mapping_counts.get(mapping.account_code, 0) + 1
227 )
228 if mapping.included:
229 statement_key = (mapping.account_code, mapping.target_statement)
230 if statement_key in seen_account_statement:
231 raise CoverageError("DESKTOP_PREVIEW_DUPLICATE_MAPPING_TARGET")
232 seen_account_statement.add(statement_key)
233 included_accounts.add(mapping.account_code)
234 note_key = (
235 mapping.target_statement, mapping.target_section,
236 mapping.target_note, mapping.target_subnote,
237 )
238 note_amounts.setdefault(note_key, []).append(
239 _money(mapping.closing_exposure)
240 )
241 note_codes.setdefault(note_key, []).append(mapping.account_code)
242 for account in coverage.accounts:
243 if (
244 type(account.mapping_count) is not int
245 or account.mapping_count != mapping_counts.get(account.account_code, 0)
246 or type(account.included) is not bool
247 or account.included != (account.account_code in included_accounts)
248 ):
249 raise CoverageError("DESKTOP_PREVIEW_MAPPING_COUNT_INVALID")
250 if (
251 coverage.candidate_mapped_accounts != len(included_accounts)
252 or coverage.blocked_accounts != len(coverage.accounts) - len(included_accounts)
253 ):
254 raise CoverageError("DESKTOP_PREVIEW_MAPPING_COUNT_INVALID")
255
256 seen_note_keys: set[tuple[str, str, str, str]] = set()
257 for note in coverage.notes:
258 note_key = (
259 note.statement, note.section, note.note_number, note.subnote_code,
260 )
261 if note_key in seen_note_keys:
262 raise CoverageError("DESKTOP_PREVIEW_MAPPING_NOTE_DUPLICATE")
263 seen_note_keys.add(note_key)
264 if (
265 note_key not in note_amounts
266 or _money(note.closing_exposure) != _sum_exact(note_amounts[note_key])
267 or tuple(note_codes[note_key]) != note.account_codes
268 ):
269 raise CoverageError("DESKTOP_PREVIEW_MAPPING_NOTE_INVALID")
270 if seen_note_keys != set(note_amounts):
271 raise CoverageError("DESKTOP_PREVIEW_MAPPING_NOTE_INVALID")
272
273 # Every displayed BS/IS/EQ candidate note must use the same exact
274 # unrounded exposure as the account-to-note mapping built from this XLSX.
275 # Do not infer accounting signs or reconcile unlike statements together.
276 candidates_by_statement = (
277 ("BS", result.balance_sheet.lines),
278 ("IS", result.income_statement.lines),
279 ("EQ", result.equity_changes.note_movements),
280 )
281 covered_notes = {
282 (note.statement, note.section, note.note_number, note.subnote_code):
283 _money(note.closing_exposure)
284 for note in coverage.notes
285 }
286 for statement, lines in candidates_by_statement:
287 for line in lines:
288 key = (
289 statement, line.statement_section,
290 line.note_number, line.subnote_code,
291 )
292 if key not in covered_notes:
293 raise CoverageError("DESKTOP_PREVIEW_NOTE_SOURCE_MISSING")
294 try:
295 line_exposure = _money(line.source_closing_exposure)
296 except CoverageError as exc:
297 raise CoverageError("DESKTOP_PREVIEW_NOTE_SOURCE_INVALID") from exc
298 if line_exposure != covered_notes[key]:
299 raise CoverageError("DESKTOP_PREVIEW_NOTE_SOURCE_MISMATCH")
300
301 overall = _require_bool(result, "eligible_for_analyst_review")
302 if overall:
303 if (not _require_bool(reconciliation, "eligible_for_analyst_review")
304 or not all(eligibility) or result.findings
305 or any(candidate.findings for candidate, _, _ in candidates)):
306 raise CoverageError("DESKTOP_PREVIEW_FALSE_ELIGIBILITY")
307 else:
308 if _require_bool(reconciliation, "eligible_for_analyst_review"):
309 raise CoverageError("DESKTOP_PREVIEW_ELIGIBILITY_MISMATCH")
310 if not reconciliation.findings and all(eligibility) and not any(
311 candidate.findings for candidate, _, _ in candidates
312 ):
313 raise CoverageError("DESKTOP_PREVIEW_BLOCKED_WITHOUT_FINDINGS")