codex/aram-mapping-source-parser-20261101
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 137 lines 5.66 KB
Raw
1 """Offline CLI for non-official read-only note exposure reconciliation.
2
3 Usage: python -m aram_backend.reconciliation_review_cli \
4 --file synthetic.xlsx --references synthetic_references.json
5
6 Returns 0 only for analyst-review matched exposure, 3 for a blocking
7 reconciliation finding, and 2 for malformed/unreadable inputs. NEVER creates
8 approved statements or edits source files.
9 """
10 from __future__ import annotations
11
12 import argparse
13 import json
14 import os
15 from pathlib import Path
16 import stat
17 import sys
18 from typing import Any
19
20 from aram_backend.coverage_preview import CoverageError
21 from aram_backend.coverage_preview_cli import safe_read_workbook
22 from aram_backend.reconciliation_review import (
23 NoteReference, reconcile_workbook_for_review,
24 )
25
26 MAX_MANIFEST_BYTES = 512 * 1024
27 EXPECTED_ROOT_KEYS = frozenset({
28 "schema_version", "company_code", "fiscal_year", "references",
29 })
30 EXPECTED_REFERENCE_KEYS = frozenset({
31 "statement", "section", "note_number", "subnote_code",
32 "expected_closing_exposure", "evidence_ref",
33 })
34
35
36 def _strict_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
37 result = {}
38 for key, value in pairs:
39 if key in result:
40 raise CoverageError("DUPLICATE_MANIFEST_KEY")
41 result[key] = value
42 return result
43
44
45 def safe_read_manifest(filename: str) -> bytes:
46 """Read a bounded, unchanged local regular JSON file without symlinks."""
47 path = Path(filename)
48 if path.suffix.lower() != ".json":
49 raise CoverageError("JSON_MANIFEST_REQUIRED")
50 try:
51 first = path.lstat()
52 if not stat.S_ISREG(first.st_mode):
53 raise CoverageError("MANIFEST_NOT_REGULAR_FILE")
54 if not 0 < first.st_size <= MAX_MANIFEST_BYTES:
55 raise CoverageError("MANIFEST_SIZE_INVALID")
56 flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
57 fd = os.open(path, flags)
58 with os.fdopen(fd, "rb") as stream:
59 opened = os.fstat(stream.fileno())
60 immediate = path.lstat()
61 if (not stat.S_ISREG(opened.st_mode)
62 or not stat.S_ISREG(immediate.st_mode)
63 or (opened.st_dev, opened.st_ino) != (first.st_dev, first.st_ino)
64 or (immediate.st_dev, immediate.st_ino) != (first.st_dev, first.st_ino)):
65 raise CoverageError("MANIFEST_CHANGED")
66 content = stream.read(MAX_MANIFEST_BYTES + 1)
67 finished = os.fstat(stream.fileno())
68 last = path.lstat()
69 if (not stat.S_ISREG(last.st_mode)
70 or (last.st_dev, last.st_ino) != (first.st_dev, first.st_ino)
71 or opened.st_size != finished.st_size
72 or opened.st_mtime_ns != finished.st_mtime_ns
73 or last.st_size != finished.st_size
74 or last.st_mtime_ns != finished.st_mtime_ns):
75 raise CoverageError("MANIFEST_CHANGED")
76 except CoverageError:
77 raise
78 except OSError as exc:
79 raise CoverageError("MANIFEST_READ_FAILED") from exc
80 if not 0 < len(content) <= MAX_MANIFEST_BYTES:
81 raise CoverageError("MANIFEST_SIZE_INVALID")
82 return content
83
84
85 def parse_manifest(content: bytes) -> tuple[str, int, tuple[NoteReference, ...]]:
86 if not isinstance(content, bytes) or not 0 < len(content) <= MAX_MANIFEST_BYTES:
87 raise CoverageError("MANIFEST_SIZE_INVALID")
88 try:
89 document = json.loads(content.decode("utf-8"), object_pairs_hook=_strict_pairs)
90 except CoverageError:
91 raise
92 except (UnicodeError, ValueError, RecursionError) as exc:
93 raise CoverageError("INVALID_MANIFEST_JSON") from exc
94 if not isinstance(document, dict) or set(document) != EXPECTED_ROOT_KEYS:
95 raise CoverageError("INVALID_MANIFEST_SCHEMA")
96 if type(document["schema_version"]) is not int or document["schema_version"] != 1:
97 raise CoverageError("INVALID_MANIFEST_VERSION")
98 company = document["company_code"]
99 if (not isinstance(company, str) or not company or company != company.strip()
100 or len(company) > 64 or any(ord(ch) < 32 for ch in company)):
101 raise CoverageError("INVALID_MANIFEST_COMPANY")
102 if type(document["fiscal_year"]) is not int or document["fiscal_year"] <= 0:
103 raise CoverageError("INVALID_MANIFEST_YEAR")
104 entries = document["references"]
105 if not isinstance(entries, list) or len(entries) > 10_000:
106 raise CoverageError("INVALID_MANIFEST_REFERENCES")
107 refs: list[NoteReference] = []
108 for item in entries:
109 if not isinstance(item, dict) or set(item) != EXPECTED_REFERENCE_KEYS:
110 raise CoverageError("INVALID_MANIFEST_REFERENCE")
111 refs.append(NoteReference(**item))
112 return document["company_code"], document["fiscal_year"], tuple(refs)
113
114
115 def main(argv: list[str] | None = None) -> int:
116 parser = argparse.ArgumentParser(
117 description="ARAM offline UNAPPROVED note reconciliation diagnostic"
118 )
119 parser.add_argument("--file", required=True, help="Local authorized Pilot XLSX")
120 parser.add_argument("--references", required=True, help="Local synthetic control totals JSON")
121 options = parser.parse_args(argv)
122 try:
123 company, year, refs = parse_manifest(safe_read_manifest(options.references))
124 workbook = safe_read_workbook(options.file)
125 result = reconcile_workbook_for_review(
126 workbook, company_code=company, fiscal_year=year,
127 references=refs,
128 )
129 except CoverageError as exc:
130 print("ARAM note review blocked: " + exc.code, file=sys.stderr)
131 return 2
132 print(json.dumps(result.to_dict(), ensure_ascii=True, sort_keys=True))
133 return 0 if result.matched_for_analyst_review else 3
134
135
136 if __name__ == "__main__":
137 raise SystemExit(main())