@davoodmehraban89 / Aram-1 / commits / 8412c56
Fork 0

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>

davoodmehraban89 committed Dec 3, 2026 at 09:33 UTC 8412c562002eb35fbf1a80f0d9365cbf15527050
30 files changed +410 -153
.github/workflows/backend-ci.yml
+62 -4
@@ -16,7 +16,8 @@ permissions:
16 contents: read
17
18 jobs:
19 - test:
19 + quality:
20 + name: Lint, types, coverage
21 runs-on: ubuntu-latest
22 defaults:
23 run:
@@ -30,13 +31,70 @@ jobs:
31 cache-dependency-path: backend/pyproject.toml
32 - name: Install
33 run: python -m pip install -e '.[test]'
33 - - name: Test
34 - run: pytest
35 - - name: Validate migration round-trip
34 + - name: Whitespace guard
35 + run: git diff --check
36 + - name: Ruff lint
37 + run: ruff check src tests
38 + - name: Ruff format (Phase-0 layers)
39 + run: ruff format --check src/aram_backend/domain src/aram_backend/services migrations
40 + - name: Mypy (domain, strict)
41 + run: mypy src/aram_backend/domain
42 + - name: Tests + coverage gates
43 + run: |
44 + pytest --cov=aram_backend --cov-report=term-missing --cov-report=xml \
45 + --cov-fail-under=80
46 + coverage report --include='*/domain/*' --fail-under=90
47 + - name: Dependency vulnerability scan
48 + run: pip-audit --progress-spinner off
49 +
50 + migrations:
51 + name: Migration round-trip (${{ matrix.dialect }})
52 + runs-on: ubuntu-latest
53 + strategy:
54 + fail-fast: false
55 + matrix:
56 + dialect: [sqlite, postgresql]
57 + defaults:
58 + run:
59 + working-directory: backend
60 + services:
61 + postgres:
62 + image: postgres:16
63 + env:
64 + POSTGRES_USER: aram
65 + POSTGRES_PASSWORD: aram
66 + POSTGRES_DB: aram_test
67 + ports:
68 + - 5432:5432
69 + options: >-
70 + --health-cmd "pg_isready -U aram"
71 + --health-interval 10s
72 + --health-timeout 5s
73 + --health-retries 5
74 + steps:
75 + - uses: actions/checkout@v4
76 + - uses: actions/setup-python@v5
77 + with:
78 + python-version: "3.12"
79 + cache: pip
80 + cache-dependency-path: backend/pyproject.toml
81 + - name: Install
82 + run: python -m pip install -e '.[test,ci]'
83 + - name: SQLite round-trip
84 + if: matrix.dialect == 'sqlite'
85 env:
86 ARAM_DATABASE_URL: sqlite:///./ci-migration.db
87 run: |
88 alembic upgrade head
89 alembic downgrade base
90 + alembic upgrade head
91 + - name: PostgreSQL round-trip
92 + if: matrix.dialect == 'postgresql'
93 + env:
94 + ARAM_DATABASE_URL: postgresql+psycopg://aram:aram@localhost:5432/aram_test
95 + run: |
96 + alembic upgrade head
97 + alembic downgrade base
98 + alembic upgrade head
99 - name: Compile
100 run: python -m compileall -q src tests migrations
backend/.gitignore
+6
@@ -6,4 +6,10 @@ __pycache__/
6 *.db
7 *.sqlite
8 *.sqlite3
9 +.coverage
10 +.coverage.*
11 +htmlcov/
12 +coverage.xml
13 +.mypy_cache/
14 +.ruff_cache/
15
backend/pyproject.toml
+43 -1
@@ -20,8 +20,16 @@ dependencies = [
20 [project.optional-dependencies]
21 test = [
22 "httpx>=0.28,<1",
23 - "pytest>=8.3,<9",
23 + "pytest>=9.0.3,<10",
24 "hypothesis>=6.100,<7",
25 + "ruff>=0.8,<1",
26 + "mypy>=1.13,<2",
27 + "coverage>=7.6,<8",
28 + "pytest-cov>=6.0,<7",
29 + "pip-audit>=2.7,<3",
30 +]
31 +ci = [
32 + "psycopg[binary]>=3.2,<4",
33 ]
34
35 [tool.setuptools.packages.find]
@@ -31,3 +39,37 @@ where = ["src"]
39 testpaths = ["tests"]
40 addopts = "-q"
41
42 +[tool.ruff]
43 +line-length = 100
44 +target-version = "py311"
45 +src = ["src", "tests"]
46 +
47 +[tool.ruff.lint]
48 +select = ["E", "F", "I", "UP", "B"]
49 +ignore = ["E501"]
50 +
51 +[tool.ruff.lint.flake8-bugbear]
52 +extend-immutable-calls = ["fastapi.File", "fastapi.Depends", "fastapi.Query", "fastapi.Form"]
53 +
54 +[tool.mypy]
55 +python_version = "3.11"
56 +plugins = []
57 +warn_unused_ignores = true
58 +warn_redundant_casts = true
59 +
60 +[[tool.mypy.overrides]]
61 +module = "aram_backend.domain.*"
62 +strict = true
63 +
64 +[[tool.mypy.overrides]]
65 +module = ["openpyxl.*", "hypothesis.*"]
66 +ignore_missing_imports = true
67 +
68 +[tool.coverage.run]
69 +source = ["aram_backend"]
70 +branch = true
71 +
72 +[tool.coverage.report]
73 +show_missing = true
74 +exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:", "raise NotImplementedError"]
75 +
backend/src/aram_backend/database.py
-1
@@ -52,4 +52,3 @@ SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
52 def get_session() -> Generator[Session, None, None]:
53 with SessionLocal() as session:
54 yield session
55 -
backend/src/aram_backend/db_triggers.py
+3 -11
@@ -20,12 +20,9 @@ _YEAR_TABLES: dict[str, str] = {
20 "mapping_rules": "{alias}.year_id",
21 "financial_statements": "{alias}.year_id",
22 "source_documents": "{alias}.year_id",
23 - "note_rows": (
24 - "(SELECT nd.year_id FROM note_definitions nd WHERE nd.id = {alias}.note_id)"
25 - ),
23 + "note_rows": ("(SELECT nd.year_id FROM note_definitions nd WHERE nd.id = {alias}.note_id)"),
24 "statement_lines": (
27 - "(SELECT fs.year_id FROM financial_statements fs "
28 - "WHERE fs.id = {alias}.statement_id)"
25 + "(SELECT fs.year_id FROM financial_statements fs WHERE fs.id = {alias}.statement_id)"
26 ),
27 }
28
@@ -53,12 +50,7 @@ def _install_sqlite(conn: Connection) -> None:
50 name = f"aram_lock_{table}_{op.lower()}"
51 conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
52 check = _locked_check_sqlite(table, alias)
56 - conn.execute(
57 - text(
58 - f"CREATE TRIGGER {name} BEFORE {op} ON {table} "
59 - f"BEGIN {check}; END"
60 - )
61 - )
53 + conn.execute(text(f"CREATE TRIGGER {name} BEFORE {op} ON {table} BEGIN {check}; END"))
54 # Audit log is append-only.
55 for op in ("UPDATE", "DELETE"):
56 name = f"aram_audit_{op.lower()}"
backend/src/aram_backend/domain/__init__.py
+1 -1
@@ -7,12 +7,12 @@ controls (C-01..C-04). Every function here is deterministic and unit-testable
7 without a database (booklet section 4, domain layer).
8 """
9
10 +from aram_backend.domain.money import Rial, allocate_remainder, round_half_up
11 from aram_backend.domain.normalization import (
12 decimal_from_cell,
13 normalize_code,
14 normalize_fa,
15 )
15 -from aram_backend.domain.money import Rial, round_half_up, allocate_remainder
16
17 __all__ = [
18 "normalize_fa",
backend/src/aram_backend/domain/controls.py
+3 -9
@@ -61,9 +61,7 @@ def _aggregate(rows: list[BalanceRow]) -> dict[str, dict[str, Decimal]]:
61 def check_c01(rows: list[BalanceRow]) -> ControlResult:
62 """C-01: every row satisfies opening + debit - credit - closing = 0."""
63 bad = tuple(
64 - str(r.row_number)
65 - for r in rows
66 - if r.opening + r.debit - r.credit - r.closing != _ZERO
64 + str(r.row_number) for r in rows if r.opening + r.debit - r.credit - r.closing != _ZERO
65 )
66 return ControlResult(
67 code="C-01",
@@ -101,9 +99,7 @@ def _is_active(bucket: dict[str, Decimal]) -> bool:
99 return any(bucket[k] != _ZERO for k in ("opening", "debit", "credit", "closing"))
100
101
104 -def check_c03(
105 - rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
106 -) -> ControlResult:
102 +def check_c03(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]) -> ControlResult:
103 """C-03: each active account has exactly one active mapping (or 100% split)."""
104 bad: list[str] = []
105 for code, bucket in sorted(_aggregate(rows).items()):
@@ -128,9 +124,7 @@ def check_c03(
124 )
125
126
131 -def check_c04(
132 - rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
133 -) -> ControlResult:
127 +def check_c04(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]) -> ControlResult:
128 """C-04: unmapped active accounts enter the unknown queue and block approval."""
129 queue = tuple(
130 code
backend/src/aram_backend/domain/hierarchy.py
+1 -1
@@ -108,7 +108,7 @@ def account_level(levels: AccountLevels) -> str:
108 """Deepest populated level name, matching the Pilot contract vocabulary."""
109 names = ("General", "Subsidiary", "Detail1", "Detail2", "Detail3", "Detail4")
110 deepest = "General"
111 - for name, code in zip(names, levels.as_tuple()):
111 + for name, code in zip(names, levels.as_tuple(), strict=True):
112 if code:
113 deepest = name
114 return deepest
backend/src/aram_backend/domain/money.py
+5 -7
@@ -11,7 +11,7 @@ between rows and their total is allocated by the largest-remainder method
11
12 from __future__ import annotations
13
14 -from decimal import Decimal, ROUND_HALF_UP
14 +from decimal import ROUND_HALF_UP, Decimal
15 from typing import Any
16
17 from sqlalchemy import BigInteger
@@ -20,7 +20,7 @@ from sqlalchemy.types import TypeDecorator
20
21 #: Integer rial; evidence-based (ADR-012). 10**0 == 1.
22 RIAL_SCALE = 0
23 -_FACTOR = 10**RIAL_SCALE
23 +_FACTOR: int = 10**RIAL_SCALE
24
25
26 class Rial(TypeDecorator[Decimal]):
@@ -59,7 +59,7 @@ class Rial(TypeDecorator[Decimal]):
59 def process_result_value(self, value: Any, dialect: Dialect) -> Decimal | None:
60 if value is None:
61 return None
62 - return Decimal(int(value)) / _FACTOR
62 + return Decimal(int(value)) / Decimal(_FACTOR)
63
64
65 def round_half_up(value: Decimal, places: int = 0) -> Decimal:
@@ -68,9 +68,7 @@ def round_half_up(value: Decimal, places: int = 0) -> Decimal:
68 return value.quantize(quantum, rounding=ROUND_HALF_UP)
69
70
71 -def allocate_remainder(
72 - values: list[Decimal], total: Decimal, places: int = 0
73 -) -> list[Decimal]:
71 +def allocate_remainder(values: list[Decimal], total: Decimal, places: int = 0) -> list[Decimal]:
72 """Round rows so they sum exactly to the rounded total (largest remainder).
73
74 Deterministic and stable: rows are adjusted in order of their rounding
@@ -86,7 +84,7 @@ def allocate_remainder(
84 if diff == 0:
85 return rounded
86 steps = int(diff / quantum)
89 - errors = [v - r for v, r in zip(values, rounded)]
87 + errors = [v - r for v, r in zip(values, rounded, strict=True)]
88 order = sorted(range(len(values)), key=lambda i: (errors[i], -i), reverse=steps > 0)
89 result = list(rounded)
90 sign = 1 if steps > 0 else -1
backend/src/aram_backend/domain/normalization.py
+7 -9
@@ -21,12 +21,12 @@ from decimal import Decimal, InvalidOperation
21 _TRANSLATION = {
22 0x064A: 0x06CC, # Arabic yeh ي -> Persian yeh ی
23 0x0643: 0x06A9, # Arabic kaf ك -> Persian kaf ک
24 - 0x0640: None, # tatweel / kashida ـ removed
25 - 0x00A0: None, # no-break space removed
26 - 0x200B: None, # zero-width space removed
27 - 0x200E: None, # left-to-right mark removed
28 - 0x200F: None, # right-to-left mark removed
29 - 0xFEFF: None, # zero-width no-break space / BOM removed
24 + 0x0640: None, # tatweel / kashida ـ removed
25 + 0x00A0: None, # no-break space removed
26 + 0x200B: None, # zero-width space removed
27 + 0x200E: None, # left-to-right mark removed
28 + 0x200F: None, # right-to-left mark removed
29 + 0xFEFF: None, # zero-width no-break space / BOM removed
30 }
31 for _i in range(10):
32 _TRANSLATION[0x06F0 + _i] = 0x30 + _i # Persian digits ۰-۹
@@ -78,9 +78,7 @@ def normalize_code(value: object, *, row: int, field: str) -> str:
78 if isinstance(value, (float, Decimal)):
79 number = decimal_from_cell(value, row=row, field=field)
80 if number != number.to_integral_value():
81 - raise NormalizationError(
82 - f"row {row}: {field} must be an integer code, got {number}"
83 - )
81 + raise NormalizationError(f"row {row}: {field} must be an integer code, got {number}")
82 return str(int(number))
83 raise NormalizationError(f"row {row}: {field} is not a valid code")
84
backend/src/aram_backend/ingestion.py
+5 -4
@@ -9,7 +9,6 @@ from sqlalchemy.orm import Session
9 from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument, SourceFile
10 from aram_backend.services.source_store import SourceStore
11
12 -
12 ALLOWED_SOURCE_SUFFIXES = frozenset({".csv", ".xlsx"})
13 ALLOWED_DOCUMENT_TYPES = frozenset(
14 {"financial_statement", "general_ledger", "mapping", "trial_balance"}
@@ -85,11 +84,13 @@ def register_source_document(
84 )
85 if existing is not None:
86 if existing.document_type != document_type and existing.filename != safe_name:
88 - raise SourceRegistrationError(f"document type and filename mismatch for existing content hash")
87 + raise SourceRegistrationError(
88 + "document type and filename mismatch for existing content hash"
89 + )
90 if existing.document_type != document_type:
90 - raise SourceRegistrationError(f"document type mismatch for existing content hash")
91 + raise SourceRegistrationError("document type mismatch for existing content hash")
92 if existing.filename != safe_name:
92 - raise SourceRegistrationError(f"filename mismatch for existing content hash")
93 + raise SourceRegistrationError("filename mismatch for existing content hash")
94 if stored is not None and existing.source_file_hash is None:
95 existing.source_file_hash = stored.sha256
96 session.flush()
backend/src/aram_backend/ledger_parser.py
+1 -3
@@ -66,9 +66,7 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
66 matching is Persian-normalized (D-05).
67 """
68 inspection = inspect_xlsx(content, document_type="general_ledger")
69 - workbook = load_workbook(
70 - BytesIO(content), read_only=True, data_only=True, keep_links=False
71 - )
69 + workbook = load_workbook(BytesIO(content), read_only=True, data_only=True, keep_links=False)
70 try:
71 worksheet = workbook[inspection.data_sheet]
72 header_values = next(
backend/src/aram_backend/models.py
+46 -25
@@ -29,13 +29,13 @@ def utc_now() -> datetime:
29 return datetime.now(UTC)
30
31
32 -class FiscalYearStatus(str, enum.Enum):
32 +class FiscalYearStatus(enum.StrEnum):
33 DRAFT = "Draft"
34 APPROVED = "Approved"
35 LOCKED = "Locked"
36
37
38 -class StatementType(str, enum.Enum):
38 +class StatementType(enum.StrEnum):
39 BALANCE_SHEET = "BS"
40 INCOME_STATEMENT = "IS"
41 CASH_FLOW = "CF"
@@ -75,7 +75,9 @@ class FiscalYear(TimestampMixin, Base):
75
76
77 class YearOwnedMixin:
78 - year_id: Mapped[int] = mapped_column(ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True)
78 + year_id: Mapped[int] = mapped_column(
79 + ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True
80 + )
81
82
83 class ReopenRequest(TimestampMixin, YearOwnedMixin, Base):
@@ -110,9 +112,7 @@ class AuditEntry(Base):
112 payload_hash: Mapped[str] = mapped_column(String(64))
113 previous_hash: Mapped[str] = mapped_column(String(64))
114 chain_hash: Mapped[str] = mapped_column(String(64))
113 - created_at: Mapped[datetime] = mapped_column(
114 - DateTime(timezone=True), default=utc_now
115 - )
115 + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
116
117
118 class SourceFile(TimestampMixin, Base):
@@ -173,7 +173,9 @@ class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
173 __tablename__ = "ledger_balances"
174 __table_args__ = (
175 UniqueConstraint(
176 - "year_id", "account_full_code", "import_version",
176 + "year_id",
177 + "account_full_code",
178 + "import_version",
179 name="uq_ledger_balance_year_code_version",
180 ),
181 CheckConstraint("import_version > 0", name="positive_import_version"),
@@ -222,7 +224,9 @@ class NoteRow(TimestampMixin, Base):
224 CheckConstraint("row_order >= 0", name="nonnegative_row_order"),
225 )
226 id: Mapped[int] = mapped_column(primary_key=True)
225 - note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True)
227 + note_id: Mapped[int] = mapped_column(
228 + ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True
229 + )
230 row_order: Mapped[int] = mapped_column(Integer)
231 label: Mapped[str] = mapped_column(String(512))
232 formula_logic: Mapped[str | None] = mapped_column(Text)
@@ -240,7 +244,9 @@ class MappingRule(TimestampMixin, YearOwnedMixin, Base):
244 rule_key: Mapped[str] = mapped_column(String(128))
245 version: Mapped[int] = mapped_column(Integer, default=1)
246 account_code: Mapped[str] = mapped_column(String(64), index=True)
243 - target_note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
247 + target_note_id: Mapped[int] = mapped_column(
248 + ForeignKey("note_definitions.id", ondelete="RESTRICT")
249 + )
250 mapping_type: Mapped[str] = mapped_column(String(32))
251 target_note: Mapped[NoteDefinition] = relationship()
252
@@ -248,7 +254,9 @@ class MappingRule(TimestampMixin, YearOwnedMixin, Base):
254 class FinancialStatement(TimestampMixin, YearOwnedMixin, Base):
255 __tablename__ = "financial_statements"
256 __table_args__ = (
251 - UniqueConstraint("year_id", "statement_type", "version", name="uq_statement_year_type_version"),
257 + UniqueConstraint(
258 + "year_id", "statement_type", "version", name="uq_statement_year_type_version"
259 + ),
260 CheckConstraint("version > 0", name="positive_version"),
261 )
262 id: Mapped[int] = mapped_column(primary_key=True)
@@ -266,10 +274,14 @@ class StatementLine(TimestampMixin, Base):
274 CheckConstraint("line_order >= 0", name="nonnegative_line_order"),
275 )
276 id: Mapped[int] = mapped_column(primary_key=True)
269 - statement_id: Mapped[int] = mapped_column(ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True)
277 + statement_id: Mapped[int] = mapped_column(
278 + ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True
279 + )
280 line_order: Mapped[int] = mapped_column(Integer)
281 line_label: Mapped[str] = mapped_column(String(512))
272 - target_note_id: Mapped[int | None] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
282 + target_note_id: Mapped[int | None] = mapped_column(
283 + ForeignKey("note_definitions.id", ondelete="RESTRICT")
284 + )
285 mapped_total: Mapped[Decimal | None] = mapped_column(Rial())
286 statement: Mapped[FinancialStatement] = relationship(back_populates="lines")
287 target_note: Mapped[NoteDefinition | None] = relationship()
@@ -295,7 +307,9 @@ def _year_id_for(obj: object, session: Session) -> int | None:
307 if isinstance(obj, NoteRow):
308 return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition)
309 if isinstance(obj, StatementLine):
298 - return _resolve_parent_year_id(obj, session, "statement", "statement_id", FinancialStatement)
310 + return _resolve_parent_year_id(
311 + obj, session, "statement", "statement_id", FinancialStatement
312 + )
313 return None
314
315
@@ -304,10 +318,12 @@ _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
318
319 def _company_has_protected_year(session: Session, company_id: int) -> bool:
320 status = session.scalar(
307 - select(FiscalYear.status).where(
321 + select(FiscalYear.status)
322 + .where(
323 FiscalYear.company_id == company_id,
324 FiscalYear.status.in_(_PROTECTED_YEAR_STATUSES),
310 - ).limit(1)
325 + )
326 + .limit(1)
327 )
328 return status is not None
329
@@ -346,15 +362,14 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
362 raise ValueError(
363 f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}"
364 )
349 - if (
350 - old_status == FiscalYearStatus.LOCKED
351 - and obj.status == FiscalYearStatus.APPROVED
352 - ):
365 + if old_status == FiscalYearStatus.LOCKED and obj.status == FiscalYearStatus.APPROVED:
366 approved_reopen = session.scalar(
354 - select(ReopenRequest.id).where(
367 + select(ReopenRequest.id)
368 + .where(
369 ReopenRequest.year_id == obj.id,
370 ReopenRequest.status == "approved",
357 - ).limit(1)
371 + )
372 + .limit(1)
373 )
374 if approved_reopen is None:
375 raise ValueError(
@@ -379,7 +394,7 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
394 f"Company {obj.id} has approved or locked fiscal years and cannot be deleted"
395 )
396
382 - protected = (session.new | session.dirty | session.deleted)
397 + protected = session.new | session.dirty | session.deleted
398 for obj in protected:
399 if isinstance(obj, FiscalYear):
400 continue
@@ -397,10 +412,16 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
412 )
413
414 if isinstance(obj, MappingRule):
400 - target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
415 + target_year_id = _resolve_parent_year_id(
416 + obj, session, "target_note", "target_note_id", NoteDefinition
417 + )
418 if target_year_id != obj.year_id:
419 raise ValueError("Mapping rule and target note must belong to the same fiscal year")
420 if isinstance(obj, StatementLine) and obj.target_note_id is not None:
404 - target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
421 + target_year_id = _resolve_parent_year_id(
422 + obj, session, "target_note", "target_note_id", NoteDefinition
423 + )
424 if target_year_id != year_id:
406 - raise ValueError("Statement line and target note must belong to the same fiscal year")
425 + raise ValueError(
426 + "Statement line and target note must belong to the same fiscal year"
427 + )
backend/src/aram_backend/pilot_api.py
+1 -1
@@ -390,7 +390,7 @@ def export_session(session_id: str) -> StreamingResponse:
390
391 @router.get("/sessions/{session_id}/workspace.xlsx")
392 def export_workspace(session_id: str) -> StreamingResponse:
393 - session = _get_session_or_404(session_id)
393 + _get_session_or_404(session_id)
394 _, working, _ = store.snapshot(session_id)
395 data = export_working_workbook(working)
396 safe_code = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
backend/src/aram_backend/pilot_engine.py
+3 -3
@@ -155,7 +155,7 @@ class WorkingModel:
155 source_sha256: str
156
157 @classmethod
158 - def from_model(cls, model: PilotModel) -> "WorkingModel":
158 + def from_model(cls, model: PilotModel) -> WorkingModel:
159 return cls(
160 company=model.company,
161 accounts=dict(model.accounts),
@@ -165,7 +165,7 @@ class WorkingModel:
165 source_sha256=model.source_sha256,
166 )
167
168 - def copy(self) -> "WorkingModel":
168 + def copy(self) -> WorkingModel:
169 return WorkingModel(
170 company=self.company,
171 accounts=dict(self.accounts),
@@ -200,7 +200,7 @@ def account_level_of(account: PilotAccount) -> str:
200 def _rows(sheet: Any, headers: tuple[str, ...]) -> list[dict[str, Any]]:
201 result = []
202 for values in sheet.iter_rows(min_row=2, values_only=True):
203 - row = dict(zip(headers, values))
203 + row = dict(zip(headers, values, strict=False))
204 if any(v is not None and not (isinstance(v, str) and not v.strip()) for v in row.values()):
205 result.append(row)
206 return result
backend/src/aram_backend/pilot_workbook.py
+1 -1
@@ -169,7 +169,7 @@ def _finite_decimal(value: Any, issues: list[PilotIssue], sheet: str, row: int,
169 def _rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
170 result: list[tuple[int, dict[str, Any]]] = []
171 for row_number, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2):
172 - row = dict(zip(headers, values))
172 + row = dict(zip(headers, values, strict=False))
173 if any(not _empty(value) for value in row.values()):
174 result.append((row_number, row))
175 return result
backend/src/aram_backend/services/preflight.py
+1 -3
@@ -62,9 +62,7 @@ def _to_balance_rows(records: Iterable[LedgerRecord]) -> list[BalanceRow]:
62
63
64 def _active_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
65 - rules = session.scalars(
66 - select(MappingRule).where(MappingRule.year_id == year_id)
67 - ).all()
65 + rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
66 mappings: dict[str, list[MappingTarget]] = {}
67 for rule in rules:
68 mappings.setdefault(rule.account_code, []).append(
backend/src/aram_backend/workbook_inspection.py
+5 -10
@@ -9,7 +9,6 @@ from openpyxl.utils.exceptions import InvalidFileException
9
10 from aram_backend.domain.normalization import normalize_fa
11
12 -
12 MAX_WORKSHEETS = 100
13 MAX_HEADER_COLUMNS = 256
14
@@ -64,9 +63,7 @@ _TABULAR_PROFILES = {
63 },
64 }
65
67 -_PRIMARY_STATEMENT_SHEETS = frozenset(
68 - {"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"}
69 -)
66 +_PRIMARY_STATEMENT_SHEETS = frozenset({"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"})
67
68
69 def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
@@ -91,9 +88,9 @@ def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
88
89 if document_type == "financial_statement":
90 actual_normalized = {normalize_fa(name) for name in sheet_names}
94 - missing = {
95 - normalize_fa(name) for name in _PRIMARY_STATEMENT_SHEETS
96 - }.difference(actual_normalized)
91 + missing = {normalize_fa(name) for name in _PRIMARY_STATEMENT_SHEETS}.difference(
92 + actual_normalized
93 + )
94 if missing:
95 raise WorkbookInspectionError(
96 f"financial statement workbook is missing sheets: {sorted(missing)}"
@@ -110,9 +107,7 @@ def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
107 target_normalized = normalize_fa(profile["sheet"])
108 sheets_by_normalized = {normalize_fa(name): name for name in workbook.sheetnames}
109 if target_normalized not in sheets_by_normalized:
113 - raise WorkbookInspectionError(
114 - f"required worksheet is missing: {profile['sheet']}"
115 - )
110 + raise WorkbookInspectionError(f"required worksheet is missing: {profile['sheet']}")
111 sheet_name = sheets_by_normalized[target_normalized]
112
113 worksheet = workbook[sheet_name]
backend/tests/conftest.py
-1
@@ -21,4 +21,3 @@ def session(tmp_path) -> Session:
21 @pytest.fixture
22 def client() -> TestClient:
23 return TestClient(app)
24 -
backend/tests/test_immutability.py
+15 -9
@@ -12,11 +12,9 @@ from sqlalchemy import text
12 from sqlalchemy.exc import IntegrityError
13
14 from aram_backend.models import (
15 - AuditEntry,
15 Company,
16 FiscalYear,
17 FiscalYearStatus,
19 - LedgerBalance,
18 ReopenRequest,
19 )
20 from aram_backend.services.audit import append_entry, verify_chain
@@ -61,7 +59,9 @@ def _seed_balance(session, year):
59 ),
60 {"y": year.id},
61 )
64 - sd_id = session.execute(text("SELECT id FROM source_documents WHERE year_id=:y"), {"y": year.id}).scalar()
62 + sd_id = session.execute(
63 + text("SELECT id FROM source_documents WHERE year_id=:y"), {"y": year.id}
64 + ).scalar()
65 session.execute(
66 text(
67 "INSERT INTO ledger_balances (year_id, source_document_id, source_sheet, source_row, import_version, "
@@ -100,9 +100,12 @@ class TestRawSqlImmutability:
100 )
101 session.rollback()
102 # Value unchanged.
103 - assert session.execute(
104 - text("SELECT debit FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
105 - ).scalar() == 100
103 + assert (
104 + session.execute(
105 + text("SELECT debit FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
106 + ).scalar()
107 + == 100
108 + )
109
110 def test_locked_year_blocks_raw_delete(self, session):
111 year = _draft_year(session)
@@ -111,9 +114,12 @@ class TestRawSqlImmutability:
114 with pytest.raises(IntegrityError, match="locked"):
115 session.execute(text("DELETE FROM ledger_balances WHERE year_id = :y"), {"y": year.id})
116 session.rollback()
114 - assert session.execute(
115 - text("SELECT COUNT(*) FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
116 - ).scalar() == 1
117 + assert (
118 + session.execute(
119 + text("SELECT COUNT(*) FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
120 + ).scalar()
121 + == 1
122 + )
123
124 def test_draft_year_allows_writes(self, session):
125 company = Company(code="DFT", name="x")
backend/tests/test_ingestion.py
+3 -3
@@ -127,7 +127,7 @@ def test_duplicate_registration_different_document_type_rejected(session):
127 "content": b"safe-test-bytes-conflict",
128 }
129
130 - first = register_source_document(session, **arguments)
130 + register_source_document(session, **arguments)
131 session.commit()
132
133 conflict_arguments = arguments.copy()
@@ -151,7 +151,7 @@ def test_duplicate_registration_different_filename_rejected(session):
151 "content": b"safe-test-bytes-conflict-2",
152 }
153
154 - first = register_source_document(session, **arguments)
154 + register_source_document(session, **arguments)
155 session.commit()
156
157 conflict_arguments = arguments.copy()
@@ -175,7 +175,7 @@ def test_duplicate_registration_different_both_rejected(session):
175 "content": b"safe-test-bytes-conflict-3",
176 }
177
178 - first = register_source_document(session, **arguments)
178 + register_source_document(session, **arguments)
179 session.commit()
180
181 conflict_arguments = arguments.copy()
backend/tests/test_ledger_balance.py
+58 -21
@@ -17,6 +17,7 @@ from pathlib import Path
17 import pytest
18 from openpyxl import Workbook
19 from sqlalchemy import text
20 +from sqlalchemy.exc import IntegrityError
21
22 from aram_backend.ingestion import register_source_document
23 from aram_backend.ledger_parser import parse_general_ledger
@@ -27,9 +28,19 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
28 BACKEND_DIR = REPO_ROOT / "backend"
29
30 HEADERS = [
30 - "حساب", "kol", "ACCOUNT_NAME", "year", "نوع",
31 - "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
32 - "OPENING", "Debit", "Credit", "CLOSING",
31 + "حساب",
32 + "kol",
33 + "ACCOUNT_NAME",
34 + "year",
35 + "نوع",
36 + "T1_CODE",
37 + "T2_CODE",
38 + "T3_CODE",
39 + "T4_CODE",
40 + "OPENING",
41 + "Debit",
42 + "Credit",
43 + "CLOSING",
44 ]
45
46
@@ -48,8 +59,7 @@ def _ledger_bytes(*rows):
59
60
61 def _row(code, kol, opening=0, debit=0, credit=0, closing=0, name="حساب نمونه"):
51 - return [code, kol, name, 1404, "O", None, None, None, None,
52 - opening, debit, credit, closing]
62 + return [code, kol, name, 1404, "O", None, None, None, None, opening, debit, credit, closing]
63
64
65 def _make_year(session):
@@ -64,8 +74,11 @@ def _make_year(session):
74
75 def _import(session, year, content):
76 doc = register_source_document(
67 - session, year_id=year.id, filename="ledger.xlsx",
68 - document_type="general_ledger", content=content,
77 + session,
78 + year_id=year.id,
79 + filename="ledger.xlsx",
80 + document_type="general_ledger",
81 + content=content,
82 )
83 records = list(parse_general_ledger(content))
84 count = import_ledger_balances(
@@ -89,8 +102,10 @@ class TestLedgerBalanceImport:
102 assert balance.debit == Decimal(50)
103 assert balance.credit == Decimal(20)
104 assert balance.closing == Decimal(130)
92 - assert all(isinstance(getattr(balance, f), Decimal)
93 - for f in ("opening", "debit", "credit", "closing"))
105 + assert all(
106 + isinstance(getattr(balance, f), Decimal)
107 + for f in ("opening", "debit", "credit", "closing")
108 + )
109
110 def test_large_rial_no_silent_rounding(self, session):
111 # Insert via the ORM (bypassing Excel's own float64 cell storage, which
@@ -98,15 +113,27 @@ class TestLedgerBalanceImport:
113 # Rial BIGINT column stores large rial exactly, unlike Numeric-on-SQLite.
114 year = _make_year(session)
115 doc = register_source_document(
101 - session, year_id=year.id, filename="l.xlsx",
102 - document_type="general_ledger", content=_ledger_bytes(_row("8348", "14")),
116 + session,
117 + year_id=year.id,
118 + filename="l.xlsx",
119 + document_type="general_ledger",
120 + content=_ledger_bytes(_row("8348", "14")),
121 )
122 big = Decimal("10823163409740108") # > 2**53, the canonical total debit
105 - session.add(LedgerBalance(
106 - year_id=year.id, source_document_id=doc.id, source_sheet="Source",
107 - source_row=3, account_full_code="148348", general_code="14",
108 - subsidiary_code="8348", account_name="x", debit=big, credit=big,
109 - ))
123 + session.add(
124 + LedgerBalance(
125 + year_id=year.id,
126 + source_document_id=doc.id,
127 + source_sheet="Source",
128 + source_row=3,
129 + account_full_code="148348",
130 + general_code="14",
131 + subsidiary_code="8348",
132 + account_name="x",
133 + debit=big,
134 + credit=big,
135 + )
136 + )
137 session.commit()
138 balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
139 assert balance.debit == big
@@ -134,10 +161,13 @@ class TestLedgerBalanceImport:
161 # Re-importing the same version conflicts; a new version is allowed.
162 doc = session.query(LedgerBalance).first().source_document_id
163 records = list(parse_general_ledger(content))
137 - with pytest.raises(Exception):
164 + with pytest.raises(IntegrityError):
165 import_ledger_balances(
139 - session, year_id=year.id, source_document_id=doc,
140 - records=records, import_version=1,
166 + session,
167 + year_id=year.id,
168 + source_document_id=doc,
169 + records=records,
170 + import_version=1,
171 )
172 session.rollback()
173
@@ -148,11 +178,15 @@ class TestMigrationRoundTrip:
178 env = {**os.environ, "ARAM_DATABASE_URL": f"sqlite:///{db}"}
179 up = subprocess.run(
180 [sys.executable, "-m", "alembic", "upgrade", "head"],
151 - cwd=BACKEND_DIR, env=env, capture_output=True, text=True,
181 + cwd=BACKEND_DIR,
182 + env=env,
183 + capture_output=True,
184 + text=True,
185 )
186 assert up.returncode == 0, up.stderr
187 # ledger_balances exists and mapped_total is BIGINT after upgrade.
188 import sqlite3
189 +
190 con = sqlite3.connect(db)
191 tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
192 assert "ledger_balances" in tables
@@ -161,7 +195,10 @@ class TestMigrationRoundTrip:
195 con.close()
196 down = subprocess.run(
197 [sys.executable, "-m", "alembic", "downgrade", "base"],
164 - cwd=BACKEND_DIR, env=env, capture_output=True, text=True,
198 + cwd=BACKEND_DIR,
199 + env=env,
200 + capture_output=True,
201 + text=True,
202 )
203 assert down.returncode == 0, down.stderr
204 con = sqlite3.connect(db)
backend/tests/test_ledger_csv.py
+15 -3
@@ -10,9 +10,21 @@ from aram_backend.ledger_parser import (
10 parse_ledger,
11 )
12
13 -HEADER = ["حساب", "kol", "ACCOUNT_NAME", "year", "نوع",
14 - "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
15 - "OPENING", "Debit", "Credit", "CLOSING"]
13 +HEADER = [
14 + "حساب",
15 + "kol",
16 + "ACCOUNT_NAME",
17 + "year",
18 + "نوع",
19 + "T1_CODE",
20 + "T2_CODE",
21 + "T3_CODE",
22 + "T4_CODE",
23 + "OPENING",
24 + "Debit",
25 + "Credit",
26 + "CLOSING",
27 +]
28 ROW = ["0101", "14", "نمونه حساب", "۱۴۰۴", "O", "", "", "", "", "۰", "۱۲۵۰", "۰", "۱۲۵۰"]
29
30
backend/tests/test_ledger_parser.py
-1
@@ -6,7 +6,6 @@ from openpyxl import Workbook
6
7 from aram_backend.ledger_parser import LedgerParseError, parse_general_ledger
8
9 -
9 HEADERS = [
10 "حساب",
11 "ACCOUNT_NAME",
backend/tests/test_phase0_fixes.py
+20 -5
@@ -22,9 +22,18 @@ from aram_backend.ledger_parser import parse_general_ledger
22 from aram_backend.workbook_inspection import inspect_xlsx
23
24 GL_HEADERS = [
25 - "حساب", "ACCOUNT_NAME", "year", "نوع",
26 - "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
27 - "OPENING", "Debit", "Credit", "CLOSING",
25 + "حساب",
26 + "ACCOUNT_NAME",
27 + "year",
28 + "نوع",
29 + "T1_CODE",
30 + "T2_CODE",
31 + "T3_CODE",
32 + "T4_CODE",
33 + "OPENING",
34 + "Debit",
35 + "Credit",
36 + "CLOSING",
37 ]
38 REPO_ROOT = Path(__file__).resolve().parents[2]
39 LEDGER_1404 = REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
@@ -96,8 +105,14 @@ class TestD05Normalization:
105
106 def test_arabic_kaf_mapping_headers_accepted(self):
107 # "كد حساب" with Arabic kaf must match the Persian "کد حساب" requirement.
99 - headers = ["كد حساب", "نوع", "كد یادداشت", "شرح یادداشت",
100 - "فرمول یادداشت اصلی", "فرمول یادداشت فرعی"]
108 + headers = [
109 + "كد حساب",
110 + "نوع",
111 + "كد یادداشت",
112 + "شرح یادداشت",
113 + "فرمول یادداشت اصلی",
114 + "فرمول یادداشت فرعی",
115 + ]
116 wb = Workbook()
117 ws = wb.active
118 ws.title = "Data"
backend/tests/test_pilot_editing.py
+12 -3
@@ -4,9 +4,16 @@ from io import BytesIO
4
5 from openpyxl import load_workbook
6
7 +from aram_backend.pilot_editing import (
8 + InvalidAccountError,
9 + InvalidCompanyError,
10 + InvalidNoteError,
11 + make_account,
12 + make_company,
13 + make_note,
14 +)
15 from aram_backend.pilot_engine import build_report, export_working_workbook, parse_pilot_model
16 from aram_backend.pilot_store import PilotSessionStore
9 -from aram_backend.pilot_editing import make_account, make_note, make_company, InvalidAccountError, InvalidNoteError
17 from test_pilot_engine import build_balanced_workbook
18
19
@@ -50,7 +57,7 @@ def test_make_note_and_company_validation():
57 subnote_code="A", subnote_title="")
58 company = make_company(code="C9", name="شرکت عمومی", fiscal_year=1405)
59 assert company.fiscal_year == 1405
53 - with pytest.raises(Exception):
60 + with pytest.raises(InvalidCompanyError):
61 make_company(code="C9", name="x", fiscal_year=-1)
62
63
@@ -71,6 +78,7 @@ def test_add_account_enters_exception_queue_then_maps():
78
79 def test_add_duplicate_account_rejected():
80 import pytest
81 +
82 from aram_backend.pilot_editing import DuplicateAccountError
83 store, session = _session()
84 with pytest.raises(DuplicateAccountError):
@@ -116,12 +124,13 @@ def test_add_note_and_subnote_then_map_new_account_to_them():
124 note_number="06", subnote_code="01", actor="tester")
125 report = build_report(session.working, session.mappings)
126 assets = report["statements"]["BS"]["sections"][0]
119 - sub = [l for l in assets["lines"] if l["note_number"] == "06" and l["subnote_code"] == "01"]
127 + sub = [ln for ln in assets["lines"] if ln["note_number"] == "06" and ln["subnote_code"] == "01"]
128 assert sub and sub[0]["accounts"][0]["code"] == "15"
129
130
131 def test_delete_note_in_use_is_blocked():
132 import pytest
133 +
134 from aram_backend.pilot_editing import NoteInUseError
135 store, session = _session()
136 with pytest.raises(NoteInUseError):
backend/tests/test_pilot_engine.py
+1 -1
@@ -3,8 +3,8 @@ from __future__ import annotations
3 from decimal import Decimal
4 from io import BytesIO
5
6 -from openpyxl import load_workbook
6 import pytest
7 +from openpyxl import load_workbook
8
9 from aram_backend.pilot_engine import (
10 PilotModelError,
backend/tests/test_preflight.py
+14 -5
@@ -11,11 +11,20 @@ from aram_backend.services.preflight import run_preflight
11
12 def _rec(row, code, opening, debit, credit, closing, general="14"):
13 return LedgerRecord(
14 - row_number=row, account_code=code, general_code=general,
15 - account_name="نمونه", source_year=1404, entry_type="O",
16 - t1_code=None, t2_code=None, t3_code=None, t4_code=None,
17 - opening=Decimal(opening), debit=Decimal(debit),
18 - credit=Decimal(credit), closing=Decimal(closing),
14 + row_number=row,
15 + account_code=code,
16 + general_code=general,
17 + account_name="نمونه",
18 + source_year=1404,
19 + entry_type="O",
20 + t1_code=None,
21 + t2_code=None,
22 + t3_code=None,
23 + t4_code=None,
24 + opening=Decimal(opening),
25 + debit=Decimal(debit),
26 + credit=Decimal(credit),
27 + closing=Decimal(closing),
28 )
29
30
backend/tests/test_source_store.py
+29 -7
@@ -19,9 +19,23 @@ def _xlsx_bytes():
19 ws = wb.active
20 ws.title = "Source"
21 ws.append(["source ledger"])
22 - ws.append(["حساب", "kol", "ACCOUNT_NAME", "year", "نوع",
23 - "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
24 - "OPENING", "Debit", "Credit", "CLOSING"])
22 + ws.append(
23 + [
24 + "حساب",
25 + "kol",
26 + "ACCOUNT_NAME",
27 + "year",
28 + "نوع",
29 + "T1_CODE",
30 + "T2_CODE",
31 + "T3_CODE",
32 + "T4_CODE",
33 + "OPENING",
34 + "Debit",
35 + "Credit",
36 + "CLOSING",
37 + ]
38 + )
39 ws.append(["0101", "14", "نمونه", 1404, "O", None, None, None, None, 0, 100, 0, 100])
40 buf = io.BytesIO()
41 wb.save(buf)
@@ -64,6 +78,7 @@ class TestSourceStore:
78 stored = store.put(b"original")
79 # Tamper with the stored bytes; the hash check must fail loudly.
80 from pathlib import Path
81 +
82 Path(stored.stored_path).write_bytes(b"tampered")
83 with pytest.raises(SourceStoreError):
84 store.get(stored.sha256)
@@ -79,8 +94,12 @@ class TestRegistrationWithStore:
94 store = SourceStore(tmp_path / "store")
95 content = _xlsx_bytes()
96 source = register_source_document(
82 - session, year_id=year.id, filename="ledger.xlsx",
83 - document_type="general_ledger", content=content, store=store,
97 + session,
98 + year_id=year.id,
99 + filename="ledger.xlsx",
100 + document_type="general_ledger",
101 + content=content,
102 + store=store,
103 )
104 session.commit()
105 assert source.source_file_hash == hashlib.sha256(content).hexdigest()
@@ -97,8 +116,11 @@ class TestRegistrationWithStore:
116 def test_without_store_backward_compatible(self, session):
117 year = _make_year(session)
118 source = register_source_document(
100 - session, year_id=year.id, filename="ledger.xlsx",
101 - document_type="general_ledger", content=_xlsx_bytes(),
119 + session,
120 + year_id=year.id,
121 + filename="ledger.xlsx",
122 + document_type="general_ledger",
123 + content=_xlsx_bytes(),
124 )
125 session.commit()
126 assert source.source_file_hash is None
docs/adr/ADR-017-ci-quality-gates.md new
+49
@@ -0,0 +1,49 @@
1 +# ADR-017 — CI quality gates and tooling
2 +
3 +- Status: Accepted (Phase 0, D-12)
4 +- Date: 2026-12-03
5 +- Booklet: §13 (CI gates), §12 (D-12), §19 (no dependency without ADR)
6 +
7 +## Context
8 +
9 +The booklet requires green CI gates: ruff, mypy --strict, coverage (domain ≥90%,
10 +total ≥80%), SQLite + PostgreSQL migration round-trips, and `git diff --check`.
11 +The existing workflow only ran pytest + SQLite migrations + compileall.
12 +
13 +## Decision
14 +
15 +Add dev tooling to the `test` extra (single install in CI):
16 +
17 +- `ruff` — lint + format check.
18 +- `mypy` — static typing, `--strict` on the pure domain layer first; the broader
19 + package is type-checked with pragmatic settings and tightened toward strict as
20 + the services/api layers mature (Phases 1–7).
21 +- `coverage` / `pytest-cov` — enforce domain ≥90% and total ≥80%.
22 +- `pip-audit` — dependency vulnerability scan (advisory; fails on known CVEs).
23 +
24 +CI matrix runs migrations on **SQLite and PostgreSQL** (service container) in
25 +addition to the test suite. `git diff --check` guards whitespace.
26 +
27 +### New dependencies (justification)
28 +
29 +| Package | Purpose | Runtime? |
30 +|---|---|---|
31 +| ruff | lint/format gate | dev only |
32 +| mypy | type gate | dev only |
33 +| coverage, pytest-cov | coverage gate | dev only |
34 +| pip-audit | vuln scan | dev only |
35 +| psycopg[binary] (`ci` extra) | PostgreSQL driver for CI migration matrix | CI only |
36 +
37 +None are imported by the application at runtime; the offline desktop build is
38 +unaffected (P-10, zero runtime network). The `ci` extra is installed only in the
39 +migration-matrix job, never in the packaged desktop runner.
40 +
41 +## Consequences
42 +
43 +- Every PR must pass lint, types, coverage, and dual-dialect migrations.
44 +- Domain code is held to strict typing from Phase 0; other layers ratchet up.
45 +
46 +## Rejected alternatives
47 +
48 +- Coverage without a threshold: no enforcement.
49 +- Skipping PostgreSQL: the booklet requires both dialects for migration safety.