codex/aram-five-statement-integration-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 161 lines 7.25 KB
Raw
1 """Bounded local-only CLI for paired direct-method cash flow preview."""
2 from __future__ import annotations
3
4 import argparse
5 import json
6 import os
7 from pathlib import Path
8 import stat
9 import sys
10 from typing import Any
11
12 from aram_backend.cash_flow_direct_candidate import (
13 MAX_CASH_ACCOUNTS, MAX_CASH_COUNTERPART_POLICIES,
14 MAX_CASH_TRANSACTIONS, CashAccountPolicy, CashCounterpartPolicy,
15 CashFlowEntry, build_direct_cash_flow_candidate,
16 )
17 from aram_backend.coverage_preview import CoverageError
18 from aram_backend.coverage_preview_cli import safe_read_workbook
19 from aram_backend.reconciliation_review_cli import _strict_pairs
20
21 MAX_CASH_MANIFEST_BYTES = 20 * 1024 * 1024
22 ROOT_FIELDS = frozenset({
23 "schema_version", "company_code", "fiscal_year", "currency", "unit",
24 "cash_accounts", "counterpart_policies", "transactions",
25 })
26 CASH_POLICY_FIELDS = frozenset({"account_code", "evidence_ref"})
27 COUNTERPART_POLICY_FIELDS = frozenset({"account_code", "activity", "evidence_ref"})
28 TRANSACTION_FIELDS = frozenset({
29 "company_code", "fiscal_year", "line_id", "transaction_id", "posting_date",
30 "cash_account_code", "counterpart_account_code", "cash_debit", "cash_credit",
31 "counterpart_debit", "counterpart_credit", "evidence_ref",
32 })
33
34
35 def safe_read_cash_manifest(filename: str) -> bytes:
36 """Read one bounded, stable regular JSON file without following symlinks."""
37 path = Path(filename)
38 if path.suffix.lower() != ".json":
39 raise CoverageError("CASH_MANIFEST_JSON_REQUIRED")
40 try:
41 before = path.lstat()
42 if not stat.S_ISREG(before.st_mode):
43 raise CoverageError("CASH_MANIFEST_NOT_REGULAR_FILE")
44 if not 0 < before.st_size <= MAX_CASH_MANIFEST_BYTES:
45 raise CoverageError("CASH_MANIFEST_SIZE_INVALID")
46 flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
47 fd = os.open(path, flags)
48 with os.fdopen(fd, "rb") as stream:
49 opened = os.fstat(stream.fileno())
50 immediate = path.lstat()
51 if (not stat.S_ISREG(opened.st_mode)
52 or not stat.S_ISREG(immediate.st_mode)
53 or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino)
54 or (immediate.st_dev, immediate.st_ino) != (before.st_dev, before.st_ino)):
55 raise CoverageError("CASH_MANIFEST_CHANGED")
56 content = stream.read(MAX_CASH_MANIFEST_BYTES + 1)
57 finished = os.fstat(stream.fileno())
58 after = path.lstat()
59 if (not stat.S_ISREG(after.st_mode)
60 or (after.st_dev, after.st_ino) != (opened.st_dev, opened.st_ino)
61 or opened.st_size != finished.st_size
62 or opened.st_mtime_ns != finished.st_mtime_ns
63 or after.st_size != finished.st_size
64 or after.st_mtime_ns != finished.st_mtime_ns):
65 raise CoverageError("CASH_MANIFEST_CHANGED")
66 except CoverageError:
67 raise
68 except OSError as exc:
69 raise CoverageError("CASH_MANIFEST_READ_FAILED") from exc
70 if not 0 < len(content) <= MAX_CASH_MANIFEST_BYTES:
71 raise CoverageError("CASH_MANIFEST_SIZE_INVALID")
72 return content
73
74
75 def parse_cash_manifest(content: bytes):
76 if (not isinstance(content, bytes)
77 or not 0 < len(content) <= MAX_CASH_MANIFEST_BYTES):
78 raise CoverageError("CASH_MANIFEST_SIZE_INVALID")
79 try:
80 payload = json.loads(content.decode("utf-8"), object_pairs_hook=_strict_pairs)
81 except CoverageError:
82 raise
83 except (UnicodeError, ValueError, RecursionError) as exc:
84 raise CoverageError("CASH_MANIFEST_JSON_INVALID") from exc
85 if not isinstance(payload, dict) or set(payload) != ROOT_FIELDS:
86 raise CoverageError("CASH_MANIFEST_SCHEMA_INVALID")
87 if type(payload["schema_version"]) is not int or payload["schema_version"] != 1:
88 raise CoverageError("CASH_MANIFEST_VERSION_INVALID")
89 company = payload["company_code"]
90 if (not isinstance(company, str) or not company or company != company.strip()
91 or len(company) > 64 or any(ord(char) < 32 for char in company)):
92 raise CoverageError("CASH_MANIFEST_COMPANY_INVALID")
93 year = payload["fiscal_year"]
94 if type(year) is not int or year <= 0:
95 raise CoverageError("CASH_MANIFEST_YEAR_INVALID")
96 currency, unit = payload["currency"], payload["unit"]
97 if not isinstance(currency, str) or not currency or not isinstance(unit, str) or not unit:
98 raise CoverageError("CASH_MANIFEST_CURRENCY_UNIT_INVALID")
99
100 cash_items = payload["cash_accounts"]
101 if (not isinstance(cash_items, list)
102 or not 0 < len(cash_items) <= MAX_CASH_ACCOUNTS):
103 raise CoverageError("CASH_MANIFEST_CASH_ACCOUNTS_INVALID")
104 cash_accounts = []
105 for item in cash_items:
106 if not isinstance(item, dict) or set(item) != CASH_POLICY_FIELDS:
107 raise CoverageError("CASH_MANIFEST_CASH_POLICY_INVALID")
108 cash_accounts.append(CashAccountPolicy(**item))
109
110 counterpart_items = payload["counterpart_policies"]
111 if (not isinstance(counterpart_items, list)
112 or len(counterpart_items) > MAX_CASH_COUNTERPART_POLICIES):
113 raise CoverageError("CASH_MANIFEST_COUNTERPART_POLICIES_INVALID")
114 counterpart_policies = []
115 for item in counterpart_items:
116 if not isinstance(item, dict) or set(item) != COUNTERPART_POLICY_FIELDS:
117 raise CoverageError("CASH_MANIFEST_COUNTERPART_POLICY_INVALID")
118 counterpart_policies.append(CashCounterpartPolicy(**item))
119
120 transaction_items = payload["transactions"]
121 if (not isinstance(transaction_items, list)
122 or len(transaction_items) > MAX_CASH_TRANSACTIONS):
123 raise CoverageError("CASH_MANIFEST_TRANSACTIONS_INVALID")
124 transactions = []
125 for item in transaction_items:
126 if not isinstance(item, dict) or set(item) != TRANSACTION_FIELDS:
127 raise CoverageError("CASH_MANIFEST_TRANSACTION_INVALID")
128 transactions.append(CashFlowEntry(**item))
129 return (
130 company, year, currency, unit, tuple(cash_accounts),
131 tuple(counterpart_policies), tuple(transactions),
132 )
133
134
135 def main(argv: list[str] | None = None) -> int:
136 parser = argparse.ArgumentParser(
137 description="ARAM offline NONOFFICIAL direct-method cash flow diagnostic"
138 )
139 parser.add_argument("--file", required=True, help="Local Pilot XLSX snapshot")
140 parser.add_argument("--manifest", required=True, help="Paired cash transaction JSON")
141 args = parser.parse_args(argv)
142 try:
143 (
144 company, year, currency, unit, cash_accounts,
145 counterpart_policies, transactions,
146 ) = parse_cash_manifest(safe_read_cash_manifest(args.manifest))
147 source = safe_read_workbook(args.file)
148 result = build_direct_cash_flow_candidate(
149 source, company_code=company, fiscal_year=year,
150 currency=currency, unit=unit, cash_accounts=cash_accounts,
151 counterpart_policies=counterpart_policies, transactions=transactions,
152 )
153 except CoverageError as exc:
154 print("ARAM direct cash flow candidate blocked: " + exc.code, file=sys.stderr)
155 return 2
156 print(json.dumps(result.to_dict(), ensure_ascii=True, sort_keys=True))
157 return 0 if result.eligible_for_analyst_review else 3
158
159
160 if __name__ == "__main__":
161 raise SystemExit(main())