@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 15:45 UTC

codex/aram-five-statement-cli-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 216 lines 8.65 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
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 ) -> tuple[Any, ...]:
86 items = payload[key]
87 if (not isinstance(items, list) or len(items) < minimum
88 or len(items) > maximum):
89 raise CoverageError("PIPELINE_MANIFEST_" + key.upper() + "_INVALID")
90 result = []
91 for item in items:
92 if not isinstance(item, dict) or set(item) != fields:
93 raise CoverageError("PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID")
94 try:
95 result.append(factory(**item))
96 except (TypeError, ValueError) as exc:
97 raise CoverageError(
98 "PIPELINE_MANIFEST_" + key.upper() + "_ROW_INVALID"
99 ) from exc
100 return tuple(result)
101
102
103 def parse_pipeline_manifest(content: bytes) -> ParsedPipelineManifest:
104 if (not isinstance(content, bytes)
105 or not 0 < len(content) <= MAX_CASH_MANIFEST_BYTES):
106 raise CoverageError("PIPELINE_MANIFEST_SIZE_INVALID")
107 try:
108 payload = json.loads(
109 content.decode("utf-8"),
110 object_pairs_hook=_strict_pairs,
111 parse_constant=_reject_json_constant,
112 )
113 except CoverageError:
114 raise
115 except (UnicodeError, ValueError, RecursionError) as exc:
116 raise CoverageError("PIPELINE_MANIFEST_JSON_INVALID") from exc
117 if not isinstance(payload, dict) or set(payload) != ROOT_FIELDS:
118 raise CoverageError("PIPELINE_MANIFEST_SCHEMA_INVALID")
119 if type(payload["schema_version"]) is not int or payload["schema_version"] != 1:
120 raise CoverageError("PIPELINE_MANIFEST_VERSION_INVALID")
121
122 company = payload["company_code"]
123 if (not isinstance(company, str) or not company
124 or company != company.strip() or len(company) > 64
125 or any(ord(char) < 32 or ord(char) == 127 for char in company)):
126 raise CoverageError("PIPELINE_MANIFEST_COMPANY_INVALID")
127 year = payload["fiscal_year"]
128 if type(year) is not int or year <= 0:
129 raise CoverageError("PIPELINE_MANIFEST_YEAR_INVALID")
130 currency, unit = payload["currency"], payload["unit"]
131 for value in (currency, unit):
132 if (not isinstance(value, str) or not value or value != value.strip()
133 or len(value) > 32
134 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
135 raise CoverageError("PIPELINE_MANIFEST_CURRENCY_UNIT_INVALID")
136
137 return ParsedPipelineManifest(
138 company_code=company,
139 fiscal_year=year,
140 currency=currency,
141 unit=unit,
142 references=_rows(
143 payload, "references", REFERENCE_FIELDS, NoteReference,
144 MAX_POLICY_ROWS, minimum=1,
145 ),
146 balance_sheet_policies=_rows(
147 payload, "balance_sheet_policies", BS_POLICY_FIELDS,
148 BalanceSheetLinePolicy, MAX_POLICY_ROWS,
149 ),
150 income_statement_policies=_rows(
151 payload, "income_statement_policies", IS_POLICY_FIELDS,
152 IncomeStatementLinePolicy, MAX_POLICY_ROWS,
153 ),
154 equity_movement_policies=_rows(
155 payload, "equity_movement_policies", EQ_POLICY_FIELDS,
156 EquityMovementPolicy, MAX_POLICY_ROWS,
157 ),
158 cash_accounts=_rows(
159 payload, "cash_accounts", CASH_ACCOUNT_FIELDS,
160 CashAccountPolicy, MAX_CASH_ACCOUNTS, minimum=1,
161 ),
162 counterpart_policies=_rows(
163 payload, "counterpart_policies", COUNTERPART_FIELDS,
164 CashCounterpartPolicy, MAX_CASH_COUNTERPART_POLICIES,
165 ),
166 transactions=_rows(
167 payload, "transactions", TRANSACTION_FIELDS,
168 CashFlowEntry, MAX_CASH_TRANSACTIONS,
169 ),
170 cash_balance_notes=_rows(
171 payload, "cash_balance_notes", CASH_NOTE_FIELDS,
172 CashBalanceNoteSelection, MAX_POLICY_ROWS, minimum=1,
173 ),
174 )
175
176
177 def run_pipeline_cli(workbook_path: str, manifest_path: str) -> FiveStatementPipelineResult:
178 manifest = parse_pipeline_manifest(safe_read_cash_manifest(manifest_path))
179 workbook = safe_read_workbook(workbook_path)
180 return build_five_statement_pipeline(
181 workbook,
182 company_code=manifest.company_code,
183 fiscal_year=manifest.fiscal_year,
184 references=manifest.references,
185 balance_sheet_policies=manifest.balance_sheet_policies,
186 income_statement_policies=manifest.income_statement_policies,
187 equity_movement_policies=manifest.equity_movement_policies,
188 currency=manifest.currency,
189 unit=manifest.unit,
190 cash_accounts=manifest.cash_accounts,
191 counterpart_policies=manifest.counterpart_policies,
192 transactions=manifest.transactions,
193 cash_balance_notes=manifest.cash_balance_notes,
194 )
195
196
197 def main(argv: list[str] | None = None) -> int:
198 parser = argparse.ArgumentParser(
199 description="ARAM offline NONOFFICIAL five-statement analyst preview"
200 )
201 parser.add_argument("--file", required=True, help="Local Pilot XLSX snapshot")
202 parser.add_argument("--manifest", required=True, help="Strict JSON policy/transaction manifest")
203 args = parser.parse_args(argv)
204 try:
205 result = run_pipeline_cli(args.file, args.manifest)
206 except CoverageError as exc:
207 print("ARAM five-statement pipeline blocked: " + exc.code, file=sys.stderr)
208 return 2
209 print(json.dumps(
210 result.to_dict(), ensure_ascii=True, sort_keys=True, separators=(",", ":"),
211 ))
212 return 0 if result.eligible_for_analyst_review else 3
213
214
215 if __name__ == "__main__":
216 raise SystemExit(main())