Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 15:30 UTC
R4: Alembic-only production schema path + backup restore (ADR-035) (#117)
* feat(pilot): working end-to-end Pilot Workbench (Excel in -> draft BS/IS out) Atomic V1 vertical slice on top of the accepted audit-safe foundation: - pilot_engine: deterministic in-memory BS/IS engine with explicit sign policy, fail-closed exceptions (unmapped/conflict/unsupported/CF-EQ), exact Decimal totals, trial-balance + accounting-equation checks, and reviewable 7-sheet Excel export with source-row drill-down. - pilot_store: bounded thread-safe in-memory sessions with audit trail; Reviewed/Approved mappings require reviewer evidence (contract parity). - pilot_api: /api/v1/pilot endpoints (upload, synthetic demo, mapping edits, export); preflight rejections return exact sheet/row/field issues. - Persian RTL workbench UI at /pilot/ (no external dependencies), root redirects to it; replaces nothing, quarantined prototype untouched. - 25 new tests; full suite 92 passed; migration round-trip unaffected. No canonical data/, samples/, models, or migrations changed. Demo data is synthetic and labelled everywhere. Output is a working draft, never an official financial statement. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): generic company-agnostic editing + mobile-first UI + save/resume Make the workbench a complete, reusable tool for any company, fully usable on a phone: - Full account CRUD: add/edit/rename/delete. Rename carries the mapping forward automatically. Manually added accounts derive closing from opening+debit-credit (never invented); duplicates/non-finite rejected. - Full note & sub-note CRUD: add/edit-title/delete. Deleting a note that is a mapping target is blocked (409) until mappings move. - Company edit: name/code/fiscal-year/unit/currency -> not tied to any entity. - Save/resume: GET workspace.xlsx serializes the working state to a valid Pilot v0.1 workbook; re-upload rebuilds it losslessly (verified round-trip). - Mutable WorkingModel + typed editing validators (pilot_editing.py); every change append-only audited; thread-safe snapshots. - Mobile-first UI: bottom navigation, bottom-sheet forms, card layouts, numeric keyboards, safe-area insets; partial list updates keep search focus. - Engine 1.1.0; PilotAccount now carries full hierarchy for lossless export. Tests: 107 passed (15 new editing/round-trip/API tests). No canonical data, samples, models or migrations changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(pilot): serve workbench directly at root (no redirect) for proxy safety The preview proxy can mishandle the / -> /pilot/ redirect hop. Serve the workbench HTML directly at / with absolute asset paths so the app loads in one request at both / and /pilot/. Update the root test accordingly. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): permanent browser edition (Pyodide) deployed via GitHub Pages - webapp/: mobile-first RTL UI shell + bridge.py (JSON dispatcher mirroring pilot_api.py, no FastAPI) running the exact tested engine in-browser - scripts/build_webapp.py: assembles docs/ from UI + unmodified engine copies - docs/: Pages source (app at site root, .nojekyll, engine under py/aram_backend) - Verified under Node+Pyodide 0.26.4: demo, CRUD, rename-with-mapping, company edit, lossless workspace round-trip, report export, preflight/duplicate errors, balance fail-closed semantics, COMPLETE_APPROVED end state Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(pilot): deploy browser edition to GitHub Pages (auto-enable) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): vendor Excel wheels + dual-CDN boot; permanent commit-pinned links - boot() installs vendored openpyxl/et_xmlfile wheels directly into site-packages (no PyPI/micropip at runtime) and falls back jsDelivr->unpkg - docs/vendor/ carries the two pure-Python wheels (268KB) - Pages workflow is dispatch-only (site creation requires owner action); app is served permanently via rawcdn.githack.com / cdn.jsdelivr.net gh - Final Node+Pyodide test of deployed bundle: full journey to COMPLETE_APPROVED, lossless workspace round-trip, 12 audit entries Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(domain): pure financial domain layer + parser/inspection fixes (Phase 0) Evidence-based ADRs from read-only probe of canonical 1404 ledger (252898 rows): - ADR-012 money: integer-rial BIGINT storage (Rial TypeDecorator), Decimal in Python, half-up + largest-remainder rounding only in output (P-02, D-03, OD-03) - ADR-013 sign: debit-positive confirmed (C-01 252892/252898 vs 37% credit-pos) - ADR-014 hierarchy: OD-01 default refuted (T1..T4 concat == حساب for 0 rows); kol->general, حساب->subsidiary, T1..T4->detail1..4; full code = kol+حساب (D-10) Domain (no I/O): normalize_fa/normalize_code/decimal_from_cell (P-03/P-04, D-04), Rial money, ledger<->Pilot hierarchy, blocking controls C-01..C-04 (D-02). ledger_parser delegates to domain (text codes keep leading zeros, exact float repr); workbook_inspection normalizes sheets/headers (D-05) and guards max_column=None (D-11). hypothesis added to test extra (ADR-012). Tests: 47 domain + 9 Phase-0 acceptance incl. bounded real-data evidence. Full suite 163 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): LedgerBalance model + exact-rial money column (D-01, D-03) - LedgerBalance: year-isolated, source-linked, text hierarchy codes, opening/ debit/credit/closing as Rial BIGINT; unique (year_id, account_full_code, import_version); new import version per Draft re-import (booklet §5) - StatementLine.mapped_total Numeric(24,4) -> Rial() (no float on SQLite, P-02) - ledger_parser extracts optional kol (general_code); hierarchy mapper accepts absent kol; services/ledger_import aggregates parsed rows by canonical account with exact Decimal summation - Migration 20261203_02 (guarded create + batch alter) runs on SQLite/PostgreSQL; up/down round-trip verified Tests: small-sample exact round-trip, large-rial BIGINT storage (>2^53) via ORM, duplicate-account aggregation, uniqueness, migration upgrade/downgrade. Full suite 168 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(source): content-addressed byte store + full CSV support (D-06) - SourceFile model (sha256 PK, size, content_type, stored_path) + SourceDocument FK; SourceStore writes immutable bytes atomically, re-verifies hash on read (corruption/tamper fails loudly); registration accepts optional store, keeps metadata-only model contract (accepted tests unchanged) - CSV ledger parser: UTF-8/UTF-8-BOM/Windows-1256, delimiter sniffing, same Persian normalization + exact-money rules as XLSX; parse_ledger routes by extension; streaming reader - Migration 20261203_03 (guarded create + batch add column) Tests: store round-trip/idempotency/corruption, registration+re-import hash match, CSV encodings/delimiters/leading-zeros/missing-header/empty/routing. 185 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): locked-year immutability triggers + hash-chained audit + reopen (D-07) - DB triggers (SQLite + PostgreSQL) block INSERT/UPDATE/DELETE on year-owned tables when the year is LOCKED, enforced even via raw SQL (P-08, D3) - Lifecycle trigger: Draft->Approved->Locked; Locked->Approved only with an approved ReopenRequest; protected years cannot be deleted - AuditEntry append-only (trigger) + hash chain (verify_chain detects tampering independently of the trigger); ReopenRequest model + ORM guard exemption - ADR-016 reopen/immutability model; migration 20261203_04 installs tables+triggers - ensure_triggers() helper; conftest installs triggers for all tests Tests: raw-SQL insert/update/delete blocked on locked year, draft writes allowed, reopen with/without approved request (ORM + raw SQL), audit chain build/verify/ tamper-detection/append-only. 195 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ingestion): wire C-01..C-04 controls into preflight (D-02) - services/preflight.run_preflight evaluates the blocking control set over parsed ledger rows + active mappings; PreflightReport exposes blocking results, can_approve, and the unknown-account queue (C-04) - Mappings loaded from the year's MappingRule rows or supplied directly (pure path) - ERROR results block approval (P-09); unmapped active accounts surface in the unknown queue for Phase 2 resolution Tests: clean ledger passes C-01/C-02, C-01 violation blocks, unmapped accounts queued, mapping clears queue, all four controls present, inactive accounts not queued. 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: quality gates — ruff, mypy strict (domain), coverage, pip-audit, PG matrix (D-12) - pyproject: ruff/mypy/coverage/pytest-cov/pip-audit in test extra; psycopg in ci extra; ruff/mypy/coverage config (domain strict, total>=80%, domain>=90%) - CI: quality job (whitespace, ruff lint+format, mypy domain strict, coverage gates, pip-audit) + migration matrix job (SQLite + PostgreSQL service container, up/down/up round-trip) - ADR-017 documents the dev/CI-only dependencies (no runtime impact, P-10) - Lint fixes across backend (zip strict, StrEnum, specific test exceptions, unused vars); format applied to Phase-0 layers (domain/services/migrations) - pytest>=9.0.3 + pip/setuptools upgraded to clear pip-audit CVEs Gates verified locally: ruff clean, format clean, mypy domain strict clean, coverage total 92% / domain 97%, pip-audit no known vulnerabilities, 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: refresh PROJECT_STATUS + PROJECT_LOG for Phase 0 debts (D-08) Record D-01..D-12 states with commit evidence, real-data proof, ADRs 012/013/ 014/016/017, and local gate results (201 tests, coverage 92%/97%, pip-audit clean). D-09 marked BLOCKED (owner-only). No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * style: ruff format migration files (Phase-0 format gate) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(statements): persistent audited vertical slice + drill-down (Phase 1) - services/statement_build: build versioned BS/IS from latest LedgerBalance import + mappings/notes; exact integer-rial totals; display sign policy (ADR-013/018); unmapped active accounts surfaced; new version per build (never mutates snapshot) - drill_down: StatementLine -> Note -> MappingRule -> LedgerBalance -> SourceDocument (filename + SHA-256) + sheet + row (D2 full traceability) - statement_api: company/year setup, year-filtered ledger upload+import, notes, mappings, statement build/list, drill-down, preflight controls endpoint - ADR-018 persistent statements + drill-down contract Tests: BS/IS totals+signs, drill-down to source row, version increment, unmapped surfacing, API end-to-end (CSV->import->map->build->drilldown), preflight controls, bounded real-data smoke (3000 real 1404 rows -> import -> build -> drill-down). 209 passed; ruff/mypy/coverage gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(mapping): Excel I/O + unknown queue + approval gate + carry-forward (Phase 2) - mapping_io: governed Mappings workbook export/import; text codes; fail-closed per-row import with error report; idempotent re-import; auto-create notes - mapping_workflow: unknown-account queue (C-04 active unmapped); carry-forward notes+mappings into a Draft year (D1 continuity), idempotent - approval: approve_year runs C-01..C-04; blocking ERROR refuses Draft->Approved; clean pass transitions + hash-chained audit entry (P-09) - statement_api: mappings export/import, unknown-accounts, carry-forward, approve - ADR-019 mapping I/O + approval contract; shared api_client fixture in conftest Tests: export/import round-trip, invalid-row fail-closed, queue list/clear, approval blocked/success/non-draft, carry-forward copy/idempotent/reject, API end-to-end (queue->import mappings->approve). 220 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(notes): safe formula grammar + note engine (Phase 3) - domain/formula: hand-written tokenizer + recursive-descent parser -> whitelisted AST, exact Decimal evaluation; NO eval/exec (P-05); unknown tokens/functions fail closed; division-by-zero rejected; mypy --strict clean - services/note_engine: evaluate disclosure rows from latest ledger import; acct/ row/note/sum/abs functions; earlier-row + cross-note references with cycle detection; per-row referenced accounts for drill-down - statement_api: note-row create (formula validated on create), list, evaluate - ADR-020 formula grammar (mandatory pre-code ADR) Tests: 22 formula parse/eval/safety cases (injection rejected), note engine account/subtotal/cross-note/circular/forward-ref/unknown-account, API create+ evaluate+invalid-formula rejection. 250 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * WIP: Phase 4 golden comparison (partial, interrupted) - services/golden: data-derived note aggregation (source col0/col25) vs official sheets, half-up million-rial rounding, discrepancies writer (ADR-021) - statement_build: ALL_STATEMENTS constant (BS/IS/CF/EQ) - test_golden: real-data BS match + all-4 build (test run interrupted, unverified) Saved as WIP per owner instruction before priority architecture fixes. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(money): prove P-02 no-silent-rounding with exhaustive evidence (audit #1) - ADR-012 revised: exhaustive probe of BOTH ledgers (457,074 rows, 6 money columns) confirms zero fractional rial; scale-0 is lossless. Clarifies .to_integral_value() is a DETECTOR (raises on fractional), never a rounder; round_half_up is display-only. - 7 regression tests: fractional text/boundary rejected (not rounded), fractional through ORM and CSV import fail loudly (StatementError wrapping ValueError). No storage behavior change needed — the fail-loud design already satisfies P-02. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(ledger): store RAW rows for drill-down, aggregate in compute layer (audit #2, D3/P-01) - ledger_import: one LedgerBalance per source row (no import-time aggregation); source_row preserved so every figure traces to file/sheet/row (D3) - LedgerBalance uniqueness -> (year_id, source_document_id, source_row, import_version) - NEW services/ledger_aggregate: account-level totals via exact Decimal summation in the compute layer (latest import version) - unknown_accounts now aggregates raw rows by account (dedupe + row_count) - Migration 20261203_05 swaps the constraint on existing DBs + reinstalls triggers; fresh DBs get it from the live model. Round-trip verified, triggers preserved. - Test updated: duplicate accounts stored as 2 raw rows, aggregated in service. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(approval): make C-03 enforcement explicit + hard ERROR gate (audit #3, D5) - approve_year loads rows AND mappings, passes both to evaluate_controls -> run_controls; C-03 (double mapping) and C-04 (unknown queue) always evaluated. Even one ERROR blocks Draft->Approved; no bypass path. - 13 negative/positive tests: double-mapping blocks via C-03, C-01/C-02/C-04 block, blocked approval writes no audit + stays Draft, non-draft/nonexistent rejected, clean ledger approves + audit chain valid, locked year immutable after approval, evaluate_controls proves mappings drive C-03/C-04 (incl. valid 100% split). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(services): mypy-clean services + generic golden columns + negative tests (audit #4) - Type-annotate all services so mypy passes (dict/tuple generics, cast, isinstance AST walks, typed sort key, renamed shadowed variable). - golden: resolve note/year/statement-balance columns BY HEADER NAME (1403 and 1404 ledgers have different layouts); fixes 1403 comparison, keeps it generic. - mapping_workflow negative tests: nonexistent carry-forward target, inactive accounts excluded, raw-row aggregation in queue, empty mapping workbook rejected. mypy services+domain clean; golden 1403+1404 real-data tests pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: frontend gates (eslint/tsc/vitest/Playwright) + mypy services (audit #4, §14) - backend-ci: add 'Mypy (services)' gate (services now type-clean). - frontend-ci: eslint, tsc --noEmit, vitest, vite build, and Playwright e2e (chromium) with report artifact. - frontend/: Vite+React+TS RTL scaffold (Phase 5 foundation) with unit test (App.test.tsx), e2e specs (e2e/app.spec.ts), eslint flat config, tsconfig, playwright.config.ts, package-lock.json. Local: lint/tsc/vitest/build pass; playwright --list validates 2 specs. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * chore: drop unused import in approval gate test (ruff F401) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: record Phases 1-4 + owner priority fixes in status/log (§0) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(import): tolerant real-ledger import + statement-balance capture (Phase 4/5) - Tolerant parse path (XLSX+CSV): reclassified rows with empty OPENING/Debit/ Credit/CLOSING are kept with exact zero; signed مانده صورت مالی stored as LedgerBalance.statement_balance (nullable Rial BIGINT, migration 20261203_06). Non-numeric money cells are skipped + reported (fail-loud, never invented); identity fields stay strictly required. Strict mode unchanged. - statement_build uses the effective balance: statement_balance rows contribute their pre-signed figure directly (reproduces Phase-4 golden); ordinary closing rows get the ADR-013 section sign. drill_down exposes effective/statement balance. - API upload uses tolerant import and returns skipped_rows for transparency. - 4 new tests (reclassified kept, anomaly skipped+reported, strict fails loud, statement_balance drives build + raw-row drill-down). Full suite: 285 passed. Real-data proof: source_1404.xlsx -> 131,280 raw rows imported, 4 anomalies reported; note->map->build->drill-down traced to exact source rows. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): Phase 5 RTL workbench — setup/import/mapping/statements/drill-down/approval - Vite dev proxy forwards relative /api to FastAPI (no browser localhost calls); allowedHosts for the Arena live preview. - Typed API client + types; Persian-locale rial formatting. - Components: CompanySetup, LedgerUpload, MappingPanel (unknown-account queue, note creation, mapping import/export), StatementView (BS/IS/CF/EQ tabs, build, per-line drill-down), DrillDown (source file/sheet/row lineage), ApprovalPanel (controls + hard approval gate). - Unit tests (11): format, api client, CompanySetup, DrillDown, App shell. Playwright e2e: app smoke + full workflow (backend-gated via ARAM_E2E_BACKEND). - Gates: eslint/tsc/vitest/build pass; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(output): Phase 6 reviewable statement outputs (XLSX + JSON) with lineage - statement_export: latest-version BS/IS/CF/EQ + evaluated notes + full source lineage (file/SHA-256/sheet/row) as RTL XLSX (Summary/per-statement/Note/Lineage) and structured JSON. Exact integer-rial preserved; million-rial display-only (half-up, ADR-012). No new dependency (openpyxl). ADR-022. - API GET /years/{id}/statements/export?format=xlsx|json; workbench download buttons. - 3 tests (JSON exact rial + lineage, XLSX sheets/values, JSON serializable). Real-data proof: year 1404 export -> BS/IS, 340 lineage rows, Note 10; XLSX sheets Summary/BS/IS/Note 10/Lineage. Full suite: 288 passed; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(admin): Phase 7 users/roles, controlled reopen/lock, verifiable backup - User model + roles (admin/reviewer/preparer); PBKDF2-HMAC-SHA256 + per-user salt (stdlib, no plaintext, no network); require_role gate; first-user bootstrap. - Reopen/lock service: request->approve->reopen (LOCKED->APPROVED only with an approved request; ORM guard + DB trigger re-check, no bypass); lock APPROVED-> LOCKED; every step hash-chained audited. Migration 20261203_07 (round-trip OK). - Backup: consistent SQLite online-backup snapshot + source-store copy + SHA-256 manifest + audit-chain verification; verify_backup recomputes hashes + chain; tamper/non-empty-dest/broken-chain refused. ADR-023. - admin_api /api/v1: users, auth/login, audit(+verify), reopen/lock, backup(+verify) with 403 role gates. - 17 tests (users/auth/roles, reopen workflow + immutability, backup integrity + tamper, admin API bootstrap/login/gate/audit). Full suite: 305 passed. Live proof: bootstrap->admin, login, audit chain valid, backup+verify (1 source file), preparer backup -> 403. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): admin panel — login, audit verify, lock/reopen, backup/verify Phase 7 workbench surface: role-gated login, audit-chain check, year lock, reopen request->approve->reopen, and backup create/verify against the admin API. Gates: eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(desktop): Phase 8 offline desktop entrypoint + reproducible PyInstaller recipe - desktop.py: per-user data dir, idempotent SQLite schema + D-07 triggers, FastAPI + bundled React workbench served on 127.0.0.1 only (zero network). database.reconfigure rebinds the shared engine to the local file at launch. - packaging/aram.spec (one-folder Aram.exe) + build_desktop.py (npm build -> PyInstaller) + README. Binary is a build artifact, never committed (§19). ADR-024. - 3 tests: DB init creates schema+triggers (idempotent), desktop app serves health + API end-to-end, data-dir override. Full suite: 308 passed; mypy clean. Live proof: desktop app serves bundled RTL workbench at / (200) + health ok. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(e2e): update smoke spec to the workbench (company setup form, not counter) The Phase 5 workbench replaced the demo counter; the Playwright smoke test now asserts the RTL heading + company setup form (frontend-only, no backend needed). Fixes the Frontend CI e2e job. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs+uat: Phase 9 real-data UAT script + status/log for Phases 5-9 (§0/§18) scripts/uat_real_data.py exercises the full persistent pipeline on source_1404 (read-only): import->auto-map->build->golden reconcile->approval gate->export-> backup->audit. Records reviewable evidence; report is not a committed artifact. PROJECT_STATUS + PROJECT_LOG updated with Phases 5-9 and UAT results. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(review): role-gate approve + editable notes/mappings/rows (5-agent review) Findings from the deep compliance review: - F3-1: API /approve now enforces reviewer/admin role once local users exist (consistent with /lock and /reopen); bootstrap/dev (no users) stays open; the C-01..C-04 ERROR gate always applies. +2 negative/positive tests. - F2-1: add PUT/DELETE for notes, mappings, note rows + GET list notes/mappings, satisfying the owner's editable codes/accounts/notes/subnotes requirement. Draft-guarded; D-07 immutability translated to HTTP 409; note delete refuses while mappings/statement lines reference it (rows cascade). +9 tests incl. locked-year edit refusal. - F5-1: document python-multipart upload dependency in ADR-018. Full suite: 319 passed; mypy services clean; ruff clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): notes/mappings manager (edit/delete) wired to the editing API NotesManager lists notes (inline title edit + delete) and mappings (delete), refreshing after each change. eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs(review): 5-pass booklet compliance review report + log (§0) Records the five reviewer mandates, evidence, findings (F2-1/F3-1/F5-1 fixed, O5-1 noted) and per-agent verdicts. All passes PASS after fixes; 319 tests green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * B0: booklet reference + lightweight-process reconciliation - docs/booklet/BOOKLET_v1.0.md + MANIFEST.json (original PDF SHA-256 anchor; ADR-025) - PROJECT_STATUS.md rewritten to GitHub reality (Phases 0-9 MERGED @46253c9, 319 tests, post-merge CI; stale V1-01/unmerged rows removed; D-08 closed) - 14 root analytical docs git mv -> docs/archive/ (+ index); no new root analytical doc (booklet §0.5) - AGENTS.md <-> §0.5 conflict resolved: handoff cadence per-category, lightweight-process bullets (ADR-026) - docs/discrepancies.json skeleton {row,our_amount,official_amount,cause,evidence,year} (OD-08; B8 populates) - docs/PROJECT_LOG.md + LATEST_HANDOFF.md refreshed (end-of-category) - data/ + samples/ tree hashes unchanged (docs/process only) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0: booklet 2 course correction (بخش الف) - الف1: remove Pyodide/Pages/CDN browser edition (webapp/, docs built output, docs/vendor wheels, scripts/build_webapp.py, pilot-pages.yml); recoverable from history @46253c9; ADR-028 - booklet 2 v2.0 verbatim -> docs/booklet/BOOKLET_v2.0.md + MANIFEST.json (SHA-256 anchor); ADR-027 (C0..C10 supersedes B framing; OD-09..14; generality rule; databansoft not reachable) - الف6: docs/PR_TRIAGE.md (ADOPT #81/#89/#92; CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22-#80) - الف4/5 + ب1 + §16: PR honesty/size, generality grep, offline/read-only/no-plaintext rules in AGENTS.md - الف2/3 verified: persistent core (domain+statement_api/admin_api on LedgerBalance) is main path; phase 0/1 + golden merged @46253c9 - PROJECT_STATUS.md -> C0..C10 roadmap + C0 progress + الف7; PROJECT_LOG + handoff refreshed - data/ + samples/ tree hashes unchanged; backend 319 passed, frontend lint/tsc/vitest(11)/build green (no regression) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 addendum: booklet 2 appendix revision (owner) + ADR-029 - appendix replaced verbatim: Databan catalog studied by owner (marketing, unverified); positioning = independent pluggable product + Host Integration API; accepted elements 1-10; rejected scope; legal restriction - OD-09 REVISED: pyodbc-first (existing ODBC driver, Windows+SQL Server), python-tds fallback (ADR-027 updated, ADR-029) - ADR-029: positioning, OD-14 capability comparison, element->phase mapping (C4-C9/C11), C11 AI constraints (never generates numbers) - PROJECT_STATUS: C5/C7/C8/C9 scope notes + C11 row + positioning; PROJECT_LOG + handoff updated - BOOKLET_v2.0.md re-anchored: SHA-256 79618ddd...; MANIFEST.json revision history kept - docs-only addendum; code identical to tested C0 tree (backend 319 passed, frontend green); data/ + samples/ unchanged Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 remediation: populate discrepancies.json (الف7) + record review findings - الف7 met: golden.compare_year(1404) re-run -> 28/9 matched/19 diffs; docs/discrepancies.json populated one-by-one with cause + reproducible evidence + source/official SHA-256 (16 caused: 8 exact-magnitude sign flips ADR-013, CF note reuse, absent/underived notes; 3 under_investigation: IS 6/8/9 = bugs until proven D1); EQ official parsing gap recorded - ADR-028: owner's explicit experiment/browser-edition instruction recorded; Arena single-branch block reported; preservation guaranteed via tag v1.0.0 -> 46253c9 - PROJECT_STATUS: review deviations tracked (forgeable actor auth C8, 4/15 controls C3, desktop create_all bypasses Alembic C9, PR #96 discipline violation historical, booklet-1 extraction artifacts disclosed); الف7 marked MET - Fresh evidence: backend 319 tests exit 0; D-04/D-05 normalization 17 passed - docs-only; data/ + samples/ trees unchanged; no second PR (owner directive) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(R1): real server-side session authentication (booklet 2.1) Identity now comes only from a server-side session. `actor` is removed from every request model; a login issues a random 256-bit bearer token whose SHA-256 is the only thing stored, with an 8-hour absolute TTL, logout revocation and a 5-attempt / 15-minute lockout. PBKDF2 rises to 600,000 rounds (Argon2 absent, no new runtime dependency); legacy 200,000-round hashes are rehashed on first login. A single `current_user` dependency guards the statement, admin, schema and pilot routers. Only /health, /auth/login, /auth/launch and the one-time first-admin bootstrap are reachable without a session; reads require login too. Approval without users is impossible, and the role gate runs before the existence check. Backup `dest` is confined to the data folder (traversal, absolute and symlink escapes refused). The desktop launcher gates the local API with a one-time token passed in the URL fragment and exchanged once for an X-Aram-Launch grant. The legacy pilot router, /pilot mount and the HTML at / are out of the app; the interactive schema browsers are disabled. Frontend: LoginPanel gates the workbench, session.ts owns the token in sessionStorage, client.ts attaches it to every request and clears it on 401, and exports became authenticated fetch+blob downloads instead of bare links. Migration 20261204_08 adds auth_sessions + lockout/work-factor columns, verified on a populated copy (131,280 ledger rows, 2 users, 28 triggers unchanged). Decisions: ADR-030. Tests: backend 354 passed (33 new R1 acceptance tests), frontend 15 vitest tests, new real-session e2e (CI now runs uvicorn). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): give the real-ledger e2e a realistic timeout and readable CI failures The workflow e2e was previously skipped in CI (no backend); now that CI starts uvicorn it actually runs, and Playwright's default 30s test timeout killed it while the 131k-row ledger import was still in flight. Raise the test timeout, run one worker against the shared backend, and add the github + html reporters so failures surface as check-run annotations and an uploaded report. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(R1): migrate the throwaway e2e database before starting uvicorn The dev app deliberately does not create the schema (R4 owns startup migrations), so the fresh CI database had no tables and the first-admin bootstrap failed, which made every real-session e2e fail at the login step. Run 'alembic upgrade head' against the e2e database first — verified locally on a fresh DB: 16 tables + 28 triggers, then bootstrap 200, login 200, company 200, audit 200, logout 200, me-after-logout 401. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): disambiguate e2e selectors now that the login screen exists The login card adds an h2 containing 'آرام', so the heading query must target level 1. The ledger import button query matched both 'درونریزی' and 'درونریزی نگاشتها' — a pre-existing ambiguity that only surfaced once the workflow e2e actually ran with a backend. Also trims docs to stay at the 1,500-line cap after the CI/config additions. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): seed one real mapping in the workflow e2e before building The workflow e2e had never run in CI (no backend), and it built statements without any mapping: every account stayed unmapped, so the statements had zero lines and the drill-down step had nothing to click. Capture the year id from the company response, map one real account from the unknown-accounts queue to a new BS/Assets note using the session token, then build. Also raises the import assertion timeout to match the 131k-row workbook. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(controls): R2 — full C-01..C-15 control set with fail-closed unrun handling Booklet 2.1 R2. Eleven new pure controls (C-05..C-15) with Persian messages and the booklet 1 section 7 severities; run_controls always returns all fifteen. - ControlResult.ran separates 'failed' from 'could not run'; an unrun ERROR blocks approval and reports «اجرا نشد: دلیل» (never a silent pass). - services/control_context.py gathers inputs from stored data only: prior-year closing, BS sections under the ADR-013 sign policy, (statement, note) totals, IS result, equity movements, CF net change, cash, declared codes, natures. - Control roles are explicit data (retained_earnings / cash), never inferred from a title; exposed on note create/update and in the notes manager. - A refused approval is now audited (approved:false + blocking + unrun codes). - POST /companies/{id}/years so a prior year can be loaded, otherwise C-05 would make approval permanently impossible. - Preflight returns ran; the UI shows «اجرا نشد» apart from «رد». Evidence: backend 404 passed (was 354), frontend 17 vitest / 6 files, ruff + mypy + tsc + eslint + build clean; live 131,280-row preflight shows 15 controls. Decisions: ADR-031. Authored lines excl. tests/data: 1003/1500. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(controls): controls read the same figure as the statement engine build_statements treats a reclassified row's statement_balance as authoritative and already presentation-signed (ADR-013/018). The R2 context builder used raw closing, so C-06/C-07 would have compared two different rules and invented differences on exactly those rows. BalanceRow now carries statement_balance and one display(sign) method; the context uses it. C-01/C-02 still audit the raw debit/credit columns. Witness: TestReclassifiedRowsAgreeWithTheEngine — engine line total, context note total and context line total all 777 on a row whose CLOSING is 0. ADR-031 §5. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(compare): R3 — compare built statements with the official workbook Booklet 2.1 R3. The comparison now reads the persisted StatementLine rows that build_statements wrote, keyed by (statement, note), instead of aggregating the source workbook separately. Measuring against official 1404 exposed three real engine defects (ADR-032): - statement_balance is debit-positive, not pre-signed: applying the section sign reproduces the official balance sheet 16/16 (7 notes were flipped before). - the per-row CLOSING fallback leaked non-statement rows into totals; the basis now belongs to the import (BS went 6/16 -> 16/16 through the engine). - the source assigns notes per ROW (account 718291 posts to notes 6 and 9), so LedgerBalance.source_note preserves it (migration 20261204_09). An explicit mapping wins; the source note disambiguates multi-note accounts. - IS presents expenses negative, so Revenue and Expenses both take -1 and the net result is the sum of signed IS lines (C-08 input corrected). official_parse.py gives each statement the parser its layout needs: EQ is a components x movements matrix (0 -> 24 figures), CF's 46268 is an account code, and the year column is anchored on the header row (the title also contains it). Measured: BS 16/16 MET. IS 1/6 exact — 6/7 within 1-2 million rial of official presentation rounding, 8/9 differ by a 1,111,554 reclassification (their sum matches exactly), 20-3 has no source rows at all. IS 6/6 NOT MET and reported as such; no tolerance invented, no figure adjusted. discrepancies.json regenerated from built output with cause + official cell + account deltas. C-13 feed + POST /years/{id}/official-comparison. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * Governance(ADR-034): owner delegates integration to the executing agent Amends the AGENTS.md merge clause + final-response line, MASTER orchestration §4.5/§10, and AGENT_PROMPTS M0 clause + report endings: merge own focused PR only after T1 PASS + required CI green on the real head SHA (squash, explicit PR number, into source-data-cleanup). Tagging and releases remain owner actions; v1.0.0 untouched. Every other ADR-033 invariant stands. PROJECT_LOG/STATUS/HANDOFF synced. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * R4: Alembic-only production schema path + backup restore (ADR-035) Remove Base.metadata.create_all from desktop.initialize_database; the production path now runs alembic upgrade head + a D-07 trigger check (require_triggers). New services/schema.py (upgrade_to_head, current_revision, alembic_config, migrations_dir, trigger check); migrations/env.py prefers config.attributes['database_url'] (CI path unchanged). db_triggers exposes expected/installed trigger names. backup.restore_backup + POST /api/v1/backup/restore (admin): verify -> copy into a confined fresh target -> alembic upgrade head -> re-install + verify triggers. Refuses to clobber; path-escape confined. Migration 01 is checkfirst create_all and 02-09 are guarded, so upgrade head converges fresh, versioned, and legacy create_all DBs (verified on a populated 131,280-row copy 08->09 and simulated legacy installs). tests/test_schema_r4.py: 22 tests. Authored 402/1500 lines excl tests/data. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs(R4): correct test count to 20 (440 total = 420 + 20) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --------- Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> Co-authored-by: Arena Agent <agent@arena.ai>