codex/aram-windows-statement-figures-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 360 lines 15.8 KB
Raw
1 """Strict offline CLI for the five-statement nonofficial pipeline."""
2 from __future__ import annotations
3
4 import argparse
5 import json
6 import sys
7 from dataclasses import dataclass
8 from typing import Any
9
10 from aram_backend.balance_sheet_candidate import BalanceSheetLinePolicy
11 from aram_backend.cash_flow_direct_candidate import (
12 MAX_CASH_ACCOUNTS, MAX_CASH_COUNTERPART_POLICIES, MAX_CASH_TRANSACTIONS,
13 CashAccountPolicy, CashCounterpartPolicy, CashFlowEntry,
14 )
15 from aram_backend.cash_flow_direct_candidate_cli import (
16 MAX_CASH_MANIFEST_BYTES, safe_read_cash_manifest,
17 )
18 from aram_backend.coverage_preview import CoverageError
19 from aram_backend.coverage_preview_cli import safe_read_workbook
20 from aram_backend.cross_statement_reconciliation import CashBalanceNoteSelection
21 from aram_backend.equity_changes_candidate import EquityMovementPolicy
22 from aram_backend.five_statement_pipeline import (
23 FiveStatementPipelineResult, build_five_statement_pipeline,
24 )
25 from aram_backend.income_statement_candidate import IncomeStatementLinePolicy
26 from aram_backend.reconciliation_review import NoteReference, _money
27 from aram_backend.reconciliation_review_cli import _strict_pairs
28
29
30 ROOT_FIELDS = frozenset({
31 "schema_version", "company_code", "fiscal_year", "currency", "unit",
32 "references", "balance_sheet_policies", "income_statement_policies",
33 "equity_movement_policies", "cash_accounts", "counterpart_policies",
34 "transactions", "cash_balance_notes",
35 })
36 REFERENCE_FIELDS = frozenset({
37 "statement", "section", "note_number", "subnote_code",
38 "expected_closing_exposure", "evidence_ref",
39 })
40 BS_POLICY_FIELDS = frozenset({
41 "statement_section", "note_number", "subnote_code", "category",
42 "sign_multiplier", "line_label", "policy_evidence_ref",
43 })
44 IS_POLICY_FIELDS = BS_POLICY_FIELDS
45 EQ_POLICY_FIELDS = frozenset({
46 "statement_section", "note_number", "subnote_code", "equity_component",
47 "movement_category", "sign_multiplier", "line_label", "policy_evidence_ref",
48 })
49 CASH_ACCOUNT_FIELDS = frozenset({"account_code", "evidence_ref"})
50 COUNTERPART_FIELDS = frozenset({"account_code", "activity", "evidence_ref"})
51 TRANSACTION_FIELDS = frozenset({
52 "company_code", "fiscal_year", "line_id", "transaction_id", "posting_date",
53 "cash_account_code", "counterpart_account_code", "cash_debit", "cash_credit",
54 "counterpart_debit", "counterpart_credit", "evidence_ref",
55 })
56 CASH_NOTE_FIELDS = frozenset({
57 "statement_section", "note_number", "subnote_code", "evidence_ref",
58 })
59 MAX_POLICY_ROWS = 10_000
60
61
62 @dataclass(frozen=True)
63 class ParsedPipelineManifest:
64 company_code: str
65 fiscal_year: int
66 currency: str
67 unit: str
68 references: tuple[NoteReference, ...]
69 balance_sheet_policies: tuple[BalanceSheetLinePolicy, ...]
70 income_statement_policies: tuple[IncomeStatementLinePolicy, ...]
71 equity_movement_policies: tuple[EquityMovementPolicy, ...]
72 cash_accounts: tuple[CashAccountPolicy, ...]
73 counterpart_policies: tuple[CashCounterpartPolicy, ...]
74 transactions: tuple[CashFlowEntry, ...]
75 cash_balance_notes: tuple[CashBalanceNoteSelection, ...]
76
77
78 def _reject_json_constant(value: str) -> None:
79 raise CoverageError("PIPELINE_MANIFEST_NONFINITE_NUMBER")
80
81
82 def _rows(
83 payload: dict[str, Any], key: str, fields: frozenset[str],
84 factory: type, maximum: int, *, minimum: int = 0,
85 string_fields: tuple[str, ...] = (),
86 sign_field: str | None = None,
87 amount_fields: tuple[str, ...] = (),
88 optional_text_fields: tuple[str, ...] = (),
89 ) -> tuple[Any, ...]:
90 items = payload[key]
91 if (not isinstance(items, list) or len(items) < minimum
92 or len(items) > maximum):
93 raise CoverageError("PIPELINE_MANIFEST_" + key.upper() + "_INVALID")
94 result = []
95 for item in items:
96 if not isinstance(item, dict) or set(item) != fields:
97 raise CoverageError("PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID")
98 for field in string_fields:
99 value = item[field]
100 if (not isinstance(value, str) or not value
101 or value != value.strip() or len(value) > 256
102 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
103 raise CoverageError(
104 "PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID"
105 )
106 for field in optional_text_fields:
107 value = item[field]
108 if (not isinstance(value, str) or value != value.strip()
109 or len(value) > 256
110 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
111 raise CoverageError(
112 "PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID"
113 )
114 for field in amount_fields:
115 value = item[field]
116 if not isinstance(value, str) or value != value.strip():
117 raise CoverageError(
118 "PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID"
119 )
120 try:
121 _money(value)
122 except CoverageError as exc:
123 raise CoverageError(
124 "PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID"
125 ) from exc
126 if sign_field is not None and (
127 type(item[sign_field]) is not int or item[sign_field] not in (-1, 1)
128 ):
129 raise CoverageError("PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID")
130 try:
131 result.append(factory(**item))
132 except (TypeError, ValueError) as exc:
133 raise CoverageError(
134 "PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID"
135 ) from exc
136 return tuple(result)
137
138
139 def _validate_manifest_references(manifest: ParsedPipelineManifest) -> ParsedPipelineManifest:
140 """Fail closed on misleading cross-links before any XLSX is opened.
141
142 The caller supplies a reference/policy graph, not an authenticated approval.
143 Missing policies are left to the engines as *blocked preview findings*,
144 while duplicate or dangling input links are malformed manifest errors.
145 """
146 refs: dict[tuple[str, str, str, str], NoteReference] = {}
147 for item in manifest.references:
148 if item.statement not in {"BS", "IS", "EQ", "CF"}:
149 raise CoverageError("PIPELINE_MANIFEST_REFERENCE_STATEMENT_INVALID")
150 key = (item.statement, item.section, item.note_number, item.subnote_code)
151 if key in refs:
152 raise CoverageError("PIPELINE_MANIFEST_DUPLICATE_NOTE_REFERENCE")
153 refs[key] = item
154
155 policies_by_statement: dict[str, dict[tuple[str, str, str, str], object]] = {}
156 for statement, policies in (
157 ("BS", manifest.balance_sheet_policies),
158 ("IS", manifest.income_statement_policies),
159 ("EQ", manifest.equity_movement_policies),
160 ):
161 policy_by_key: dict[tuple[str, str, str, str], object] = {}
162 for item in policies:
163 key = (
164 statement, item.statement_section, item.note_number,
165 item.subnote_code,
166 )
167 if key in policy_by_key:
168 raise CoverageError("PIPELINE_MANIFEST_DUPLICATE_" + statement + "_POLICY")
169 if key not in refs:
170 raise CoverageError("PIPELINE_MANIFEST_ORPHAN_" + statement + "_POLICY")
171 policy_by_key[key] = item
172 policies_by_statement[statement] = policy_by_key
173
174 cash_note_keys: set[tuple[str, str, str, str]] = set()
175 for selection in manifest.cash_balance_notes:
176 key = (
177 "BS", selection.statement_section, selection.note_number,
178 selection.subnote_code,
179 )
180 if key in cash_note_keys:
181 raise CoverageError("PIPELINE_MANIFEST_DUPLICATE_CASH_NOTE_SELECTION")
182 cash_note_keys.add(key)
183 if key not in refs:
184 raise CoverageError("PIPELINE_MANIFEST_CASH_NOTE_REFERENCE_MISSING")
185 policy = policies_by_statement["BS"].get(key)
186 if policy is None or policy.category != "ASSETS":
187 raise CoverageError("PIPELINE_MANIFEST_CASH_NOTE_NOT_ASSET")
188
189 cash_codes: set[str] = set()
190 for item in manifest.cash_accounts:
191 if item.account_code in cash_codes:
192 raise CoverageError("PIPELINE_MANIFEST_DUPLICATE_CASH_ACCOUNT")
193 cash_codes.add(item.account_code)
194
195 counterpart_codes: set[str] = set()
196 for item in manifest.counterpart_policies:
197 if item.account_code in cash_codes:
198 raise CoverageError("PIPELINE_MANIFEST_CASH_COUNTERPART_OVERLAP")
199 if item.account_code in counterpart_codes:
200 raise CoverageError("PIPELINE_MANIFEST_DUPLICATE_COUNTERPART_POLICY")
201 counterpart_codes.add(item.account_code)
202
203 line_ids: set[str] = set()
204 for item in manifest.transactions:
205 if item.line_id in line_ids:
206 raise CoverageError("PIPELINE_MANIFEST_DUPLICATE_TRANSACTION_LINE")
207 line_ids.add(item.line_id)
208 if item.cash_account_code not in cash_codes:
209 raise CoverageError("PIPELINE_MANIFEST_UNKNOWN_CASH_ACCOUNT")
210 if item.cash_account_code == item.counterpart_account_code:
211 raise CoverageError("PIPELINE_MANIFEST_SAME_ACCOUNT_PAIR")
212 if (item.counterpart_account_code not in counterpart_codes
213 and item.counterpart_account_code not in cash_codes):
214 raise CoverageError("PIPELINE_MANIFEST_UNKNOWN_COUNTERPART_ACCOUNT")
215 return manifest
216
217
218 def parse_pipeline_manifest(content: bytes) -> ParsedPipelineManifest:
219 if (not isinstance(content, bytes)
220 or not 0 < len(content) <= MAX_CASH_MANIFEST_BYTES):
221 raise CoverageError("PIPELINE_MANIFEST_SIZE_INVALID")
222 try:
223 payload = json.loads(
224 content.decode("utf-8"),
225 object_pairs_hook=_strict_pairs,
226 parse_constant=_reject_json_constant,
227 )
228 except CoverageError:
229 raise
230 except (UnicodeError, ValueError, RecursionError) as exc:
231 raise CoverageError("PIPELINE_MANIFEST_JSON_INVALID") from exc
232 if not isinstance(payload, dict) or set(payload) != ROOT_FIELDS:
233 raise CoverageError("PIPELINE_MANIFEST_SCHEMA_INVALID")
234 if type(payload["schema_version"]) is not int or payload["schema_version"] != 1:
235 raise CoverageError("PIPELINE_MANIFEST_VERSION_INVALID")
236
237 company = payload["company_code"]
238 if (not isinstance(company, str) or not company
239 or company != company.strip() or len(company) > 64
240 or any(ord(char) < 32 or ord(char) == 127 for char in company)):
241 raise CoverageError("PIPELINE_MANIFEST_COMPANY_INVALID")
242 year = payload["fiscal_year"]
243 if type(year) is not int or year <= 0:
244 raise CoverageError("PIPELINE_MANIFEST_YEAR_INVALID")
245 currency, unit = payload["currency"], payload["unit"]
246 for value in (currency, unit):
247 if (not isinstance(value, str) or not value or value != value.strip()
248 or len(value) > 32
249 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
250 raise CoverageError("PIPELINE_MANIFEST_CURRENCY_UNIT_INVALID")
251
252 for item in payload["transactions"]:
253 if (isinstance(item, dict) and
254 (item.get("company_code") != company
255 or type(item.get("fiscal_year")) is not int
256 or item.get("fiscal_year") != year)):
257 raise CoverageError("PIPELINE_MANIFEST_TRANSACTION_SCOPE_MISMATCH")
258
259 manifest = ParsedPipelineManifest(
260 company_code=company,
261 fiscal_year=year,
262 currency=currency,
263 unit=unit,
264 references=_rows(
265 payload, "references", REFERENCE_FIELDS, NoteReference,
266 MAX_POLICY_ROWS, minimum=1,
267 string_fields=("statement", "section", "note_number", "evidence_ref"),
268 amount_fields=("expected_closing_exposure",),
269 optional_text_fields=("subnote_code",),
270 ),
271 balance_sheet_policies=_rows(
272 payload, "balance_sheet_policies", BS_POLICY_FIELDS,
273 BalanceSheetLinePolicy, MAX_POLICY_ROWS, sign_field="sign_multiplier",
274 string_fields=("statement_section", "note_number", "category",
275 "line_label", "policy_evidence_ref"),
276 optional_text_fields=("subnote_code",),
277 ),
278 income_statement_policies=_rows(
279 payload, "income_statement_policies", IS_POLICY_FIELDS,
280 IncomeStatementLinePolicy, MAX_POLICY_ROWS, sign_field="sign_multiplier",
281 string_fields=("statement_section", "note_number", "category",
282 "line_label", "policy_evidence_ref"),
283 optional_text_fields=("subnote_code",),
284 ),
285 equity_movement_policies=_rows(
286 payload, "equity_movement_policies", EQ_POLICY_FIELDS,
287 EquityMovementPolicy, MAX_POLICY_ROWS, sign_field="sign_multiplier",
288 string_fields=("statement_section", "note_number", "equity_component",
289 "movement_category", "line_label", "policy_evidence_ref"),
290 optional_text_fields=("subnote_code",),
291 ),
292 cash_accounts=_rows(
293 payload, "cash_accounts", CASH_ACCOUNT_FIELDS,
294 CashAccountPolicy, MAX_CASH_ACCOUNTS, minimum=1,
295 string_fields=("account_code", "evidence_ref"),
296 ),
297 counterpart_policies=_rows(
298 payload, "counterpart_policies", COUNTERPART_FIELDS,
299 CashCounterpartPolicy, MAX_CASH_COUNTERPART_POLICIES,
300 string_fields=("account_code", "activity", "evidence_ref"),
301 ),
302 transactions=_rows(
303 payload, "transactions", TRANSACTION_FIELDS,
304 CashFlowEntry, MAX_CASH_TRANSACTIONS,
305 string_fields=("company_code", "line_id", "transaction_id",
306 "posting_date", "cash_account_code",
307 "counterpart_account_code", "evidence_ref"),
308 amount_fields=("cash_debit", "cash_credit",
309 "counterpart_debit", "counterpart_credit"),
310 ),
311 cash_balance_notes=_rows(
312 payload, "cash_balance_notes", CASH_NOTE_FIELDS,
313 CashBalanceNoteSelection, MAX_POLICY_ROWS, minimum=1,
314 string_fields=("statement_section", "note_number", "evidence_ref"),
315 optional_text_fields=("subnote_code",),
316 ),
317 )
318 return _validate_manifest_references(manifest)
319
320
321 def run_pipeline_cli(workbook_path: str, manifest_path: str) -> FiveStatementPipelineResult:
322 manifest = parse_pipeline_manifest(safe_read_cash_manifest(manifest_path))
323 workbook = safe_read_workbook(workbook_path)
324 return build_five_statement_pipeline(
325 workbook,
326 company_code=manifest.company_code,
327 fiscal_year=manifest.fiscal_year,
328 references=manifest.references,
329 balance_sheet_policies=manifest.balance_sheet_policies,
330 income_statement_policies=manifest.income_statement_policies,
331 equity_movement_policies=manifest.equity_movement_policies,
332 currency=manifest.currency,
333 unit=manifest.unit,
334 cash_accounts=manifest.cash_accounts,
335 counterpart_policies=manifest.counterpart_policies,
336 transactions=manifest.transactions,
337 cash_balance_notes=manifest.cash_balance_notes,
338 )
339
340
341 def main(argv: list[str] | None = None) -> int:
342 parser = argparse.ArgumentParser(
343 description="ARAM offline NONOFFICIAL five-statement analyst preview"
344 )
345 parser.add_argument("--file", required=True, help="Local Pilot XLSX snapshot")
346 parser.add_argument("--manifest", required=True, help="Strict JSON policy/transaction manifest")
347 args = parser.parse_args(argv)
348 try:
349 result = run_pipeline_cli(args.file, args.manifest)
350 except CoverageError as exc:
351 print("ARAM five-statement pipeline blocked: " + exc.code, file=sys.stderr)
352 return 2
353 print(json.dumps(
354 result.to_dict(), ensure_ascii=True, sort_keys=True, separators=(",", ":"),
355 ))
356 return 0 if result.eligible_for_analyst_review else 3
357
358
359 if __name__ == "__main__":
360 raise SystemExit(main())