codex/windows-native-pilot-shell-20261030
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 | """Read-only Mapping batch classification: no writes, identities or approvals. |
| 2 | |
| 3 | Rows here are canonical proposal entries supplied by a trusted future adapter, |
| 4 | not evidence that an XLSX is authorized. The module MUST NOT call save_mapping_rule. |
| 5 | """ |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | from dataclasses import asdict, dataclass |
| 9 | from hashlib import sha256 |
| 10 | import json |
| 11 | from unicodedata import category |
| 12 | |
| 13 | from sqlalchemy.orm import Session |
| 14 | |
| 15 | from aram_backend.mapping_change_preview import ( |
| 16 | MappingChangePreview, MappingNoChange, _require_clean_mapping_state, |
| 17 | preview_mapping_change, |
| 18 | ) |
| 19 | from aram_backend.mapping_service import MappingValidationError |
| 20 | from aram_backend.models import FiscalYear, FiscalYearStatus |
| 21 | |
| 22 | MAX_BATCH_ROWS = 10_000 |
| 23 | MAX_LOCATOR_LENGTH = 256 |
| 24 | |
| 25 | |
| 26 | @dataclass(frozen=True) |
| 27 | class ProposedMappingRow: |
| 28 | source_locator: str |
| 29 | rule_key: str |
| 30 | account_code: str |
| 31 | target_note_id: int |
| 32 | mapping_type: str |
| 33 | expected_base_version: int |
| 34 | |
| 35 | |
| 36 | @dataclass(frozen=True) |
| 37 | class MappingBatchRowResult: |
| 38 | source_locator: str |
| 39 | rule_key: str |
| 40 | status: str |
| 41 | preview: MappingChangePreview | None = None |
| 42 | duplicate_of: str | None = None |
| 43 | reason: str | None = None |
| 44 | |
| 45 | |
| 46 | @dataclass(frozen=True) |
| 47 | class MappingBatchPreview: |
| 48 | year_id: int |
| 49 | rows: tuple[MappingBatchRowResult, ...] |
| 50 | fingerprint: str |
| 51 | # Exact submitted typed evidence, not an authentication token. |
| 52 | # Required to replay and revalidate every row before later review. |
| 53 | source_rows: tuple[ProposedMappingRow, ...] |
| 54 | |
| 55 | @property |
| 56 | def counts(self) -> dict[str, int]: |
| 57 | counts: dict[str, int] = {} |
| 58 | for item in self.rows: |
| 59 | counts[item.status] = counts.get(item.status, 0) + 1 |
| 60 | return counts |
| 61 | |
| 62 | @property |
| 63 | def has_changes(self) -> bool: |
| 64 | return any(item.status in ("new", "changed") for item in self.rows) |
| 65 | |
| 66 | @property |
| 67 | def ready_for_review(self) -> bool: |
| 68 | return self.has_changes and all( |
| 69 | item.status in ("new", "changed", "unchanged", "coalesced") |
| 70 | for item in self.rows |
| 71 | ) |
| 72 | |
| 73 | |
| 74 | def _row_content(row: ProposedMappingRow) -> tuple[object, ...]: |
| 75 | # Python considers True == 1. Financial identity comparisons must not |
| 76 | # coalesce malformed booleans with valid numeric IDs or versions. |
| 77 | values = (row.account_code, row.target_note_id, row.mapping_type, row.expected_base_version) |
| 78 | return tuple((type(value).__name__, value) for value in values) |
| 79 | |
| 80 | |
| 81 | def _validate_envelope(rows: object) -> tuple[ProposedMappingRow, ...]: |
| 82 | if type(rows) not in (list, tuple) or not 0 < len(rows) <= MAX_BATCH_ROWS: |
| 83 | raise MappingValidationError("mapping batch requires 1 to 10000 rows") |
| 84 | locators: set[str] = set() |
| 85 | for row in rows: |
| 86 | if not isinstance(row, ProposedMappingRow): |
| 87 | raise MappingValidationError("mapping batch entries must be typed proposals") |
| 88 | locator = row.source_locator |
| 89 | if (not isinstance(locator, str) or not locator or |
| 90 | len(locator) > MAX_LOCATOR_LENGTH or locator != locator.strip() |
| 91 | or any(category(char) in ("Cc", "Cf", "Cs") for char in locator)): |
| 92 | raise MappingValidationError("invalid source locator") |
| 93 | if locator in locators: |
| 94 | raise MappingValidationError("duplicate source locator") |
| 95 | locators.add(locator) |
| 96 | return tuple(rows) |
| 97 | |
| 98 | |
| 99 | def preview_mapping_batch( |
| 100 | session: Session, *, year_id: int, rows: list[ProposedMappingRow] | tuple[ProposedMappingRow, ...], |
| 101 | ) -> MappingBatchPreview: |
| 102 | """Classify every row; conflict/invalid entries block the WHOLE batch. |
| 103 | |
| 104 | A successful preview is *not* an approval token or a transaction lock. |
| 105 | No mapping is automatically committed, and excluded source rules are not |
| 106 | interpreted as removals. Explicit reviewer approval/apply is not built yet. |
| 107 | """ |
| 108 | if type(year_id) is not int or year_id <= 0: |
| 109 | raise MappingValidationError("year_id must be a positive integer") |
| 110 | entries = _validate_envelope(rows) |
| 111 | |
| 112 | with session.no_autoflush: |
| 113 | _require_clean_mapping_state(session) |
| 114 | year = session.get(FiscalYear, year_id, populate_existing=True) |
| 115 | if year is None or year.status is not FiscalYearStatus.DRAFT: |
| 116 | raise MappingValidationError("fiscal year must exist and be Draft") |
| 117 | |
| 118 | by_key: dict[str, list[int]] = {} |
| 119 | for index, entry in enumerate(entries): |
| 120 | # Invalid key types are reported as invalid rows; they never |
| 121 | # participate in accidental equality-based coalescing. |
| 122 | if isinstance(entry.rule_key, str): |
| 123 | by_key.setdefault(entry.rule_key, []).append(index) |
| 124 | |
| 125 | conflicting: set[int] = set() |
| 126 | for group in by_key.values(): |
| 127 | if len(group) > 1 and any( |
| 128 | _row_content(entries[position]) != _row_content(entries[group[0]]) |
| 129 | for position in group[1:] |
| 130 | ): |
| 131 | conflicting.update(group) |
| 132 | |
| 133 | first_by_key: dict[str, MappingBatchRowResult] = {} |
| 134 | results: list[MappingBatchRowResult] = [] |
| 135 | for index, entry in enumerate(entries): |
| 136 | source = entry.source_locator |
| 137 | if index in conflicting: |
| 138 | result = MappingBatchRowResult( |
| 139 | source, str(entry.rule_key), "conflict", |
| 140 | reason="conflicting source rows for the same rule key", |
| 141 | ) |
| 142 | elif isinstance(entry.rule_key, str) and entry.rule_key in first_by_key: |
| 143 | original = first_by_key[entry.rule_key] |
| 144 | if original.status == "invalid": |
| 145 | result = MappingBatchRowResult( |
| 146 | source, entry.rule_key, "invalid", |
| 147 | reason=f"duplicate of invalid {original.source_locator}: {original.reason}", |
| 148 | ) |
| 149 | else: |
| 150 | result = MappingBatchRowResult( |
| 151 | source, entry.rule_key, "coalesced", |
| 152 | duplicate_of=original.source_locator, |
| 153 | ) |
| 154 | else: |
| 155 | try: |
| 156 | preview = preview_mapping_change( |
| 157 | session, year_id=year_id, rule_key=entry.rule_key, |
| 158 | account_code=entry.account_code, |
| 159 | target_note_id=entry.target_note_id, |
| 160 | mapping_type=entry.mapping_type, |
| 161 | expected_base_version=entry.expected_base_version, |
| 162 | allow_unchanged=True, |
| 163 | ) |
| 164 | except MappingNoChange: |
| 165 | # Defensive compatibility: only the single-item API is |
| 166 | # expected to raise no-change with allow_unchanged=False. |
| 167 | result = MappingBatchRowResult(source, str(entry.rule_key), "invalid", |
| 168 | reason="missing unchanged state evidence") |
| 169 | except MappingValidationError as exc: |
| 170 | result = MappingBatchRowResult( |
| 171 | source, str(entry.rule_key), "invalid", reason=str(exc), |
| 172 | ) |
| 173 | else: |
| 174 | unchanged = preview.before is not None and ( |
| 175 | preview.before.account_code, preview.before.target_note_id, |
| 176 | preview.before.mapping_type, |
| 177 | ) == ( |
| 178 | preview.proposed.account_code, preview.proposed.target_note_id, |
| 179 | preview.proposed.mapping_type, |
| 180 | ) |
| 181 | result = MappingBatchRowResult( |
| 182 | source, entry.rule_key, |
| 183 | "unchanged" if unchanged else ( |
| 184 | "new" if preview.before is None else "changed" |
| 185 | ), |
| 186 | # Keep full catalog and rule version snapshot even for |
| 187 | # unchanged rows so later changes cannot go unnoticed. |
| 188 | preview=preview, |
| 189 | ) |
| 190 | if isinstance(entry.rule_key, str): |
| 191 | first_by_key.setdefault(entry.rule_key, result) |
| 192 | results.append(result) |
| 193 | |
| 194 | stable = [ |
| 195 | { |
| 196 | "source_locator": item.source_locator, |
| 197 | "rule_key": item.rule_key, |
| 198 | "status": item.status, |
| 199 | "duplicate_of": item.duplicate_of, |
| 200 | "reason": item.reason, |
| 201 | "preview": asdict(item.preview) if item.preview is not None else None, |
| 202 | } |
| 203 | for item in results |
| 204 | ] |
| 205 | fingerprint = sha256( |
| 206 | json.dumps( |
| 207 | {"year_id": year_id, "rows": stable}, |
| 208 | sort_keys=True, separators=(",", ":"), ensure_ascii=True, |
| 209 | ).encode("utf-8") |
| 210 | ).hexdigest() |
| 211 | return MappingBatchPreview( |
| 212 | year_id=year_id, rows=tuple(results), fingerprint=fingerprint, |
| 213 | source_rows=entries, |
| 214 | ) |
| 215 | |
| 216 | |
| 217 | def verify_mapping_batch_current(session: Session, snapshot: MappingBatchPreview) -> None: |
| 218 | """Fail closed if ANY source row, catalog or result changed after preview. |
| 219 | |
| 220 | Read-only verifier; it is neither authenticated approval nor authorization |
| 221 | to write. Never replace a reviewed snapshot with a refreshed one silently. |
| 222 | """ |
| 223 | if not isinstance(snapshot, MappingBatchPreview): |
| 224 | raise MappingValidationError("invalid mapping batch snapshot") |
| 225 | if not snapshot.ready_for_review: |
| 226 | raise MappingValidationError("mapping batch is not ready for review") |
| 227 | try: |
| 228 | current = preview_mapping_batch( |
| 229 | session, year_id=snapshot.year_id, rows=snapshot.source_rows, |
| 230 | ) |
| 231 | except (MappingValidationError, TypeError, ValueError) as exc: |
| 232 | raise MappingValidationError("mapping batch review is stale or invalid") from exc |
| 233 | if current != snapshot or not current.ready_for_review: |
| 234 | raise MappingValidationError("mapping batch review is stale or altered") |
| 235 |