@mcp-graph-workflow/mcp-graph 5.31.0 → 5.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +1 -1
  2. package/dist/api/routes/benchmark.d.ts.map +1 -1
  3. package/dist/api/routes/benchmark.js +15 -2
  4. package/dist/api/routes/benchmark.js.map +1 -1
  5. package/dist/api/routes/translation-project.js +2 -2
  6. package/dist/api/routes/translation-project.js.map +1 -1
  7. package/dist/api/routes/translation.js +2 -2
  8. package/dist/api/routes/translation.js.map +1 -1
  9. package/dist/core/translation/generators/ast-placeholder-extractor.d.ts +20 -0
  10. package/dist/core/translation/generators/ast-placeholder-extractor.d.ts.map +1 -0
  11. package/dist/core/translation/generators/ast-placeholder-extractor.js +215 -0
  12. package/dist/core/translation/generators/ast-placeholder-extractor.js.map +1 -0
  13. package/dist/core/translation/generators/placeholder-resolver.d.ts +18 -0
  14. package/dist/core/translation/generators/placeholder-resolver.d.ts.map +1 -0
  15. package/dist/core/translation/generators/placeholder-resolver.js +487 -0
  16. package/dist/core/translation/generators/placeholder-resolver.js.map +1 -0
  17. package/dist/core/translation/generators/source-text-extractor.d.ts +20 -0
  18. package/dist/core/translation/generators/source-text-extractor.d.ts.map +1 -0
  19. package/dist/core/translation/generators/source-text-extractor.js +190 -0
  20. package/dist/core/translation/generators/source-text-extractor.js.map +1 -0
  21. package/dist/core/translation/generators/universal-generator.d.ts +23 -0
  22. package/dist/core/translation/generators/universal-generator.d.ts.map +1 -0
  23. package/dist/core/translation/generators/universal-generator.js +137 -0
  24. package/dist/core/translation/generators/universal-generator.js.map +1 -0
  25. package/dist/core/translation/parsers/parser-adapter.d.ts +4 -0
  26. package/dist/core/translation/parsers/parser-adapter.d.ts.map +1 -1
  27. package/dist/core/translation/project-translation-orchestrator.d.ts +3 -3
  28. package/dist/core/translation/project-translation-orchestrator.d.ts.map +1 -1
  29. package/dist/core/translation/project-translation-orchestrator.js +4 -4
  30. package/dist/core/translation/project-translation-orchestrator.js.map +1 -1
  31. package/dist/core/translation/prompt-builder.d.ts +4 -0
  32. package/dist/core/translation/prompt-builder.d.ts.map +1 -1
  33. package/dist/core/translation/prompt-builder.js +13 -3
  34. package/dist/core/translation/prompt-builder.js.map +1 -1
  35. package/dist/core/translation/translation-orchestrator.d.ts +2 -1
  36. package/dist/core/translation/translation-orchestrator.d.ts.map +1 -1
  37. package/dist/core/translation/translation-orchestrator.js +21 -2
  38. package/dist/core/translation/translation-orchestrator.js.map +1 -1
  39. package/dist/docs-manifest.json +8 -2
  40. package/dist/mcp/tools/translate-code.js +1 -1
  41. package/dist/mcp/tools/translate-code.js.map +1 -1
  42. package/dist/web/dashboard/dist/assets/benchmark-tab-en-UkR66.js +1 -0
  43. package/dist/web/dashboard/dist/assets/{circle-alert-RxlCxXj1.js → circle-alert-5GIBBP3L.js} +1 -1
  44. package/dist/web/dashboard/dist/assets/{context-tab-DTPFGxle.js → context-tab-DjfwQik8.js} +1 -1
  45. package/dist/web/dashboard/dist/assets/{docs-tab-2uo7-Ybt.js → docs-tab-gEBzBEEV.js} +1 -1
  46. package/dist/web/dashboard/dist/assets/{gitnexus-tab-CiiNOf3e.js → gitnexus-tab-BE2pi0xe.js} +1 -1
  47. package/dist/web/dashboard/dist/assets/{graph-section-DKMay1zv.js → graph-section-Cwx-Bmeh.js} +1 -1
  48. package/dist/web/dashboard/dist/assets/{graph-tab-BYRVanTv.js → graph-tab-BcS75lY0.js} +1 -1
  49. package/dist/web/dashboard/dist/assets/{graph-utils-1O2cEKuy.js → graph-utils-OY_fOvB3.js} +1 -1
  50. package/dist/web/dashboard/dist/assets/{index-CSeiGgX8.js → index-1aGs8JPI.js} +1 -1
  51. package/dist/web/dashboard/dist/assets/{index-B5DzSMGg.js → index-4X4gmCkA.js} +1 -1
  52. package/dist/web/dashboard/dist/assets/index-BVhCKhGJ.css +1 -0
  53. package/dist/web/dashboard/dist/assets/{index-CIhDR5rf.js → index-C3Kad9YO.js} +2 -2
  54. package/dist/web/dashboard/dist/assets/{insights-tab-DdI7TLP7.js → insights-tab-CP2uIpid.js} +1 -1
  55. package/dist/web/dashboard/dist/assets/{journey-tab-CDuvIW6V.js → journey-tab-ChwNK_8S.js} +1 -1
  56. package/dist/web/dashboard/dist/assets/languages-tab-DnBvSh4N.js +123 -0
  57. package/dist/web/dashboard/dist/assets/{loader-circle-Bl0DpM5P.js → loader-circle-Bxe_TLXv.js} +1 -1
  58. package/dist/web/dashboard/dist/assets/{logs-tab-QYKxeHna.js → logs-tab-BH86QvKe.js} +1 -1
  59. package/dist/web/dashboard/dist/assets/{lsp-tab-CLO4RFMh.js → lsp-tab-DUpaQXtx.js} +1 -1
  60. package/dist/web/dashboard/dist/assets/{memories-tab-BT7A7YOy.js → memories-tab-CkwtNv3t.js} +1 -1
  61. package/dist/web/dashboard/dist/assets/{prd-backlog-tab-M1j0tAm2.js → prd-backlog-tab-CPJanaVF.js} +1 -1
  62. package/dist/web/dashboard/dist/assets/{refresh-cw-0ApsgAym.js → refresh-cw-DL1dUrhF.js} +1 -1
  63. package/dist/web/dashboard/dist/assets/{siebel-tab-CsZz2y2b.js → siebel-tab-D7x34UXy.js} +3 -3
  64. package/dist/web/dashboard/dist/assets/{skills-tab-BrkrK7AC.js → skills-tab-BuqCMS29.js} +1 -1
  65. package/dist/web/dashboard/dist/assets/{style-UgkJJqFQ.js → style-iy_ryTT6.js} +1 -1
  66. package/dist/web/dashboard/dist/assets/{triangle-alert-BcgxNLLr.js → triangle-alert-CPzksLkC.js} +1 -1
  67. package/dist/web/dashboard/dist/index.html +2 -2
  68. package/package.json +2 -2
  69. package/dist/web/dashboard/dist/assets/benchmark-tab-BD02uofm.js +0 -1
  70. package/dist/web/dashboard/dist/assets/index-BxDGbcbB.css +0 -1
  71. package/dist/web/dashboard/dist/assets/languages-tab-CrbP4u3b.js +0 -123
@@ -26,6 +26,9 @@ import { scoreConstructs } from "./confidence/equivalence-scorer.js";
26
26
  import { detectAmbiguities } from "./confidence/ambiguity-detector.js";
27
27
  import { buildTranslationPrompt } from "./prompt-builder.js";
28
28
  import { TranslationError } from "../utils/errors.js";
29
+ import { extractPlaceholdersFromAst } from "./generators/ast-placeholder-extractor.js";
30
+ import { UniversalGenerator } from "./generators/universal-generator.js";
31
+ import { logger } from "../utils/logger.js";
29
32
  /**
30
33
  * Mapping of equivalent constructs across languages.
31
34
  * When source construct X translates to target construct Y,
@@ -169,7 +172,7 @@ export class TranslationOrchestrator {
169
172
  /**
170
173
  * Prepare a translation job — creates the job, analyzes source, builds prompt.
171
174
  */
