codex/aram-five-statement-cli-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
| 1 | """Strict, read-only note reconciliation for a synthetic or authorized Pilot workbook. |
| 2 | |
| 3 | The module compares candidate mapped closing exposures to explicit, separately |
| 4 | provided reference totals. It neither infers debit/credit sign semantics nor |
| 5 | creates statutory financial statements, approvals, postings, or files. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from dataclasses import asdict, dataclass |
| 10 | from decimal import Decimal, InvalidOperation, localcontext |
| 11 | from hashlib import sha256 |
| 12 | import json |
| 13 | from typing import Any, Sequence |
| 14 | |
| 15 | from aram_backend.coverage_preview import ( |
| 16 | CoverageError, |
| 17 | CoveragePreview, |
| 18 | preview_mapping_coverage, |
| 19 | ) |
| 20 | |
| 21 | MAX_REFERENCES = 10_000 |
| 22 | MAX_TEXT = 256 |
| 23 | ALLOWED_STATEMENTS = frozenset({"BS", "IS", "CF", "EQ"}) |
| 24 | |
| 25 | |
| 26 | @dataclass(frozen=True) |
| 27 | class NoteReference: |
| 28 | statement: str |
| 29 | section: str |
| 30 | note_number: str |
| 31 | subnote_code: str |
| 32 | expected_closing_exposure: str |
| 33 | evidence_ref: str |
| 34 | |
| 35 | |
| 36 | @dataclass(frozen=True) |
| 37 | class ReconciledNote: |
| 38 | statement: str |
| 39 | section: str |
| 40 | note_number: str |
| 41 | subnote_code: str |
| 42 | candidate_closing_exposure: str | None |
| 43 | reference_closing_exposure: str | None |
| 44 | difference: str | None |
| 45 | evidence_ref: str | None |
| 46 | matched: bool |
| 47 | |
| 48 | |
| 49 | @dataclass(frozen=True) |
| 50 | class ReviewFinding: |
| 51 | code: str |
| 52 | account_code: str |
| 53 | statement: str |
| 54 | section: str |
| 55 | note_number: str |
| 56 | subnote_code: str |
| 57 | |
| 58 | |
| 59 | @dataclass(frozen=True) |
| 60 | class ReconciliationReview: |
| 61 | source_sha256: str |
| 62 | reference_sha256: str |
| 63 | company_code: str |
| 64 | fiscal_year: int |
| 65 | account_count: int |
| 66 | candidate_mapped_accounts: int |
| 67 | blocked_accounts: int |
| 68 | source_closing_exposure: str |
| 69 | candidate_closing_exposure: str |
| 70 | blocked_closing_exposure: str |
| 71 | notes: tuple[ReconciledNote, ...] |
| 72 | findings: tuple[ReviewFinding, ...] |
| 73 | matched_for_analyst_review: bool |
| 74 | kind: str = "UNAPPROVED_NOTE_RECONCILIATION_REVIEW" |
| 75 | financial_statement: bool = False |
| 76 | trusted_approvals: bool = False |
| 77 | approved: bool = False |
| 78 | releasable: bool = False |
| 79 | |
| 80 | def to_dict(self) -> dict[str, Any]: |
| 81 | return asdict(self) |
| 82 | |
| 83 | |
| 84 | def _text(value: object, *, allow_blank: bool = False) -> str: |
| 85 | if not isinstance(value, str): |
| 86 | raise CoverageError("INVALID_REFERENCE_TEXT") |
| 87 | if len(value) > MAX_TEXT or value != value.strip(): |
| 88 | raise CoverageError("INVALID_REFERENCE_TEXT") |
| 89 | if any(ord(char) < 32 or ord(char) == 127 for char in value): |
| 90 | raise CoverageError("INVALID_REFERENCE_TEXT") |
| 91 | if not allow_blank and not value: |
| 92 | raise CoverageError("INVALID_REFERENCE_TEXT") |
| 93 | return value |
| 94 | |
| 95 | |
| 96 | def _money(value: object) -> Decimal: |
| 97 | if not isinstance(value, str) or len(value) > 180 or not value.strip(): |
| 98 | raise CoverageError("INVALID_REFERENCE_AMOUNT") |
| 99 | try: |
| 100 | number = Decimal(value) |
| 101 | except (InvalidOperation, ValueError) as exc: |
| 102 | raise CoverageError("INVALID_REFERENCE_AMOUNT") from exc |
| 103 | # Prevent giant-context denial of service even for zero exponent values. |
| 104 | if (not number.is_finite() or abs(number.as_tuple().exponent) > 140 |
| 105 | or (number != 0 and abs(number.adjusted()) > 70)): |
| 106 | raise CoverageError("INVALID_REFERENCE_AMOUNT") |
| 107 | if len(number.as_tuple().digits) > 150: |
| 108 | raise CoverageError("INVALID_REFERENCE_AMOUNT") |
| 109 | return number |
| 110 | |
| 111 | |
| 112 | def _key( |
| 113 | statement: str, section: str, note: str, subnote: str |
| 114 | ) -> tuple[str, str, str, str]: |
| 115 | return statement, section, note, subnote |
| 116 | |
| 117 | |
| 118 | def _sum_exact(amounts: Sequence[Decimal]) -> Decimal: |
| 119 | if not amounts: |
| 120 | return Decimal(0) |
| 121 | integer_digits = max((amount.adjusted() + 1 for amount in amounts if amount), default=1) |
| 122 | decimal_places = max(0, *(-amount.as_tuple().exponent for amount in amounts)) |
| 123 | with localcontext() as context: |
| 124 | context.prec = max(100, integer_digits + decimal_places + len(str(len(amounts))) + 8) |
| 125 | return sum(amounts, Decimal(0)) |
| 126 | |
| 127 | |
| 128 | def _validated_preview(content: bytes, preview: CoveragePreview) -> None: |
| 129 | if (preview.financial_statement or preview.trusted_approvals |
| 130 | or preview.releasable or preview.kind != "UNAPPROVED_MAPPING_COVERAGE_PREVIEW"): |
| 131 | raise CoverageError("COVERAGE_PROVENANCE_INVALID") |
| 132 | if sha256(content).hexdigest() != preview.source_sha256: |
| 133 | raise CoverageError("SOURCE_HASH_MISMATCH") |
| 134 | if (type(preview.account_count) is not int or preview.account_count < 1 |
| 135 | or preview.account_count != len(preview.accounts) |
| 136 | or preview.account_count != preview.candidate_mapped_accounts + preview.blocked_accounts |
| 137 | or preview.candidate_mapped_accounts != sum(a.included for a in preview.accounts) |
| 138 | or preview.blocked_accounts != sum(not a.included for a in preview.accounts)): |
| 139 | raise CoverageError("COVERAGE_COUNT_MISMATCH") |
| 140 | |
| 141 | accounts = {account.account_code: account for account in preview.accounts} |
| 142 | if len(accounts) != preview.account_count: |
| 143 | raise CoverageError("DUPLICATE_SOURCE_ACCOUNT") |
| 144 | |
| 145 | mappings_by_account: dict[str, list[Any]] = {} |
| 146 | mappings_by_statement: dict[tuple[str, str], list[Any]] = {} |
| 147 | mapping_ids: set[str] = set() |
| 148 | mapping_rows: set[int] = set() |
| 149 | grouped: dict[tuple[str, str, str, str], list[tuple[str, Decimal]]] = {} |
| 150 | |
| 151 | for mapping in preview.mappings: |
| 152 | account = accounts.get(mapping.account_code) |
| 153 | if account is None: |
| 154 | raise CoverageError("MAPPING_TRACE_UNKNOWN_ACCOUNT") |
| 155 | if (mapping.account_name != account.account_name |
| 156 | or mapping.account_excel_row != account.account_excel_row |
| 157 | or mapping.source_row != account.source_row |
| 158 | or _money(mapping.closing_exposure) != _money(account.closing_exposure)): |
| 159 | raise CoverageError("MAPPING_TRACE_SOURCE_MISMATCH") |
| 160 | if (not isinstance(mapping.mapping_id, str) or not mapping.mapping_id |
| 161 | or mapping.mapping_id != mapping.mapping_id.strip() |
| 162 | or type(mapping.mapping_excel_row) is not int |
| 163 | or mapping.mapping_excel_row < 2 |
| 164 | or mapping.mapping_excel_row in mapping_rows): |
| 165 | raise CoverageError("DUPLICATE_MAPPING_TRACE") |
| 166 | if mapping.mapping_id in mapping_ids: |
| 167 | raise CoverageError("DUPLICATE_MAPPING_TRACE") |
| 168 | if mapping.target_statement not in ALLOWED_STATEMENTS: |
| 169 | raise CoverageError("INVALID_MAPPING_TRACE_STATEMENT") |
| 170 | for value in ( |
| 171 | mapping.target_section, mapping.target_note, mapping.target_subnote, |
| 172 | ): |
| 173 | if (not isinstance(value, str) or value != value.strip() |
| 174 | or any(ord(char) < 32 or ord(char) == 127 for char in value)): |
| 175 | raise CoverageError("INVALID_MAPPING_TRACE_TARGET") |
| 176 | if not mapping.target_section or not mapping.target_note: |
| 177 | raise CoverageError("INVALID_MAPPING_TRACE_TARGET") |
| 178 | |
| 179 | mapping_ids.add(mapping.mapping_id) |
| 180 | mapping_rows.add(mapping.mapping_excel_row) |
| 181 | mappings_by_account.setdefault(mapping.account_code, []).append(mapping) |
| 182 | statement_key = (mapping.account_code, mapping.target_statement) |
| 183 | mappings_by_statement.setdefault(statement_key, []).append(mapping) |
| 184 | |
| 185 | for statement_key, items in mappings_by_statement.items(): |
| 186 | if len(items) > 1 and any(item.included for item in items): |
| 187 | raise CoverageError("AMBIGUOUS_MAPPING_INCLUDED") |
| 188 | |
| 189 | for mapping in preview.mappings: |
| 190 | if not mapping.included: |
| 191 | continue |
| 192 | target = _key( |
| 193 | mapping.target_statement, mapping.target_section, |
| 194 | mapping.target_note, mapping.target_subnote, |
| 195 | ) |
| 196 | grouped.setdefault(target, []).append( |
| 197 | (mapping.account_code, _money(mapping.closing_exposure)) |
| 198 | ) |
| 199 | |
| 200 | for account in preview.accounts: |
| 201 | rows = mappings_by_account.get(account.account_code, []) |
| 202 | if (type(account.mapping_count) is not int |
| 203 | or account.mapping_count < 0 |
| 204 | or account.mapping_count != len(rows)): |
| 205 | raise CoverageError("MAPPING_TRACE_COUNT_MISMATCH") |
| 206 | if account.included != any(item.included for item in rows): |
| 207 | raise CoverageError("ACCOUNT_MAPPING_ELIGIBILITY_MISMATCH") |
| 208 | if account.mapping_count == 1: |
| 209 | only = rows[0] |
| 210 | actual = ( |
| 211 | account.mapping_excel_row, account.mapping_id, |
| 212 | account.target_statement, account.target_section, |
| 213 | account.target_note, account.target_subnote, |
| 214 | ) |
| 215 | expected = ( |
| 216 | only.mapping_excel_row, only.mapping_id, |
| 217 | only.target_statement if only.included else None, |
| 218 | only.target_section if only.included else None, |
| 219 | only.target_note if only.included else None, |
| 220 | only.target_subnote if only.included else None, |
| 221 | ) |
| 222 | if actual != expected: |
| 223 | raise CoverageError("ACCOUNT_MAPPING_TRACE_MISMATCH") |
| 224 | elif any(value is not None for value in ( |
| 225 | account.mapping_excel_row, account.mapping_id, |
| 226 | account.target_statement, account.target_section, |
| 227 | account.target_note, account.target_subnote, |
| 228 | )): |
| 229 | raise CoverageError("ACCOUNT_MAPPING_TRACE_MISMATCH") |
| 230 | |
| 231 | source_values = [_money(account.closing_exposure) for account in preview.accounts] |
| 232 | candidate_values = [ |
| 233 | _money(account.closing_exposure) for account in preview.accounts if account.included |
| 234 | ] |
| 235 | blocked_values = [ |
| 236 | _money(account.closing_exposure) for account in preview.accounts if not account.included |
| 237 | ] |
| 238 | note_keys = [ |
| 239 | _key(note.statement, note.section, note.note_number, note.subnote_code) |
| 240 | for note in preview.notes |
| 241 | ] |
| 242 | if len(note_keys) != len(set(note_keys)): |
| 243 | raise CoverageError("DUPLICATE_CANDIDATE_NOTE") |
| 244 | note_by_key = dict(zip(note_keys, preview.notes)) |
| 245 | if set(note_by_key) != set(grouped): |
| 246 | raise CoverageError("COVERAGE_NOTE_MAPPING_MISMATCH") |
| 247 | for target, note in note_by_key.items(): |
| 248 | mapped = grouped[target] |
| 249 | codes = tuple(code for code, _ in mapped) |
| 250 | if (len(codes) != len(set(codes)) |
| 251 | or _money(note.closing_exposure) != _sum_exact( |
| 252 | [amount for _, amount in mapped] |
| 253 | ) |
| 254 | or note.account_codes != codes): |
| 255 | raise CoverageError("COVERAGE_NOTE_MAPPING_MISMATCH") |
| 256 | if (_sum_exact(source_values) != _money(preview.source_closing_exposure) |
| 257 | or _sum_exact(candidate_values) != _money(preview.candidate_closing_exposure) |
| 258 | or _sum_exact(blocked_values) != _money(preview.blocked_closing_exposure) |
| 259 | or _sum_exact(source_values) != _sum_exact([ |
| 260 | _money(preview.candidate_closing_exposure), |
| 261 | _money(preview.blocked_closing_exposure), |
| 262 | ])): |
| 263 | raise CoverageError("COVERAGE_RECONCILIATION_FAILED") |
| 264 | |
| 265 | |
| 266 | def reconcile_workbook_for_review( |
| 267 | content: bytes, *, company_code: str, fiscal_year: int, |
| 268 | references: Sequence[NoteReference], |
| 269 | ) -> ReconciliationReview: |
| 270 | """Compare workbook-marked candidate closings with explicit *untrusted* references. |
| 271 | |
| 272 | The result is at most an analyst review packet, not approval. Strict, |
| 273 | zero-tolerance Decimal matching does not certify any statement semantics. |
| 274 | """ |
| 275 | if not isinstance(references, (tuple, list)) or len(references) > MAX_REFERENCES: |
| 276 | raise CoverageError("INVALID_REFERENCE_COLLECTION") |
| 277 | |
| 278 | normalized: dict[tuple[str, str, str, str], tuple[Decimal, str]] = {} |
| 279 | for ref in references: |
| 280 | if not isinstance(ref, NoteReference): |
| 281 | raise CoverageError("INVALID_REFERENCE_OBJECT") |
| 282 | statement = _text(ref.statement) |
| 283 | if statement not in ALLOWED_STATEMENTS: |
| 284 | raise CoverageError("INVALID_REFERENCE_STATEMENT") |
| 285 | target = _key( |
| 286 | statement, _text(ref.section), _text(ref.note_number), |
| 287 | _text(ref.subnote_code, allow_blank=True), |
| 288 | ) |
| 289 | if target in normalized: |
| 290 | raise CoverageError("DUPLICATE_NOTE_REFERENCE") |
| 291 | normalized[target] = (_money(ref.expected_closing_exposure), _text(ref.evidence_ref)) |
| 292 | |
| 293 | canonical = [ |
| 294 | { |
| 295 | "target": list(target), |
| 296 | "expected_closing_exposure": str(amount), |
| 297 | "evidence_ref": reference, |
| 298 | } |
| 299 | for target, (amount, reference) in sorted(normalized.items()) |
| 300 | ] |
| 301 | reference_hash = sha256( |
| 302 | json.dumps(canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8") |
| 303 | ).hexdigest() |
| 304 | |
| 305 | preview = preview_mapping_coverage( |
| 306 | content, company_code=company_code, fiscal_year=fiscal_year, |
| 307 | ) |
| 308 | _validated_preview(content, preview) |
| 309 | |
| 310 | candidates = { |
| 311 | _key(n.statement, n.section, n.note_number, n.subnote_code): n |
| 312 | for n in preview.notes |
| 313 | } |
| 314 | findings: list[ReviewFinding] = [ |
| 315 | ReviewFinding( |
| 316 | code="BLOCKED_ACCOUNT_" + exception.code, |
| 317 | account_code=exception.account_code, |
| 318 | statement="", section="", note_number="", subnote_code="", |
| 319 | ) for exception in preview.exceptions |
| 320 | ] |
| 321 | |
| 322 | lines: list[ReconciledNote] = [] |
| 323 | for target in sorted(set(candidates) | set(normalized)): |
| 324 | candidate = candidates.get(target) |
| 325 | baseline = normalized.get(target) |
| 326 | actual = _money(candidate.closing_exposure) if candidate is not None else None |
| 327 | expected = baseline[0] if baseline is not None else None |
| 328 | if actual is None: |
| 329 | code = "UNKNOWN_REFERENCE_TARGET" |
| 330 | elif expected is None: |
| 331 | code = "MISSING_NOTE_REFERENCE" |
| 332 | elif actual != expected: |
| 333 | code = "NOTE_EXPOSURE_MISMATCH" |
| 334 | else: |
| 335 | code = None |
| 336 | if code is not None: |
| 337 | findings.append(ReviewFinding( |
| 338 | code=code, account_code="", |
| 339 | statement=target[0], section=target[1], |
| 340 | note_number=target[2], subnote_code=target[3], |
| 341 | )) |
| 342 | difference = None |
| 343 | if actual is not None and expected is not None: |
| 344 | difference = str(_sum_exact([actual, -expected])) |
| 345 | lines.append(ReconciledNote( |
| 346 | statement=target[0], section=target[1], |
| 347 | note_number=target[2], subnote_code=target[3], |
| 348 | candidate_closing_exposure=str(actual) if actual is not None else None, |
| 349 | reference_closing_exposure=str(expected) if expected is not None else None, |
| 350 | difference=difference, evidence_ref=baseline[1] if baseline else None, |
| 351 | matched=code is None, |
| 352 | )) |
| 353 | |
| 354 | if preview.blocked_accounts > 0 and not preview.exceptions: |
| 355 | raise CoverageError("BLOCKED_ACCOUNTS_UNEXPLAINED") |
| 356 | return ReconciliationReview( |
| 357 | source_sha256=preview.source_sha256, reference_sha256=reference_hash, |
| 358 | company_code=preview.company_code, fiscal_year=preview.fiscal_year, |
| 359 | account_count=preview.account_count, |
| 360 | candidate_mapped_accounts=preview.candidate_mapped_accounts, |
| 361 | blocked_accounts=preview.blocked_accounts, |
| 362 | source_closing_exposure=preview.source_closing_exposure, |
| 363 | candidate_closing_exposure=preview.candidate_closing_exposure, |
| 364 | blocked_closing_exposure=preview.blocked_closing_exposure, |
| 365 | notes=tuple(lines), |
| 366 | findings=tuple(sorted( |
| 367 | findings, key=lambda f: ( |
| 368 | f.account_code, f.statement, f.section, |
| 369 | f.note_number, f.subnote_code, f.code, |
| 370 | ) |
| 371 | )), |
| 372 | matched_for_analyst_review=not findings and preview.blocked_accounts == 0 |
| 373 | and bool(lines), |
| 374 | ) |