Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 19:15 UTC
codex/aram-reconciliation-review-gate-20261031
add-index-html-10623938925177053894
arena/094f314c-aram
arena/2d4eda07-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
dependabot/github_actions/actions/setup-node-6
dependabot/github_actions/actions/setup-python-7
dependabot/github_actions/actions/upload-artifact-7
dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1
dependabot/npm_and_yarn/frontend/vite-8.4.0
dependabot/npm_and_yarn/frontend/vitest-5.1.2
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 (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 | raise CoverageError("COVERAGE_COUNT_MISMATCH") |
| 139 | if len({account.account_code for account in preview.accounts}) != preview.account_count: |
| 140 | raise CoverageError("DUPLICATE_SOURCE_ACCOUNT") |
| 141 | source_values = [_money(a.closing_exposure) for a in preview.accounts] |
| 142 | candidate_values = [ |
| 143 | _money(a.closing_exposure) for a in preview.accounts if a.included |
| 144 | ] |
| 145 | blocked_values = [ |
| 146 | _money(a.closing_exposure) for a in preview.accounts if not a.included |
| 147 | ] |
| 148 | note_values = [_money(n.closing_exposure) for n in preview.notes] |
| 149 | if (len(preview.notes) != len({ |
| 150 | _key(n.statement, n.section, n.note_number, n.subnote_code) |
| 151 | for n in preview.notes |
| 152 | })): |
| 153 | raise CoverageError("DUPLICATE_CANDIDATE_NOTE") |
| 154 | if (_sum_exact(source_values) != _money(preview.source_closing_exposure) |
| 155 | or _sum_exact(candidate_values) != _money(preview.candidate_closing_exposure) |
| 156 | or _sum_exact(blocked_values) != _money(preview.blocked_closing_exposure) |
| 157 | or _sum_exact(note_values) != _sum_exact(candidate_values)): |
| 158 | raise CoverageError("COVERAGE_RECONCILIATION_FAILED") |
| 159 | |
| 160 | |
| 161 | def reconcile_workbook_for_review( |
| 162 | content: bytes, *, company_code: str, fiscal_year: int, |
| 163 | references: Sequence[NoteReference], |
| 164 | ) -> ReconciliationReview: |
| 165 | """Compare workbook-marked candidate closings with explicit *untrusted* references. |
| 166 | |
| 167 | The result is at most an analyst review packet, not approval. Strict, |
| 168 | zero-tolerance Decimal matching does not certify any statement semantics. |
| 169 | """ |
| 170 | if not isinstance(references, (tuple, list)) or len(references) > MAX_REFERENCES: |
| 171 | raise CoverageError("INVALID_REFERENCE_COLLECTION") |
| 172 | |
| 173 | normalized: dict[tuple[str, str, str, str], tuple[Decimal, str]] = {} |
| 174 | for ref in references: |
| 175 | if not isinstance(ref, NoteReference): |
| 176 | raise CoverageError("INVALID_REFERENCE_OBJECT") |
| 177 | statement = _text(ref.statement) |
| 178 | if statement not in ALLOWED_STATEMENTS: |
| 179 | raise CoverageError("INVALID_REFERENCE_STATEMENT") |
| 180 | target = _key( |
| 181 | statement, _text(ref.section), _text(ref.note_number), |
| 182 | _text(ref.subnote_code, allow_blank=True), |
| 183 | ) |
| 184 | if target in normalized: |
| 185 | raise CoverageError("DUPLICATE_NOTE_REFERENCE") |
| 186 | normalized[target] = (_money(ref.expected_closing_exposure), _text(ref.evidence_ref)) |
| 187 | |
| 188 | canonical = [ |
| 189 | { |
| 190 | "target": list(target), |
| 191 | "expected_closing_exposure": str(amount), |
| 192 | "evidence_ref": reference, |
| 193 | } |
| 194 | for target, (amount, reference) in sorted(normalized.items()) |
| 195 | ] |
| 196 | reference_hash = sha256( |
| 197 | json.dumps(canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8") |
| 198 | ).hexdigest() |
| 199 | |
| 200 | preview = preview_mapping_coverage( |
| 201 | content, company_code=company_code, fiscal_year=fiscal_year, |
| 202 | ) |
| 203 | _validated_preview(content, preview) |
| 204 | |
| 205 | candidates = { |
| 206 | _key(n.statement, n.section, n.note_number, n.subnote_code): n |
| 207 | for n in preview.notes |
| 208 | } |
| 209 | findings: list[ReviewFinding] = [ |
| 210 | ReviewFinding( |
| 211 | code="BLOCKED_ACCOUNT_" + exception.code, |
| 212 | account_code=exception.account_code, |
| 213 | statement="", section="", note_number="", subnote_code="", |
| 214 | ) for exception in preview.exceptions |
| 215 | ] |
| 216 | |
| 217 | lines: list[ReconciledNote] = [] |
| 218 | for target in sorted(set(candidates) | set(normalized)): |
| 219 | candidate = candidates.get(target) |
| 220 | baseline = normalized.get(target) |
| 221 | actual = _money(candidate.closing_exposure) if candidate is not None else None |
| 222 | expected = baseline[0] if baseline is not None else None |
| 223 | if actual is None: |
| 224 | code = "UNKNOWN_REFERENCE_TARGET" |
| 225 | elif expected is None: |
| 226 | code = "MISSING_NOTE_REFERENCE" |
| 227 | elif actual != expected: |
| 228 | code = "NOTE_EXPOSURE_MISMATCH" |
| 229 | else: |
| 230 | code = None |
| 231 | if code is not None: |
| 232 | findings.append(ReviewFinding( |
| 233 | code=code, account_code="", |
| 234 | statement=target[0], section=target[1], |
| 235 | note_number=target[2], subnote_code=target[3], |
| 236 | )) |
| 237 | difference = None |
| 238 | if actual is not None and expected is not None: |
| 239 | difference = str(_sum_exact([actual, -expected])) |
| 240 | lines.append(ReconciledNote( |
| 241 | statement=target[0], section=target[1], |
| 242 | note_number=target[2], subnote_code=target[3], |
| 243 | candidate_closing_exposure=str(actual) if actual is not None else None, |
| 244 | reference_closing_exposure=str(expected) if expected is not None else None, |
| 245 | difference=difference, evidence_ref=baseline[1] if baseline else None, |
| 246 | matched=code is None, |
| 247 | )) |
| 248 | |
| 249 | if preview.blocked_accounts > 0 and not preview.exceptions: |
| 250 | raise CoverageError("BLOCKED_ACCOUNTS_UNEXPLAINED") |
| 251 | return ReconciliationReview( |
| 252 | source_sha256=preview.source_sha256, reference_sha256=reference_hash, |
| 253 | company_code=preview.company_code, fiscal_year=preview.fiscal_year, |
| 254 | account_count=preview.account_count, |
| 255 | candidate_mapped_accounts=preview.candidate_mapped_accounts, |
| 256 | blocked_accounts=preview.blocked_accounts, |
| 257 | source_closing_exposure=preview.source_closing_exposure, |
| 258 | candidate_closing_exposure=preview.candidate_closing_exposure, |
| 259 | blocked_closing_exposure=preview.blocked_closing_exposure, |
| 260 | notes=tuple(lines), |
| 261 | findings=tuple(sorted( |
| 262 | findings, key=lambda f: ( |
| 263 | f.account_code, f.statement, f.section, |
| 264 | f.note_number, f.subnote_code, f.code, |
| 265 | ) |
| 266 | )), |
| 267 | matched_for_analyst_review=not findings and preview.blocked_accounts == 0 |
| 268 | and bool(lines), |
| 269 | ) |