Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions docs/architecture-compliance-audit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Architecture compliance audit

Дата аудита: 2026-06-18

Источник требований: [ProverCoderAI/architecture-skills#1](https://github.com/ProverCoderAI/architecture-skills/issues/1).

## Summary

Текущая кодовая база частично соответствует требованиям. В проекте уже есть сильная
база: monorepo, CI с build/typecheck/lint/test/e2e, Effect lint profile,
property-based tests и jscpd в части пакетов. По строгой трактовке issue
репозиторий пока нельзя считать соответствующим: есть крупные нарушения по
размеру модулей, файлов и функций; OpenAPI/generated client отсутствует;
mutation testing отсутствует; coverage не enforced в CI; API `lint:effect` не
подключён в CI; остаются прямые `fetch`, `unknown` и casts.

Строгость оценки: strict with documented exceptions. Boundary `unknown`
допустим только при явном schema decoding и без утечки в domain API.
Comment on lines +7 to +18

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Summary недооценивает серьёзность несоответствий матрицы.

Summary утверждает: «репозиторий пока нельзя считать соответствующим» и перечисляет «крупные нарушения», но матрица показывает более суровую картину:

  • Fail: 11 требований (File size, Function size, Casts, Monorepo modules, Folder size, ORM, OpenAPI, CI safe lint fix, Coverage enforcement, Diff coverage, Mutation testing).
  • Partial: 8 требований (Parameters, Nesting, Suppressions, unknown handling, Unused deps, Unused modules, Duplication, Coverage thresholds).
  • Pass: 2 требования (Property-based testing, E2E testing).

Итого: 19 из 20 требований не полностью выполнены (11 Fail + 8 Partial).

Рекомендация: усилить выводы Summary, чтобы явно указать процент несоответствия и критичность (например, 55% требований полностью не выполнено, 40% выполнено частично). Это поднимет осведомленность о масштабе работ.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture-compliance-audit.md` around lines 7 - 18, The Summary
section in the architecture-compliance-audit.md file understates the actual
severity of non-compliance shown in the compliance matrix. Update the Summary to
explicitly state the quantified results from the matrix: 11 requirements
completely fail (55%), 8 are partially implemented (40%), and only 2 pass (10%).
Strengthen the language to clearly communicate the scale of non-compliance and
the extent of work needed, ensuring the Summary's severity matches the actual
compliance data shown in the matrix below it.


## Audit matrix

| Требование | Статус | Evidence |
| --- | --- | --- |
| File size <= 400 lines | Fail | 33 tracked TS code files exceed 400 lines. Largest: `packages/api/src/http.ts` 2121, `packages/api/src/services/federation.ts` 1916, `packages/api/src/services/terminal-sessions.ts` 1836. |
| Function size <= 50 lines | Fail | 270 functions exceed 50 lines. Largest: `makeRouter` in `packages/api/src/http.ts` starts at line 942 and spans about 1179 lines. |
| Parameters <= 5 | Partial | 7 functions exceed the limit. Worst: `packages/api/src/services/terminal-sessions.ts:1203` has 7 params. |
| Nesting depth <= 4 | Partial | 2 functions exceed the limit: `packages/api/src/services/auth-menu.ts:114` depth 7 and `packages/api/src/services/auth-menu.ts:165` depth 5. |
| Cyclomatic complexity <= 8 | Fail | 35 functions exceed the limit. Worst: `packages/api/src/services/projects.ts:449` complexity 36. |
| Suppression comments blocked | Partial | Only 4 `eslint-disable` / TS suppression hits, but they are config-level comments allowing test disables. jscpd suppression is broad: 40 `jscpd:ignore-start` blocks. |
| `any`, `unknown`, dynamic blocked | Partial | Explicit `any`: 0 AST occurrences. `unknown`: 163 AST occurrences; some are legitimate boundary values, but literal policy is not globally enforced. |
| Casts / `as` blocked | Fail | 59 TypeScript casts/type assertions in TS-only audit; broader JS/TS scope found 74. |
| Monorepo modules <= 5000 LOC | Fail | Top packages exceed the limit: app about 48k lines, lib about 28k, api about 26k, terminal about 10k, container about 8k. |
| Folder <= 10 code files | Fail | Top flat folders: `packages/app/src/web` 149 files, `packages/app/src/docker-git` 100, `packages/lib/src/usecases` 77, `packages/api/src/services` 42. |
| No unused dependencies | Partial | `dist-deps-prune` exists for packaged app dependency pruning, but there is no workspace-wide `knip`, `depcheck`, or equivalent unused dependency gate. |
| No unused modules | Partial | TypeScript and ESLint catch local unused symbols, but no workspace-wide unused export/module gate such as `knip` or `ts-prune` was found. |
| No duplicate code | Partial | `.jscpd.json` exists for app/lib/terminal and jscpd dependencies exist in app/lib/terminal/container. API and session-sync lack jscpd config, and many files use `jscpd:ignore`. |
| ORM or typed query layer for DB | Fail / not currently applicable | No Prisma/Drizzle/Kysely/TypeORM/Knex/Effect SqlClient usage was found. Existing DB-related code mainly handles typed database profile/proxy configuration, not database persistence. |
| Swagger/OpenAPI generated client | Fail | No OpenAPI/Swagger files or generated API client pipeline found. API schemas and clients appear handwritten with Effect Schema. |
| CI safe `lint --fix` bot flow | Fail | CI runs lint, but no deterministic auto-fix commit/fixed-point workflow was found. |
| Test coverage >= 10% | Partial | Vitest coverage thresholds exist in app/lib/container/terminal configs, but package test scripts and CI run plain `vitest run` without `--coverage`; API and session-sync lack coverage thresholds. |
| Property-based testing for invariants | Pass | `fast-check` is used broadly: 42 files and 77 `fc.property` usages were found. |
| E2E testing | Pass | CI runs 7 E2E jobs in `.github/workflows/check.yml`: local package, browser command, opencode, clone cache, login context, runtime volumes + SSH, clone auto-open SSH. |
| 100% changed code covered in PR | Fail | No diff coverage gate was found. |
| Mutation testing on PR changes | Fail | No Stryker or equivalent mutation testing config/tooling was found. |
Comment on lines +7 to +44

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚖️ Poor tradeoff

Документ не содержит явного Story + Prove блока, требуемого SDD.

Согласно docs/process.md и coding_guidelines (раздел "Story + Prove"), каждый аудит должен содержать:

  1. Story — описание цели аудита в терминах заинтересованного лица (кто, зачем, какая ценность).
  2. Prove — для каждого инварианта матрицы указать способ проверки:
    • unit/property тест
    • CI job
    • read-only скрипт верификации

Текущий документ содержит only Audit matrix (WHAT) и Top blockers (почему), но не содержит явного Story (WHO/WHY) и не привязывает каждый инвариант к способу его проверки.

Рекомендация: добавить перед Audit matrix раздел вида:

## Story

Как архитектор проекта, я хочу убедиться, что кодовая база соответствует 
функциональной парадигме с чистыми функциями и контролируемыми эффектами,
чтобы обеспечить воспроизводимость, типовую безопасность и математическую 
доказуемость решений.

### Prove (инварианты проверяемости)

- INV-1: ∀ файл ∈ TS-files: lines(файл) ≤ 400
  Проверка: `bun run audit:lines` (read-only скрипт)
  
- INV-2: ∀ функция ∈ функции: lines(функция) ≤ 50
  Проверка: `bun run audit:functions` (read-only скрипт)
  
... и т.д. для каждого требования

Это обеспечит:

  • Ясность цели аудита для всех участников.
  • Автоматическую проверяемость каждого требования.
  • Связь между инвариантами матрицы и способом их верификации.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture-compliance-audit.md` around lines 7 - 44, The
architecture-compliance-audit.md document is missing the explicit Story and
Prove sections required by the SDD methodology. Add a new "Story" section before
the Audit matrix that describes WHO (architect/stakeholder) and WHY (the
business goal) for this audit in clear terms. Then add a "Prove" section that
maps each requirement/invariant in the Audit matrix to its verification method,
specifying whether each will be verified via a read-only audit script (like `bun
run audit:lines`), a CI job, or a unit/property test. This ensures every
requirement in the matrix has a clear, automated verification path and makes the
audit's purpose and verifiability transparent to all project participants.


## Top blockers

1. `packages/api` is the biggest architectural risk: large files, large functions,
direct `fetch`, remaining Effect migration warnings, and weak regular ESLint
enforcement compared with app/lib/container/terminal.
2. OpenAPI/generated-client workflow is absent.
3. Mutation testing and diff coverage are absent.
4. Coverage thresholds exist only partially and are not enforced by CI.
5. Module and folder size limits are not satisfied by current package/folder
boundaries.
6. Duplication checks are partial and heavily bypassed in copied frontend-lib
code.

## Recommended PR sequence

1. Enforcement PR: add a read-only architecture audit script for LOC, folder
width, function size, params, nesting, complexity, casts and direct `fetch`;
connect API `lint:effect` to CI.
2. Coverage PR: add `test:coverage` scripts, thresholds for API/session-sync,
and a CI coverage job.
3. Duplication and unused-code PR: add workspace-wide jscpd coverage plus a
`knip` or equivalent unused dependency/export gate.
4. API contract PR: choose and introduce OpenAPI as source of truth, then
generate client/types and block handwritten internal API access.
5. Refactor PR series: split the largest API files first:
`http.ts`, `federation.ts`, `terminal-sessions.ts`, `skiller.ts`.
6. Mutation PR: add mutation testing on changed files after the test/coverage
baseline is stable.
Comment on lines +59 to +73

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Рекомендуемая PR sequence не привязана к инвариантам Audit matrix.

Раздел "Recommended PR sequence" содержит 6 PR'ов, но не указывает, какие требования из Audit matrix (строки 20–44) каждая PR закрывает. Это затрудняет:

  1. Приоритизацию: неясно, какие требования Fail критичнее других.
  2. Верификацию: после выполнения PR неясно, какие строки матрицы проверить.
  3. Отслеживание: при переиспользовании плана позже, какие требования он решал?

Рекомендация: добавить трассировку вида:

## Recommended PR sequence

1. **Enforcement PR** (closes: File size, Function size, Parameters, Cyclomatic complexity, Casts)
   - Description: add read-only architecture audit script...

2. **Coverage PR** (closes: Test coverage >= 10%, 100% diff coverage)
   - Description: add `test:coverage` scripts...

3. **Duplication and unused-code PR** (closes: No duplicate code, No unused modules, No unused dependencies)
   - Description: add workspace-wide jscpd coverage...

... и т.д.

Это позволит быстро найти в матрице, какие требования решает каждая PR, и проверить их выполнение.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture-compliance-audit.md` around lines 59 - 73, The Recommended
PR sequence section lists six PRs but doesn't link them to the specific
requirements from the Audit matrix (lines 20-44), making it hard to verify which
requirements each PR addresses and prioritize work. For each of the six PR items
in the sequence (Enforcement PR, Coverage PR, Duplication and unused-code PR,
API contract PR, Refactor PR series, and Mutation PR), add a "closes:"
annotation that explicitly maps to the corresponding Audit matrix requirements
that each PR fulfills, so readers can quickly cross-reference the matrix and
verify completion.


## Verification commands

The audit used read-only checks only:

```bash
rtk gh issue view 1 --repo ProverCoderAI/architecture-skills --json title,body,comments
rtk rg --files -g 'package.json' -g '*eslint*' -g '*biome*' -g '*jscpd*' -g '*openapi*' -g '*swagger*' -g '*stryker*' -g '*vitest*'
rtk bun run lint:effect
rtk rg -n 'fast-check|fc\\.property|fc\\.assert' packages -g '*.ts' -g '*.tsx'
rtk rg -n '\\bfetch\\(|\\.fetch\\(' packages scripts -g '*.ts' -g '*.tsx' -g '*.mjs'
```
Comment on lines +75 to +85

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Команды верификации используют неизвестный префикс rtk и не являются воспроизводимыми.

Строки 80–85 ссылаются на утилиту rtk, которая не является стандартной частью docker-git. Согласно требованиям SDD (coding_guidelines, docs/process.md), все команды должны быть реальными и проверяемыми.

На основе context snippets (package.json:49 и .github/workflows/check.yml:136–160) актуальные команды должны быть:

# Проверка lint:effect
bun run lint:effect

# Или по отдельным пакетам:
bun run --cwd packages/container lint:effect
bun run --cwd packages/api lint:effect

# Поиск fast-check использований
rg -n 'fast-check|fc\.property|fc\.assert' packages -g '*.ts' -g '*.tsx'

# Поиск прямых fetch вызовов
rg -n '\bfetch\(|\.fetch\(' packages scripts -g '*.ts' -g '*.tsx' -g '*.mjs'

Рекомендация: заменить все вхождения rtk на реальные команды или явно объяснить, что rtk — это внутренний скрипт репозитория (с указанием его расположения).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture-compliance-audit.md` around lines 75 - 85, The verification
commands in the "Verification commands" section contain a non-standard `rtk`
prefix that makes them non-reproducible and not aligned with the actual build
tools shown in the package.json and GitHub workflows. Replace the `rtk` prefixed
commands with their actual equivalents: change `rtk bun run lint:effect` to `bun
run lint:effect`, change `rtk rg` commands to use `rg` directly without the
prefix, and ensure the commands match those defined in the project's
package.json and .github/workflows/check.yml. If `rtk` is an internal project
script, explicitly document its location and purpose instead of using it in the
audit verification section.


The AST metrics were computed with the TypeScript compiler API against tracked
files under `packages/` and `scripts/`, excluding generated build output.
Loading