Skip to content

fix: Architecture invariant — model centralization (INV-14) + doc-drift (INV-7→#1309, INV-8→#1310 split out) #654

Closed

Description

@vybe

Architecture Validation Report (2026-05-05)

Automated validation detected 3 invariant violations and 2 doc-drift items requiring attention.

Invariant Compliance

# Invariant Status Details
1 Three-Layer Backend: Router → Service → DB PASS pipe.execute() calls are Redis pipeline, not SQL. DB layer has no FastAPI imports.
2 DB Layer: Class-per-domain with Mixin Composition PASS All db/*.py files define *Operations classes; all db/agent_settings/*.py define *Mixin classes.
3 Schema in db/schema.py, Migrations in db/migrations.py PASS No CREATE TABLE found outside schema.py/migrations.py.
4 Router Registration Order PASS /context-stats, /autonomy-status, /sync-health, /slots, /permissions-edges all registered before /{agent_name} catch-all.
5 Agent Server Mirrors Backend (Subset) PASS Agent server has snapshot.py, trinity.py, info.py, activity.py, dashboard.py which are legitimate agent-internal-only routers (not required to have backend mirrors).
6 Frontend: Store = Domain, View = Page PASS No views import api directly or make API calls via stores.
7 Single API Client (api.js) FAIL 20+ files bypass api.js singleton: stores (agents.js, auth.js, operatorQueue.js, monitoring.js, network.js, etc.) import raw axios with manual auth headers; views (AgentDetail.vue, ApiKeys.vue) use raw fetch() with manual Authorization headers. This means token refresh logic in api.js interceptors is skipped.
8 Auth Pattern: Depends(get_current_user) + AuthorizedAgent FAIL 51 inline raise HTTPException(status_code=403) calls across 19 router files (threshold: 5). internal.py correctly has no get_current_user. High-volume sites: agent_config.py (6 sites), avatar.py (5 sites), agent_files.py (3 sites), chat.py (2 sites), plus 14 more files. Authorization logic is duplicated across routers instead of being centralized in AuthorizedAgent/dependency factories.
9 Channel Adapter ABC PASS adapters/base.py defines ChannelAdapter ABC. SlackAdapter, TelegramAdapter, and WhatsappAdapter all inherit from it.
10 WebSocket Events for Real-Time WARN operatorQueue.js uses setInterval polling the /api/operator-queue REST endpoint every N seconds. HostTelemetry.vue polls /api/telemetry/host every 5000ms with raw fetch. websocket.js exists. These are minor exceptions (operator queue and host telemetry are not agent-state push events) but are noted.
11 Docker as Source of Truth PASS No module-level container state dicts found. docker_service.py exists.
12 Credentials: File Injection, Never Stored in DB PASS No credential values in schema.py tables.
13 MCP Server = Third Surface in Sync PASS 16 tool modules present. tags.ts is registered in server.ts but not exported from tools/index.ts (stale re-export index — minor).
14 Pydantic Models Centralized in models.py FAIL 71 Pydantic BaseModel class definitions found scattered across router files (audit_log.py, fan_out.py, git.py, internal.py, avatar.py, event_subscriptions.py, image_generation.py, logs.py, messages.py, and more). These should live in models.py.
15 API URL Nesting Convention PASS Agent-scoped resources correctly nest under /api/agents/{name}/.

Result: 11/15 PASS, 3/15 FAIL, 1/15 WARN

Violations

INV-8 (P1): Auth Sprawl — Inline Authorization in 19 Router Files (51 sites)

51 raise HTTPException(status_code=403) calls spread across 19 router files including agent_config.py, avatar.py, chat.py, logs.py, sharing.py, slack.py, operator_queue.py, settings.py, system_agent.py, system_views.py, whatsapp.py, and more.

Fix: Consolidate into AuthorizedAgent, OwnedAgentByName, or require_role() dependencies in dependencies.py. Each new inline auth check increases the attack surface for auth bypass and makes auditing harder.

INV-7 (P1): API Client Fragmentation — Raw axios and fetch Bypass api.js

20+ frontend files import axios directly or use fetch() instead of the api.js Axios singleton that handles token refresh and auth interceptors:

  • Stores: agents.js, auth.js, operatorQueue.js, monitoring.js, observability.js, network.js, settings.js, notifications.js, systemViews.js
  • Components: ChatPanel.vue, PlaybooksPanel.vue, PublicLinksPanel.vue, SkillsPanel.vue, CreateAgentModal.vue, NavBar.vue, HostTelemetry.vue (raw fetch)
  • Views: AgentDetail.vue (raw fetch for autonomy, read-only, rename endpoints), ApiKeys.vue (raw fetch for all MCP key operations)

Fix: Migrate all API calls to import and use the api singleton from src/api.js.

INV-14 (P1): Pydantic Model Sprawl — 71 Models Outside models.py

71 BaseModel class definitions found in router files. Significant violators: fan_out.py (4 models), git.py (5 models), internal.py (5 models), audit_log.py (4 models), logs.py (2 models).

Fix: Move all request/response models to src/backend/models.py and import from there.

Doc Drift — Suggested architecture.md Edits

Item Doc Claims Actual Action
D1: Service module count "37 service modules" 47 modules Update to 47; document 10 undocumented services: fan_out_service, fleet_audit_service, gemini_voice, github_pat_propagation_service, platform_audit_service, platform_prompt_service, pre_check_service, subscription_auto_switch, upload_service, validation_service, ws_ticket_service, sync_waiter, telegram_media
D1: Router module count "53 router modules" 52 modules Update to 52
D1: MCP tool count "62 tools" (CLAUDE.md) 73 tools Update to 73; chat.ts has 4 tools (doc says 3 — fan_out is undocumented)
D1: agents.py line count "642 lines" 799 lines Update to ~800 lines
D1: main.py reference (implicit) 973 lines No claim to update, but doc says "300+ endpoints across 40+ routers" — routers is now 52
D2: audit_retention_service Listed in Background Services table but missing from Services module list Exists as active service Add to Services section
D2: sync_health_service Listed in Background Services table but missing from Services module list Exists as active service Add to Services section

Activity

  1. added
    priority-p1
    type-bug
    automated
    on May 5, 2026
  2. vybe commented on May 11, 2026

    @vybe
    ContributorAuthor

    Re-run on c65ceef (2026-05-11): same invariants still failing (7,8,14). Fresh report below.

    Architecture Validation Report — 2026-05-11

    Commit: c65ceef

    Invariant Compliance

    # Invariant Status
    1 Three-Layer Backend ✅ PASS
    2 DB Layer: Class-per-domain ✅ PASS
    3 Schema in schema.py ✅ PASS
    4 Router Registration Order ⚠️ WARN
    5 Agent Server Mirrors Backend ✅ PASS (minor)
    6 Frontend: Store = Domain ✅ PASS
    7 Single API Client (api.js) ❌ FAIL
    8 Auth Pattern: Inline Authorization Sprawl ❌ FAIL
    9 Channel Adapter ABC ✅ PASS
    10 WebSocket Events for Real-Time ✅ PASS
    11 Docker as Source of Truth ✅ PASS
    12 Credentials: Never in DB ✅ PASS
    13 MCP Server = Third Surface in Sync ✅ PASS
    14 Pydantic Models Centralized ❌ FAIL
    15 API URL Nesting Convention ✅ PASS

    Result: 11/15 PASS, 3/15 FAIL, 1 WARN


    Violations

    Invariant #4 — Router Registration Order (WARN)

    src/backend/routers/agents.py:746 — @router.get("/activities/timeline") is registered after @router.get("/{agent_name}") at line 328. FastAPI doesn't misroute this particular case (different segment counts prevent shadowing), but it violates the stated invariant that static paths precede catch-all params. Move the /activities/timeline route above line 328.

    Note: This route is also redundant — src/backend/routers/activities.py already serves GET /api/activities/timeline with the dedicated prefix. The /api/agents/activities/timeline endpoint in agents.py may be a leftover duplicate.

    Invariant #7 — Single API Client (FAIL)

    Raw fetch() calls with hand-crafted Authorization headers found in view components — bypassing the single api.js Axios instance:

    • src/frontend/src/views/AgentDetail.vue:387 — fetch(/api/agents/.../autonomy, {Authorization: Bearer ...})
    • src/frontend/src/views/AgentDetail.vue:427 — fetch(/api/agents/.../read-only, ...)
    • src/frontend/src/views/AgentDetail.vue:480 — fetch(/api/agents/.../rename, ...)
    • src/frontend/src/views/ApiKeys.vue:393 — fetch(/api/users/me, ...)
    • src/frontend/src/views/ApiKeys.vue:409 — fetch(/api/mcp/keys, ...)
    • src/frontend/src/views/ApiKeys.vue:427,451,489,513 — multiple MCP key operations

    Fix: Replace all fetch() calls with api.put()/api.get() etc. calls through the Pinia stores, or at minimum through the api.js singleton. Token management should not be duplicated in views.

    Invariant #8 — Inline Authorization Sprawl (FAIL)

    51 inline raise HTTPException(status_code=403) blocks across 19 router files. Permission logic should be in Depends() dependencies, not scattered across endpoints.

    Top offenders:

    • src/backend/routers/slack.py — 7 inline 403s
    • src/backend/routers/agent_config.py — 6 inline 403s
    • src/backend/routers/avatar.py — 5 inline 403s
    • src/backend/routers/subscriptions.py — 4 inline 403s
    • src/backend/routers/notifications.py — 4 inline 403s
    • src/backend/routers/nevermined.py — 4 inline 403s
    • src/backend/routers/chat.py — 4 inline 403s

    Fix: Extract common patterns (can_user_access_agent, can_user_share_agent, owner-only checks) into reusable Depends() factories in dependencies.py.

    Invariant #14 — Pydantic Models Centralized (FAIL)

    71 Pydantic model class definitions scattered across 25 router files instead of being in models.py.

    Top offenders (by model count):

    • src/backend/routers/settings.py — 9 models
    • src/backend/routers/telegram.py — 7 models
    • src/backend/routers/git.py — 6 models
    • src/backend/routers/fan_out.py — 4 models
    • src/backend/routers/messages.py — 4 models
    • src/backend/routers/voice.py — 4 models

    Fix: Move model classes to src/backend/models.py.


    Doc Drift — Suggested architecture.md Edits

    D1 — Count Mismatches

    • architecture.md:L94 — claims "53 router modules" but actual count is 52 (ls src/backend/routers/*.py | grep -v __init__). Suggested: update to "52 router modules".

    • architecture.md:L163 — claims "37 service modules" but actual count is 47 (ls src/backend/services/*.py | grep -v __init__). Suggested: update to "47 service modules" and add the 12 undocumented services: fan_out_service, fleet_audit_service, gemini_voice, github_pat_propagation_service, platform_audit_service, platform_prompt_service, pre_check_service, subscription_auto_switch, sync_waiter, telegram_media, upload_service, validation_service.

    D2 — Missing Router Documentation

    The following 5 routers are in code but not listed in architecture.md:

    D3 — Agent Server Router List Outdated

    architecture.md:L721 lists agent-server routers as: "chat, credentials, files, git, skills, dashboard". Actual routers: activity, chat, credentials, dashboard, files, git, info, skills, snapshot, trinity (10 routers, not 6). Suggested: update invariant #5 to list all 10.

  3. added
    complexity-low
    theme-reliability
    on Jun 3, 2026
  4. added
    status-ready
    priority-p2
    and removed
    priority-p1
    on Jun 14, 2026
  5. added
    status-in-progress
    and removed
    status-ready
    on Jun 22, 2026
  6. AndriiPasternak31 commented on Jun 22, 2026

    @AndriiPasternak31
    Contributor

    /claim

  7. github-actions commented on Jun 22, 2026

    @github-actions

    @AndriiPasternak31 This issue is already assigned to AndriiPasternak31. Use /unclaim first if you want to take over.

  8. AndriiPasternak31 commented on Jun 22, 2026

    @AndriiPasternak31
    Contributor

    Scope narrowed (2026-06-23)

    Re-measurement showed the original 2026-05-05 automated report undercounted every dimension, and fully clearing all three FAIL invariants spans backend + frontend + two other owners' areas — a multi-PR epic mismatched with P2/complexity-low. Decision: this issue clears INV-14 (model centralization) + the D1/D2 doc-drift only. INV-7 and INV-8 are split into their own issues with ground-truth counts.

    Invariant Report (2026-05-05) Actual (2026-06-22) Disposition
    #14 models 71 98 / 32 routers ✅ This issue — PR #1308 (97 moved + 1 documented allowlist exception)
    #7 frontend api.js 20+ files ~46 files / ~400 calls → split to #1309 (frontend-owned, behavioral verify)
    #8 auth 51 / 19 files 64 / 22 files → split to #1310 (security-sensitive, new factories)

    Done here (PR #1308): INV-14 cleared via a flat models.py move — behavior proven by a byte-identical normalized OpenAPI snapshot diff (330 paths / 198 schemas) + validator-preservation tests; static guard added; D1/D2 doc-drift (Invariant #14 scope note + re-measured router/service/agents.py counts) applied to architecture.md.

    Carved out: INV-7 → #1309 · INV-8 → #1310.

  9. changed the title [-]fix: Architecture invariant violations — auth sprawl, API client fragmentation, model centralization[/-] [+]fix: Architecture invariant — model centralization (INV-14) + doc-drift (INV-7→#1309, INV-8→#1310 split out)[/+] on Jun 22, 2026
  10. added
    status-in-dev
    and removed
    status-in-progress
    on Jun 26, 2026
  11. removed
    status-in-dev
    on Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

automatedcomplexity-lowpriority-p2theme-reliabilitytype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions