Saltar a contenido

Estado de fase (MASTER-00): POST_MVP — documento de catálogo de producto sujeto a validación; no es alcance aprobado de Gate 0 / PoC / MVP. Gobernanza: MASTER-00.

Alcance multiplataforma (DEC-002): esta arquitectura describe el catálogo completo. La secuencia vigente (MASTER-00 v0.7 §5) implementa Mobile (Fases A–C) y Desktop (Fase D, entorno operativo principal) sobre el núcleo compartido :docugraph-core; el módulo Web/Wasm queda fuera del alcance aprobado.

DocuGraph System Architecture & Technical Design

Nota de alcance vigente (DEC-013/DEC-014): este documento conserva diagramas y contratos históricos del catálogo de producto. La arquitectura implementada actualmente se limita a :docugraph-core, :docugraph-mcp, el workspace Git y las superficies Obsidian/Gitea/MkDocs; :docugraph-app y :docugraph-backend ya no existen como módulos activos.

1. Architectural Overview & Monorepo Topology

DocuGraph is structured as a high-performance, modular Kotlin monorepo. It isolates core business logic, visual UI components, Model Context Protocol (MCP) server endpoints, and asynchronous backend microservices into four primary modules:

                +-------------------------------------------------+
                |                 :docugraph-app                  |
                | Compose Multiplatform UI (Android, iOS, Desktop)|
                +------------------------+------------------------+
                                         |
                                         v
+------------------------+        +------------------------+        +------------------------+
|    :docugraph-mcp      |------->|    :docugraph-core     |<-------|   :docugraph-backend   |
|  Kotlin MCP Server     |        |   KMP Graph Engine     |        | Ktor / PostgreSQL Sync |
| (Stdio / SSE Transport)|        | & Frontmatter Parser   |        |  Relational Indexer    |
+------------------------+        +------------------------+        +------------------------+

Module Responsibilities

  • :docugraph-core: Pure Kotlin Multiplatform (KMP) library. Implements Markdown YAML frontmatter parsing, graph data structures, Tarjan's Strongly Connected Components (SCC) cycle detection algorithm ($O(V+E)$), reverse topological sorting, and link auditing. Has zero UI or DB dependencies.
  • :docugraph-app: Compose Multiplatform client UI application targeting Android, iOS, Desktop (JVM), and Web (Wasm/JS). Implements the interactive 2D node-edge visual DAG canvas, inspector drawer, project setup wizard, and RevenueCat paywall interface.
  • :docugraph-mcp: Kotlin MCP SDK server. Exposes standard tools (get_task_context, get_dependency_graph, validate_traceability), resources, and prompts over Stdio (local CLI agents) and HTTP SSE (IDE/remote agents).
  • :docugraph-backend: Ktor Framework REST API server and PostgreSQL indexer. Handles user authentication (JWT RS256), workspace change indexing, relational database sync (6 tables), and RevenueCat entitlement verification.

2. Module Micro-Architectures & Technical Design

2.1 :docugraph-core Engine Subcomponents

  1. YAML Frontmatter Parser: Reads Markdown headers delimited by ---, validates syntax against standard schemas, and extracts metadata keys (id, title, type, status, tags, links).
  2. Graph Data Model: Represents the documentation workspace as an in-memory Adjacency List (Map<String, Node>, List<Edge>).
  3. Cycle Detection Engine (Tarjan SCC): Executes Tarjan's algorithm to identify strongly connected components containing more than one vertex, returning exact circular dependency paths.
  4. Topological Sort & Pruning Engine: Calculates reverse topological ordering starting from a target node ID for context bundle generation, enforcing depth limits (maxDepth).
  5. Link Verifier: Audits relative Markdown file links, OpenAPI operation IDs, and database table declarations against the workspace index.

2.2 :docugraph-app Client Subcomponents

  1. Architecture Pattern: MVI / MVVM pattern utilizing Kotlin StateFlow, SharedFlow, and Coroutines.
  2. GraphCanvas (FE-03): Custom Compose Canvas renderer utilizing force-directed placement algorithms, a 60 FPS viewport transform matrix (pan and pinch-zoom from 0.25x to 3.0x), node color-coding by type, and directed edge arrow drawing.
  3. NodeInspector (FE-04): Animated slide-out drawer rendering YAML frontmatters, formatted Markdown bodies, and upstream/downstream navigation controls.
  4. LoginForm (FE-01) & ProjectDashboard (FE-02): Onboarding, authentication, and workspace creation UI views.
  5. PaywallModal (FE-05): Modal UI component wrapping RevenueCat purchasing flows and Pro feature unlocking.

2.3 :docugraph-mcp Server Subcomponents

  1. Transports: Stdio transport for local AI CLI tools (Claude Code, Cursor, Junie) and HTTP SSE transport for remote/IDE integrations.
  2. Tools Layer:
  3. get_task_context(taskId, maxDepth): Computes reverse topological context bundles.
  4. get_dependency_graph(nodeId, depth = 3): Returns JSON directed adjacency graph (nodes/edges) bounded to depth hops upstream/downstream from nodeId.
  5. validate_traceability(workspacePath): Runs automated cycle and link verification.
  6. Resources Layer: Exposes docugraph://workspace/nodes, docugraph://workspace/graph, docugraph://workspace/node/{id}, and docugraph://workspace/audit-report.
  7. Prompts Layer: Defines prompt_implement_task and prompt_audit_traceability templates.