172
- prepareTranslation(input) {
175
+ async prepareTranslation(input) {
173
176
  const sourceCode = input.sourceCode ?? "";
174
177
  const analysis = this.analyzeSource(sourceCode, {
175
178
  languageHint: input.sourceLanguage,
@@ -206,7 +209,23 @@ export class TranslationOrchestrator {
206
209
  ambiguities: safeAmbiguities,
207
210
  };
208
211
  const prompt = buildTranslationPrompt(promptCtx);
209
- return { jobId: job.id, prompt, analysis };
212
+ // Generate deterministic code via AST extraction + UniversalGenerator
213
+ // Works for ALL cases: 100% deterministic and partial (generates code for matched constructs)
214
+ let deterministicCode;
215
+ if (parsed.length > 0) {
216
+ try {
217
+ const enriched = await extractPlaceholdersFromAst(sourceCode, parsed, analysis.detectedLanguage);
218
+ const generator = new UniversalGenerator(this.registry, input.targetLanguage, sourceCode, analysis.detectedLanguage);
219
+ const genResult = generator.generate(enriched);
220
+ if (genResult.code.trim().length > 0) {
221
+ deterministicCode = genResult.code;
222
+ }
223
+ }
224
+ catch (err) {
225
+ logger.warn("Deterministic translation failed, falling back to AI prompt", { error: String(err) });
226
+ }
227
+ }
228
+ return { jobId: job.id, prompt, analysis, deterministicCode };
210
229
  }
211
230
  /**
212
231
  * Finalize a translation — validate output, compute confidence, generate evidence.
@@ -1 +1 @@
1
- {"version":3,"file":"translation-orchestrator.js","sourceRoot":"","sources":["../../../src/core/translation/translation-orchestrator.ts"],"names":[],"mappings":"AAAA;;;;GAIG;A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,IAAI,EAAE,GAAG,UAAU,KAAK,MAAM,CAAC,MAAM,kBAAkB,UAAU,KAAK,MAAM,CAAC,MAAM,cAAc;QACjG,oBAAoB,EAAE,UAAU;QAChC,KAAK;QACL,eAAe;QACf,iBAAiB,EAAE,YAAY;KAChC,CAAC;AACJ,CAAC;AAED,SAAS,aAAa;IACpB,OAAO;QACL,IAAI,EAAE,EAAE;QACR,oBAAoB,EAAE,EAAE;QACxB,KAAK,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,wCAAwC,EAAE,CAAC;QACtG,eAAe,EAAE,CAAC;QAClB,iBAAiB,EAAE,CAAC,6BAA6B,CAAC;KACnD,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"translation-orchestrator.js","sourceRoot":"","sources":["../../../src/core/translation/translation-orchestrator.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAG7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAE,mBAAmB,E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IAED,4BAA4B;IAC5B,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7E,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,GAAG,GAAG,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC;IAE1D,OAAO;QACL,IAAI,EAAE,GAAG,UAAU,KAAK,MAAM,CAAC,MAAM,kBAAkB,UAAU,KAAK,MAAM,CAAC,MAAM,cAAc;QACjG,oBAAoB,EAAE,UAAU;QAChC,KAAK;QACL,eAAe;QACf,iBAAiB,EAAE,YAAY;KAChC,CAAC;AACJ,CAAC;AAED,SAAS,aAAa;IACpB,OAAO;QACL,IAAI,EAAE,EAAE;QACR,oBAAoB,EAAE,EAAE;QACxB,KAAK,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,wCAAwC,EAAE,CAAC;QACtG,eAAe,EAAE,CAAC;QAClB,iBAAiB,EAAE,CAAC,6BAA6B,CAAC;KACnD,CAAC;AACJ,CAAC"}
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-03-30T02:40:49.909Z",
2
+ "generatedAt": "2026-03-31T01:37:21.403Z",
3
3
  "tools": [
4
4
  {
5
5
  "name": "analyze",
@@ -1093,7 +1093,7 @@
1093
1093
  "slug": "architecture/ARCHITECTURE-GUIDE",
1094
1094
  "title": "ARCHITECTURE GUIDE",
1095
1095
  "category": "architecture",
1096
- "content": "# Architecture Guide — mcp-graph\n\n## Overview\n\nmcp-graph is a local-first tool that transforms PRD text files into persistent execution graphs stored in SQLite, with an integrated knowledge store, RAG pipeline, and multi-agent integration mesh. It provides structured, token-efficient context for agentic workflows.\n\n## Layers\n\n### Layer 1: CLI — `src/cli/`\n\n**Framework:** Commander.js v14\n\nThin orchestration layer. Commands call core functions and format output. No business logic.\n\n| Command | File | Description |\n|---------|------|-------------|\n| `init` | `commands/init.ts` | Initialize project + SQLite DB |\n| `import` | `commands/import-cmd.ts` | Import PRD file into graph |\n| `index` | `commands/index-cmd.ts` | Rebuild knowledge indexes and embeddings |\n| `stats` | `commands/stats.ts` | Show graph statistics |\n| `serve` | `commands/serve.ts` | Start HTTP server + MCP + dashboard |\n\n### Layer 2: MCP Server — `src/mcp/`\n\n**Protocol:** Model Context Protocol (Streamable HTTP + Stdio)\n\n<!-- mcp-graph:arch-mcp:start -->\n51 tool registrations (45 active + 6 deprecated shims) via `@modelcontextprotocol/sdk`. Two transport modes:\n\n- **HTTP** (`server.ts`) — Express server with `/mcp` endpoint + REST API + static dashboard\n- **Stdio** (`stdio.ts`) — Standard I/O transport for direct MCP client integration\n\nTool categories:\n- **Core** (30) — analyze, clone_node, context, delete_memory, edge, export, help, import_graph, import_prd, init, journey, list, list_memories, manage_skill, metrics, move_node, next, node, plan_sprint, rag_context, read_memory, reindex_knowledge, search, set_phase, show, snapshot, sync_stack_docs, update_status, validate, write_memory\n- **Translation** (3) — analyze_translation, translate_code, translation_jobs\n- **Code Intelligence** (1) — code_intelligence\n- **Knowledge** (3) — export_knowledge, knowledge_feedback, knowledge_stats\n- **Siebel CRM** (8) — siebel_analyze, siebel_composer, siebel_env, siebel_generate_sif, siebel_import_docs, siebel_import_sif, siebel_search, siebel_validate\n- **Deprecated shims** (6) — add_node, delete_node, list_skills, update_node, validate_ac, validate_task (removed in v7.0)\n<!-- mcp-graph:arch-mcp:end -->\n\n### Layer 3: REST API — `src/api/`\n\n**Framework:** Express v5\n\n<!-- mcp-graph:arch-api:start -->\n25 routers, 128 endpoints. Modular router architecture:\n<!-- mcp-graph:arch-api:end -->\n\n```\nrouter.ts # Main router composition\nroutes/\n project.ts # GET/POST /project\n nodes.ts # GET/POST/PATCH/DELETE /nodes\n edges.ts # GET/POST/DELETE /edges\n stats.ts # GET /stats\n search.ts # GET /search\n graph.ts # GET /graph, /graph/mermaid\n import.ts # POST /import (multipart file upload)\n knowledge.ts # GET/POST/DELETE /knowledge\n rag.ts # POST /rag/query, /rag/reindex, GET /rag/stats\n code-graph.ts # GET /code-graph/* — native code intelligence endpoints\n integrations.ts # GET /integrations/status|memories|enriched-context|knowledge-status\n insights.ts # GET /insights/bottlenecks|recommendations|metrics\n context.ts # GET /context/preview\n capture.ts # POST /capture\n docs-cache.ts # GET/POST /docs\n events.ts # GET /events (SSE stream)\n skills.ts # GET /skills\nmiddleware/\n error-handler.ts # Centralized error handling\n validate.ts # Zod-based request validation\n```\n\nSee [REST API Reference](../reference/REST-API-REFERENCE.md) for full endpoint documentation.\n\n### Layer 4: Core — `src/core/`\n\nPure functions with explicit dependencies. No framework coupling. 16 subdirectories.\n\n#### Parser (`core/parser/`)\n\nPipeline: `readFile → segment → classify → extract`\n\n| Module | Purpose |\n|--------|---------|\n| `file-reader.ts` | Read .md, .txt, .pdf, .html files with format detection |\n| `read-file.ts` | Legacy PRD reader |\n| `read-pdf.ts` | PDF extraction via pdf-parse |\n| `read-html.ts` | HTML to markdown extraction |\n| `segment.ts` | Split text by headings into sections |\n| `classify.ts` | Heuristic block classification (epic, task, requirement, etc.) |\n| `extract.ts` | Extract structured entities from classified blocks |\n| `normalize.ts` | Text normalization (whitespace, encoding) |\n\n#### Importer (`core/importer/`)\n\n| Module | Purpose |\n|--------|---------|\n| `prd-to-graph.ts` | Convert extraction results to graph nodes + edges with dependency inference |\n| `import-prd.ts` | High-level import orchestration |\n\n#### Planner (`core/planner/`)\n\n| Module | Purpose |\n|--------|---------|\n| `next-task.ts` | Suggest next task: filter eligible → resolve dependencies → sort by priority/size/age |\n| `enhanced-next.ts` | Augments next-task with knowledge coverage + velocity context |\n| `decompose.ts` | Detect large tasks, suggest subtask breakdown |\n| `dependency-chain.ts` | Analyze dependency graphs, detect cycles, compute critical paths |\n| `velocity.ts` | Calculate historical sprint velocity and time estimates |\n| `planning-report.ts` | Generate sprint planning reports (capacity, blockers, risk) |\n\n#### Context Builder (`core/context/`)\n\n| Module | Purpose |\n|--------|---------|\n| `compact-context.ts` | Build minimal context for a task (parent, children, deps, blockers, AC) |\n| `rag-context.ts` | Semantic RAG context builder with token budgeting |\n| `tiered-context.ts` | Three-tier compression: summary (~20 tok) / standard (~150 tok) / deep (~500+ tok) |\n| `bm25-compressor.ts` | BM25 ranking to filter knowledge chunks by relevance |\n| `context-assembler.ts` | Combines graph (60%) + knowledge (30%) + header (10%) with token accounting |\n| `token-estimator.ts` | Estimate token count for context payloads |\n\n#### RAG (`core/rag/`)\n\n| Module | Purpose |\n|--------|---------|\n| `embedding-store.ts` | Persist TF-IDF vectors in SQLite, cosine similarity search |\n| `rag-pipeline.ts` | TF-IDF vectorizer: index nodes + knowledge as embeddings |\n| `memory-indexer.ts` | Index memory documents into embeddings |\n| `docs-indexer.ts` | Index fetched documentation into embeddings |\n| `capture-indexer.ts` | Index web-captured content into embeddings |\n| `memory-rag-query.ts` | Query memories via FTS / semantic / hybrid modes |\n| `chunk-text.ts` | Split text into ~500 token chunks with overlap |\n\nSee [Knowledge Pipeline](./KNOWLEDGE-PIPELINE.md) for the full RAG documentation.\n\n#### Integrations (`core/integrations/`)\n\n| Module | Purpose |\n|--------|---------|\n| `integration-orchestrator.ts` | Event-driven mesh: auto-triggers reindex on import/sync events |\n| `memory-reader.ts` | Read `workflow-graph/memories/` directory recursively (in `src/core/memory/`) |\n| `enriched-context.ts` | Combine Memories + Code Graph + Knowledge into unified context |\n| `mcp-servers-config.ts` | Manage `.mcp.json` server configurations |\n| `mcp-deps-installer.ts` | Auto-install MCP server dependencies |\n| `tool-status.ts` | Track integration availability and health |\n\nSee [Integrations Guide](../reference/INTEGRATIONS-GUIDE.md) for the full integrations documentation.\n\n#### Docs (`core/docs/`)\n\n| Module | Purpose |\n|--------|---------|\n| `stack-detector.ts` | Auto-detect project tech stack from manifest files |\n| `mcp-context7-fetcher.ts` | Fetch docs from Context7 for detected libraries |\n| `docs-cache-store.ts` | SQLite-backed documentation cache |\n| `docs-syncer.ts` | Sync docs for detected libraries + trigger embedding pipeline |\n\n#### Capture (`core/capture/`)\n\n| Module | Purpose |\n|--------|---------|\n| `web-capture.ts` | Playwright-based page capture (HTML, screenshots, a11y tree) |\n| `validate-runner.ts` | Task validation with A/B comparison support |\n| `content-extractor.ts` | Extract clean text from captured HTML |\n\n#### Insights (`core/insights/`)\n\n| Module | Purpose |\n|--------|---------|\n| `bottleneck-detector.ts` | Detect blocked tasks, critical paths, missing AC, oversized tasks |\n| `metrics-calculator.ts` | Sprint velocity, completion rates, burndown |\n| `skill-recommender.ts` | Recommend skills based on task context |\n\n#### Search (`core/search/`)\n\n| Module | Purpose |\n|--------|---------|\n| `fts-search.ts` | FTS5 full-text search with BM25 ranking |\n| `tfidf.ts` | TF-IDF reranking for improved relevance |\n| `tokenizer.ts` | Text tokenization with stopword removal |\n\n#### Events (`core/events/`)\n\n| Module | Purpose |\n|--------|---------|\n| `event-bus.ts` | `GraphEventBus` — typed event emitter for real-time updates |\n| `event-types.ts` | Event type definitions (node:created, knowledge:indexed, etc.) |\n\n#### Store (`core/store/`)\n\n| Module | Purpose |\n|--------|---------|\n| `sqlite-store.ts` | Main data access layer — CRUD, bulk ops, snapshots, FTS5 |\n| `migrations.ts` | Schema migrations (additive, backward-compatible) |\n| `knowledge-store.ts` | CRUD + FTS for knowledge_documents table |\n\n#### Config (`core/config/`)\n\n| Module | Purpose |\n|--------|---------|\n| `config-schema.ts` | Zod schema for project configuration |\n| `config-loader.ts` | Load and validate config from filesystem |\n\n#### Graph (`core/graph/`)\n\n| Module | Purpose |\n|--------|---------|\n| `graph-types.ts` | Core interfaces (GraphNode, GraphEdge, NodeType, NodeStatus) |\n| `graph-indexes.ts` | B-tree and FTS indexes for fast queries |\n| `mermaid-export.ts` | Export graph as Mermaid flowchart/mindmap |\n\n#### Utils (`core/utils/`)\n\n| Module | Purpose |\n|--------|---------|\n| `errors.ts` | Custom typed error classes |\n| `logger.ts` | Structured logger (info, error, debug) |\n| `id.ts` | ID generation (nanoid-based) |\n| `time.ts` | Timestamp utilities |\n| `fs.ts` | Filesystem utilities |\n\n### Layer 5: Storage — SQLite\n\n- **WAL mode** for concurrent reads\n- **FTS5** virtual tables for full-text search (nodes + knowledge)\n- **Indexes** on type, status, parentId, sprint\n- **Snapshots** for graph versioning\n- **Docs cache** table for external documentation\n- **knowledge_documents** table with FTS5 + SHA-256 dedup\n- **embeddings** table for TF-IDF vectors\n\nData stored in `workflow-graph/graph.db` (local, gitignored). Legacy `.mcp-graph/` directories are auto-migrated.\n\n### Layer 6: Web Dashboard — `src/web/dashboard/`\n\n**Stack:** React 19 + TypeScript + Vite + Tailwind CSS + React Flow\n\n| Component | Purpose |\n|-----------|---------|\n| `components/graph/` | Interactive workflow graph (React Flow + Dagre layout) |\n| `components/tabs/graph-tab.tsx` | Graph visualization with filters and detail panel |\n| `components/tabs/code-graph-tab.tsx` | Code dependency graph (D3-based) |\n| `components/tabs/prd-backlog-tab.tsx` | PRD backlog list view |\n| `components/tabs/insights-tab.tsx` | Metrics, bottlenecks, velocity |\n| `components/modals/` | Import and capture modals |\n| `hooks/` | Graph data, SSE, stats hooks |\n\n4 tabs: Graph, Code Graph, PRD Backlog, Insights. Real-time updates via SSE. Dark/light theme.\n\n### Layer 7: Skills & Agents\n\nSkills are local workflow extensions stored in `copilot-ecosystem/`. Each skill is a directory with a `SKILL.md` containing frontmatter and instructions.\n\nKey skills: `/xp-bootstrap`, `/project-scaffold`, `/dev-flow-orchestrator`, `/track-with-mcp-graph`.\n\n### Layer 8: Integrations\n\n| Integration | Purpose | Detection |\n|-------------|---------|-----------|\n| Native Memories | Persistent project knowledge | `workflow-graph/memories/` directory |\n| Code Intelligence | Code graph, dependency analysis | Native via `src/core/code/` |\n| Context7 | Library documentation fetching | MCP server config |\n| Playwright | Browser automation, web capture | `@playwright/test` devDependency |\n\nSee [Integrations Guide](../reference/INTEGRATIONS-GUIDE.md) for detailed documentation.\n\n## Data Flow\n\n### PRD Import Flow\n\n```\nPRD File (.md/.txt/.pdf/.html)\n → readFileContent() # Parser\n → extractEntities() # Parser\n → convertToGraph() # Importer\n → store.bulkInsert() # SQLite\n → eventBus.emit() # Events\n → SSE → Dashboard update # Web\n```\n\n### Knowledge Indexing Flow\n\n```\nSources (Memories, Context7 docs, web captures)\n → Indexer (memory/docs/capture) # RAG\n → chunkText() # RAG\n → knowledgeStore.upsert() # Store\n → ragPipeline.buildIndex() # RAG\n → embeddingStore.persist() # RAG\n```\n\n### Context Assembly Flow\n\n```\nQuery/Task ID\n → Tiered context (graph) # Context\n → BM25 knowledge search # Context\n → Token budget allocation # Context\n → Assembled payload (70-85% reduction)\n```\n\n## Token Efficiency\n\nThe context system achieves 70-85% token reduction through:\n\n1. **Tiered compression** — Summary/standard/deep per node relevance\n2. **BM25 filtering** — Only relevant knowledge chunks included\n3. **Token budgeting** — 60% graph, 30% knowledge, 10% header\n4. **Structural summarization** — Key-value pairs instead of prose\n\n## Design Principles\n\n- **Local-first** — No external services, no Docker, no cloud dependencies\n- **Pure functions** — Core modules are side-effect-free where possible\n- **Typed boundaries** — Zod v4 schemas validate all external input\n- **Strict TypeScript** — No `any`, explicit return types, ESM-only\n- **Thin orchestration** — CLI/MCP/API layers only call core, never contain logic\n- **Backward compatibility** — Schema changes are additive, old data formats supported\n- **Event-driven** — Integration mesh reacts to graph mutations, no polling\n"
1096
+ "content": "# Architecture Guide — mcp-graph\n\n## Overview\n\nmcp-graph is a local-first tool that transforms PRD text files into persistent execution graphs stored in SQLite, with an integrated knowledge store, RAG pipeline, and multi-agent integration mesh. It provides structured, token-efficient context for agentic workflows.\n\n## Layers\n\n### Layer 1: CLI — `src/cli/`\n\n**Framework:** Commander.js v14\n\nThin orchestration layer. Commands call core functions and format output. No business logic.\n\n| Command | File | Description |\n|---------|------|-------------|\n| `init` | `commands/init.ts` | Initialize project + SQLite DB |\n| `import` | `commands/import-cmd.ts` | Import PRD file into graph |\n| `index` | `commands/index-cmd.ts` | Rebuild knowledge indexes and embeddings |\n| `stats` | `commands/stats.ts` | Show graph statistics |\n| `serve` | `commands/serve.ts` | Start HTTP server + MCP + dashboard |\n\n### Layer 2: MCP Server — `src/mcp/`\n\n**Protocol:** Model Context Protocol (Streamable HTTP + Stdio)\n\n<!-- mcp-graph:arch-mcp:start -->\n51 tool registrations (45 active + 6 deprecated shims) via `@modelcontextprotocol/sdk`. Two transport modes:\n\n- **HTTP** (`server.ts`) — Express server with `/mcp` endpoint + REST API + static dashboard\n- **Stdio** (`stdio.ts`) — Standard I/O transport for direct MCP client integration\n\nTool categories:\n- **Core** (30) — analyze, clone_node, context, delete_memory, edge, export, help, import_graph, import_prd, init, journey, list, list_memories, manage_skill, metrics, move_node, next, node, plan_sprint, rag_context, read_memory, reindex_knowledge, search, set_phase, show, snapshot, sync_stack_docs, update_status, validate, write_memory\n- **Translation** (3) — analyze_translation, translate_code, translation_jobs\n- **Code Intelligence** (1) — code_intelligence\n- **Knowledge** (3) — export_knowledge, knowledge_feedback, knowledge_stats\n- **Siebel CRM** (8) — siebel_analyze, siebel_composer, siebel_env, siebel_generate_sif, siebel_import_docs, siebel_import_sif, siebel_search, siebel_validate\n- **Deprecated shims** (6) — add_node, delete_node, list_skills, update_node, validate_ac, validate_task (removed in v7.0)\n<!-- mcp-graph:arch-mcp:end -->\n\n### Layer 3: REST API — `src/api/`\n\n**Framework:** Express v5\n\n<!-- mcp-graph:arch-api:start -->\n26 routers, 135 endpoints. Modular router architecture:\n<!-- mcp-graph:arch-api:end -->\n\n```\nrouter.ts # Main router composition\nroutes/\n project.ts # GET/POST /project\n nodes.ts # GET/POST/PATCH/DELETE /nodes\n edges.ts # GET/POST/DELETE /edges\n stats.ts # GET /stats\n search.ts # GET /search\n graph.ts # GET /graph, /graph/mermaid\n import.ts # POST /import (multipart file upload)\n knowledge.ts # GET/POST/DELETE /knowledge\n rag.ts # POST /rag/query, /rag/reindex, GET /rag/stats\n code-graph.ts # GET /code-graph/* — native code intelligence endpoints\n integrations.ts # GET /integrations/status|memories|enriched-context|knowledge-status\n insights.ts # GET /insights/bottlenecks|recommendations|metrics\n context.ts # GET /context/preview\n capture.ts # POST /capture\n docs-cache.ts # GET/POST /docs\n events.ts # GET /events (SSE stream)\n skills.ts # GET /skills\nmiddleware/\n error-handler.ts # Centralized error handling\n validate.ts # Zod-based request validation\n```\n\nSee [REST API Reference](../reference/REST-API-REFERENCE.md) for full endpoint documentation.\n\n### Layer 4: Core — `src/core/`\n\nPure functions with explicit dependencies. No framework coupling. 16 subdirectories.\n\n#### Parser (`core/parser/`)\n\nPipeline: `readFile → segment → classify → extract`\n\n| Module | Purpose |\n|--------|---------|\n| `file-reader.ts` | Read .md, .txt, .pdf, .html files with format detection |\n| `read-file.ts` | Legacy PRD reader |\n| `read-pdf.ts` | PDF extraction via pdf-parse |\n| `read-html.ts` | HTML to markdown extraction |\n| `segment.ts` | Split text by headings into sections |\n| `classify.ts` | Heuristic block classification (epic, task, requirement, etc.) |\n| `extract.ts` | Extract structured entities from classified blocks |\n| `normalize.ts` | Text normalization (whitespace, encoding) |\n\n#### Importer (`core/importer/`)\n\n| Module | Purpose |\n|--------|---------|\n| `prd-to-graph.ts` | Convert extraction results to graph nodes + edges with dependency inference |\n| `import-prd.ts` | High-level import orchestration |\n\n#### Planner (`core/planner/`)\n\n| Module | Purpose |\n|--------|---------|\n| `next-task.ts` | Suggest next task: filter eligible → resolve dependencies → sort by priority/size/age |\n| `enhanced-next.ts` | Augments next-task with knowledge coverage + velocity context |\n| `decompose.ts` | Detect large tasks, suggest subtask breakdown |\n| `dependency-chain.ts` | Analyze dependency graphs, detect cycles, compute critical paths |\n| `velocity.ts` | Calculate historical sprint velocity and time estimates |\n| `planning-report.ts` | Generate sprint planning reports (capacity, blockers, risk) |\n\n#### Context Builder (`core/context/`)\n\n| Module | Purpose |\n|--------|---------|\n| `compact-context.ts` | Build minimal context for a task (parent, children, deps, blockers, AC) |\n| `rag-context.ts` | Semantic RAG context builder with token budgeting |\n| `tiered-context.ts` | Three-tier compression: summary (~20 tok) / standard (~150 tok) / deep (~500+ tok) |\n| `bm25-compressor.ts` | BM25 ranking to filter knowledge chunks by relevance |\n| `context-assembler.ts` | Combines graph (60%) + knowledge (30%) + header (10%) with token accounting |\n| `token-estimator.ts` | Estimate token count for context payloads |\n\n#### RAG (`core/rag/`)\n\n| Module | Purpose |\n|--------|---------|\n| `embedding-store.ts` | Persist TF-IDF vectors in SQLite, cosine similarity search |\n| `rag-pipeline.ts` | TF-IDF vectorizer: index nodes + knowledge as embeddings |\n| `memory-indexer.ts` | Index memory documents into embeddings |\n| `docs-indexer.ts` | Index fetched documentation into embeddings |\n| `capture-indexer.ts` | Index web-captured content into embeddings |\n| `memory-rag-query.ts` | Query memories via FTS / semantic / hybrid modes |\n| `chunk-text.ts` | Split text into ~500 token chunks with overlap |\n\nSee [Knowledge Pipeline](./KNOWLEDGE-PIPELINE.md) for the full RAG documentation.\n\n#### Integrations (`core/integrations/`)\n\n| Module | Purpose |\n|--------|---------|\n| `integration-orchestrator.ts` | Event-driven mesh: auto-triggers reindex on import/sync events |\n| `memory-reader.ts` | Read `workflow-graph/memories/` directory recursively (in `src/core/memory/`) |\n| `enriched-context.ts` | Combine Memories + Code Graph + Knowledge into unified context |\n| `mcp-servers-config.ts` | Manage `.mcp.json` server configurations |\n| `mcp-deps-installer.ts` | Auto-install MCP server dependencies |\n| `tool-status.ts` | Track integration availability and health |\n\nSee [Integrations Guide](../reference/INTEGRATIONS-GUIDE.md) for the full integrations documentation.\n\n#### Docs (`core/docs/`)\n\n| Module | Purpose |\n|--------|---------|\n| `stack-detector.ts` | Auto-detect project tech stack from manifest files |\n| `mcp-context7-fetcher.ts` | Fetch docs from Context7 for detected libraries |\n| `docs-cache-store.ts` | SQLite-backed documentation cache |\n| `docs-syncer.ts` | Sync docs for detected libraries + trigger embedding pipeline |\n\n#### Capture (`core/capture/`)\n\n| Module | Purpose |\n|--------|---------|\n| `web-capture.ts` | Playwright-based page capture (HTML, screenshots, a11y tree) |\n| `validate-runner.ts` | Task validation with A/B comparison support |\n| `content-extractor.ts` | Extract clean text from captured HTML |\n\n#### Insights (`core/insights/`)\n\n| Module | Purpose |\n|--------|---------|\n| `bottleneck-detector.ts` | Detect blocked tasks, critical paths, missing AC, oversized tasks |\n| `metrics-calculator.ts` | Sprint velocity, completion rates, burndown |\n| `skill-recommender.ts` | Recommend skills based on task context |\n\n#### Search (`core/search/`)\n\n| Module | Purpose |\n|--------|---------|\n| `fts-search.ts` | FTS5 full-text search with BM25 ranking |\n| `tfidf.ts` | TF-IDF reranking for improved relevance |\n| `tokenizer.ts` | Text tokenization with stopword removal |\n\n#### Events (`core/events/`)\n\n| Module | Purpose |\n|--------|---------|\n| `event-bus.ts` | `GraphEventBus` — typed event emitter for real-time updates |\n| `event-types.ts` | Event type definitions (node:created, knowledge:indexed, etc.) |\n\n#### Store (`core/store/`)\n\n| Module | Purpose |\n|--------|---------|\n| `sqlite-store.ts` | Main data access layer — CRUD, bulk ops, snapshots, FTS5 |\n| `migrations.ts` | Schema migrations (additive, backward-compatible) |\n| `knowledge-store.ts` | CRUD + FTS for knowledge_documents table |\n\n#### Config (`core/config/`)\n\n| Module | Purpose |\n|--------|---------|\n| `config-schema.ts` | Zod schema for project configuration |\n| `config-loader.ts` | Load and validate config from filesystem |\n\n#### Graph (`core/graph/`)\n\n| Module | Purpose |\n|--------|---------|\n| `graph-types.ts` | Core interfaces (GraphNode, GraphEdge, NodeType, NodeStatus) |\n| `graph-indexes.ts` | B-tree and FTS indexes for fast queries |\n| `mermaid-export.ts` | Export graph as Mermaid flowchart/mindmap |\n\n#### Utils (`core/utils/`)\n\n| Module | Purpose |\n|--------|---------|\n| `errors.ts` | Custom typed error classes |\n| `logger.ts` | Structured logger (info, error, debug) |\n| `id.ts` | ID generation (nanoid-based) |\n| `time.ts` | Timestamp utilities |\n| `fs.ts` | Filesystem utilities |\n\n### Layer 5: Storage — SQLite\n\n- **WAL mode** for concurrent reads\n- **FTS5** virtual tables for full-text search (nodes + knowledge)\n- **Indexes** on type, status, parentId, sprint\n- **Snapshots** for graph versioning\n- **Docs cache** table for external documentation\n- **knowledge_documents** table with FTS5 + SHA-256 dedup\n- **embeddings** table for TF-IDF vectors\n\nData stored in `workflow-graph/graph.db` (local, gitignored). Legacy `.mcp-graph/` directories are auto-migrated.\n\n### Layer 6: Web Dashboard — `src/web/dashboard/`\n\n**Stack:** React 19 + TypeScript + Vite + Tailwind CSS + React Flow\n\n| Component | Purpose |\n|-----------|---------|\n| `components/graph/` | Interactive workflow graph (React Flow + Dagre layout) |\n| `components/tabs/graph-tab.tsx` | Graph visualization with filters and detail panel |\n| `components/tabs/code-graph-tab.tsx` | Code dependency graph (D3-based) |\n| `components/tabs/prd-backlog-tab.tsx` | PRD backlog list view |\n| `components/tabs/insights-tab.tsx` | Metrics, bottlenecks, velocity |\n| `components/modals/` | Import and capture modals |\n| `hooks/` | Graph data, SSE, stats hooks |\n\n4 tabs: Graph, Code Graph, PRD Backlog, Insights. Real-time updates via SSE. Dark/light theme.\n\n### Layer 7: Skills & Agents\n\nSkills are local workflow extensions stored in `copilot-ecosystem/`. Each skill is a directory with a `SKILL.md` containing frontmatter and instructions.\n\nKey skills: `/xp-bootstrap`, `/project-scaffold`, `/dev-flow-orchestrator`, `/track-with-mcp-graph`.\n\n### Layer 8: Integrations\n\n| Integration | Purpose | Detection |\n|-------------|---------|-----------|\n| Native Memories | Persistent project knowledge | `workflow-graph/memories/` directory |\n| Code Intelligence | Code graph, dependency analysis | Native via `src/core/code/` |\n| Context7 | Library documentation fetching | MCP server config |\n| Playwright | Browser automation, web capture | `@playwright/test` devDependency |\n\nSee [Integrations Guide](../reference/INTEGRATIONS-GUIDE.md) for detailed documentation.\n\n## Data Flow\n\n### PRD Import Flow\n\n```\nPRD File (.md/.txt/.pdf/.html)\n → readFileContent() # Parser\n → extractEntities() # Parser\n → convertToGraph() # Importer\n → store.bulkInsert() # SQLite\n → eventBus.emit() # Events\n → SSE → Dashboard update # Web\n```\n\n### Knowledge Indexing Flow\n\n```\nSources (Memories, Context7 docs, web captures)\n → Indexer (memory/docs/capture) # RAG\n → chunkText() # RAG\n → knowledgeStore.upsert() # Store\n → ragPipeline.buildIndex() # RAG\n → embeddingStore.persist() # RAG\n```\n\n### Context Assembly Flow\n\n```\nQuery/Task ID\n → Tiered context (graph) # Context\n → BM25 knowledge search # Context\n → Token budget allocation # Context\n → Assembled payload (70-85% reduction)\n```\n\n## Token Efficiency\n\nThe context system achieves 70-85% token reduction through:\n\n1. **Tiered compression** — Summary/standard/deep per node relevance\n2. **BM25 filtering** — Only relevant knowledge chunks included\n3. **Token budgeting** — 60% graph, 30% knowledge, 10% header\n4. **Structural summarization** — Key-value pairs instead of prose\n\n## Design Principles\n\n- **Local-first** — No external services, no Docker, no cloud dependencies\n- **Pure functions** — Core modules are side-effect-free where possible\n- **Typed boundaries** — Zod v4 schemas validate all external input\n- **Strict TypeScript** — No `any`, explicit return types, ESM-only\n- **Thin orchestration** — CLI/MCP/API layers only call core, never contain logic\n- **Backward compatibility** — Schema changes are additive, old data formats supported\n- **Event-driven** — Integration mesh reacts to graph mutations, no polling\n"
1097
1097
  },
1098
1098
  {
1099
1099
  "slug": "architecture/ARCHITECTURE-MERMAID",
@@ -1209,6 +1209,12 @@
1209
1209
  "category": "prd",
1210
1210
  "content": "# PRD: Code Graph Multi-Language — Indexação Universal\n\n> **Versão:** 1.0\n> **Data:** 2026-03-29\n> **Autor:** Diego Nogueira\n> **Status:** Draft\n> **Prioridade:** P1\n\n---\n\n## 1. Problema\n\nO mcp-graph hoje indexa **apenas TypeScript/JavaScript** no Code Graph. Quando instalado em projetos de outras linguagens (Java, Go, Rust, Python, C/C++, Ruby, PHP, Kotlin, Swift, C#, Lua), o Code Intelligence fica vazio — sem symbols, sem impact analysis, sem RAG de código, sem visualização no dashboard.\n\nIsso limita a proposta de valor do mcp-graph como ferramenta universal de gestão de execução com code intelligence integrado.\n\n## 2. Objetivo\n\nTornar o mcp-graph capaz de **indexar automaticamente qualquer projeto em qualquer linguagem**, extraindo symbols, relações, docstrings e visibilidade de forma **determinística** (AST-based), com IA como fallback apenas para cenários ambíguos.\n\n## 3. Público-alvo\n\n- Desenvolvedores que usam mcp-graph em projetos não-TypeScript\n- Equipes com projetos multi-linguagem (ex: backend Go + frontend React)\n- Projetos legados em Java, C/C++, Ruby, PHP que precisam de code intelligence\n\n## 4. Princípio Arquitetural\n\n**Determinismo primeiro, IA como fallback.**\n\n```\n1. DETERMINÍSTICO — Tree-sitter AST + S-expression queries\n2. RULE-BASED — Regras documentadas por linguagem (visibility, docstrings, test patterns)\n3. LSP-ENRICHED — Language Server Protocol (opcional, se disponível)\n4. AI FALLBACK — LLM como último recurso (syntax errors graves, linguagens sem grammar)\n```\n\n## 5. Linguagens Suportadas\n\n| Tier | Linguagens | Prioridade |\n|------|-----------|------------|\n| Tier 1 (core) | Python, Go, Rust | Alta — grammars mais maduros |\n| Tier 2 (enterprise) | Java, C/C++, C# | Alta — projetos enterprise |\n| Tier 3 (complementar) | Ruby, PHP, Kotlin, Swift, Lua | Média |\n| Existente | TypeScript, JavaScript | Mantido (TsAnalyzer nativo) |\n\n## 6. User Stories\n\n### US-01: Indexação automática de projeto Python\n**Como** desenvolvedor Python,\n**Quero** instalar o mcp-graph no meu projeto e ter todas as funções, classes e imports indexados automaticamente,\n**Para que** o Code Intelligence funcione com impact analysis, RAG e visualização no dashboard.\n\n**Acceptance Criteria:**\n- AC-01.1: `npm install mcp-graph` em projeto com `pyproject.toml` → auto-detecta Python\n- AC-01.2: `reindex` extrai functions, classes, methods, decorators com nomes e linhas corretos\n- AC-01.3: Docstrings (PEP 257) extraídas e armazenadas no campo `docstring`\n- AC-01.4: Visibility detectada: `_private`, `__mangled`, public (sem prefixo)\n- AC-01.5: Imports (`import`, `from x import y`) geram relações `imports` no grafo\n- AC-01.6: Chamadas de função geram relações `calls`\n- AC-01.7: Herança (`class Foo(Bar)`) gera relações `extends`\n- AC-01.8: Symbols aparecem no dashboard Code Graph tab com filtro \"Python\"\n- AC-01.9: `rag_context` retorna symbols Python com docstrings\n\n### US-02: Indexação automática de projeto Go\n**Como** desenvolvedor Go,\n**Quero** que funções, structs, interfaces e methods do meu projeto sejam indexados,\n**Para que** impact analysis funcione corretamente com as convenções Go.\n\n**Acceptance Criteria:**\n- AC-02.1: Projeto com `go.mod` → auto-detecta Go\n- AC-02.2: Functions, methods (com receiver), structs, interfaces extraídos\n- AC-02.3: Export detection por uppercase: `HandleRequest` = exported, `handleRequest` = unexported\n- AC-02.4: GoDoc (comentário `//` antes da declaração) extraído como docstring\n- AC-02.5: `*_test.go` excluídos da indexação (test pattern)\n- AC-02.6: Package declarations detectadas como `package` symbol kind\n- AC-02.7: `vendor/` ignorado na varredura de diretórios\n\n### US-03: Indexação automática de projeto Rust\n**Como** desenvolvedor Rust,\n**Quero** que functions, structs, traits, impls e modules sejam indexados,\n**Para que** blast radius analysis funcione com o sistema de ownership do Rust.\n\n**Acceptance Criteria:**\n- AC-03.1: Projeto com `Cargo.toml` → auto-detecta Rust\n- AC-03.2: Functions, structs, enums, traits, impl blocks, modules extraídos\n- AC-03.3: Visibility: `pub`, `pub(crate)`, `pub(super)`, private (default) detectados\n- AC-03.4: Rustdoc (`///`, `//!`) extraídos como docstring\n- AC-03.5: `use` declarations geram relações `imports`\n- AC-03.6: Macro definitions detectadas como `macro` symbol kind\n- AC-03.7: `target/` ignorado\n\n### US-04: Indexação automática de projeto Java\n**Como** desenvolvedor Java,\n**Quero** que classes, interfaces, methods, annotations e packages sejam indexados,\n**Para que** o grafo represente a hierarquia do projeto fielmente.\n\n**Acceptance Criteria:**\n- AC-04.1: Projeto com `pom.xml` ou `build.gradle` → auto-detecta Java\n- AC-04.2: Classes, interfaces, enums, records, methods, constructors, fields extraídos\n- AC-04.3: Visibility: `public`, `protected`, `private`, package-private detectados\n- AC-04.4: Javadoc (`/** */`) extraído como docstring\n- AC-04.5: Annotations detectadas como `annotation` symbol kind\n- AC-04.6: `import` declarations geram relações `imports`\n- AC-04.7: `method_invocation` gera relações `calls`\n- AC-04.8: `extends`/`implements` geram relações correspondentes\n- AC-04.9: `src/test/` e `*Test.java` excluídos da indexação\n\n### US-05: Indexação de projeto C/C++\n**Como** desenvolvedor C/C++,\n**Quero** que functions, structs, classes, namespaces e includes sejam indexados,\n**Para que** impact analysis funcione em codebases C/C++ grandes.\n\n**Acceptance Criteria:**\n- AC-05.1: Projeto com `CMakeLists.txt` ou `compile_commands.json` → auto-detecta C/C++\n- AC-05.2: Functions, structs, unions, enums (C), classes, namespaces, templates (C++) extraídos\n- AC-05.3: `#include` gera relações `imports`\n- AC-05.4: `static` = internal linkage detectado como visibility `private`\n- AC-05.5: Doxygen (`/** */`, `///`) extraído como docstring\n- AC-05.6: `build/`, `cmake-build-*/` ignorados\n\n### US-06: Indexação de projeto C#\n**Como** desenvolvedor .NET,\n**Quero** que classes, structs, interfaces, methods, properties e namespaces sejam indexados.\n\n**Acceptance Criteria:**\n- AC-06.1: Projeto com `.csproj` → auto-detecta C#\n- AC-06.2: Classes, structs, interfaces, records, enums, methods, properties, fields extraídos\n- AC-06.3: Visibility: `public`, `internal`, `protected`, `private`, `protected internal` detectados\n- AC-06.4: XML doc comments (`/// <summary>`) extraídos como docstring\n- AC-06.5: `using` directives geram relações `imports`\n- AC-06.6: `bin/`, `obj/` ignorados\n\n### US-07: Syntax Enrichment no banco de dados\n**Como** o sistema RAG,\n**Quero** que cada symbol tenha `docstring`, `source_snippet`, `visibility` e `language` armazenados,\n**Para que** queries retornem contexto semântico real (não apenas nomes de funções).\n\n**Acceptance Criteria:**\n- AC-07.1: Coluna `language TEXT` no `code_symbols` com default 'typescript'\n- AC-07.2: Coluna `docstring TEXT` armazenando documentação extraída do código\n- AC-07.3: Coluna `source_snippet TEXT` com primeiras ~20 linhas do corpo do symbol\n- AC-07.4: Coluna `visibility TEXT` com public/private/protected/internal/package\n- AC-07.5: FTS5 index recriado incluindo `docstring` para busca por descrição\n- AC-07.6: Migration backward-compatible (ALTERs com defaults)\n- AC-07.7: TsAnalyzer existente populando os novos campos para TS/JS\n\n### US-08: Referência determinística por linguagem\n**Como** o sistema de indexação,\n**Quero** ter regras determinísticas documentadas para cada linguagem (visibility, docstrings, test patterns, imports, ignored dirs),\n**Para que** a extração seja previsível e não dependa de heurísticas de IA.\n\n**Acceptance Criteria:**\n- AC-08.1: Arquivo `reference-content.ts` com `LANGUAGE_REFERENCES` tipado\n- AC-08.2: Cada linguagem tem: nodeTypes, visibilityRules, docstringPattern, testPatterns, importPatterns, ignoredDirs\n- AC-08.3: Regras baseadas em documentação oficial (PEP 257, GoDoc, Rustdoc, Javadoc, etc.)\n- AC-08.4: Testes validam que cada referência cobre os cenários da linguagem\n\n### US-09: RAG integration multi-language\n**Como** agente usando `rag_context`,\n**Quero** que o contexto retornado inclua symbols de todas as linguagens do projeto com docstrings reais,\n**Para que** eu tenha entendimento semântico do codebase completo.\n\n**Acceptance Criteria:**\n- AC-09.1: `code-context-indexer` cria knowledge docs agrupados por linguagem\n- AC-09.2: Docstrings reais incluídas nos docs (não apenas nomes)\n- AC-09.3: `code-search` aceita filtro `language` opcional\n- AC-09.4: Code Intelligence wrapper inclui language stats no `_code_intelligence` block\n- AC-09.5: `rag_context` com query \"Python functions\" retorna symbols Python\n\n### US-10: Dashboard multi-language\n**Como** usuário do dashboard,\n**Quero** ver symbols de todas as linguagens no Code Graph tab com filtros e cores por linguagem,\n**Para que** eu visualize a estrutura do projeto multi-linguagem.\n\n**Acceptance Criteria:**\n- AC-10.1: Cores diferentes por linguagem (Python=#3776ab, Go=#00add8, Rust=#dea584, etc.)\n- AC-10.2: Filtro por linguagem no painel de filtros\n- AC-10.3: Badge de linguagem nos nodes do grafo\n- AC-10.4: Hover em node mostra docstring preview\n- AC-10.5: Status endpoint retorna stats por linguagem (`/code-graph/status`)\n\n### US-11: AI Fallback para cenários ambíguos\n**Como** o sistema de indexação,\n**Quero** ter um fallback baseado em LLM para quando o parser determinístico falha,\n**Para que** o sistema nunca retorne vazio mesmo em código quebrado ou linguagens não suportadas.\n\n**Acceptance Criteria:**\n- AC-11.1: Linguagem sem grammar tree-sitter → LLM extrai symbols via prompt structured\n- AC-11.2: Arquivos com ERROR nodes graves → symbols parciais do tree-sitter + gaps do LLM\n- AC-11.3: Resultado do fallback marcado com `metadata.aiGenerated: true`\n- AC-11.4: Fallback nunca executado quando parser determinístico funciona\n\n### US-12: Projeto multi-linguagem (mixed)\n**Como** desenvolvedor com projeto TS + Python + Go,\n**Quero** que todas as linguagens sejam indexadas simultaneamente,\n**Para que** o grafo represente o projeto completo.\n\n**Acceptance Criteria:**\n- AC-12.1: TsAnalyzer indexa `.ts/.js`, TreeSitterAnalyzer indexa `.py/.go`\n- AC-12.2: Sem conflito de extensões (TsAnalyzer tem prioridade para TS/JS)\n- AC-12.3: Stats por linguagem corretas no `/code-graph/status`\n- AC-12.4: Filtro por linguagem funciona no dashboard\n- AC-12.5: Impact analysis funciona cross-language (se symbols compartilham nomes)\n\n### US-13: Tradutor com contexto de referência\n**Como** o `translate_code` tool,\n**Quero** usar as regras de referência por linguagem para mapear construtos entre source e target,\n**Para que** a tradução preserve visibility, naming conventions e padrões idiomáticos.\n\n**Acceptance Criteria:**\n- AC-13.1: Tradutor consulta `LANGUAGE_REFERENCES` para source e target language\n- AC-13.2: Visibility mapeada: `pub` (Rust) → `public` (Java), Uppercase (Go) → `pub` (Rust)\n- AC-13.3: Docstring format convertido: `///` (Rust) → `/** */` (Java) → `\"\"\"` (Python)\n\n## 7. Requisitos Não-Funcionais\n\n| Requisito | Meta |\n|-----------|------|\n| Performance | Indexar 1000+ arquivos multi-lang em < 30s |\n| Memory | Grammars WASM carregados lazy (apenas linguagens detectadas) |\n| Backward compat | Projetos TS/JS existentes não afetados |\n| Graceful degradation | Grammar não instalado → linguagem ignorada (sem crash) |\n| Disk footprint | `optionalDependencies` para grammars (~2-5MB cada) |\n\n## 8. Fora de Escopo (v1)\n\n- Mixed-language files (PHP dentro de HTML, JSX com CSS) — skip embedded languages\n- Incremental parsing com `tree.edit()` — full reparse por enquanto\n- Custom grammars definidos pelo usuário\n- Cross-file type resolution (requer type checker, não apenas parser)\n\n## 9. Dependências\n\n| Dependência | Tipo | Versão |\n|------------|------|--------|\n| `web-tree-sitter` | npm dependency | ^0.24.0 |\n| `tree-sitter-python` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-go` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-rust` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-java` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-c` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-cpp` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-ruby` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-php` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-kotlin` | npm optionalDep | ^0.3.0 |\n| `tree-sitter-swift` | npm optionalDep | ^0.5.0 |\n| `tree-sitter-c-sharp` | npm optionalDep | ^0.23.0 |\n| `tree-sitter-lua` | npm optionalDep | ^0.2.0 |\n\n## 10. Métricas de Sucesso\n\n- 11 linguagens indexando corretamente em projetos reais\n- Docstrings extraídas em > 90% dos symbols documentados\n- RAG retornando contexto multi-language com docstrings\n- Dashboard visualizando grafo multi-language com filtros\n- Zero regressão em projetos TS/JS existentes\n- Performance < 30s para 1000 arquivos\n"
1211
1211
  },
1212
+ {
1213
+ "slug": "prd/universal-deterministic-translation",
1214
+ "title": "Universal Deterministic Translation",
1215
+ "category": "prd",
1216
+ "content": "# PRD: Universal Deterministic Code Translation\n\n## Problem Statement\n\nWhen the Languages tab analysis shows \"100% Deterministic Translation / No AI Required\", there is no way to download the converted code. The user must still go through the AI prompt → paste → finalize flow, which makes no sense when AI isn't needed.\n\nRoot cause: the system can detect determinism (via UCR construct analysis) but cannot execute the translation. Rule templates have {{placeholders}} that are never filled with actual source values. Generators exist only for TS/Python and produce skeleton code with TODOs — not real code.\n\n## Goals\n\n1. **100% deterministic** → engine converts automatically → download direto (zero AI)\n2. **< 100% deterministic** → show % → generate prompt ONLY for ambiguous constructs → user uses AI just for that part → paste and validate\n3. **Remove scope selector** (snippet/function/module) — auto-detect; simplify UX\n4. **Universal** — any of the 12 supported languages as source/target\n\n## Epic: SourceTextExtractor\n\n### Task: Add sourceText field to ParsedConstruct\n- Add optional `sourceText?: string` field to ParsedConstruct interface\n- Backward-compatible — existing parsers unchanged\n- AC: field added, all existing tests pass\n\n### Task: Implement extractSourceText for brace languages\n- Extract source text for constructs in brace-delimited languages (TS, Java, Go, Rust, C#, C++, PHP, Swift, Kotlin, Scala, Dart)\n- Smart block detection: scan forward counting {/} for block constructs\n- Handle string/comment escaping in brace counter\n- AC: correctly extracts function bodies, class bodies, if/else blocks, loops in TS/Java/Go\n\n### Task: Implement extractSourceText for indent languages\n- Extract source text for constructs in indent-delimited languages (Python, Haskell)\n- Scan until indentation drops below construct level\n- AC: correctly extracts function bodies, class bodies, if/else blocks in Python\n\n### Task: Implement extractSourceText for keyword-end languages\n- Extract source text for constructs in keyword-end languages (Ruby, Lua, Elixir)\n- Scan until `end` keyword at matching indent level\n- AC: correctly extracts def/class/if blocks in Ruby/Lua/Elixir\n\n### Task: Implement extractSourceText for single-line constructs\n- Extract source text for single-line constructs (return, break, continue, import, throw, variable declarations)\n- Just the line or until semicolon\n- AC: correctly extracts return statements, imports, variable declarations\n\n## Epic: PlaceholderResolver\n\n### Task: Implement function construct extractors\n- Extract name, params, body, returnType from function source text (uc_fn_def, uc_method_def, uc_arrow_fn, uc_async_fn)\n- Support brace family and indent family extraction patterns\n- AC: extracts all parts from TS functions, Python defs, Java methods\n\n### Task: Implement class construct extractors\n- Extract name, parent, members/body from class source text (uc_class_def, uc_interface, uc_abstract_class)\n- Support extends/implements detection\n- AC: extracts class parts from TS, Python, Java classes\n\n### Task: Implement control flow extractors\n- Extract condition, body, elseBody from if/else (uc_if_else)\n- Extract variable, iterable, body from loops (uc_for_loop, uc_for_each, uc_while)\n- Extract expression from switch/case (uc_switch)\n- AC: extracts parts from TS/Python/Java control flow\n\n### Task: Implement remaining construct extractors\n- Extract body, error, catchBody from try/catch (uc_try_catch)\n- Extract module, names from imports (uc_import_named, uc_import_default)\n- Extract expression from return/throw (uc_return, uc_throw)\n- Extract name, value from variable declarations (uc_const_decl, uc_let_decl, uc_var_decl)\n- AC: extracts parts for all remaining construct types\n\n### Task: Implement type mapper and param transformer\n- Type mapper: cross-language type conversion (number→int, string→str, boolean→bool, void→None, etc.)\n- Param transformer: strip type annotations for dynamic targets (TS→Python), keep/add for static targets\n- Body normalizer: strip surrounding braces, normalize indentation to zero-indent\n- AC: type mapping works for all 12 languages, param stripping works TS→Python/Ruby/PHP\n\n## Epic: UniversalGenerator\n\n### Task: Create UniversalGenerator class\n- Implements GeneratorAdapter interface\n- Constructor takes ConstructRegistry, targetLanguageId, sourceCode, sourceLanguageId\n- generate() method: extractSourceText → resolvePlaceholders → UCR getPrimaryMapping → substitute\n- Handles remaining unresolved {{...}} with language-appropriate defaults\n- AC: generates real Python from TS, real Go from Java, tracks mapped/unmapped\n\n### Task: Wire UniversalGenerator into TranslationOrchestrator\n- Replace convertToIR + RuleEngine + getDeterministicRuleSet path in prepareTranslation\n- Generate deterministicCode for ALL cases (100% and partial)\n- Remove old rule-engine imports and getDeterministicRuleSet method\n- AC: prepareTranslation returns real code in deterministicCode, not templates\n\n### Task: Add partial prompt for ambiguous constructs only\n- Add option to buildTranslationPrompt for ambiguous-only mode\n- When < 100%: prompt includes only needsAiAssist constructs\n- Include already-translated deterministic code as context in prompt\n- AC: prompt is smaller, focused on ambiguous constructs only\n\n## Epic: Frontend UX\n\n### Task: Remove scope selector from translation form\n- Remove SCOPES array and toggle buttons from translation-form.tsx\n- Remove scope/setScope props and state\n- Hardcode scope as \"module\" internally\n- AC: scope selector gone, form simpler, all builds pass\n\n### Task: Fix download file extension\n- Accept targetLanguage prop in AnalysisResults\n- Use LANG_EXT map for correct extension (.py, .go, .java, .rs, etc.)\n- Pass targetLanguage from languages-tab.tsx\n- AC: download produces translated.py, translated.go, etc.\n\n### Task: Wire project-mode auto-translation for deterministic files\n- In generateDownloadZip(), auto-translate deterministic files using UniversalGenerator\n- No more .prompt.md sidecars for deterministic files\n- AC: project zip contains real translated code for deterministic files\n"
1217
+ },
1212
1218
  {
1213
1219
  "slug": "reference/INTEGRATIONS-GUIDE",
1214
1220
  "title": "INTEGRATIONS GUIDE",
@@ -96,7 +96,7 @@ export function registerTranslateCode(server, store) {
96
96
  if (!projectId) {
97
97
  return mcpError("No active project. Use init or activate a project first.");
98
98
  }
99
- const prepareResult = orchestrator.prepareTranslation({
99
+ const prepareResult = await orchestrator.prepareTranslation({
100
100
  projectId,
101
101
  sourceCode: resolvedCode,
102
102
  sourceLanguage: resolvedSourceLanguage,
@@ -1 +1 @@
1
- {"version":3,"file":"translate-code.js","sourceRoot":"","sources":["../../../src/mcp/tools/translate-code.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAG7B,OAAO,EAAE,gBAAgB,EAAE,MAAM,6CAA6C,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,oDAAoD,CAAC;AAC7F,OAAO,EAAE,iBAAiB,EAAE,MAAM,kDAAkD,CAAC;AACrF,OAAO,EAAE,mBAAmB,EAAE,MAAM,8CAA8C,CAAC;AACnF,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAE3D,MAAM,qBAAqB,GAA2B;IACpD,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,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H;aAChI,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAC5D,CAAC;IACH,CAAC,CACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1 @@
1
+ import{r as h,a as p,j as e}from"./index-C3Kad9YO.js";function j(){const[r,n]=h.useState(null),[i,m]=h.useState(!0),[u,a]=h.useState(null);return h.useEffect(()=>{async function s(){try{const c=await p.request("/benchmark");n(c)}catch(c){a(c instanceof Error?c.message:"Failed to load benchmark data")}finally{m(!1)}}s()},[]),{data:r,loading:i,error:u}}function f(){const{data:r,loading:n,error:i}=j(),[m,u]=h.useState(!1);if(n)return e.jsxs("div",{className:"p-6 max-w-5xl mx-auto space-y-6",children:[e.jsx("div",{className:"h-5 w-40 rounded bg-surface animate-pulse"}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Array.from({length:3}).map((o,t)=>e.jsx("div",{className:"h-20 rounded-xl border border-edge bg-surface-alt animate-pulse"},t))}),e.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((o,t)=>e.jsx("div",{className:"h-6 rounded bg-surface animate-pulse",style:{width:`${60+Math.random()*30}%`}},t))})]});if(i)return e.jsx("div",{className:"flex flex-col items-center justify-center h-full gap-4",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Failed to load benchmark"}),e.jsx("p",{className:"text-xs text-muted mt-1",children:i})]})});if(!r)return e.jsx("div",{});const{tokenEconomy:a,layeredCompression:s,dependencyIntelligence:c,toolTokenUsage:d}=r,g=(s==null?void 0:s.avgTotalRealSavingsPercent)??a.avgCompressionPercent;return e.jsxs("div",{className:"p-6 max-w-5xl mx-auto space-y-6 overflow-y-auto h-full",children:[e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Token Savings"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"p-4 rounded-xl border border-edge shadow-sm bg-surface-alt text-center","data-testid":"metric-card",children:[e.jsxs("div",{className:"text-3xl font-bold text-accent",children:[g,"%"]}),e.jsx("div",{className:"text-[10px] text-muted uppercase mt-1",children:"compression rate"})]}),e.jsx(l,{value:a.totalTokensSaved.toLocaleString(),label:`tokens saved (${a.sampleSize} tasks)`}),e.jsx(l,{value:a.avgTokensSavedPerTask.toLocaleString(),label:"avg saved / task"})]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Cost Impact"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[e.jsx(v,{label:"Opus",before:a.costSavings.opusCostPerTaskUncompressed,after:a.costSavings.opusCostPerTask,totalSaved:a.costSavings.opusTotalSaved}),e.jsx(v,{label:"Sonnet",before:a.costSavings.sonnetCostPerTaskUncompressed,after:a.costSavings.sonnetCostPerTask,totalSaved:a.costSavings.sonnetTotalSaved})]})]}),a.perTaskMetrics.length>0&&e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Compression per Task"}),e.jsx("div",{className:"space-y-1.5","data-testid":"compression-bars",children:a.perTaskMetrics.slice(0,15).map(o=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-32 truncate",title:o.title,children:o.title}),e.jsx("div",{className:"flex-1 h-3 bg-surface-elevated rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-accent",style:{width:`${Math.min(o.compressionPercent,100)}%`}})}),e.jsxs("span",{className:"text-muted w-28 text-right",children:[o.compressionPercent,"% (",o.estimatedTokens.toLocaleString()," tok)"]})]},o.id))})]}),s&&s.avgLayer1SavingsPercent!=null&&e.jsxs("section",{children:[e.jsxs("button",{type:"button",className:"text-sm font-semibold mb-3 flex items-center gap-1 hover:text-accent transition-colors",onClick:()=>u(!m),children:[e.jsx("span",{className:"text-xs",children:m?"▼":"▶"}),"How compression works"]}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-5 gap-3 mb-2",children:[e.jsx(l,{value:`${s.avgLayer1SavingsPercent}%`,label:"Field cleanup"}),e.jsx(l,{value:`${s.avgLayer2SavingsPercent}%`,label:"Desc summary"}),e.jsx(l,{value:`${s.avgLayer3SavingsPercent}%`,label:"Default omit"}),e.jsx(l,{value:`${s.avgLayer4SavingsPercent}%`,label:"Key shorten"}),e.jsx(l,{value:`${s.avgTotalRealSavingsPercent}%`,label:"Total saved"})]}),(()=>{const o=Math.max(s.avgNaiveNeighborhoodTokens,1),t=[{label:"Original context",tokens:s.avgNaiveNeighborhoodTokens,color:"#ef4444"},{label:"Field cleanup",tokens:s.avgCompactContextTokens,color:"#f97316"},{label:"Desc summary",tokens:s.avgNeighborTruncatedTokens,color:"#eab308"},{label:"Default omit",tokens:s.avgDefaultOmittedTokens,color:"#22c55e"},{label:"Key shorten",tokens:s.avgShortKeysTokens,color:"#3b82f6"},{label:"Minimal context",tokens:s.avgSummaryTierTokens,color:"#8b5cf6"}];return e.jsx("div",{className:"space-y-1.5","data-testid":"waterfall-bars",children:t.map(x=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-32 truncate",title:x.label,children:x.label}),e.jsx("div",{className:"flex-1 h-3 bg-surface-elevated rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.min(x.tokens/o*100,100)}%`,backgroundColor:x.color}})}),e.jsxs("span",{className:"text-muted w-20 text-right",children:[x.tokens.toLocaleString()," tok"]})]},x.label))})})()]})]}),d&&d.totalCalls>0&&e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Token Usage per Tool"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsx(l,{value:d.totalCalls.toLocaleString(),label:"Total calls"}),e.jsx(l,{value:d.totalInputTokens.toLocaleString(),label:"Input tokens"}),e.jsx(l,{value:d.totalOutputTokens.toLocaleString(),label:"Output tokens"})]}),d.perTool.length>0&&(()=>{const o=Math.max(...d.perTool.map(t=>t.totalTokens),1);return e.jsx("div",{className:"space-y-1.5","data-testid":"tool-token-bars",children:d.perTool.slice(0,15).map(t=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-32 truncate font-mono",title:t.toolName,children:t.toolName}),e.jsx("div",{className:"flex-1 h-3 bg-surface-elevated rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-accent",style:{width:`${Math.min(t.totalTokens/o*100,100)}%`}})}),e.jsxs("span",{className:"text-muted w-32 text-right",children:[t.callCount," calls, ",t.totalTokens.toLocaleString()," tok"]})]},t.toolName))})})()]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Graph Integrity"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(l,{value:c.inferredDeps,label:"Auto-inferred deps"}),e.jsx(l,{value:`${c.blockedTasks}/${a.totalNodes}`,label:"Blocked tasks"}),e.jsx(l,{value:c.cycles,label:"Cycles detected"})]})]})]})}function l({value:r,label:n}){return e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center","data-testid":"metric-card",children:[e.jsx("div",{className:"text-xl font-bold",children:r}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:n})]})}function v({label:r,before:n,after:i,totalSaved:m}){const u=n>0?Math.round((n-i)/n*100):0;return e.jsxs("div",{className:"p-4 rounded-xl border border-edge shadow-sm bg-surface-alt","data-testid":"metric-card",children:[e.jsx("div",{className:"text-xs font-medium text-muted mb-2",children:r}),e.jsxs("div",{className:"flex items-baseline gap-3 mb-1",children:[e.jsxs("span",{className:"text-sm text-muted line-through",children:["$",n.toFixed(3)]}),e.jsxs("span",{className:"text-xl font-bold",children:["$",i.toFixed(3)]}),e.jsxs("span",{className:"text-xs text-accent",children:["-",u,"%"]})]}),e.jsxs("div",{className:"text-[10px] text-muted uppercase",children:["per task · $",m.toFixed(2)," total saved"]})]})}export{f as BenchmarkTab};
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-CIhDR5rf.js";/**
1
+ import{c as e}from"./index-C3Kad9YO.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1 +1 @@
1
- import{r as o,a as m,j as e,R as v}from"./index-CIhDR5rf.js";function C(){const[t,s]=o.useState(null),[l,n]=o.useState(!0),[a,i]=o.useState(null),x=o.useCallback(async()=>{n(!0),i(null);try{const u=await m.getContextBudget();s(u)}catch(u){i(u instanceof Error?u.message:"Failed to load context budget")}finally{n(!1)}},[]);return o.useEffect(()=>{x()},[x]),{budget:t,loading:l,error:a,refresh:x}}function S(){const[t,s]=o.useState(null),[l,n]=o.useState([]),[a,i]=o.useState(null),[x,u]=o.useState(!0),[g,r]=o.useState(null),d=o.useCallback(async()=>{u(!0),r(null);try{const[c,h,k]=await Promise.all([m.dreamGetStatus(),m.dreamGetHistory(20),m.dreamGetMetrics()]);s(c),n(h),i(k)}catch(c){r(c instanceof Error?c.message:"Failed to load dream data")}finally{u(!1)}},[]);o.useEffect(()=>{d()},[d]);const y=o.useCallback(async c=>{try{await m.dreamStartCycle(c),setTimeout(()=>void d(),500)}catch(h){r(h instanceof Error?h.message:"Failed to start dream cycle")}},[d]),N=o.useCallback(async()=>{try{await m.dreamCancelCycle(),d()}catch(c){r(c instanceof Error?c.message:"Failed to cancel dream cycle")}},[d]),w=o.useCallback(async()=>{try{return await m.dreamGetPreview()}catch(c){return r(c instanceof Error?c.message:"Failed to get dream preview"),null}},[]);return{status:t,history:l,metrics:a,loading:x,error:g,startCycle:y,cancelCycle:N,preview:w,refresh:d}}const b=[{key:"nrem",label:"NREM",subtitle:"Replay + Decay + Prune"},{key:"rem",label:"REM",subtitle:"Priority + Merge + Associate"},{key:"wake-ready",label:"Wake",subtitle:"Report + Synthesize"}],p={completed:"#10b981",active:"#3B82F6",pending:"#6b7280"};function f(t,s,l){if(!l)return"pending";const n=["nrem","rem","wake-ready"],a=n.indexOf(s??""),i=n.indexOf(t);return i<a?"completed":i===a?"active":"pending"}function M({status:t}){return e.jsx("div",{className:"flex items-center gap-2",children:b.map((s,l)=>{const n=f(s.key,t.currentPhase,t.running),a=p[n];return e.jsxs(v.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 min-w-[80px]",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-colors duration-200",style:{backgroundColor:n==="pending"?"transparent":a,border:`2px solid ${a}`,color:n==="pending"?a:"#fff"},children:l+1}),e.jsx("span",{className:"text-[10px] font-semibold transition-colors duration-200",style:{color:a},children:s.label}),e.jsx("span",{className:"text-[9px] text-muted text-center leading-tight",children:s.subtitle})]}),l<b.length-1&&e.jsx("div",{className:"h-0.5 flex-1 transition-colors duration-200",style:{backgroundColor:f(b[l+1].key,t.currentPhase,t.running)!=="pending"?p.completed:p.pending}})]},s.key)})})}function D({status:t,onStartCycle:s,onCancelCycle:l,onPreview:n}){const[a,i]=v.useState(!1),x=async()=>{i(!0);try{await n()}finally{i(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-xl border border-edge shadow-sm bg-surface-alt",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.running?"bg-blue-500 animate-pulse":"bg-gray-500"}`}),e.jsx("span",{className:"text-sm font-medium",children:t.running?"Dream Cycle Running":"Idle"}),t.running&&t.progress!==void 0&&e.jsxs("span",{className:"text-xs text-muted",children:["(",Math.round(t.progress*100),"%)"]})]})}),e.jsx(M,{status:t})]}),e.jsx("div",{className:"flex items-center gap-2",children:t.running?e.jsx("button",{onClick:l,className:"px-4 py-2 text-sm font-medium rounded-lg bg-red-600/80 text-white hover:bg-red-600 cursor-pointer transition-colors duration-200",children:"Cancel Cycle"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:s,className:"px-4 py-2 text-sm font-medium rounded-lg bg-blue-600 text-white hover:bg-blue-700 cursor-pointer transition-colors duration-200",children:"Start Dream Cycle"}),e.jsx("button",{onClick:()=>void x(),disabled:a,className:"px-4 py-2 text-sm font-medium rounded-lg border border-edge text-muted hover:text-white hover:border-blue-500 cursor-pointer transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",children:a?"Previewing...":"Preview (Dry Run)"})]})})]})}const T=[{key:"totalCycles",label:"Total Cycles",format:t=>t.toString()},{key:"totalPruned",label:"Docs Pruned",format:t=>t.toLocaleString()},{key:"totalMerged",label:"Docs Merged",format:t=>t.toLocaleString()},{key:"avgQualityImprovement",label:"Avg Quality Delta",format:t=>(t>=0?"+":"")+(t*100).toFixed(1)+"%"}];function P({metrics:t}){return t?e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:T.map(({key:s,label:l,format:n})=>e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:n(t[s])}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:l})]},s))}):e.jsx(e.Fragment,{})}const E={completed:"text-green-500",running:"text-blue-500",failed:"text-red-500",cancelled:"text-yellow-500"};function R(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function $(t){return t?new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"-"}function L({cycles:t}){return t.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted",children:"No dream cycles yet"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-muted uppercase text-[10px]",children:[e.jsx("th",{className:"text-left p-2",children:"Date"}),e.jsx("th",{className:"text-left p-2",children:"Status"}),e.jsx("th",{className:"text-right p-2",children:"Pruned"}),e.jsx("th",{className:"text-right p-2",children:"Merged"}),e.jsx("th",{className:"text-right p-2",children:"Duration"})]})}),e.jsx("tbody",{children:t.map(s=>{const l=s.phases.nrem.durationMs+s.phases.rem.durationMs+s.phases.wakeReady.durationMs;return e.jsxs("tr",{className:"border-t border-edge hover:bg-surface-alt/50 transition-colors",children:[e.jsx("td",{className:"p-2",children:$(s.startedAt)}),e.jsx("td",{className:`p-2 font-medium ${E[s.status]??"text-muted"}`,children:s.status}),e.jsx("td",{className:"p-2 text-right",children:s.summary.totalPruned}),e.jsx("td",{className:"p-2 text-right",children:s.summary.totalMerged}),e.jsx("td",{className:"p-2 text-right",children:R(l)})]},s.id)})})]})})}const j={green:{bg:"bg-green-500/10",text:"text-green-500",border:"border-green-500/30"},yellow:{bg:"bg-yellow-500/10",text:"text-yellow-500",border:"border-yellow-500/30"},red:{bg:"bg-red-500/10",text:"text-red-500",border:"border-red-500/30"}};function A(){const{budget:t,loading:s,error:l,refresh:n}=C(),a=S(),[i,x]=o.useState(null);if(l)return e.jsxs("div",{className:"flex items-center justify-center h-full text-danger",children:["Failed to load context budget: ",l]});if(s||!t)return e.jsxs("div",{className:"p-6 max-w-6xl mx-auto space-y-6",children:[e.jsx("div",{className:"h-5 w-48 rounded bg-surface animate-pulse"}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:Array.from({length:4}).map((r,d)=>e.jsx("div",{className:"h-20 rounded-xl border border-edge bg-surface-alt animate-pulse"},d))}),e.jsx("div",{className:"h-24 rounded-lg border border-edge bg-surface-alt animate-pulse"}),e.jsx("div",{className:"h-12 rounded-xl border border-edge bg-surface-alt animate-pulse"})]});const u=j[t.health]??j.green,g=r=>{i===r?(x(null),m.toggleSkill(r,!1).then(()=>n())):(x(r),setTimeout(()=>x(d=>d===r?null:d),3e3))};return e.jsxs("div",{className:"p-6 max-w-6xl mx-auto space-y-6 overflow-y-auto h-full",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Context Management"}),e.jsx("button",{onClick:()=>n(),className:"text-xs px-3 py-1.5 rounded-lg bg-accent text-white hover:opacity-90 transition-opacity",children:"Refresh"})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.activeTokens.toLocaleString()}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Active Tokens"})]}),e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.totalTokens.toLocaleString()}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Total Tokens"})]}),e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.activeCount}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Active Skills"})]}),e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.totalCount}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Total Skills"})]})]}),e.jsxs("div",{className:`p-4 rounded-lg border ${u.bg} ${u.border}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${t.health==="green"?"bg-green-500":t.health==="yellow"?"bg-yellow-500":"bg-red-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:`text-sm font-medium ${u.text}`,children:["Session Health: ",t.health.charAt(0).toUpperCase()+t.health.slice(1)]}),e.jsx("div",{className:"text-xs text-muted mt-0.5",children:t.healthMessage})]})]}),t.recommendations.length>0&&e.jsx("div",{className:"mt-3 space-y-1",children:t.recommendations.map((r,d)=>e.jsx("div",{className:"text-xs text-muted",children:r},d))})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-xs font-semibold text-muted uppercase",children:"Token Budget"}),e.jsxs("span",{className:"text-xs text-muted",children:[t.activeTokens.toLocaleString()," / 4,000 (",Math.round(t.activeTokens/40),"%)"]})]}),e.jsxs("div",{className:"w-full h-3 rounded-full bg-edge relative",children:[e.jsx("div",{className:"h-full rounded-full absolute top-0 left-0 opacity-20",style:{width:`${Math.min(Math.round(t.totalTokens/40),100)}%`,background:"#6b7280"}}),e.jsx("div",{className:"h-full rounded-full absolute top-0 left-0 transition-all",style:{width:`${Math.min(Math.round(t.activeTokens/40),100)}%`,background:t.health==="red"?"#ef4444":t.health==="yellow"?"#f59e0b":"#10b981"}})]})]}),e.jsxs("div",{className:"border-t border-edge pt-6 space-y-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"DreamMode"}),e.jsx("p",{className:"text-xs text-muted",children:"REM-inspired knowledge consolidation: replay, decay, prune, merge, and synthesize."}),a.error&&e.jsx("div",{className:"text-xs text-red-400",children:a.error}),a.status&&e.jsx(D,{status:a.status,onStartCycle:()=>void a.startCycle(),onCancelCycle:()=>void a.cancelCycle(),onPreview:a.preview}),e.jsx(P,{metrics:a.metrics}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold text-muted uppercase",children:"Cycle History"}),e.jsx(L,{cycles:a.history})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold text-muted uppercase",children:"Token Breakdown by Skill"}),e.jsx("div",{className:"space-y-1",children:t.breakdown.map(r=>{const d=t.totalTokens>0?Math.round(r.tokens/t.totalTokens*100):0;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt ${r.enabled?"":"opacity-40"}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium truncate",children:r.name}),e.jsx("span",{className:`px-1 py-0.5 rounded text-[9px] ${r.source==="custom"?"bg-purple-500/10 text-purple-500":"bg-blue-500/10 text-blue-500"}`,children:r.source})]}),e.jsx("div",{className:"w-full h-1 rounded-full bg-edge mt-1",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${d}%`,background:r.enabled?"#3b82f6":"#6b7280"}})})]}),e.jsxs("span",{className:"text-[10px] text-muted shrink-0 w-16 text-right",children:[r.tokens.toLocaleString()," tok"]}),r.enabled&&e.jsx("button",{onClick:()=>g(r.name),className:`text-[10px] px-1.5 py-0.5 rounded border shrink-0 cursor-pointer transition-all ${i===r.name?"bg-red-500/10 text-red-400 border-red-500/30 font-medium":"border-edge text-muted hover:text-red-500 hover:border-red-500/50"}`,children:i===r.name?"Sure?":"Disable"})]},r.name)})})]})]})}export{A as ContextTab};
1
+ import{r as o,a as m,j as e,R as v}from"./index-C3Kad9YO.js";function C(){const[t,s]=o.useState(null),[l,n]=o.useState(!0),[a,i]=o.useState(null),x=o.useCallback(async()=>{n(!0),i(null);try{const u=await m.getContextBudget();s(u)}catch(u){i(u instanceof Error?u.message:"Failed to load context budget")}finally{n(!1)}},[]);return o.useEffect(()=>{x()},[x]),{budget:t,loading:l,error:a,refresh:x}}function S(){const[t,s]=o.useState(null),[l,n]=o.useState([]),[a,i]=o.useState(null),[x,u]=o.useState(!0),[g,r]=o.useState(null),d=o.useCallback(async()=>{u(!0),r(null);try{const[c,h,k]=await Promise.all([m.dreamGetStatus(),m.dreamGetHistory(20),m.dreamGetMetrics()]);s(c),n(h),i(k)}catch(c){r(c instanceof Error?c.message:"Failed to load dream data")}finally{u(!1)}},[]);o.useEffect(()=>{d()},[d]);const y=o.useCallback(async c=>{try{await m.dreamStartCycle(c),setTimeout(()=>void d(),500)}catch(h){r(h instanceof Error?h.message:"Failed to start dream cycle")}},[d]),N=o.useCallback(async()=>{try{await m.dreamCancelCycle(),d()}catch(c){r(c instanceof Error?c.message:"Failed to cancel dream cycle")}},[d]),w=o.useCallback(async()=>{try{return await m.dreamGetPreview()}catch(c){return r(c instanceof Error?c.message:"Failed to get dream preview"),null}},[]);return{status:t,history:l,metrics:a,loading:x,error:g,startCycle:y,cancelCycle:N,preview:w,refresh:d}}const b=[{key:"nrem",label:"NREM",subtitle:"Replay + Decay + Prune"},{key:"rem",label:"REM",subtitle:"Priority + Merge + Associate"},{key:"wake-ready",label:"Wake",subtitle:"Report + Synthesize"}],p={completed:"#10b981",active:"#3B82F6",pending:"#6b7280"};function f(t,s,l){if(!l)return"pending";const n=["nrem","rem","wake-ready"],a=n.indexOf(s??""),i=n.indexOf(t);return i<a?"completed":i===a?"active":"pending"}function M({status:t}){return e.jsx("div",{className:"flex items-center gap-2",children:b.map((s,l)=>{const n=f(s.key,t.currentPhase,t.running),a=p[n];return e.jsxs(v.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 min-w-[80px]",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-colors duration-200",style:{backgroundColor:n==="pending"?"transparent":a,border:`2px solid ${a}`,color:n==="pending"?a:"#fff"},children:l+1}),e.jsx("span",{className:"text-[10px] font-semibold transition-colors duration-200",style:{color:a},children:s.label}),e.jsx("span",{className:"text-[9px] text-muted text-center leading-tight",children:s.subtitle})]}),l<b.length-1&&e.jsx("div",{className:"h-0.5 flex-1 transition-colors duration-200",style:{backgroundColor:f(b[l+1].key,t.currentPhase,t.running)!=="pending"?p.completed:p.pending}})]},s.key)})})}function D({status:t,onStartCycle:s,onCancelCycle:l,onPreview:n}){const[a,i]=v.useState(!1),x=async()=>{i(!0);try{await n()}finally{i(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-xl border border-edge shadow-sm bg-surface-alt",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.running?"bg-blue-500 animate-pulse":"bg-gray-500"}`}),e.jsx("span",{className:"text-sm font-medium",children:t.running?"Dream Cycle Running":"Idle"}),t.running&&t.progress!==void 0&&e.jsxs("span",{className:"text-xs text-muted",children:["(",Math.round(t.progress*100),"%)"]})]})}),e.jsx(M,{status:t})]}),e.jsx("div",{className:"flex items-center gap-2",children:t.running?e.jsx("button",{onClick:l,className:"px-4 py-2 text-sm font-medium rounded-lg bg-red-600/80 text-white hover:bg-red-600 cursor-pointer transition-colors duration-200",children:"Cancel Cycle"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:s,className:"px-4 py-2 text-sm font-medium rounded-lg bg-blue-600 text-white hover:bg-blue-700 cursor-pointer transition-colors duration-200",children:"Start Dream Cycle"}),e.jsx("button",{onClick:()=>void x(),disabled:a,className:"px-4 py-2 text-sm font-medium rounded-lg border border-edge text-muted hover:text-white hover:border-blue-500 cursor-pointer transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed",children:a?"Previewing...":"Preview (Dry Run)"})]})})]})}const T=[{key:"totalCycles",label:"Total Cycles",format:t=>t.toString()},{key:"totalPruned",label:"Docs Pruned",format:t=>t.toLocaleString()},{key:"totalMerged",label:"Docs Merged",format:t=>t.toLocaleString()},{key:"avgQualityImprovement",label:"Avg Quality Delta",format:t=>(t>=0?"+":"")+(t*100).toFixed(1)+"%"}];function P({metrics:t}){return t?e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:T.map(({key:s,label:l,format:n})=>e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:n(t[s])}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:l})]},s))}):e.jsx(e.Fragment,{})}const E={completed:"text-green-500",running:"text-blue-500",failed:"text-red-500",cancelled:"text-yellow-500"};function R(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function $(t){return t?new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"-"}function L({cycles:t}){return t.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted",children:"No dream cycles yet"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-muted uppercase text-[10px]",children:[e.jsx("th",{className:"text-left p-2",children:"Date"}),e.jsx("th",{className:"text-left p-2",children:"Status"}),e.jsx("th",{className:"text-right p-2",children:"Pruned"}),e.jsx("th",{className:"text-right p-2",children:"Merged"}),e.jsx("th",{className:"text-right p-2",children:"Duration"})]})}),e.jsx("tbody",{children:t.map(s=>{const l=s.phases.nrem.durationMs+s.phases.rem.durationMs+s.phases.wakeReady.durationMs;return e.jsxs("tr",{className:"border-t border-edge hover:bg-surface-alt/50 transition-colors",children:[e.jsx("td",{className:"p-2",children:$(s.startedAt)}),e.jsx("td",{className:`p-2 font-medium ${E[s.status]??"text-muted"}`,children:s.status}),e.jsx("td",{className:"p-2 text-right",children:s.summary.totalPruned}),e.jsx("td",{className:"p-2 text-right",children:s.summary.totalMerged}),e.jsx("td",{className:"p-2 text-right",children:R(l)})]},s.id)})})]})})}const j={green:{bg:"bg-green-500/10",text:"text-green-500",border:"border-green-500/30"},yellow:{bg:"bg-yellow-500/10",text:"text-yellow-500",border:"border-yellow-500/30"},red:{bg:"bg-red-500/10",text:"text-red-500",border:"border-red-500/30"}};function A(){const{budget:t,loading:s,error:l,refresh:n}=C(),a=S(),[i,x]=o.useState(null);if(l)return e.jsxs("div",{className:"flex items-center justify-center h-full text-danger",children:["Failed to load context budget: ",l]});if(s||!t)return e.jsxs("div",{className:"p-6 max-w-6xl mx-auto space-y-6",children:[e.jsx("div",{className:"h-5 w-48 rounded bg-surface animate-pulse"}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:Array.from({length:4}).map((r,d)=>e.jsx("div",{className:"h-20 rounded-xl border border-edge bg-surface-alt animate-pulse"},d))}),e.jsx("div",{className:"h-24 rounded-lg border border-edge bg-surface-alt animate-pulse"}),e.jsx("div",{className:"h-12 rounded-xl border border-edge bg-surface-alt animate-pulse"})]});const u=j[t.health]??j.green,g=r=>{i===r?(x(null),m.toggleSkill(r,!1).then(()=>n())):(x(r),setTimeout(()=>x(d=>d===r?null:d),3e3))};return e.jsxs("div",{className:"p-6 max-w-6xl mx-auto space-y-6 overflow-y-auto h-full",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Context Management"}),e.jsx("button",{onClick:()=>n(),className:"text-xs px-3 py-1.5 rounded-lg bg-accent text-white hover:opacity-90 transition-opacity",children:"Refresh"})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.activeTokens.toLocaleString()}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Active Tokens"})]}),e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.totalTokens.toLocaleString()}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Total Tokens"})]}),e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.activeCount}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Active Skills"})]}),e.jsxs("div",{className:"p-3 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:t.totalCount}),e.jsx("div",{className:"text-[10px] text-muted uppercase",children:"Total Skills"})]})]}),e.jsxs("div",{className:`p-4 rounded-lg border ${u.bg} ${u.border}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${t.health==="green"?"bg-green-500":t.health==="yellow"?"bg-yellow-500":"bg-red-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:`text-sm font-medium ${u.text}`,children:["Session Health: ",t.health.charAt(0).toUpperCase()+t.health.slice(1)]}),e.jsx("div",{className:"text-xs text-muted mt-0.5",children:t.healthMessage})]})]}),t.recommendations.length>0&&e.jsx("div",{className:"mt-3 space-y-1",children:t.recommendations.map((r,d)=>e.jsx("div",{className:"text-xs text-muted",children:r},d))})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-xs font-semibold text-muted uppercase",children:"Token Budget"}),e.jsxs("span",{className:"text-xs text-muted",children:[t.activeTokens.toLocaleString()," / 4,000 (",Math.round(t.activeTokens/40),"%)"]})]}),e.jsxs("div",{className:"w-full h-3 rounded-full bg-edge relative",children:[e.jsx("div",{className:"h-full rounded-full absolute top-0 left-0 opacity-20",style:{width:`${Math.min(Math.round(t.totalTokens/40),100)}%`,background:"#6b7280"}}),e.jsx("div",{className:"h-full rounded-full absolute top-0 left-0 transition-all",style:{width:`${Math.min(Math.round(t.activeTokens/40),100)}%`,background:t.health==="red"?"#ef4444":t.health==="yellow"?"#f59e0b":"#10b981"}})]})]}),e.jsxs("div",{className:"border-t border-edge pt-6 space-y-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"DreamMode"}),e.jsx("p",{className:"text-xs text-muted",children:"REM-inspired knowledge consolidation: replay, decay, prune, merge, and synthesize."}),a.error&&e.jsx("div",{className:"text-xs text-red-400",children:a.error}),a.status&&e.jsx(D,{status:a.status,onStartCycle:()=>void a.startCycle(),onCancelCycle:()=>void a.cancelCycle(),onPreview:a.preview}),e.jsx(P,{metrics:a.metrics}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold text-muted uppercase",children:"Cycle History"}),e.jsx(L,{cycles:a.history})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold text-muted uppercase",children:"Token Breakdown by Skill"}),e.jsx("div",{className:"space-y-1",children:t.breakdown.map(r=>{const d=t.totalTokens>0?Math.round(r.tokens/t.totalTokens*100):0;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-xl border border-edge shadow-sm hover:shadow-md transition-shadow bg-surface-alt ${r.enabled?"":"opacity-40"}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium truncate",children:r.name}),e.jsx("span",{className:`px-1 py-0.5 rounded text-[9px] ${r.source==="custom"?"bg-purple-500/10 text-purple-500":"bg-blue-500/10 text-blue-500"}`,children:r.source})]}),e.jsx("div",{className:"w-full h-1 rounded-full bg-edge mt-1",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${d}%`,background:r.enabled?"#3b82f6":"#6b7280"}})})]}),e.jsxs("span",{className:"text-[10px] text-muted shrink-0 w-16 text-right",children:[r.tokens.toLocaleString()," tok"]}),r.enabled&&e.jsx("button",{onClick:()=>g(r.name),className:`text-[10px] px-1.5 py-0.5 rounded border shrink-0 cursor-pointer transition-all ${i===r.name?"bg-red-500/10 text-red-400 border-red-500/30 font-medium":"border-edge text-muted hover:text-red-500 hover:border-red-500/50"}`,children:i===r.name?"Sure?":"Disable"})]},r.name)})})]})]})}export{A as ContextTab};
@@ -1 +1 @@
1
- import{r as c,a as p,j as e}from"./index-CIhDR5rf.js";function $(){const[t,l]=c.useState([]),[n,s]=c.useState([]),[o,b]=c.useState([]),[f,r]=c.useState(null),[u,a]=c.useState(!0),[N,x]=c.useState(null),h=c.useCallback(async()=>{try{a(!0),x(null);const[d,g,v,z]=await Promise.all([p.getDocsTools().catch(()=>({tools:[]})),p.getDocsRoutes().catch(()=>({routes:[]})),p.getDocsList().catch(()=>({docs:[]})),p.getDocsStats().catch(()=>null)]);l(d.tools),s(g.routes),b(v.docs),r(z)}catch(d){x(d instanceof Error?d.message:"Failed to load docs")}finally{a(!1)}},[]);c.useEffect(()=>{h()},[h]);const C=c.useCallback(async(d,g)=>(await p.getDocContent(d,g)).content,[]);return{tools:t,routes:n,docs:o,stats:f,loading:u,error:N,fetchDocContent:C,refresh:h}}const E={Core:"bg-blue-500/20 text-blue-400","Siebel CRM":"bg-purple-500/20 text-purple-400",Translation:"bg-green-500/20 text-green-400",Knowledge:"bg-yellow-500/20 text-yellow-400","Code Intelligence":"bg-cyan-500/20 text-cyan-400",Deprecated:"bg-red-500/20 text-red-400"},M={get:"bg-green-600/30 text-green-300",post:"bg-blue-600/30 text-blue-300",patch:"bg-yellow-600/30 text-yellow-300",put:"bg-orange-600/30 text-orange-300",delete:"bg-red-600/30 text-red-300"};function H(){const{tools:t,routes:l,docs:n,stats:s,loading:o,error:b,fetchDocContent:f}=$(),[r,u]=c.useState("overview"),[a,N]=c.useState(""),[x,h]=c.useState("all"),[C,d]=c.useState(""),[g,v]=c.useState(""),[z,S]=c.useState(!1),L=c.useMemo(()=>{const i=new Set(t.map(m=>m.category));return["all",...Array.from(i).sort()]},[t]),D=c.useMemo(()=>t.filter(i=>!(x!=="all"&&i.category!==x||a&&!i.name.toLowerCase().includes(a.toLowerCase())&&!i.description.toLowerCase().includes(a.toLowerCase()))),[t,x,a]),R=c.useMemo(()=>l.filter(i=>!(a&&!i.mountPath.toLowerCase().includes(a.toLowerCase())&&!i.routerName.toLowerCase().includes(a.toLowerCase()))),[l,a]),T=c.useMemo(()=>{const i=new Map;for(const m of n){const j=i.get(m.category)??[];j.push(m),i.set(m.category,j)}return i},[n]),G=c.useCallback(async(i,m,j)=>{S(!0),v(j),u("guide-content");try{const k=m.split("/"),P=await f(k[0],k[1]);d(P)}catch{d("Failed to load document.")}finally{S(!1)}},[f]);return o?e.jsx("div",{className:"flex items-center justify-center h-64 text-zinc-400",children:"Loading docs..."}):b?e.jsxs("div",{className:"p-4 text-red-400",children:["Error: ",b]}):e.jsxs("div",{className:"flex h-full",children:[e.jsxs("nav",{className:"w-56 shrink-0 border-r border-zinc-700 p-3 space-y-1 overflow-y-auto",children:[e.jsx(y,{label:"Overview",active:r==="overview",onClick:()=>u("overview"),count:null}),e.jsx(y,{label:"MCP Tools",active:r==="tools",onClick:()=>u("tools"),count:(s==null?void 0:s.tools.active)??0}),e.jsx(y,{label:"API Routes",active:r==="routes",onClick:()=>u("routes"),count:(s==null?void 0:s.routes.endpoints)??0}),e.jsx(y,{label:"Guides",active:r==="guides"||r==="guide-content",onClick:()=>u("guides"),count:n.length})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[(r==="tools"||r==="routes")&&e.jsx("div",{className:"mb-4",children:e.jsx("input",{type:"text",placeholder:`Search ${r}...`,value:a,onChange:i=>N(i.target.value),className:"w-full px-3 py-2 bg-zinc-800 border border-zinc-600 rounded-md text-zinc-200 placeholder-zinc-500 focus:outline-none focus:ring-1 focus:ring-blue-500"})}),r==="overview"&&e.jsx(A,{stats:s,toolCount:t.length,routeCount:l.length,docCount:n.length}),r==="tools"&&e.jsx(O,{tools:D,categories:L,categoryFilter:x,onCategoryChange:h}),r==="routes"&&e.jsx(I,{routes:R}),r==="guides"&&e.jsx(F,{categories:T,onGuideClick:G}),r==="guide-content"&&e.jsx(B,{title:g,content:C,loading:z,onBack:()=>u("guides")})]})]})}function y({label:t,active:l,onClick:n,count:s}){return e.jsxs("button",{onClick:n,className:`w-full text-left px-3 py-2 rounded-md text-sm transition-colors ${l?"bg-blue-600/20 text-blue-400 font-medium":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,children:[t,s!==null&&e.jsxs("span",{className:"ml-2 text-xs text-zinc-500",children:["(",s,")"]})]})}function A({stats:t,toolCount:l,routeCount:n,docCount:s}){return e.jsxs("div",{className:"space-y-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-zinc-100",children:"mcp-graph Documentation"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(w,{label:"MCP Tools",value:(t==null?void 0:t.tools.active)??l,sub:`+ ${(t==null?void 0:t.tools.deprecated)??0} deprecated`}),e.jsx(w,{label:"API Endpoints",value:(t==null?void 0:t.routes.endpoints)??0,sub:`${(t==null?void 0:t.routes.routers)??n} routers`}),e.jsx(w,{label:"Guides",value:(t==null?void 0:t.docs)??s,sub:"markdown docs"})]}),e.jsx("p",{className:"text-zinc-400 text-sm",children:"Use the sidebar to browse MCP tools, API routes, and project guides. All data is introspected live from the source code."})]})}function w({label:t,value:l,sub:n}){return e.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4 border border-zinc-700",children:[e.jsx("div",{className:"text-2xl font-bold text-zinc-100",children:l}),e.jsx("div",{className:"text-sm font-medium text-zinc-300",children:t}),e.jsx("div",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function O({tools:t,categories:l,categoryFilter:n,onCategoryChange:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:l.map(o=>e.jsx("button",{onClick:()=>s(o),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors ${n===o?"bg-blue-600 text-white":"bg-zinc-800 text-zinc-400 hover:bg-zinc-700"}`,children:o==="all"?"All":o},o))}),e.jsxs("div",{className:"text-xs text-zinc-500 mb-2",children:[t.length," tools"]}),e.jsx("div",{className:"space-y-1",children:t.map(o=>e.jsxs("div",{className:`flex items-start gap-3 p-3 rounded-md ${o.deprecated?"opacity-50":"hover:bg-zinc-800/50"}`,children:[e.jsx("code",{className:"text-sm font-mono text-blue-400 shrink-0 w-40",children:o.name}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full shrink-0 ${E[o.category]??"bg-zinc-700 text-zinc-300"}`,children:o.category}),e.jsx("span",{className:"text-sm text-zinc-400 flex-1",children:o.description})]},o.name))})]})}function I({routes:t}){const l=t.reduce((n,s)=>n+s.endpoints.length,0);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-zinc-500",children:[t.length," routers, ",l," endpoints"]}),t.map(n=>e.jsxs("div",{className:"border border-zinc-700 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-zinc-800 px-4 py-2 flex items-center justify-between",children:[e.jsx("code",{className:"text-sm font-mono text-green-400",children:n.mountPath}),e.jsxs("span",{className:"text-xs text-zinc-500",children:[n.endpoints.length," endpoints"]})]}),e.jsx("div",{className:"divide-y divide-zinc-800",children:n.endpoints.map((s,o)=>e.jsxs("div",{className:"px-4 py-2 flex items-center gap-3",children:[e.jsx("span",{className:`text-xs font-mono uppercase px-2 py-0.5 rounded ${M[s.method]??"bg-zinc-700 text-zinc-300"}`,children:s.method}),e.jsxs("code",{className:"text-sm text-zinc-300",children:[n.mountPath,s.path]})]},`${s.method}-${s.path}-${o}`))})]},n.mountPath))]})}function F({categories:t,onGuideClick:l}){return e.jsx("div",{className:"space-y-6",children:Array.from(t).map(([n,s])=>e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-zinc-300 uppercase tracking-wider mb-2",children:n}),e.jsx("div",{className:"space-y-1",children:s.map(o=>e.jsx("button",{onClick:()=>l(o.category,o.slug,o.title),className:"w-full text-left px-3 py-2 rounded-md text-sm text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200 transition-colors",children:o.title},o.slug))})]},n))})}function B({title:t,content:l,loading:n,onBack:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("button",{onClick:s,className:"text-sm text-blue-400 hover:text-blue-300",children:"← Back to Guides"}),e.jsx("h2",{className:"text-lg font-semibold text-zinc-100",children:t}),n?e.jsx("div",{className:"text-zinc-400",children:"Loading..."}):e.jsx("pre",{className:"whitespace-pre-wrap text-sm text-zinc-300 bg-zinc-900 rounded-lg p-4 border border-zinc-700 overflow-auto max-h-[70vh]",children:l})]})}export{H as DocsTab};
1
+ import{r as c,a as p,j as e}from"./index-C3Kad9YO.js";function $(){const[t,l]=c.useState([]),[n,s]=c.useState([]),[o,b]=c.useState([]),[f,r]=c.useState(null),[u,a]=c.useState(!0),[N,x]=c.useState(null),h=c.useCallback(async()=>{try{a(!0),x(null);const[d,g,v,z]=await Promise.all([p.getDocsTools().catch(()=>({tools:[]})),p.getDocsRoutes().catch(()=>({routes:[]})),p.getDocsList().catch(()=>({docs:[]})),p.getDocsStats().catch(()=>null)]);l(d.tools),s(g.routes),b(v.docs),r(z)}catch(d){x(d instanceof Error?d.message:"Failed to load docs")}finally{a(!1)}},[]);c.useEffect(()=>{h()},[h]);const C=c.useCallback(async(d,g)=>(await p.getDocContent(d,g)).content,[]);return{tools:t,routes:n,docs:o,stats:f,loading:u,error:N,fetchDocContent:C,refresh:h}}const E={Core:"bg-blue-500/20 text-blue-400","Siebel CRM":"bg-purple-500/20 text-purple-400",Translation:"bg-green-500/20 text-green-400",Knowledge:"bg-yellow-500/20 text-yellow-400","Code Intelligence":"bg-cyan-500/20 text-cyan-400",Deprecated:"bg-red-500/20 text-red-400"},M={get:"bg-green-600/30 text-green-300",post:"bg-blue-600/30 text-blue-300",patch:"bg-yellow-600/30 text-yellow-300",put:"bg-orange-600/30 text-orange-300",delete:"bg-red-600/30 text-red-300"};function H(){const{tools:t,routes:l,docs:n,stats:s,loading:o,error:b,fetchDocContent:f}=$(),[r,u]=c.useState("overview"),[a,N]=c.useState(""),[x,h]=c.useState("all"),[C,d]=c.useState(""),[g,v]=c.useState(""),[z,S]=c.useState(!1),L=c.useMemo(()=>{const i=new Set(t.map(m=>m.category));return["all",...Array.from(i).sort()]},[t]),D=c.useMemo(()=>t.filter(i=>!(x!=="all"&&i.category!==x||a&&!i.name.toLowerCase().includes(a.toLowerCase())&&!i.description.toLowerCase().includes(a.toLowerCase()))),[t,x,a]),R=c.useMemo(()=>l.filter(i=>!(a&&!i.mountPath.toLowerCase().includes(a.toLowerCase())&&!i.routerName.toLowerCase().includes(a.toLowerCase()))),[l,a]),T=c.useMemo(()=>{const i=new Map;for(const m of n){const j=i.get(m.category)??[];j.push(m),i.set(m.category,j)}return i},[n]),G=c.useCallback(async(i,m,j)=>{S(!0),v(j),u("guide-content");try{const k=m.split("/"),P=await f(k[0],k[1]);d(P)}catch{d("Failed to load document.")}finally{S(!1)}},[f]);return o?e.jsx("div",{className:"flex items-center justify-center h-64 text-zinc-400",children:"Loading docs..."}):b?e.jsxs("div",{className:"p-4 text-red-400",children:["Error: ",b]}):e.jsxs("div",{className:"flex h-full",children:[e.jsxs("nav",{className:"w-56 shrink-0 border-r border-zinc-700 p-3 space-y-1 overflow-y-auto",children:[e.jsx(y,{label:"Overview",active:r==="overview",onClick:()=>u("overview"),count:null}),e.jsx(y,{label:"MCP Tools",active:r==="tools",onClick:()=>u("tools"),count:(s==null?void 0:s.tools.active)??0}),e.jsx(y,{label:"API Routes",active:r==="routes",onClick:()=>u("routes"),count:(s==null?void 0:s.routes.endpoints)??0}),e.jsx(y,{label:"Guides",active:r==="guides"||r==="guide-content",onClick:()=>u("guides"),count:n.length})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[(r==="tools"||r==="routes")&&e.jsx("div",{className:"mb-4",children:e.jsx("input",{type:"text",placeholder:`Search ${r}...`,value:a,onChange:i=>N(i.target.value),className:"w-full px-3 py-2 bg-zinc-800 border border-zinc-600 rounded-md text-zinc-200 placeholder-zinc-500 focus:outline-none focus:ring-1 focus:ring-blue-500"})}),r==="overview"&&e.jsx(A,{stats:s,toolCount:t.length,routeCount:l.length,docCount:n.length}),r==="tools"&&e.jsx(O,{tools:D,categories:L,categoryFilter:x,onCategoryChange:h}),r==="routes"&&e.jsx(I,{routes:R}),r==="guides"&&e.jsx(F,{categories:T,onGuideClick:G}),r==="guide-content"&&e.jsx(B,{title:g,content:C,loading:z,onBack:()=>u("guides")})]})]})}function y({label:t,active:l,onClick:n,count:s}){return e.jsxs("button",{onClick:n,className:`w-full text-left px-3 py-2 rounded-md text-sm transition-colors ${l?"bg-blue-600/20 text-blue-400 font-medium":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,children:[t,s!==null&&e.jsxs("span",{className:"ml-2 text-xs text-zinc-500",children:["(",s,")"]})]})}function A({stats:t,toolCount:l,routeCount:n,docCount:s}){return e.jsxs("div",{className:"space-y-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-zinc-100",children:"mcp-graph Documentation"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(w,{label:"MCP Tools",value:(t==null?void 0:t.tools.active)??l,sub:`+ ${(t==null?void 0:t.tools.deprecated)??0} deprecated`}),e.jsx(w,{label:"API Endpoints",value:(t==null?void 0:t.routes.endpoints)??0,sub:`${(t==null?void 0:t.routes.routers)??n} routers`}),e.jsx(w,{label:"Guides",value:(t==null?void 0:t.docs)??s,sub:"markdown docs"})]}),e.jsx("p",{className:"text-zinc-400 text-sm",children:"Use the sidebar to browse MCP tools, API routes, and project guides. All data is introspected live from the source code."})]})}function w({label:t,value:l,sub:n}){return e.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4 border border-zinc-700",children:[e.jsx("div",{className:"text-2xl font-bold text-zinc-100",children:l}),e.jsx("div",{className:"text-sm font-medium text-zinc-300",children:t}),e.jsx("div",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function O({tools:t,categories:l,categoryFilter:n,onCategoryChange:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:l.map(o=>e.jsx("button",{onClick:()=>s(o),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors ${n===o?"bg-blue-600 text-white":"bg-zinc-800 text-zinc-400 hover:bg-zinc-700"}`,children:o==="all"?"All":o},o))}),e.jsxs("div",{className:"text-xs text-zinc-500 mb-2",children:[t.length," tools"]}),e.jsx("div",{className:"space-y-1",children:t.map(o=>e.jsxs("div",{className:`flex items-start gap-3 p-3 rounded-md ${o.deprecated?"opacity-50":"hover:bg-zinc-800/50"}`,children:[e.jsx("code",{className:"text-sm font-mono text-blue-400 shrink-0 w-40",children:o.name}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full shrink-0 ${E[o.category]??"bg-zinc-700 text-zinc-300"}`,children:o.category}),e.jsx("span",{className:"text-sm text-zinc-400 flex-1",children:o.description})]},o.name))})]})}function I({routes:t}){const l=t.reduce((n,s)=>n+s.endpoints.length,0);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-zinc-500",children:[t.length," routers, ",l," endpoints"]}),t.map(n=>e.jsxs("div",{className:"border border-zinc-700 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-zinc-800 px-4 py-2 flex items-center justify-between",children:[e.jsx("code",{className:"text-sm font-mono text-green-400",children:n.mountPath}),e.jsxs("span",{className:"text-xs text-zinc-500",children:[n.endpoints.length," endpoints"]})]}),e.jsx("div",{className:"divide-y divide-zinc-800",children:n.endpoints.map((s,o)=>e.jsxs("div",{className:"px-4 py-2 flex items-center gap-3",children:[e.jsx("span",{className:`text-xs font-mono uppercase px-2 py-0.5 rounded ${M[s.method]??"bg-zinc-700 text-zinc-300"}`,children:s.method}),e.jsxs("code",{className:"text-sm text-zinc-300",children:[n.mountPath,s.path]})]},`${s.method}-${s.path}-${o}`))})]},n.mountPath))]})}function F({categories:t,onGuideClick:l}){return e.jsx("div",{className:"space-y-6",children:Array.from(t).map(([n,s])=>e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-zinc-300 uppercase tracking-wider mb-2",children:n}),e.jsx("div",{className:"space-y-1",children:s.map(o=>e.jsx("button",{onClick:()=>l(o.category,o.slug,o.title),className:"w-full text-left px-3 py-2 rounded-md text-sm text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200 transition-colors",children:o.title},o.slug))})]},n))})}function B({title:t,content:l,loading:n,onBack:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("button",{onClick:s,className:"text-sm text-blue-400 hover:text-blue-300",children:"← Back to Guides"}),e.jsx("h2",{className:"text-lg font-semibold text-zinc-100",children:t}),n?e.jsx("div",{className:"text-zinc-400",children:"Loading..."}):e.jsx("pre",{className:"whitespace-pre-wrap text-sm text-zinc-300 bg-zinc-900 rounded-lg p-4 border border-zinc-700 overflow-auto max-h-[70vh]",children:l})]})}export{H as DocsTab};