D27: infrastructure/cli/i18n → infrastructure/i18n; снята зависимость AI от CLI

This commit is contained in:
oqyude committed 2026-10-25 17:04:38 +03:00
1 parent 9c069b9e7f
commit bd23b03c08
20 files changed
+108 -26

No files matched your search

+6
View File
@@ -159,6 +159,12 @@ Spreadsheet Export
- Web UI; - Web UI;
- Mobile App; - Mobile App;
- AI Financial Assistant. - AI Financial Assistant.
> **Статус после D27.** Блокирующей связи `infrastructure/ai/` → `infrastructure/cli/`
> больше нет: i18n вынесен в `infrastructure/i18n/`, и AI-слой переиспользуем
> без CLI. REST API и Web UI могут строиться поверх `application/` +
> `infrastructure/ai/` напрямую; направление зависимостей закреплено тестом
> `tests/test_architecture.py`.
## Структура репозитория ## Структура репозитория
+15 -6
View File
@@ -158,8 +158,11 @@ cashflow-forecast/
│ │ ├── app.py # Entry point │ │ ├── app.py # Entry point
│ │ ├── commands/ # 10 файлов команд + config sub-typer │ │ ├── commands/ # 10 файлов команд + config sub-typer
│ │ ├── paths.py # AppPaths — пути (CF_DATA_DIR) │ │ ├── paths.py # AppPaths — пути (CF_DATA_DIR)
│ │ ├── services.py # Composition root + helpers │ │ └── services.py # Composition root + helpers
│ │ └── i18n.py # ru-переводы (словарь "en" пуст, откат на ru) │ ├── i18n/ # Локализация (не зависит от CLI)
│ │ ├── __init__.py # t(), setup_i18n(), set_lang(), резолв языка
│ │ ├── ru.py # ru-словарь (единственный заполненный)
│ │ └── en.py # en-словарь (пуст → откат на ru)
│ ├── ai/ # AI-ассистент (заглушка) │ ├── ai/ # AI-ассистент (заглушка)
│ │ ├── prompts.py │ │ ├── prompts.py
│ │ └── assistant.py # AssistantService │ │ └── assistant.py # AssistantService
@@ -167,7 +170,7 @@ cashflow-forecast/
│ ├── json_file_repository.py │ ├── json_file_repository.py
│ └── excel_repository.py │ └── excel_repository.py
│ │
├── tests/ # pytest, 229 тестов ├── tests/ # pytest, 236 тестов
│ ├── conftest.py │ ├── conftest.py
│ ├── test_model.py │ ├── test_model.py
│ ├── test_forecast.py │ ├── test_forecast.py
@@ -176,6 +179,7 @@ cashflow-forecast/
│ ├── test_ai.py │ ├── test_ai.py
│ ├── test_cli.py │ ├── test_cli.py
│ ├── test_cli_contract.py # Инвариант публичной поверхности CLI │ ├── test_cli_contract.py # Инвариант публичной поверхности CLI
│ ├── test_architecture.py # Направления зависимостей (нет AI → CLI)
│ ├── test_excel_sync.py # Тесты ExcelRepository │ ├── test_excel_sync.py # Тесты ExcelRepository
│ ├── test_i18n.py │ ├── test_i18n.py
│ ├── test_paths.py # Пути и CF_DATA_DIR │ ├── test_paths.py # Пути и CF_DATA_DIR
@@ -227,12 +231,17 @@ ruff format .
- **Repository pattern**: `ModelRepository` Protocol, реализации `JsonFileRepository` и `ExcelRepository`. - **Repository pattern**: `ModelRepository` Protocol, реализации `JsonFileRepository` и `ExcelRepository`.
- **DI**: Composition root в `infrastructure/cli/services.py:build_services()`. - **DI**: Composition root в `infrastructure/cli/services.py:build_services()`.
- **Schema versioning**: `FinancialModel.to_dict()` пишет `version: 1`; `from_dict()` поддерживает legacy v0. - **Schema versioning**: `FinancialModel.to_dict()` пишет `version: 1`; `from_dict()` поддерживает legacy v0.
- **i18n**: `infrastructure/cli/i18n.py` — словарь только на русском. Английские - **i18n**: `infrastructure/i18n/` — рантайм (`t()`, `setup_i18n()`, `set_lang()`,
переводы не реализованы: словарь `"en"` пуст, поэтому `CF_LANG=en` **молча резолв языка) в `__init__.py`, словари в `ru.py` и `en.py`. Словарь только на
откатывается на `ru`** (интерфейс остаётся русским, предупреждения нет). русском. Английские переводы не реализованы: словарь `"en"` пуст, поэтому
`CF_LANG=en` **молча откатывается на `ru`** (интерфейс остаётся русским,
предупреждения нет).
Язык определяется при импорте модуля i18n — до первого вызова `t()`, поэтому Язык определяется при импорте модуля i18n — до первого вызова `t()`, поэтому
`CF_LANG` действует и на строки, собираемые на этапе импорта команд. `CF_LANG` действует и на строки, собираемые на этапе импорта команд.
Как только в словаре появится непустой перевод, он будет выбран по `CF_LANG`. Как только в словаре появится непустой перевод, он будет выбран по `CF_LANG`.
Пакет не зависит от `infrastructure/cli/`: `infrastructure/ai/prompts.py`
импортирует `infrastructure.i18n`, поэтому AI-слой переиспользуем без CLI
(REST API / Web UI). Направление зависимостей закреплено `tests/test_architecture.py`.
- **Тесты**: pytest, файлы состояния не пишутся в дерево репозитория (CWD теста - **Тесты**: pytest, файлы состояния не пишутся в дерево репозитория (CWD теста
переводится во временный каталог). переводится во временный каталог).
+1 -1
View File
@@ -1,4 +1,4 @@
from infrastructure.cli.i18n import t from infrastructure.i18n import t
ANALYZE_PROMPT = t("prompt.analyze") ANALYZE_PROMPT = t("prompt.analyze")
ADVICE_PROMPT = t("prompt.advice") ADVICE_PROMPT = t("prompt.advice")
+2 -2
View File
@@ -21,9 +21,9 @@ from infrastructure.cli.commands import (
scenario, scenario,
whatif, whatif,
) )
from infrastructure.cli.i18n import setup_i18n, t from infrastructure.i18n import setup_i18n, t
setup_i18n() # язык уже определён при импорте infrastructure.cli.i18n (D20) setup_i18n() # язык уже определён при импорте infrastructure.i18n (D20)
app = typer.Typer(name="cf", help=t("app.help")) app = typer.Typer(name="cf", help=t("app.help"))
+1 -1
View File
@@ -2,8 +2,8 @@
import typer import typer
from infrastructure.cli.i18n import t
from infrastructure.cli.services import build_services, console, load_model, resolve_currency from infrastructure.cli.services import build_services, console, load_model, resolve_currency
from infrastructure.i18n import t
CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency"))
+1 -1
View File
@@ -4,7 +4,6 @@ import typer
from pydantic import ValidationError from pydantic import ValidationError
from rich.table import Table from rich.table import Table
from infrastructure.cli.i18n import t
from infrastructure.cli.services import ( from infrastructure.cli.services import (
build_services, build_services,
console, console,
@@ -14,6 +13,7 @@ from infrastructure.cli.services import (
load_model, load_model,
resolve_currency, resolve_currency,
) )
from infrastructure.i18n import t
CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency"))
+1 -1
View File
@@ -15,8 +15,8 @@ from domain import (
RecurringCashflow, RecurringCashflow,
Transaction, Transaction,
) )
from infrastructure.cli.i18n import t
from infrastructure.cli.services import console, fail_validation, load_model, save_model from infrastructure.cli.services import console, fail_validation, load_model, save_model
from infrastructure.i18n import t
app = typer.Typer(name="config", help=t("config.help")) app = typer.Typer(name="config", help=t("config.help"))
+1 -1
View File
@@ -2,9 +2,9 @@
import typer import typer
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import AppPaths from infrastructure.cli.paths import AppPaths
from infrastructure.cli.services import console, load_model from infrastructure.cli.services import console, load_model
from infrastructure.i18n import t
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
_repo = ExcelRepository() _repo = ExcelRepository()
+1 -1
View File
@@ -3,7 +3,6 @@
import typer import typer
from rich.table import Table from rich.table import Table
from infrastructure.cli.i18n import t
from infrastructure.cli.services import ( from infrastructure.cli.services import (
build_services, build_services,
console, console,
@@ -12,6 +11,7 @@ from infrastructure.cli.services import (
load_model, load_model,
resolve_currency, resolve_currency,
) )
from infrastructure.i18n import t
CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency"))
+1 -1
View File
@@ -2,8 +2,8 @@
import typer import typer
from infrastructure.cli.i18n import t
from infrastructure.cli.services import console, save_model from infrastructure.cli.services import console, save_model
from infrastructure.i18n import t
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
_repo = ExcelRepository() _repo = ExcelRepository()
+1 -1
View File
@@ -3,8 +3,8 @@
from rich.table import Table from rich.table import Table
from domain import CurrencyConverter from domain import CurrencyConverter
from infrastructure.cli.i18n import t
from infrastructure.cli.services import console, load_model from infrastructure.cli.services import console, load_model
from infrastructure.i18n import t
def info() -> None: def info() -> None:
+1 -1
View File
@@ -1,9 +1,9 @@
"""cf init — создать пустую модель.""" """cf init — создать пустую модель."""
from domain import FinancialModel from domain import FinancialModel
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import AppPaths from infrastructure.cli.paths import AppPaths
from infrastructure.cli.services import console, save_model from infrastructure.cli.services import console, save_model
from infrastructure.i18n import t
def init() -> None: def init() -> None:
+1 -1
View File
@@ -4,7 +4,6 @@ import typer
from pydantic import ValidationError from pydantic import ValidationError
from application.scenarios import DEFAULT_SCENARIOS from application.scenarios import DEFAULT_SCENARIOS
from infrastructure.cli.i18n import t
from infrastructure.cli.services import ( from infrastructure.cli.services import (
build_services, build_services,
console, console,
@@ -14,6 +13,7 @@ from infrastructure.cli.services import (
load_model, load_model,
resolve_currency, resolve_currency,
) )
from infrastructure.i18n import t
CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency"))
+1 -1
View File
@@ -3,7 +3,6 @@
import typer import typer
from pydantic import ValidationError from pydantic import ValidationError
from infrastructure.cli.i18n import t
from infrastructure.cli.services import ( from infrastructure.cli.services import (
build_services, build_services,
console, console,
@@ -13,6 +12,7 @@ from infrastructure.cli.services import (
load_model, load_model,
resolve_currency, resolve_currency,
) )
from infrastructure.i18n import t
CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency"))
+1 -1
View File
@@ -13,8 +13,8 @@ from application.forecast import ForecastService
from application.scenarios import ScenarioService from application.scenarios import ScenarioService
from domain import CurrencyConverter, FinancialModel from domain import CurrencyConverter, FinancialModel
from infrastructure.ai.assistant import AssistantService from infrastructure.ai.assistant import AssistantService
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import AppPaths from infrastructure.cli.paths import AppPaths
from infrastructure.i18n import t
from infrastructure.repositories import JsonFileRepository from infrastructure.repositories import JsonFileRepository
console = Console() console = Console()
@@ -7,8 +7,8 @@
import os import os
from infrastructure.cli.i18n.en import MESSAGES as _EN_MESSAGES from infrastructure.i18n.en import MESSAGES as _EN_MESSAGES
from infrastructure.cli.i18n.ru import MESSAGES as _RU_MESSAGES from infrastructure.i18n.ru import MESSAGES as _RU_MESSAGES
_TRANSLATIONS: dict[str, dict[str, str]] = {"ru": _RU_MESSAGES, "en": _EN_MESSAGES} _TRANSLATIONS: dict[str, dict[str, str]] = {"ru": _RU_MESSAGES, "en": _EN_MESSAGES}
File renamed without changes.
File renamed without changes.
+67
View File
@@ -0,0 +1,67 @@
"""Инварианты направлений зависимостей внутри `infrastructure/` (D27).
Смысл: `infrastructure/ai/` был связан с `infrastructure/cli/` только через
`infrastructure.cli.i18n`, из-за чего AI-слой нельзя было переиспользовать в
REST API / Web UI без затаскивания CLI. После выноса i18n в
`infrastructure/i18n/` горизонтальная связь «не-CLI → CLI» запрещена и
проверяется разбором AST, а не глазами.
"""
import ast
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
INFRA_ROOT = REPO_ROOT / "infrastructure"
CLI_ROOT = INFRA_ROOT / "cli"
I18N_ROOT = INFRA_ROOT / "i18n"
CLI_PREFIX = "infrastructure.cli"
def _iter_modules():
for path in sorted(INFRA_ROOT.rglob("*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
yield path, tree
def _cli_imports(tree: ast.Module) -> list[str]:
"""Все импорты `infrastructure.cli.*` в модуле (from-import и import)."""
found: list[str] = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module:
if node.module == CLI_PREFIX or node.module.startswith(CLI_PREFIX + "."):
found.append(node.module)
elif isinstance(node, ast.Import):
for alias in node.names:
if alias.name == CLI_PREFIX or alias.name.startswith(CLI_PREFIX + "."):
found.append(alias.name)
return found
class TestNoCliDependency:
def test_modules_outside_cli_do_not_import_cli(self):
offenders = {}
for path, tree in _iter_modules():
if path == CLI_ROOT or CLI_ROOT in path.parents:
continue
imports = _cli_imports(tree)
if imports:
offenders[str(path.relative_to(REPO_ROOT))] = imports
assert not offenders, f"модули вне infrastructure/cli импортируют CLI: {offenders}"
def test_i18n_package_does_not_import_cli(self):
assert I18N_ROOT.is_dir()
offenders = {}
for path in sorted(I18N_ROOT.rglob("*.py")):
imports = _cli_imports(ast.parse(path.read_text(encoding="utf-8"), filename=str(path)))
if imports:
offenders[str(path.relative_to(REPO_ROOT))] = imports
assert not offenders, f"infrastructure/i18n импортирует CLI: {offenders}"
def test_ai_layer_does_not_import_cli(self):
offenders = {}
for path in sorted((INFRA_ROOT / "ai").rglob("*.py")):
imports = _cli_imports(ast.parse(path.read_text(encoding="utf-8"), filename=str(path)))
if imports:
offenders[str(path.relative_to(REPO_ROOT))] = imports
assert not offenders, f"infrastructure/ai импортирует CLI: {offenders}"
+4 -4
View File
@@ -2,7 +2,7 @@ import os
import subprocess import subprocess
import sys import sys
from infrastructure.cli.i18n import ( from infrastructure.i18n import (
_TRANSLATIONS, _TRANSLATIONS,
Translator, Translator,
get_lang, get_lang,
@@ -10,8 +10,8 @@ from infrastructure.cli.i18n import (
setup_i18n, setup_i18n,
t, t,
) )
from infrastructure.cli.i18n.en import MESSAGES as EN_MESSAGES from infrastructure.i18n.en import MESSAGES as EN_MESSAGES
from infrastructure.cli.i18n.ru import MESSAGES as RU_MESSAGES from infrastructure.i18n.ru import MESSAGES as RU_MESSAGES
class TestTranslator: class TestTranslator:
@@ -117,7 +117,7 @@ class TestCfLang:
def test_cf_lang_is_resolved_at_import_time(self, repo_root): def test_cf_lang_is_resolved_at_import_time(self, repo_root):
# t() вызывается на этапе импорта модулей команд — язык должен быть # t() вызывается на этапе импорта модулей команд — язык должен быть
# определён уже тогда, иначе CF_LANG не влияет на вывод. # определён уже тогда, иначе CF_LANG не влияет на вывод.
code = "from infrastructure.cli.i18n import get_lang, t;print(get_lang());print(t('cmd.init.help'))" code = "from infrastructure.i18n import get_lang, t;print(get_lang());print(t('cmd.init.help'))"
env = dict(os.environ) env = dict(os.environ)
env["CF_LANG"] = "en" env["CF_LANG"] = "en"
env["PYTHONPATH"] = str(repo_root) env["PYTHONPATH"] = str(repo_root)