2.4 :docugraph-backend Service Subcomponents

  1. Ktor Server Routing: Asynchronous HTTP routing layer handling REST endpoints (BE-01 through BE-06).
  2. Relational Indexer Service: Monitors filesystem events, parses updated Markdown files, and updates PostgreSQL tables (nodes, node_edges).
  3. Database Layer (Exposed ORM): PostgreSQL persistence mapping 6 core tables (users, subscriptions, projects, nodes, node_edges, mcp_api_keys).
  4. Auth & Entitlement Engine: Argon2id/bcrypt password hashing, RS256 JWT generation, RevenueCat webhook integration, and entitlement claim verification (pro_tier).

3. End-to-End Sequence & Data Flow Diagrams

Flow 1: User Login & Session Management (US-01 / IX-01 / FE-01 / BE-01)

[User] -> (FE-01 LoginForm) -> POST /api/v1/auth/login (BE-01) -> (PostgreSQL: users)
(FE-01) <- 200 OK (JWT Access & Refresh Tokens) <- (BE-01)
(FE-01) -> Store in Platform Encrypted Storage -> Navigate to (FE-02 ProjectDashboard)

Flow 2: Project Creation & Initial Graph Parsing (US-02 / IX-02 / FE-02 / BE-02)

[User] -> (FE-02 ProjectDashboard) -> Submit Workspace Path & Name -> POST /api/v1/projects (BE-02)
(BE-02) -> Check Entitlement (projects < 3 or pro_tier) -> Insert (PostgreSQL: projects)
(BE-02) -> Invoke (:docugraph-core) -> Sweep Markdown files & parse frontmatters
(BE-02) -> Populate (PostgreSQL: nodes, node_edges) -> Return 201 Created to (FE-02)

Flow 3: Interactive Graph Inspection (US-03 / IX-03 / FE-03 / FE-04 / BE-03)

(FE-03 GraphCanvas) -> GET /api/v1/projects/{id}/graph (BE-03) -> Query (nodes, node_edges)
(FE-03) <- 200 OK (Adjacency Matrix JSON) <- (BE-03)
(FE-03) -> Render Nodes & Edges @ 60 FPS -> User Clicks Node -> Slide Open (FE-04 NodeInspector)

Flow 4: MCP Context Bundle Extraction (US-04 / IX-04 / BE-04 / tool: get_task_context)

[AI Agent] -> JSON-RPC request get_task_context(taskId="BE-01", maxDepth=5) -> (:docugraph-mcp)
(:docugraph-mcp) -> Verify entitlement (pro_tier or cap maxDepth=2) -> Call (:docugraph-core)
(:docugraph-core) -> Execute Reverse Topological Traversal -> Collect US-01, IX-01, loginUser, table: users
(:docugraph-core) -> Prune unrelated subtrees -> Return formatted Markdown Context Bundle to [AI Agent]

Flow 5: Automated Traceability Audit (US-05 / BE-05 / tool: validate_traceability)

[User / CI / AI] -> Invoke validate_traceability(workspacePath) -> (:docugraph-core Engine)
(:docugraph-core) -> Run Tarjan's SCC Algorithm -> Detect Cycles & Broken Links
[User / CI / AI] <- JSON Audit Report (Errors, Warnings, Health Score %) <- (:docugraph-mcp)

Flow 6: Paywall & RevenueCat Entitlement Check (US-06 / FE-05 / BE-06)

[User] -> Trigger Pro Action (e.g. 4th Project or maxDepth > 2) -> Open (FE-05 PaywallModal)
(FE-05) -> Execute Purchase via RevenueCat SDK / Web Checkout -> Entitlement pro_tier granted
(FE-05) -> GET /api/v1/subscriptions/entitlement (BE-06) -> Update (PostgreSQL: subscriptions)
(FE-05) <- Updated JWT Access Token (claim: entitlement="pro_tier") <- (BE-06) -> Unlock Features

4. Data Storage & Schema Summary

The relational backend persists system state in PostgreSQL across 6 core tables detailed in docs/domain/01_DATABASE_SCHEMA.md:

  1. users: User identity, hashed credentials (Argon2id), and OAuth metadata.
  2. subscriptions: Subscription tier status, RevenueCat customer ID, entitlement ID (pro_tier), and offline grace period timestamp.
  3. projects: Workspace directory registration, Git remote repository links, node/edge count caches, and schema configuration JSON.
  4. nodes: Parsed atomic documentation nodes (atomic ID, title, document type, status, file path, checksum, and GIN-indexed tags/frontmatter JSON).
  5. node_edges: Directed adjacency graph edges connecting source and target nodes with specific relationship types (depends_on, depended_by, related, tables).
  6. mcp_api_keys: Cryptographically hashed API keys issued to users for MCP server authentication and AI agent access.

5. Cross-Cutting Architectural Mechanisms

5.1 Security Architecture

  • Authentication: JWT RS256 asymmetric signature verification. Access tokens expire in 15 minutes; refresh tokens expire in 30 days.
  • Password Security: Argon2id password hashing with random salt.
  • Secure Key Storage: Mobile/Desktop clients use OS-native encrypted keychains (EncryptedSharedPreferences, iOS Keychain, Secret Service API).

5.2 Performance Optimization

  • Memoized Topological Sort: Cache topological traversal subtrees using document checksum hashes to achieve <150ms MCP response times.
  • Spatial Indexing: Visual canvas viewport applies bounding-box spatial indexing to render only visible nodes/edges during pan/zoom.

5.3 Offline Resilience & Grace Period

  • Client applications and local MCP servers cache JWT entitlement claims locally.
  • Subscriptions support up to 7 consecutive days of offline operation (offline_grace_until) before requiring online re-validation against RevenueCat servers.

6. Traceability Index