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

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>

davoodmehraban89 committed Dec 4, 2026 at 18:56 UTC bf25724106b4d94d923afefc765485d90c4f0591
10 files changed +732 -13
PROJECT_STATUS.md
+14 -2
@@ -96,7 +96,7 @@ Booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram», [`docs/
96 | R1 | Real authentication (backend + frontend), backup confinement, desktop launch token, legacy surfaces | **MET** — PR #98 squash-merged 2026-12-04T09:38:06Z → `07a8ae0e` |
97 | R2 | Controls C-05..C-15 wired into `run_controls` + approval | **MET** — PR #100 squash-merged 2026-12-04T10:40:42Z → `a8ba20c1` |
98 | R3 | `build_statements` vs official; (statement, note) aggregation; IS 6/8/9 root cause; EQ/CF parsing | **PARTIAL** (this PR) — BS 16/16 met; IS 6/6 **not met**, blocked by source data (evidence below) |
99 -| R4 | Remove `create_all` from the production path; backup → `alembic upgrade head` → trigger check | NOT_STARTED |
99 +| R4 | Remove `create_all` from the production path; backup → `alembic upgrade head` → trigger check | **MET** (this PR) — Alembic-only init + restore flow; ADR-035; 20 tests |
100 | R5 | `docs/c01_exceptions.json` — the six C-01 source rows, unapprovable until resolved | NOT_STARTED |
101 | R6 | Propose marking the `v1.0.0` Release as pre-release; `experiment/browser-edition` = owner action | NOT_STARTED |
102
@@ -149,6 +149,18 @@ Three real engine defects were found and fixed by measuring against the official
149 non-statement rows (BS 6/16 → 16/16), and per-row note assignment was lost (migration
150 `20261204_09`). Decisions in **ADR-032**.
151
152 +### R4 acceptance ← evidence
153 +
154 +| معیار پذیرش | شاهد | وضعیت |
155 +| --- | --- | --- |
156 +| `create_all` removed from the production path | `desktop.py initialize_database` → `upgrade_to_head`; `test_no_create_all_in_production_source` (no `.create_all(` in `src/aram_backend/`) | MET |
157 +| Desktop init = `alembic upgrade head` + trigger check | `services/schema.py`; `require_triggers` raises `SchemaError` on a missing trigger (`test_require_triggers_fails_when_one_is_missing`) | MET |
158 +| Existing/legacy installs migrate on update | `test_initialize_database_migrates_legacy_full_schema`, `…_legacy_v100_era`, `…_upgrades_stamp_08_to_09`; populated copy 08→09 (131,280 rows + 28 triggers preserved) | MET |
159 +| Backup flow → `alembic upgrade head` → trigger check | `backup.restore_backup` + `POST /backup/restore`; `test_restore_backup_migrates_and_checks_triggers`, `…_upgrades_a_stale_snapshot` | MET |
160 +| Restore is fail-safe + confined | overwrite refusal, corruption refusal, path-escape 422, non-admin 403, anonymous 401 | MET |
161 +
162 +`backend/tests/test_schema_r4.py` **20 passed**; desktop/auth/admin regression **55 passed**; ruff check + format, mypy (domain strict + services) clean. Decisions in **ADR-035**. No new runtime dependency; protected data untouched.
163 +
164 ## Known gaps feeding the C-phases (honest residual risks)
165
166 - **Authorization forgeability — CLOSED in R1 (2026-12-04, ADR-030).** Was: roles derived from a client-supplied `actor` body string; `"actor":"admin"` granted admin to anyone; most endpoints unguarded; approval open when no users existed; `pilot_api.py` exposed 17 unauthenticated routes. Now: `actor` removed from every request model; identity comes only from `current_user` resolving a 256-bit bearer token whose SHA-256 is stored server-side (8-hour absolute TTL, logout, 5-attempt lockout for 15 minutes, PBKDF2 600,000); every route except `/health`, `/auth/login`, `/auth/launch` and the one-time first-admin bootstrap requires a session, reads included; approval without users is impossible; the pilot router and the legacy `/` UI are out of the app; backup `dest` is confined to the data folder; the desktop launcher gates the local API with a one-time token. Evidence: `backend/tests/test_auth_r1.py` (33 tests). Remaining C8 scope: DPAPI vault, encrypted backup, plugin allowlist, row/field-level access layers.
@@ -158,7 +170,7 @@ non-statement rows (BS 6/16 → 16/16), and per-row note assignment was lost (mi
170 - **Account natures are not populated** by any import path (`account_versions` is empty on real data), so C-15 reports «اجرا نشد» (WARN, non-blocking). A chart-of-accounts import is still missing.
171 - **CF/EQ are still not rendered** (`RENDERED_STATEMENTS=("BS","IS")`). Their official layouts are parsed (R3) but no built statement exists, so CF is 0/6 and C-07 compares their note totals against nothing → carried forward.
172 - **IS 8/9 need an explicit reclassification decision** (1,111,554 million rial) and **IS 20-3 has no source rows**; both are recorded with cause in `docs/discrepancies.json`.
161 -- **Desktop install bypasses Alembic** (`desktop.py` `Base.metadata.create_all`); existing user DBs will not migrate on update → **R4** (booklet 2.1; was C9). R1 added migration `20261204_08` and verified it on a copy of a populated database (131,280 ledger rows, 2 users, 28 triggers unchanged), but the startup path still uses `create_all`.
173 +- ~~Desktop install bypasses Alembic~~ — **CLOSED in R4 (2026-12-04, ADR-035).** `desktop.py initialize_database` now runs `alembic upgrade head` + a D-07 trigger check (no `create_all` in `src/aram_backend/`, guarded by a test); `backup.restore_backup` + `POST /backup/restore` verify → migrate → trigger-check a snapshot. Fresh, versioned, and legacy `create_all` DBs all converge to head (migration 01 is checkfirst `create_all`; 02–09 are guarded) — verified on a populated 131,280-row copy (08→09, rows + 28 triggers preserved) and simulated legacy installs. Evidence: `backend/tests/test_schema_r4.py` (20 tests).
174 - ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent; pilot exception queue not persisted in `domain/` (C1/C4).
175 - `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (C1/C3).
176 - No connector framework / Source Adapter / snapshot reconciliation / packs yet; generality grep test pending (C4/C5/C6).
backend/migrations/env.py
+5 -1
@@ -10,7 +10,11 @@ from aram_backend import models # noqa: F401
10 config = context.config
11 if config.config_file_name:
12 fileConfig(config.config_file_name)
13 -config.set_main_option("sqlalchemy.url", get_settings().database_url)
13 +# R4: a programmatic caller (desktop init, backup restore) passes the exact
14 +# target URL via config.attributes; otherwise fall back to the ambient settings
15 +# (the CI path, where ARAM_DATABASE_URL is set). No behavior change for CI.
16 +_url = config.attributes.get("database_url") or get_settings().database_url
17 +config.set_main_option("sqlalchemy.url", _url)
18 target_metadata = Base.metadata
19
20
backend/src/aram_backend/admin_api.py
+46 -1
@@ -26,7 +26,14 @@ from aram_backend.config import get_settings
26 from aram_backend.database import get_session
27 from aram_backend.models import AuditEntry, User, UserRole
28 from aram_backend.services.audit import verify_chain
29 -from aram_backend.services.backup import BackupError, create_backup, verify_backup
29 +from aram_backend.services.backup import (
30 + BackupError,
31 + allowed_backup_root,
32 + confine_dest,
33 + create_backup,
34 + restore_backup,
35 + verify_backup,
36 +)
37 from aram_backend.services.reopen import (
38 ReopenError,
39 approve_reopen,
@@ -377,3 +384,41 @@ def backup_verify(
384 )
385 except BackupError as exc:
386 raise HTTPException(status_code=422, detail=str(exc)) from exc
387 +
388 +
389 +class RestoreBackupIn(BaseModel):
390 + dest: str = Field(min_length=1, max_length=512)
391 + target: str = Field(default="restored", min_length=1, max_length=128)
392 +
393 +
394 +@router.post("/backup/restore")
395 +def backup_restore(
396 + body: RestoreBackupIn,
397 + session: Session = Depends(get_session),
398 + user: User = Depends(current_user),
399 +) -> dict:
400 + """Restore a verified backup, then migrate to head + check triggers (R4).
401 +
402 + The snapshot is restored into a fresh ``target`` subdirectory of the allowed
403 + data root (never over the live database); the operator then points the app at
404 + it. ``target`` is confined to the data folder. Admin only.
405 + """
406 + _require(user, _ADMIN)
407 + settings = get_settings()
408 + root = allowed_backup_root(settings.source_store_root, settings.backup_root)
409 + try:
410 + data_dir = confine_dest(body.target, store_root=settings.source_store_root,
411 + backup_root=settings.backup_root)
412 + except BackupError as exc:
413 + raise HTTPException(status_code=422, detail=str(exc)) from exc
414 + if data_dir == root:
415 + raise HTTPException(status_code=422, detail="restore target must be a subdirectory")
416 + try:
417 + return restore_backup(
418 + body.dest,
419 + data_dir=data_dir,
420 + store_root=settings.source_store_root,
421 + backup_root=settings.backup_root,
422 + )
423 + except BackupError as exc:
424 + raise HTTPException(status_code=422, detail=str(exc)) from exc
backend/src/aram_backend/db_triggers.py
+40 -1
@@ -245,4 +245,43 @@ def install_on_engine(engine: Engine) -> None:
245 install_triggers(conn)
246
247
248 -__all__ = ["install_triggers", "install_on_engine"]
248 +def expected_trigger_names() -> frozenset[str]:
249 + """The full D-07 trigger set, identical on SQLite and PostgreSQL (R4).
250 +
251 + Used by the post-migration trigger check: a restored or upgraded database
252 + must carry every one of these before it is served (booklet 2.1 R4).
253 + """
254 + names = {
255 + f"aram_lock_{table}_{op}"
256 + for table in _YEAR_TABLES
257 + for op in ("insert", "update", "delete")
258 + }
259 + names |= {
260 + "aram_audit_update",
261 + "aram_audit_delete",
262 + "aram_fiscal_year_transition",
263 + "aram_fiscal_year_no_delete",
264 + }
265 + return frozenset(names)
266 +
267 +
268 +def installed_trigger_names(engine: Engine) -> frozenset[str]:
269 + """Trigger names actually present in the database, per dialect (R4)."""
270 + with engine.connect() as conn:
271 + if conn.dialect.name == "sqlite":
272 + rows = conn.execute(
273 + text("SELECT name FROM sqlite_master WHERE type='trigger'")
274 + ).all()
275 + else:
276 + rows = conn.execute(
277 + text("SELECT tgname FROM pg_trigger WHERE NOT tgisinternal")
278 + ).all()
279 + return frozenset(row[0] for row in rows)
280 +
281 +
282 +__all__ = [
283 + "install_triggers",
284 + "install_on_engine",
285 + "expected_trigger_names",
286 + "installed_trigger_names",
287 +]
backend/src/aram_backend/desktop.py
+18 -7
@@ -25,9 +25,10 @@ from aram_backend.admin_api import public_router as auth_router
25 from aram_backend.admin_api import router as admin_router
26 from aram_backend.auth import LaunchGuard
27 from aram_backend.config import get_settings
28 -from aram_backend.database import Base, build_engine, ensure_triggers
28 +from aram_backend.database import build_engine, ensure_triggers
29 from aram_backend.models import FiscalYearStatus, StatementType # noqa: F401 (register mappers)
30 from aram_backend.schemas import HealthResponse
31 +from aram_backend.services.schema import require_triggers, upgrade_to_head
32 from aram_backend.statement_api import router as statement_router
33
34
@@ -57,14 +58,24 @@ def _bundled_frontend() -> Path | None:
58
59
60 def initialize_database(data_dir: Path) -> None:
60 - """Create the schema + triggers idempotently for a fresh local install."""
61 + """Bring the local database to the current schema via Alembic (R4).
62 +
63 + Replaces the old ``Base.metadata.create_all`` production path: an existing
64 + install is *migrated* on update (``alembic upgrade head``) rather than left
65 + on a stale schema. Fresh, versioned, and legacy ``create_all`` databases all
66 + converge to head (ADR-035). The D-07 trigger set is re-installed and then
67 + verified before the app serves — a missing trigger is a hard failure.
68 + """
69 data_dir.mkdir(parents=True, exist_ok=True)
70 (data_dir / "source_store").mkdir(exist_ok=True)
63 - db_path = data_dir / "aram.db"
64 - engine = build_engine(f"sqlite:///{db_path}")
65 - Base.metadata.create_all(engine)
66 - ensure_triggers(engine)
67 - engine.dispose()
71 + db_url = f"sqlite:///{data_dir / 'aram.db'}"
72 + upgrade_to_head(db_url)
73 + engine = build_engine(db_url)
74 + try:
75 + ensure_triggers(engine)
76 + require_triggers(engine)
77 + finally:
78 + engine.dispose()
79
80
81 def create_desktop_app() -> FastAPI:
backend/src/aram_backend/services/backup.py
+67 -1
@@ -184,4 +184,70 @@ def verify_backup(
184 }
185
186
187 -__all__ = ["BackupError", "allowed_backup_root", "confine_dest", "create_backup", "verify_backup"]
187 +def restore_backup(
188 + backup_dir: str | Path,
189 + *,
190 + data_dir: str | Path,
191 + store_root: str | Path | None = None,
192 + backup_root: str | Path | None = None,
193 +) -> dict[str, Any]:
194 + """Restore a verified backup, then migrate it to head and check triggers (R4).
195 +
196 + Flow (booklet 2.1 R4): ``verify_backup`` (hashes + audit chain) → copy the
197 + snapshot into ``data_dir`` → ``alembic upgrade head`` → re-install and verify
198 + the D-07 trigger set. A restored install is never served on a stale schema.
199 +
200 + Fail-safe: refuses to clobber an existing database or a non-empty store, and
201 + confines the backup read to the allowed data folder when ``store_root`` is
202 + given. The caller stops the app before restoring over a live data directory.
203 + """
204 + # Import here to avoid a cycle: schema -> database -> config, and backup is
205 + # imported by admin_api at module load.
206 + from aram_backend.database import build_engine, ensure_triggers
207 + from aram_backend.services.schema import require_triggers, upgrade_to_head
208 +
209 + if store_root is not None or backup_root:
210 + backup_dir = confine_dest(backup_dir, store_root=store_root or "", backup_root=backup_root)
211 + else:
212 + backup_dir = Path(backup_dir)
213 + report = verify_backup(backup_dir)
214 +
215 + data_dir = Path(data_dir)
216 + db_dest = data_dir / "aram.db"
217 + store_dest = data_dir / "source_store"
218 + if db_dest.exists():
219 + raise BackupError(f"restore target '{db_dest}' already exists; refusing to overwrite")
220 + if store_dest.exists() and any(store_dest.iterdir()):
221 + raise BackupError(f"restore store '{store_dest}' is not empty")
222 + data_dir.mkdir(parents=True, exist_ok=True)
223 + shutil.copyfile(backup_dir / "aram.db", db_dest)
224 + store_src = backup_dir / "source_store"
225 + if store_src.exists():
226 + shutil.copytree(store_src, store_dest, dirs_exist_ok=True)
227 + else:
228 + store_dest.mkdir(parents=True, exist_ok=True)
229 +
230 + db_url = f"sqlite:///{db_dest}"
231 + revision = upgrade_to_head(db_url)
232 + engine = build_engine(db_url)
233 + try:
234 + ensure_triggers(engine)
235 + require_triggers(engine)
236 + finally:
237 + engine.dispose()
238 + return {
239 + **report,
240 + "restored_to": str(db_dest),
241 + "schema_revision": revision,
242 + "triggers_ok": True,
243 + }
244 +
245 +
246 +__all__ = [
247 + "BackupError",
248 + "allowed_backup_root",
249 + "confine_dest",
250 + "create_backup",
251 + "verify_backup",
252 + "restore_backup",
253 +]
backend/src/aram_backend/services/schema.py new
+104
@@ -0,0 +1,104 @@
1 +"""Alembic-only production schema path (R4, booklet 2.1; ADR-035).
2 +
3 +The desktop entrypoint and the backup-restore flow no longer call
4 +``Base.metadata.create_all``: every schema change goes through Alembic so an
5 +existing user database is *migrated* on update instead of being left behind
6 +(the R4 defect — an old install would otherwise never receive migrations 08/09).
7 +
8 +Migration ``20260820_01`` is itself ``create_all`` (checkfirst) and every later
9 +migration is guarded (it checks table/column existence before acting), so
10 +``alembic upgrade head`` converges a fresh, an already-versioned, AND a legacy
11 +``create_all`` database to the same head. This was verified empirically on a
12 +populated 131,280-row copy (08→09, rows + 28 triggers preserved) and on simulated
13 +legacy installs (full-schema and v1.0.0-era, both → revision 09, 28 triggers).
14 +
15 +Offline: no runtime network. The migrations directory ships in the PyInstaller
16 +bundle (``packaging/aram.spec``) and is located relative to this module in a
17 +repo checkout.
18 +"""
19 +
20 +from __future__ import annotations
21 +
22 +import sys
23 +from pathlib import Path
24 +
25 +from alembic import command
26 +from alembic.config import Config
27 +from alembic.migration import MigrationContext
28 +from sqlalchemy.engine import Engine
29 +
30 +from aram_backend.database import build_engine
31 +from aram_backend.db_triggers import expected_trigger_names, installed_trigger_names
32 +
33 +
34 +class SchemaError(RuntimeError):
35 + """Raised when the schema cannot be migrated or the trigger set is incomplete."""
36 +
37 +
38 +def migrations_dir() -> Path:
39 + """Locate the Alembic migrations (PyInstaller bundle or repo checkout)."""
40 + meipass = getattr(sys, "_MEIPASS", None)
41 + if meipass:
42 + bundled = Path(meipass) / "migrations"
43 + if bundled.is_dir():
44 + return bundled
45 + # backend/src/aram_backend/services/schema.py -> backend/migrations
46 + return Path(__file__).resolve().parents[3] / "migrations"
47 +
48 +
49 +def alembic_config(database_url: str) -> Config:
50 + """A Config that targets exactly ``database_url`` without mutating the env.
51 +
52 + ``env.py`` prefers ``config.attributes['database_url']`` over the ambient
53 + settings URL, so the migration runs against the database the caller named
54 + (the desktop data dir, a restored backup) rather than ``ARAM_DATABASE_URL``.
55 + """
56 + cfg = Config()
57 + cfg.set_main_option("script_location", str(migrations_dir()))
58 + cfg.attributes["database_url"] = database_url
59 + cfg.set_main_option("sqlalchemy.url", database_url)
60 + return cfg
61 +
62 +
63 +def current_revision(database_url: str) -> str | None:
64 + """The stamped Alembic revision, or ``None`` for an unversioned database."""
65 + engine = build_engine(database_url)
66 + try:
67 + with engine.connect() as conn:
68 + return MigrationContext.configure(conn).get_current_revision()
69 + finally:
70 + engine.dispose()
71 +
72 +
73 +def upgrade_to_head(database_url: str) -> str:
74 + """Run ``alembic upgrade head`` and return the resulting revision id."""
75 + command.upgrade(alembic_config(database_url), "head")
76 + revision = current_revision(database_url)
77 + if revision is None:
78 + raise SchemaError("alembic upgrade head left no version stamp")
79 + return revision
80 +
81 +
82 +def missing_triggers(engine: Engine) -> frozenset[str]:
83 + """Expected D-07 triggers absent from the database (empty when complete)."""
84 + return expected_trigger_names() - installed_trigger_names(engine)
85 +
86 +
87 +def require_triggers(engine: Engine) -> None:
88 + """Fail loudly if any D-07 trigger is missing after a migration/restore."""
89 + missing = missing_triggers(engine)
90 + if missing:
91 + raise SchemaError(
92 + "trigger check failed after migration; missing: " + ", ".join(sorted(missing))
93 + )
94 +
95 +
96 +__all__ = [
97 + "SchemaError",
98 + "migrations_dir",
99 + "alembic_config",
100 + "current_revision",
101 + "upgrade_to_head",
102 + "missing_triggers",
103 + "require_triggers",
104 +]
backend/tests/test_schema_r4.py new
+343
@@ -0,0 +1,343 @@
1 +"""R4 (booklet 2.1): Alembic-only production schema path + backup restore flow.
2 +
3 +Proves the desktop init and the backup-restore flow go through
4 +``alembic upgrade head`` (never ``create_all`` in production), that fresh,
5 +versioned, and legacy ``create_all`` databases all converge to head with the
6 +full D-07 trigger set, and that a restored backup is migrated + trigger-checked
7 +before it is reported ready (ADR-035).
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +import sqlite3
13 +from pathlib import Path
14 +
15 +import pytest
16 +from sqlalchemy.orm import sessionmaker
17 +
18 +from aram_backend.database import Base, build_engine, ensure_triggers
19 +from aram_backend.db_triggers import expected_trigger_names, installed_trigger_names
20 +from aram_backend.desktop import initialize_database
21 +from aram_backend.services.backup import BackupError, create_backup, restore_backup
22 +from aram_backend.services.schema import (
23 + SchemaError,
24 + alembic_config,
25 + current_revision,
26 + migrations_dir,
27 + missing_triggers,
28 + require_triggers,
29 + upgrade_to_head,
30 +)
31 +from conftest import make_user
32 +
33 +HEAD = "20261204_09"
34 +
35 +
36 +def _inspect(path: Path) -> dict:
37 + conn = sqlite3.connect(str(path))
38 + try:
39 + try:
40 + version = conn.execute("SELECT version_num FROM alembic_version").fetchone()[0]
41 + except sqlite3.OperationalError:
42 + version = None
43 + tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
44 + lb_cols = {r[1] for r in conn.execute("PRAGMA table_info(ledger_balances)")}
45 + user_cols = {r[1] for r in conn.execute("PRAGMA table_info(users)")}
46 + triggers = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='trigger'")}
47 + rows = conn.execute("SELECT COUNT(*) FROM ledger_balances").fetchone()[0]
48 + finally:
49 + conn.close()
50 + return {
51 + "version": version,
52 + "tables": tables,
53 + "lb_cols": lb_cols,
54 + "user_cols": user_cols,
55 + "triggers": triggers,
56 + "rows": rows,
57 + }
58 +
59 +
60 +def _legacy_create_all(path: Path) -> None:
61 + """Simulate a pre-Alembic desktop install: create_all, no alembic_version."""
62 + engine = build_engine(f"sqlite:///{path}")
63 + Base.metadata.create_all(engine)
64 + ensure_triggers(engine)
65 + engine.dispose()
66 +
67 +
68 +# ----------------------------------------------------------- schema service
69 +
70 +
71 +def test_migrations_dir_exists_and_has_versions():
72 + d = migrations_dir()
73 + assert d.is_dir()
74 + assert (d / "versions").is_dir()
75 + assert (d / "env.py").exists()
76 +
77 +
78 +def test_alembic_config_targets_the_named_url(tmp_path):
79 + url = f"sqlite:///{tmp_path / 'x.db'}"
80 + cfg = alembic_config(url)
81 + assert cfg.attributes["database_url"] == url
82 + assert cfg.get_main_option("script_location") == str(migrations_dir())
83 +
84 +
85 +def test_current_revision_none_on_unversioned(tmp_path):
86 + path = tmp_path / "legacy.db"
87 + _legacy_create_all(path)
88 + assert current_revision(f"sqlite:///{path}") is None
89 +
90 +
91 +def test_upgrade_to_head_on_fresh_db(tmp_path):
92 + url = f"sqlite:///{tmp_path / 'fresh.db'}"
93 + assert upgrade_to_head(url) == HEAD
94 + info = _inspect(tmp_path / "fresh.db")
95 + assert info["version"] == HEAD
96 + assert "auth_sessions" in info["tables"]
97 + assert "source_note" in info["lb_cols"]
98 +
99 +
100 +# ----------------------------------------------------------- desktop init (R4)
101 +
102 +
103 +def test_initialize_database_uses_alembic_not_create_all(tmp_path):
104 + data_dir = tmp_path / "aram-data"
105 + initialize_database(data_dir)
106 + info = _inspect(data_dir / "aram.db")
107 + # The production path now stamps an Alembic version (create_all never did).
108 + assert info["version"] == HEAD
109 + assert (data_dir / "source_store").is_dir()
110 + assert expected_trigger_names() <= info["triggers"]
111 +
112 +
113 +def test_initialize_database_is_idempotent(tmp_path):
114 + data_dir = tmp_path / "aram-data"
115 + initialize_database(data_dir)
116 + initialize_database(data_dir)
117 + assert _inspect(data_dir / "aram.db")["version"] == HEAD
118 +
119 +
120 +def test_initialize_database_migrates_legacy_full_schema(tmp_path):
121 + """A legacy create_all install (current schema, no version) converges to head."""
122 + data_dir = tmp_path / "aram-data"
123 + data_dir.mkdir()
124 + _legacy_create_all(data_dir / "aram.db")
125 + assert _inspect(data_dir / "aram.db")["version"] is None
126 + initialize_database(data_dir)
127 + info = _inspect(data_dir / "aram.db")
128 + assert info["version"] == HEAD
129 + assert expected_trigger_names() <= info["triggers"]
130 +
131 +
132 +def test_initialize_database_migrates_legacy_v100_era(tmp_path):
133 + """A v1.0.0-era install (no auth_sessions/source_note/password_rounds) is upgraded."""
134 + data_dir = tmp_path / "aram-data"
135 + data_dir.mkdir()
136 + db = data_dir / "aram.db"
137 + _legacy_create_all(db)
138 + conn = sqlite3.connect(str(db))
139 + conn.execute("DROP TABLE auth_sessions")
140 + conn.execute("ALTER TABLE ledger_balances RENAME TO lb_old")
141 + cols = [r[1] for r in conn.execute("PRAGMA table_info(lb_old)") if r[1] != "source_note"]
142 + conn.execute(f"CREATE TABLE ledger_balances AS SELECT {','.join(cols)} FROM lb_old")
143 + conn.execute("DROP TABLE lb_old")
144 + for col in ("password_rounds", "failed_login_count", "locked_until"):
145 + conn.execute(f"ALTER TABLE users DROP COLUMN {col}")
146 + conn.commit()
147 + conn.close()
148 + before = _inspect(db)
149 + assert "auth_sessions" not in before["tables"]
150 + assert "source_note" not in before["lb_cols"]
151 +
152 + initialize_database(data_dir)
153 + after = _inspect(db)
154 + assert after["version"] == HEAD
155 + assert "auth_sessions" in after["tables"]
156 + assert "source_note" in after["lb_cols"]
157 + assert "password_rounds" in after["user_cols"]
158 + assert expected_trigger_names() <= after["triggers"]
159 +
160 +
161 +def test_initialize_database_upgrades_stamp_08_to_09(tmp_path):
162 + """A DB stamped at 08 (source_note absent) is upgraded to 09 by init."""
163 + data_dir = tmp_path / "aram-data"
164 + data_dir.mkdir()
165 + db = data_dir / "aram.db"
166 + url = f"sqlite:///{db}"
167 + # Build at head, then rewind the stamp to 08 and drop source_note to mimic 08.
168 + upgrade_to_head(url)
169 + engine = build_engine(url)
170 + Base.metadata.create_all(engine) # ensure all tables (no-op at head)
171 + ensure_triggers(engine)
172 + engine.dispose()
173 + conn = sqlite3.connect(str(db))
174 + conn.execute("UPDATE alembic_version SET version_num='20261204_08'")
175 + conn.execute("ALTER TABLE ledger_balances RENAME TO lb_old")
176 + cols = [r[1] for r in conn.execute("PRAGMA table_info(lb_old)") if r[1] != "source_note"]
177 + conn.execute(f"CREATE TABLE ledger_balances AS SELECT {','.join(cols)} FROM lb_old")
178 + conn.execute("DROP TABLE lb_old")
179 + conn.commit()
180 + conn.close()
181 +
182 + initialize_database(data_dir)
183 + after = _inspect(db)
184 + assert after["version"] == HEAD
185 + assert "source_note" in after["lb_cols"]
186 +
187 +
188 +# ----------------------------------------------------------- trigger check
189 +
190 +
191 +def test_require_triggers_passes_on_complete_set(tmp_path):
192 + url = f"sqlite:///{tmp_path / 't.db'}"
193 + upgrade_to_head(url)
194 + engine = build_engine(url)
195 + ensure_triggers(engine)
196 + try:
197 + assert missing_triggers(engine) == frozenset()
198 + require_triggers(engine) # must not raise
199 + assert expected_trigger_names() <= installed_trigger_names(engine)
200 + finally:
201 + engine.dispose()
202 +
203 +
204 +def test_require_triggers_fails_when_one_is_missing(tmp_path):
205 + url = f"sqlite:///{tmp_path / 't.db'}"
206 + upgrade_to_head(url)
207 + engine = build_engine(url)
208 + ensure_triggers(engine)
209 + with engine.begin() as conn:
210 + from sqlalchemy import text
211 +
212 + conn.execute(text("DROP TRIGGER aram_audit_update"))
213 + try:
214 + assert "aram_audit_update" in missing_triggers(engine)
215 + with pytest.raises(SchemaError, match="aram_audit_update"):
216 + require_triggers(engine)
217 + finally:
218 + engine.dispose()
219 +
220 +
221 +# ----------------------------------------------------------- backup restore (R4)
222 +
223 +
224 +def _make_backup(tmp_path: Path) -> Path:
225 + """Create a real backup of a small populated DB inside the allowed root."""
226 + store = tmp_path / "store"
227 + store.mkdir()
228 + db = tmp_path / "live.db"
229 + url = f"sqlite:///{db}"
230 + upgrade_to_head(url)
231 + engine = build_engine(url)
232 + ensure_triggers(engine)
233 + factory = sessionmaker(bind=engine, expire_on_commit=False)
234 + with factory() as session:
235 + backup_dir = tmp_path / "bk"
236 + create_backup(session, backup_dir, store_root=store)
237 + engine.dispose()
238 + return backup_dir
239 +
240 +
241 +def test_restore_backup_migrates_and_checks_triggers(tmp_path):
242 + backup_dir = _make_backup(tmp_path)
243 + target = tmp_path / "restored"
244 + report = restore_backup(backup_dir, data_dir=target, store_root=tmp_path / "store")
245 + assert report["valid"] is True
246 + assert report["schema_revision"] == HEAD
247 + assert report["triggers_ok"] is True
248 + info = _inspect(target / "aram.db")
249 + assert info["version"] == HEAD
250 + assert expected_trigger_names() <= info["triggers"]
251 + assert (target / "source_store").is_dir()
252 +
253 +
254 +def test_restore_backup_refuses_to_overwrite_existing_db(tmp_path):
255 + backup_dir = _make_backup(tmp_path)
256 + target = tmp_path / "restored"
257 + target.mkdir()
258 + (target / "aram.db").write_bytes(b"existing")
259 + with pytest.raises(BackupError, match="already exists"):
260 + restore_backup(backup_dir, data_dir=target, store_root=tmp_path / "store")
261 +
262 +
263 +def test_restore_backup_rejects_corrupt_snapshot(tmp_path):
264 + backup_dir = _make_backup(tmp_path)
265 + # Tamper with the backed-up database so its hash no longer matches.
266 + (backup_dir / "aram.db").write_bytes(b"corrupt")
267 + with pytest.raises(BackupError, match="hash mismatch"):
268 + restore_backup(backup_dir, data_dir=tmp_path / "restored", store_root=tmp_path / "store")
269 +
270 +
271 +def test_restore_backup_upgrades_a_stale_snapshot(tmp_path):
272 + """A backup whose DB is stamped at 08 is migrated to 09 on restore."""
273 + backup_dir = _make_backup(tmp_path)
274 + db = backup_dir / "aram.db"
275 + conn = sqlite3.connect(str(db))
276 + conn.execute("UPDATE alembic_version SET version_num='20261204_08'")
277 + conn.execute("ALTER TABLE ledger_balances RENAME TO lb_old")
278 + cols = [r[1] for r in conn.execute("PRAGMA table_info(lb_old)") if r[1] != "source_note"]
279 + conn.execute(f"CREATE TABLE ledger_balances AS SELECT {','.join(cols)} FROM lb_old")
280 + conn.execute("DROP TABLE lb_old")
281 + conn.commit()
282 + conn.close()
283 + # Re-hash so verify_backup passes (the manifest must match the edited file).
284 + import hashlib
285 + import json
286 +
287 + digest = hashlib.sha256(db.read_bytes()).hexdigest()
288 + manifest = json.loads((backup_dir / "manifest.json").read_text(encoding="utf-8"))
289 + manifest["database_sha256"] = digest
290 + (backup_dir / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
291 +
292 + report = restore_backup(backup_dir, data_dir=tmp_path / "restored", store_root=tmp_path / "store")
293 + assert report["schema_revision"] == HEAD
294 + assert "source_note" in _inspect(tmp_path / "restored" / "aram.db")["lb_cols"]
295 +
296 +
297 +# ----------------------------------------------------------- restore API (R4)
298 +
299 +
300 +def test_restore_api_admin_roundtrip(api_client, tmp_path):
301 + created = api_client.post("/api/v1/backup", json={"dest": "bk"})
302 + assert created.status_code == 200, created.text
303 + restored = api_client.post("/api/v1/backup/restore", json={"dest": "bk", "target": "restored"})
304 + assert restored.status_code == 200, restored.text
305 + body = restored.json()
306 + assert body["schema_revision"] == HEAD
307 + assert body["triggers_ok"] is True
308 + assert (tmp_path / "restored" / "aram.db").exists()
309 +
310 +
311 +def test_restore_api_rejects_path_escape(api_client):
312 + api_client.post("/api/v1/backup", json={"dest": "bk"})
313 + escape = api_client.post(
314 + "/api/v1/backup/restore", json={"dest": "bk", "target": "../../etc"}
315 + )
316 + assert escape.status_code == 422
317 +
318 +
319 +def test_restore_api_requires_admin(api_client):
320 + api_client.post("/api/v1/backup", json={"dest": "bk"})
321 + token = make_user(api_client, "prep", "preparer")
322 + api_client.headers.update({"Authorization": f"Bearer {token}"})
323 + denied = api_client.post("/api/v1/backup/restore", json={"dest": "bk", "target": "restored"})
324 + assert denied.status_code == 403
325 +
326 +
327 +def test_restore_api_unauthenticated_is_401(anon_client):
328 + r = anon_client.post("/api/v1/backup/restore", json={"dest": "bk", "target": "restored"})
329 + assert r.status_code == 401
330 +
331 +
332 +# ----------------------------------------------------------- production-path guard
333 +
334 +
335 +def test_no_create_all_in_production_source():
336 + """The production path must not call create_all (R4); tests/migrations may."""
337 + src = Path(__file__).resolve().parents[1] / "src" / "aram_backend"
338 + offenders = []
339 + for py in src.rglob("*.py"):
340 + text = py.read_text(encoding="utf-8")
341 + if ".create_all(" in text:
342 + offenders.append(str(py.relative_to(src)))
343 + assert offenders == [], f"create_all still in production source: {offenders}"
docs/PROJECT_LOG.md
+12
@@ -505,3 +505,15 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
505 - Base verified live before editing: `origin/source-data-cleanup` = **07e879ba1946e22c85560c8b886ba7b3ef26cde1** (#115 governance sync, after #99 `70a0110` and #114 `3c7638d`); working branch merged to it, tree identical. Open-PR collision scan: Dependabot #102–#113 + legacy #70–#92 — none touch governance docs.
506 - T1 evidence on this tree (docs-only delta over the accepted head): `pre-commit run --all-files` 8/8 Passed exit 0; secret gate «19 baselined finding(s), 0 new»; `git diff --check` clean; protected trees `data` `2ef8a512…` / `samples` `00aba54b…` unchanged; backend `pytest --cov=aram_backend --cov-fail-under=80` → **89.91%** total, `coverage report --include='*/domain/*' --fail-under=90` → **96%**; fail-closed approval reproduced on a fresh DB (15 controls, unrun C-05..C-15 report «اجرا نشد:», year stays Draft).
507 - Next under the amended loop: retroactive T1 verdicts for R2/#100 and R3/#101, then R4 (create_all → alembic upgrade head; backup → upgrade → trigger check), R5 (`docs/c01_exceptions.json`), R6 (pre-release checklist; marking = owner action).
508 +
509 +### 2026-12-04T15:05:00Z — R4: Alembic-only production schema path + backup restore (ADR-035)
510 +
511 +- Actor: Arena agent (B1 implement → T1 gate → M0 integrate, ADR-034). Base: `4dd29cde2b854c771d0569add620a87e9d8df835` (PR #116 governance squash, verified live; working branch tree-identical before starting).
512 +- **Defect reproduced live:** the preview DB (stamped `20261204_08`, 131,280 rows) raised `no such column: ledger_balances.source_note` under the R3 ORM — `create_all` never alters existing tables, so an updating install was left on a stale schema (booklet 2.1 R4, was C9).
513 +- **`services/schema.py` (new):** `upgrade_to_head` / `current_revision` / `alembic_config` / `migrations_dir` (repo or PyInstaller `_MEIPASS`) + `missing_triggers` / `require_triggers`. Target URL passed via `config.attributes["database_url"]`; `migrations/env.py` prefers it over ambient settings (CI path unchanged, no env mutation).
514 +- **`desktop.py initialize_database`:** `Base.metadata.create_all` removed → `alembic upgrade head` + `ensure_triggers` + `require_triggers` (hard `SchemaError` on any missing D-07 trigger). `test_no_create_all_in_production_source` guards `src/aram_backend/`.
515 +- **`db_triggers.py`:** `expected_trigger_names()` (the full 28-trigger set, same names on SQLite/PostgreSQL) + `installed_trigger_names(engine)` (dialect-aware).
516 +- **`backup.restore_backup` + `POST /api/v1/backup/restore` (admin):** verify (hashes + audit chain) → copy into a confined fresh `target` subdir → `alembic upgrade head` → re-install + verify triggers → report `schema_revision`/`triggers_ok`. Refuses to clobber an existing DB/non-empty store; path-escape confined (R1 discipline).
517 +- **Why upgrade head is universally safe (evidence before code):** migration 01 is checkfirst `create_all`; 02–09 are all guarded. Verified: populated copy 08→09 (131,280 rows + 28 triggers preserved); legacy full-schema create_all (no version) → 09; legacy v1.0.0-era (auth_sessions/source_note/password_rounds absent) → 09 with all re-added. No stamping ladder needed.
518 +- Gates: `tests/test_schema_r4.py` **20 passed**; desktop+auth_r1+phase7_admin regression **55 passed**; `ruff check src tests` clean; `ruff format --check` (domain/services/migrations) 36 files clean; mypy domain-strict (6) + services (20) clean. Full suite + coverage floors recorded in the PR.
519 +- Protected data: `data/` `2ef8a512…` / `samples/` `00aba54b…` unchanged; no financial value touched; no new runtime dependency (Alembic already required). Tag `v1.0.0` untouched.
docs/adr/ADR-035-alembic-only-production-schema.md new
+83
@@ -0,0 +1,83 @@
1 +# ADR-035 — Alembic-only production schema path; backup restore migrates + checks triggers (R4)
2 +
3 +- Status: accepted
4 +- Date: 2026-12-04
5 +- Scope: backend production schema initialization and the backup-restore flow.
6 +- Implements: booklet 2.1 **R4** — «remove `create_all` from the production path;
7 + backup flow → `alembic upgrade head` → trigger check».
8 +- Supersedes: the Phase-8 desktop practice of calling `Base.metadata.create_all`
9 + at startup (`desktop.py initialize_database`). The model metadata is still the
10 + single schema definition; only the *production application path* changes.
11 +
12 +## Context
13 +
14 +`desktop.py initialize_database` created the schema with
15 +`Base.metadata.create_all(engine)`. `create_all` only creates **missing tables**;
16 +it never alters an existing one. An install made at v1.0.0 therefore never
17 +received migration `20261204_08` (auth sessions / lockout) or `20261204_09`
18 +(`LedgerBalance.source_note`) when the application updated — the database was
19 +silently left on a stale schema while the ORM expected the new columns. This was
20 +reproduced live: the preview database (stamped `20261204_08`, 131,280 ledger rows)
21 +raised `no such column: ledger_balances.source_note` under the R3 ORM.
22 +
23 +The backup flow could create and verify a snapshot but had no restore path, so a
24 +restored database was never migrated or trigger-checked before use.
25 +
26 +## Decision
27 +
28 +1. **Alembic is the only production schema path.** `initialize_database` now runs
29 + `alembic upgrade head` against the local database, then re-installs and
30 + **verifies** the D-07 trigger set (`require_triggers`); a missing trigger is a
31 + hard `SchemaError`. No `create_all` call remains in `src/aram_backend/`
32 + (enforced by `test_no_create_all_in_production_source`).
33 +2. **A new `services/schema.py`** owns `upgrade_to_head`, `current_revision`,
34 + `alembic_config`, `migrations_dir` (repo checkout or PyInstaller `_MEIPASS`),
35 + and the trigger check. The target URL is passed via
36 + `config.attributes["database_url"]`; `migrations/env.py` prefers it over the
37 + ambient settings URL, so no process-environment mutation is needed and the CI
38 + path (`ARAM_DATABASE_URL` set, no attribute) is unchanged.
39 +3. **Restore = verify → migrate → trigger check.** `backup.restore_backup`
40 + verifies the snapshot (hashes + audit chain), copies it into a fresh target,
41 + runs `alembic upgrade head`, re-installs and verifies triggers, and only then
42 + reports ready (`schema_revision`, `triggers_ok`). It refuses to clobber an
43 + existing database or non-empty store. `POST /api/v1/backup/restore` (admin
44 + only) restores into a confined `target` subdirectory of the data root — never
45 + over the live install.
46 +4. **`db_triggers.expected_trigger_names()` / `installed_trigger_names()`** expose
47 + the full 28-trigger D-07 set (identical names on SQLite and PostgreSQL) so the
48 + check is dialect-aware and exact.
49 +
50 +## Why `alembic upgrade head` is safe on every existing database
51 +
52 +Migration `20260820_01` is itself `Base.metadata.create_all(bind)` (checkfirst),
53 +and **every** later migration (02–09) is guarded — it inspects table/column/
54 +constraint existence before acting. Consequently `upgrade head` converges:
55 +
56 +- a **fresh** database (01 creates the schema, 02–09 are guarded no-ops);
57 +- an **already-versioned** database (only the missing revisions run);
58 +- a **legacy `create_all` install with no `alembic_version`** (01's checkfirst
59 + create_all skips existing tables; 02–09 add exactly what is missing).
60 +
61 +No stamping ladder or schema archaeology is required. Verified empirically before
62 +implementation (ADR evidence, reproducible):
63 +
64 +| Case | Before | After `upgrade head` |
65 +| --- | --- | --- |
66 +| Populated copy, stamped 08 | 131,280 rows, 28 triggers, no `source_note` | rev 09, **131,280 rows preserved**, 28 triggers, `source_note` added |
67 +| Legacy full-schema `create_all`, no version | rev None, all objects | rev 09, 28 triggers |
68 +| Legacy v1.0.0-era (no `auth_sessions`/`source_note`/`password_rounds`) | rev None, objects absent | rev 09, all re-added, 28 triggers |
69 +
70 +## Consequences
71 +
72 +- Existing desktop installs migrate forward on update; the stale-schema defect
73 + (booklet 2.1 R4, was C9) is closed.
74 +- `tests/test_schema_r4.py` (20 tests) covers fresh/idempotent/legacy/versioned
75 + init, the trigger check (positive + negative), restore (roundtrip, overwrite
76 + refusal, corruption refusal, stale-snapshot upgrade), the restore API (admin
77 + roundtrip, path-escape 422, non-admin 403, anonymous 401), and the
78 + no-`create_all`-in-production guard.
79 +- Test fixtures and migration 01 still use `create_all` — that is correct: the
80 + guard scopes only `src/aram_backend/`, and migration 01 *is* the Alembic path.
81 +- No new runtime dependency (Alembic is already required for migrations). Offline
82 + runtime preserved; protected `data/`/`samples/` untouched; no financial value
83 + changed. Tagging/releases remain owner actions (ADR-034).