cognitivebc 0.1.0 → 0.2.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 (66) hide show
  1. package/LICENSE +70 -0
  2. package/README.md +98 -4
  3. package/SECURITY.md +29 -0
  4. package/TERMS_OF_SERVICE.md +55 -0
  5. package/bin/cbc-cloud-bootstrap.js +108 -0
  6. package/bin/cbc-seed-projects.js +29 -0
  7. package/bin/cbc-server.js +45 -0
  8. package/bin/cognitivebc.js +251 -0
  9. package/docs/ACCESS_CONTROL.md +111 -0
  10. package/docs/ARTIFACT_AUDIT.md +36 -0
  11. package/docs/CONNECT_CLIENTS.md +116 -0
  12. package/docs/DEPLOY_AZURE.md +136 -0
  13. package/docs/INGESTION.md +29 -0
  14. package/docs/OPERATIONS.md +85 -0
  15. package/docs/PROJECT_IDENTITY.md +35 -0
  16. package/docs/RESOLVER.md +86 -0
  17. package/docs/SDK.md +96 -0
  18. package/docs/STORAGE.md +63 -0
  19. package/docs/TECHNICAL_SPECIFICATION.md +365 -0
  20. package/docs/TELEMETRY.md +119 -0
  21. package/index.js +27 -2
  22. package/package.json +45 -5
  23. package/packages/cbc-compiler/index.js +357 -0
  24. package/packages/cbc-compiler/sanitizer.js +43 -0
  25. package/packages/cbc-identity/index.js +92 -0
  26. package/packages/cbc-mcp/http-backend.js +138 -0
  27. package/packages/cbc-mcp/http-route.js +64 -0
  28. package/packages/cbc-mcp/index.js +50 -0
  29. package/packages/cbc-mcp/tools.js +122 -0
  30. package/packages/cbc-resolver/catalog-linker.js +215 -0
  31. package/packages/cbc-resolver/graph-builder.js +533 -0
  32. package/packages/cbc-resolver/index.js +548 -0
  33. package/packages/cbc-resolver/obsidian-bridge.js +564 -0
  34. package/packages/cbc-schema/index.js +194 -0
  35. package/packages/cbc-sdk-js/client.js +162 -0
  36. package/services/cbc-api/access-policy.js +130 -0
  37. package/services/cbc-api/artifact-audit.js +167 -0
  38. package/services/cbc-api/cloud.js +56 -0
  39. package/services/cbc-api/context-service.js +48 -0
  40. package/services/cbc-api/ingestion-service.js +234 -0
  41. package/services/cbc-api/pg-store.js +172 -0
  42. package/services/cbc-api/project-registry.js +322 -0
  43. package/services/cbc-api/public/app.html +123 -0
  44. package/services/cbc-api/public/graph.html +1168 -0
  45. package/services/cbc-api/public/graph2.html +455 -0
  46. package/services/cbc-api/public/graph3.html +503 -0
  47. package/services/cbc-api/public/index.html +78 -0
  48. package/services/cbc-api/public/vendor/cbc-app.js +209 -0
  49. package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
  50. package/services/cbc-api/public/vendor/cbc-site.css +101 -0
  51. package/services/cbc-api/public/vendor/cose-base.js +3214 -0
  52. package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
  53. package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
  54. package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
  55. package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
  56. package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
  57. package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
  58. package/services/cbc-api/public/vendor/layout-base.js +5230 -0
  59. package/services/cbc-api/public/vendor/pf-graph.css +86 -0
  60. package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
  61. package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
  62. package/services/cbc-api/runtime-info.js +39 -0
  63. package/services/cbc-api/server.js +642 -0
  64. package/services/cbc-api/store-loader.js +269 -0
  65. package/services/cbc-api/telemetry.js +148 -0
  66. package/services/cbc-api/token-service.js +61 -0
@@ -0,0 +1,1168 @@
1
+ <!DOCTYPE html>
2
+ <html lang="pt-BR">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>CognitiveBC · Neural Graph Canvas (Obsidian Evolution)</title>
7
+ <script src="/vendor/cbc-auth.js"></script>
8
+ <script src="https://cdn.tailwindcss.com"></script>
9
+ <style>
10
+ body { background-color: #07090E; color: #F1F5F9; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; overflow: hidden; }
11
+ .glass-panel { background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(14px); border: 1px solid rgba(255, 255, 255, 0.08); }
12
+ .neon-pulse { box-shadow: 0 0 20px rgba(59, 130, 246, 0.4); }
13
+ .hazard-pulse { animation: hazardPulse 1.2s infinite alternate; }
14
+ @keyframes hazardPulse {
15
+ from { box-shadow: 0 0 10px rgba(239, 68, 68, 0.4); }
16
+ to { box-shadow: 0 0 25px rgba(239, 68, 68, 0.9); }
17
+ }
18
+ canvas { cursor: grab; }
19
+ canvas:active { cursor: grabbing; }
20
+ ::-webkit-scrollbar { width: 6px; }
21
+ ::-webkit-scrollbar-thumb { background: #1E293B; border-radius: 4px; }
22
+ </style>
23
+ </head>
24
+ <body class="w-screen h-screen flex flex-col select-none">
25
+
26
+ <!-- TOP HEADER & CONTROLS -->
27
+ <header class="glass-panel z-20 px-6 py-2.5 flex items-center justify-between border-b border-slate-800">
28
+ <div class="flex items-center space-x-4">
29
+ <div class="flex items-center space-x-2">
30
+ <span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span>
31
+ <h1 class="text-base font-bold tracking-tight text-white flex items-center gap-2">
32
+ <span class="text-blue-500 font-mono">CognitiveBC</span>
33
+ <span class="text-[10px] px-2 py-0.5 rounded bg-blue-500/10 text-blue-400 border border-blue-500/30 uppercase tracking-wider font-mono">Neural Graph</span>
34
+ </h1>
35
+ </div>
36
+ <span class="text-slate-700">|</span>
37
+ <div id="statsBar" class="text-xs text-slate-400 font-mono flex items-center gap-3">
38
+ Carregando rede...
39
+ </div>
40
+ </div>
41
+
42
+ <!-- ROLE LENSES & TOKEN METER -->
43
+ <div class="flex items-center gap-2">
44
+ <div class="flex items-center gap-1 bg-slate-900/90 p-1 rounded-xl border border-slate-800">
45
+ <span class="text-[10px] font-mono px-2 text-slate-500 uppercase tracking-wider">Lentes JIT:</span>
46
+ <button onclick="setRoleLens(null)" class="lens-btn px-2.5 py-1 rounded-lg text-xs font-medium bg-blue-600 text-white transition-all shadow-sm" data-role="">Todos</button>
47
+ <button onclick="setRoleLens('roteirista')" class="lens-btn px-2.5 py-1 rounded-lg text-xs font-medium text-slate-400 hover:text-white transition-all" data-role="roteirista">✍️ Roteirista</button>
48
+ <button onclick="setRoleLens('construtor_3d')" class="lens-btn px-2.5 py-1 rounded-lg text-xs font-medium text-slate-400 hover:text-white transition-all" data-role="construtor_3d">🧬 Construtor 3D</button>
49
+ <button onclick="setRoleLens('revisor')" class="lens-btn px-2.5 py-1 rounded-lg text-xs font-medium text-slate-400 hover:text-white transition-all" data-role="revisor">🔍 Revisor</button>
50
+ <button onclick="setRoleLens('diretor_arte')" class="lens-btn px-2.5 py-1 rounded-lg text-xs font-medium text-slate-400 hover:text-white transition-all" data-role="diretor_arte">🎬 Diretor</button>
51
+ </div>
52
+
53
+ <!-- TOKEN BUDGET GAUGE -->
54
+ <div id="tokenBudgetBox" class="hidden items-center gap-2 bg-slate-900/90 px-3 py-1 rounded-xl border border-slate-800 text-xs font-mono">
55
+ <span class="text-slate-400 text-[10px] uppercase">Token Load:</span>
56
+ <span id="tokenCountLabel" class="text-emerald-400 font-bold">164 / 600</span>
57
+ <div class="w-16 h-1.5 bg-slate-800 rounded-full overflow-hidden">
58
+ <div id="tokenProgressBar" class="h-full bg-emerald-500 transition-all duration-300" style="width: 27%;"></div>
59
+ </div>
60
+ </div>
61
+ </div>
62
+
63
+ <!-- ACTION BUTTONS -->
64
+ <div class="flex items-center space-x-2">
65
+ <div class="relative">
66
+ <input type="text" id="searchInput" placeholder="Pesquisar nó/regra..." oninput="onSearch(this.value)"
67
+ class="bg-slate-900/90 text-xs text-slate-200 px-3 py-1.5 rounded-lg border border-slate-700 focus:outline-none focus:border-blue-500 w-36 transition-all">
68
+ </div>
69
+
70
+ <!-- INTERACTIVE LINTER / GATE TESTER -->
71
+ <button onclick="toggleLinterModal()" class="px-2.5 py-1.5 rounded-lg border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 text-red-400 text-xs font-medium transition-all flex items-center gap-1.5" title="Testar Roteiro ou Código contra o Grafo">
72
+ <span>🧪</span> Testar Gate
73
+ </button>
74
+
75
+ <!-- VISUAL RULE CREATOR -->
76
+ <button onclick="openRuleCreatorModal()" class="px-2.5 py-1.5 rounded-lg border border-emerald-500/30 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-medium transition-all flex items-center gap-1.5" title="Criar nova restrição ou heurística">
77
+ <span>➕</span> Nova Regra
78
+ </button>
79
+
80
+ <!-- EXPORT OBSIDIAN VAULT -->
81
+ <button onclick="exportToObsidian()" class="px-2.5 py-1.5 rounded-lg border border-purple-500/30 bg-purple-500/10 hover:bg-purple-500/20 text-purple-300 text-xs font-medium transition-all flex items-center gap-1.5" title="Exportar Vault Nativo do Obsidian">
82
+ <span>📂</span> Exportar Obsidian
83
+ </button>
84
+
85
+ <!-- RECENTER & PHYSICS -->
86
+ <button onclick="resetCamera()" class="p-1.5 rounded-lg border border-slate-700 bg-slate-900 text-slate-400 hover:text-white text-xs px-2 transition-all" title="Recentrar Câmera">
87
+ ⟲
88
+ </button>
89
+ <button onclick="togglePhysics()" id="btnPhysics" class="p-1.5 rounded-lg border border-slate-700 bg-slate-900 text-slate-400 hover:text-white text-xs px-2 transition-all" title="Pausar Física">
90
+ ⏸
91
+ </button>
92
+ </div>
93
+ </header>
94
+
95
+ <!-- ESCOPO DO PORTFÓLIO: organização › projeto › produto (catálogo Synap-se) -->
96
+ <nav id="scopeBar" class="glass-panel z-20 px-6 py-1.5 flex items-center gap-2 border-b border-slate-800 text-xs font-mono">
97
+ <span class="text-[10px] text-slate-500 uppercase tracking-wider">Escopo:</span>
98
+ <select id="scopeOrg" onchange="onScopeChange('org')" class="bg-slate-900/90 text-slate-200 px-2 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-blue-500">
99
+ <option value="">Todas as organizações</option>
100
+ </select>
101
+ <span class="text-slate-600">›</span>
102
+ <select id="scopeProject" onchange="onScopeChange('project')" class="bg-slate-900/90 text-slate-200 px-2 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-blue-500">
103
+ <option value="">Todos os projetos</option>
104
+ </select>
105
+ <span class="text-slate-600">›</span>
106
+ <select id="scopeProduct" onchange="onScopeChange('product')" class="bg-slate-900/90 text-slate-200 px-2 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-blue-500">
107
+ <option value="">Todos os produtos</option>
108
+ </select>
109
+ <button onclick="clearScope()" class="px-2 py-1 rounded-lg border border-slate-700 text-slate-400 hover:text-white" title="Limpar filtros">✕</button>
110
+ <span id="scopeInfo" class="text-slate-500 ml-2"></span>
111
+ </nav>
112
+
113
+ <!-- MAIN CANVAS & FLOATING OVERLAYS -->
114
+ <main class="relative flex-1 w-full h-full overflow-hidden">
115
+ <!-- TIMELINE: simulação de construção por created_at -->
116
+ <div class="glass-panel absolute bottom-4 left-1/2 -translate-x-1/2 z-20 rounded-xl px-4 py-2 flex items-center gap-3 text-xs font-mono" style="width:min(720px,90vw)">
117
+ <button id="timelinePlay" onclick="toggleTimelinePlay()" class="px-2.5 py-1 rounded-lg bg-blue-600 text-white" title="Reproduzir construção do grafo">▶</button>
118
+ <input id="timelineSlider" type="range" min="0" max="0" value="0" class="flex-1 accent-blue-500" oninput="timelineSeek(this.value)">
119
+ <span id="timelineLabel" class="text-slate-400 truncate" style="max-width:320px">—</span>
120
+ </div>
121
+ <canvas id="graphCanvas" class="w-full h-full block"></canvas>
122
+
123
+ <!-- FLOATING LEGEND -->
124
+ <div class="absolute bottom-5 left-5 glass-panel p-3 rounded-2xl text-xs space-y-1.5 pointer-events-auto">
125
+ <div class="text-[10px] font-mono text-slate-400 uppercase tracking-wider font-semibold">Legenda Semântica</div>
126
+ <div class="grid grid-cols-2 gap-x-4 gap-y-1 text-slate-300 text-[11px]">
127
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-blue-500"></span> <span>Papel de Agente</span></div>
128
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-red-500"></span> <span>Restrição Rígida (Gate)</span></div>
129
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-yellow-400"></span> <span>Heurística (When/Then)</span></div>
130
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-emerald-500"></span> <span>Princípio Decisório</span></div>
131
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-cyan-400"></span> <span>Caso Causal</span></div>
132
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-orange-500"></span> <span>Vault de Marca</span></div>
133
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full" style="background:#F8FAFC"></span> <span>Organização</span></div>
134
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full" style="background:#94A3B8"></span> <span>Projeto</span></div>
135
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full" style="background:#14B8A6"></span> <span>Produto</span></div>
136
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-pink-500"></span> <span>Job Real (Azure)</span></div>
137
+ <div class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-sky-500"></span> <span>Origem Cloud</span></div>
138
+ </div>
139
+ <div class="pt-1 border-t border-slate-800 text-[10px] text-slate-500 font-mono flex items-center justify-between">
140
+ <span>Partículas: Fluxo de Tokens</span>
141
+ <span class="text-emerald-400">Azure Telemetry Ingested</span>
142
+ </div>
143
+ </div>
144
+
145
+ <!-- INSPECTION DRAWER -->
146
+ <div id="inspectorDrawer" class="absolute top-4 right-4 bottom-4 w-96 glass-panel rounded-2xl p-5 shadow-2xl flex flex-col z-30 transform translate-x-[420px] transition-transform duration-300 ease-out">
147
+ <div class="flex items-center justify-between pb-3 border-b border-slate-800">
148
+ <div class="flex items-center gap-2">
149
+ <span id="drawerBadge" class="text-[10px] font-mono uppercase px-2 py-0.5 rounded font-bold">TIPO</span>
150
+ <h2 id="drawerTitle" class="text-sm font-bold text-white truncate max-w-[200px]">Título</h2>
151
+ </div>
152
+ <button onclick="closeDrawer()" class="text-slate-400 hover:text-white text-lg">&times;</button>
153
+ </div>
154
+
155
+ <div id="drawerBody" class="flex-1 overflow-y-auto py-4 space-y-4 text-xs text-slate-300"></div>
156
+
157
+ <div class="pt-3 border-t border-slate-800 flex gap-2">
158
+ <button onclick="simulateJitForSelected()" class="w-full bg-blue-600 hover:bg-blue-500 text-white font-medium py-2 rounded-xl text-xs transition-all flex items-center justify-center gap-2 shadow-lg shadow-blue-600/30">
159
+ ⚡ Simular Resolução JIT (Pareto)
160
+ </button>
161
+ </div>
162
+ </div>
163
+
164
+ <!-- INTERACTIVE LINTER MODAL -->
165
+ <div id="linterModal" class="hidden absolute top-16 right-4 w-[460px] glass-panel rounded-2xl p-5 shadow-2xl z-40 border border-slate-700/80 space-y-4">
166
+ <div class="flex items-center justify-between pb-2 border-b border-slate-800">
167
+ <div class="flex items-center gap-2">
168
+ <span class="text-base">🧪</span>
169
+ <h3 class="text-sm font-bold text-white">Linter Interativo de Gates</h3>
170
+ </div>
171
+ <button onclick="toggleLinterModal()" class="text-slate-400 hover:text-white text-lg">&times;</button>
172
+ </div>
173
+
174
+ <div class="space-y-3">
175
+ <div>
176
+ <label class="text-[11px] font-mono text-slate-400 block mb-1">Selecione o Estágio:</label>
177
+ <div class="flex gap-2">
178
+ <button onclick="setLinterStage('roteiro')" id="btnStageRoteiro" class="flex-1 py-1.5 rounded-lg text-xs font-medium bg-blue-600 text-white">Roteiro (Texto)</button>
179
+ <button onclick="setLinterStage('construcao_3d')" id="btnStage3D" class="flex-1 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-slate-300">Script 3D (Blender)</button>
180
+ </div>
181
+ </div>
182
+
183
+ <!-- Quick Presets -->
184
+ <div>
185
+ <label class="text-[10px] font-mono text-slate-500 block mb-1">Exemplos Rápidos de Teste:</label>
186
+ <div class="grid grid-cols-2 gap-1.5">
187
+ <button onclick="loadLinterPreset('roteiro_valido')" class="p-1 rounded bg-slate-800/80 hover:bg-slate-700 text-[10px] text-slate-300 truncate">✅ Roteiro Válido</button>
188
+ <button onclick="loadLinterPreset('roteiro_invalido')" class="p-1 rounded bg-red-950/40 hover:bg-red-900/40 border border-red-800/40 text-[10px] text-red-300 truncate">❌ Citação Comercial (Ozempic)</button>
189
+ <button onclick="loadLinterPreset('blender_valido')" class="p-1 rounded bg-slate-800/80 hover:bg-slate-700 text-[10px] text-slate-300 truncate">✅ 3D: za_baked + cam_dist</button>
190
+ <button onclick="loadLinterPreset('blender_invalido')" class="p-1 rounded bg-red-950/40 hover:bg-red-900/40 border border-red-800/40 text-[10px] text-red-300 truncate">❌ 3D: obj.scale Proibido</button>
191
+ </div>
192
+ </div>
193
+
194
+ <div>
195
+ <label class="text-[11px] font-mono text-slate-400 block mb-1">Conteúdo do Draft / Código:</label>
196
+ <textarea id="linterDraftText" rows="4" class="w-full bg-slate-900/90 text-xs font-mono text-slate-200 p-2.5 rounded-xl border border-slate-700 focus:outline-none focus:border-red-500"></textarea>
197
+ </div>
198
+
199
+ <button onclick="runGateVerification()" class="w-full bg-red-600 hover:bg-red-500 text-white font-medium py-2 rounded-xl text-xs transition-all flex items-center justify-center gap-2 shadow-lg shadow-red-600/30">
200
+ ⚡ Avaliar no Grafo
201
+ </button>
202
+
203
+ <div id="linterResult" class="hidden text-xs rounded-xl p-3 space-y-1.5"></div>
204
+ </div>
205
+ </div>
206
+
207
+ <!-- RULE CREATOR MODAL -->
208
+ <div id="ruleCreatorModal" class="hidden absolute top-20 left-1/2 transform -translate-x-1/2 w-[480px] glass-panel rounded-2xl p-6 shadow-2xl z-40 border border-slate-700 space-y-4">
209
+ <div class="flex items-center justify-between pb-2 border-b border-slate-800">
210
+ <div class="flex items-center gap-2">
211
+ <span class="text-base">➕</span>
212
+ <h3 class="text-sm font-bold text-white">Criar Nova Regra no Grafo</h3>
213
+ </div>
214
+ <button onclick="closeRuleCreatorModal()" class="text-slate-400 hover:text-white text-lg">&times;</button>
215
+ </div>
216
+
217
+ <div class="space-y-3 text-xs">
218
+ <div>
219
+ <label class="text-[11px] font-mono text-slate-400 block mb-1">Tipo de Regra:</label>
220
+ <select id="newRuleType" class="w-full bg-slate-900 border border-slate-700 text-slate-200 p-2 rounded-lg font-mono">
221
+ <option value="constraint">🛑 Restrição Rígida (Gate Candidate)</option>
222
+ <option value="heuristic">💡 Heurística Operacional (When/Then)</option>
223
+ <option value="principle">🟢 Princípio Decisório Central</option>
224
+ </select>
225
+ </div>
226
+
227
+ <div>
228
+ <label class="text-[11px] font-mono text-slate-400 block mb-1">Identificador Único (ID):</label>
229
+ <input type="text" id="newRuleId" placeholder="ex: AC-ED-NOVA-REGRA ou AH-3D-LIGHTING" class="w-full bg-slate-900 border border-slate-700 text-slate-200 p-2 rounded-lg font-mono">
230
+ </div>
231
+
232
+ <div>
233
+ <label class="text-[11px] font-mono text-slate-400 block mb-1">Papéis-Alvo (separados por vírgula):</label>
234
+ <input type="text" id="newRuleRoles" value="roteirista, construtor_3d" class="w-full bg-slate-900 border border-slate-700 text-slate-200 p-2 rounded-lg font-mono">
235
+ </div>
236
+
237
+ <div>
238
+ <label class="text-[11px] font-mono text-slate-400 block mb-1">Enunciado da Regra / Condição:</label>
239
+ <textarea id="newRuleContent" rows="3" placeholder="Descreva a restrição imperativa ou a heurística operacional..." class="w-full bg-slate-900 border border-slate-700 text-slate-200 p-2 rounded-lg"></textarea>
240
+ </div>
241
+
242
+ <button onclick="submitNewRule()" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-medium py-2.5 rounded-xl text-xs transition-all flex items-center justify-center gap-2 shadow-lg shadow-emerald-600/30">
243
+ Salvar Regra e Injetar no Grafo
244
+ </button>
245
+ </div>
246
+ </div>
247
+
248
+ <!-- TOAST NOTIFICATION -->
249
+ <div id="toastNotification" class="hidden absolute top-16 left-1/2 transform -translate-x-1/2 glass-panel border border-emerald-500/40 text-emerald-300 px-4 py-2 rounded-xl text-xs font-mono shadow-2xl z-50 flex items-center gap-2">
250
+ <span class="w-2 h-2 rounded-full bg-emerald-400 animate-ping"></span>
251
+ <span id="toastMessage">Operação realizada com sucesso!</span>
252
+ </div>
253
+ </main>
254
+
255
+ <script>
256
+ const canvas = document.getElementById('graphCanvas');
257
+ const ctx = canvas.getContext('2d');
258
+
259
+ let graphData = { nodes: [], links: [], stats: {} };
260
+ let activeRoleLens = null;
261
+ let selectedNode = null;
262
+ let hoveredNode = null;
263
+ let physicsRunning = true;
264
+ let searchQuery = '';
265
+ let linterStage = 'roteiro';
266
+ let verifiedNodeStatuses = {};
267
+ let isLooping = false;
268
+
269
+ // Neural Synapse Particles
270
+ let particles = [];
271
+ const MAX_PARTICLES = 30;
272
+
273
+ // Camera view transform
274
+ let camera = { x: 0, y: 0, zoom: 1 };
275
+ let isDragging = false;
276
+ let dragStart = { x: 0, y: 0 };
277
+ let draggedNode = null;
278
+
279
+ function resize() {
280
+ canvas.width = window.innerWidth;
281
+ const topo = (document.querySelector('header')?.offsetHeight || 52) + (document.getElementById('scopeBar')?.offsetHeight || 0);
282
+ canvas.height = window.innerHeight - topo;
283
+ }
284
+ window.addEventListener('resize', resize);
285
+
286
+ // ===== Timeline (simulação de construção, estilo Obsidian) =====
287
+ let fullGraph = null; // grafo completo vindo da API
288
+ let timelineOrder = []; // nós ordenados por created_at
289
+ let timelineIndex = -1; // -1 = timeline desligada (mostra tudo)
290
+ let timelinePlaying = false;
291
+ let timelineTimer = null;
292
+ const TIMELINE_STEP_MS = 450;
293
+
294
+ const TYPE_ORDER = ['organization', 'project', 'product', 'stack', 'tenant', 'role', 'principle', 'constraint', 'heuristic', 'experience', 'telemetry_source', 'production_job'];
295
+ function typeRank(n) { const i = TYPE_ORDER.indexOf(n.type); return i < 0 ? 99 : i; }
296
+
297
+ function buildTimelineOrder() {
298
+ timelineOrder = fullGraph.nodes.slice().sort((a, b) =>
299
+ (a.created_at || '').localeCompare(b.created_at || '') || typeRank(a) - typeRank(b) || a.id.localeCompare(b.id));
300
+ const slider = document.getElementById('timelineSlider');
301
+ slider.max = Math.max(0, timelineOrder.length - 1);
302
+ if (timelineIndex < 0) slider.value = slider.max;
303
+ }
304
+
305
+ function applyTimeline(spawnNew = true) {
306
+ if (!fullGraph) return;
307
+ if (timelineIndex < 0) {
308
+ graphData.nodes = fullGraph.nodes;
309
+ graphData.links = fullGraph.links;
310
+ } else {
311
+ const visible = new Set(timelineOrder.slice(0, timelineIndex + 1).map(n => n.id));
312
+ const prev = new Set(graphData.nodes.map(n => n.id));
313
+ graphData.nodes = fullGraph.nodes.filter(n => visible.has(n.id));
314
+ graphData.links = fullGraph.links.filter(l => visible.has(l.source) && visible.has(l.target));
315
+ if (spawnNew) {
316
+ graphData.nodes.forEach(n => {
317
+ if (prev.has(n.id)) return;
318
+ // nasce ao lado de um vizinho já visível
319
+ const link = graphData.links.find(l => (l.source === n.id && prev.has(l.target)) || (l.target === n.id && prev.has(l.source)));
320
+ const nbId = link ? (link.source === n.id ? link.target : link.source) : null;
321
+ const nb = nbId && graphData.nodes.find(x => x.id === nbId);
322
+ const bx = nb ? nb.x : canvas.width / 2, by = nb ? nb.y : canvas.height / 2;
323
+ n.x = bx + (Math.random() - 0.5) * 40;
324
+ n.y = by + (Math.random() - 0.5) * 40;
325
+ n.vx = 0; n.vy = 0;
326
+ n._bornAt = performance.now();
327
+ });
328
+ }
329
+ }
330
+ graphData.stats = fullGraph.stats;
331
+ initParticles();
332
+ updateTimelineLabel();
333
+ }
334
+
335
+ function updateTimelineLabel() {
336
+ const label = document.getElementById('timelineLabel');
337
+ const slider = document.getElementById('timelineSlider');
338
+ if (timelineIndex < 0) {
339
+ slider.value = slider.max;
340
+ label.textContent = `Completo · ${fullGraph.nodes.length} nós`;
341
+ return;
342
+ }
343
+ slider.value = timelineIndex;
344
+ const n = timelineOrder[timelineIndex];
345
+ const d = n && n.created_at ? new Date(n.created_at) : null;
346
+ const when = d ? d.toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' }) : '?';
347
+ const inferred = n && n.created_at_source === 'inferred' ? ' (origem inferida)' : '';
348
+ label.textContent = `${timelineIndex + 1}/${timelineOrder.length} · ${when}${inferred} · ${n ? n.name : ''}`;
349
+ }
350
+
351
+ function timelineSeek(i) {
352
+ stopTimelinePlay();
353
+ const idx = parseInt(i, 10);
354
+ timelineIndex = idx >= timelineOrder.length - 1 ? -1 : idx;
355
+ applyTimeline(true);
356
+ }
357
+
358
+ function stopTimelinePlay() {
359
+ timelinePlaying = false;
360
+ clearInterval(timelineTimer);
361
+ document.getElementById('timelinePlay').textContent = '▶';
362
+ }
363
+
364
+ function toggleTimelinePlay() {
365
+ if (timelinePlaying) return stopTimelinePlay();
366
+ if (timelineIndex < 0 || timelineIndex >= timelineOrder.length - 1) {
367
+ timelineIndex = 0;
368
+ graphData.nodes = [];
369
+ applyTimeline(true);
370
+ fitToScreen();
371
+ }
372
+ timelinePlaying = true;
373
+ physicsRunning = true;
374
+ document.getElementById('timelinePlay').textContent = '⏸';
375
+ timelineTimer = setInterval(() => {
376
+ if (timelineIndex >= timelineOrder.length - 1) {
377
+ stopTimelinePlay();
378
+ timelineIndex = -1;
379
+ applyTimeline(false);
380
+ return;
381
+ }
382
+ timelineIndex++;
383
+ applyTimeline(true);
384
+ }, TIMELINE_STEP_MS);
385
+ }
386
+
387
+ // ---- Escopo do portfólio (organização › projeto › produto), espelhado na URL (?org=&project=&product=) ----
388
+ const initialParams = new URLSearchParams(location.search);
389
+ let scope = {
390
+ org: initialParams.get('org') || initialParams.get('organization') || '',
391
+ project: initialParams.get('project') || '',
392
+ product: initialParams.get('product') || '',
393
+ };
394
+ let catalogFacets = [];
395
+ const escHtml = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
396
+
397
+ function fillSelect(el, placeholder, items, value) {
398
+ el.innerHTML = `<option value="">${placeholder}</option>` +
399
+ items.map(i => `<option value="${escHtml(i.id)}" ${i.id === value ? 'selected' : ''}>${escHtml(i.name)}</option>`).join('');
400
+ el.disabled = items.length === 0;
401
+ }
402
+
403
+ function renderScopeBar() {
404
+ const org = catalogFacets.find(o => o.id === scope.org);
405
+ const projects = org ? org.projects : catalogFacets.flatMap(o => o.projects.map(p => ({ ...p, name: `${o.name} › ${p.name}`, _org: o.id })));
406
+ const project = (org ? org.projects : []).find(p => p.id === scope.project);
407
+ const products = project ? project.products
408
+ : (org ? org.projects.flatMap(p => p.products.map(d => ({ ...d, name: `${p.name} › ${d.name}`, _project: p.id }))) : []);
409
+ fillSelect(document.getElementById('scopeOrg'), 'Todas as organizações', catalogFacets, scope.org);
410
+ fillSelect(document.getElementById('scopeProject'), org ? 'Todos os projetos' : 'Todos os projetos (escolha a organização)', org ? projects : [], scope.project);
411
+ fillSelect(document.getElementById('scopeProduct'), project ? 'Todos os produtos' : 'Todos os produtos (escolha o projeto)', project ? products : [], scope.product);
412
+ const s = fullGraph?.stats || {};
413
+ document.getElementById('scopeInfo').textContent = catalogFacets.length
414
+ ? `${s.organizations_count || 0} orgs · ${s.projects_count || 0} projetos · ${s.products_count || 0} produtos · ${s.visible_nodes ?? 0}/${s.total_nodes || 0} nós visíveis`
415
+ : 'Catálogo Synap-se não encontrado (~/.synap-se/catalogo.json)';
416
+ }
417
+
418
+ function syncScopeUrl() {
419
+ const p = new URLSearchParams(location.search);
420
+ ['org', 'organization', 'project', 'product'].forEach(k => p.delete(k));
421
+ if (scope.org) p.set('org', scope.org);
422
+ if (scope.project) p.set('project', scope.project);
423
+ if (scope.product) p.set('product', scope.product);
424
+ const qs = p.toString();
425
+ history.replaceState(null, '', location.pathname + (qs ? `?${qs}` : ''));
426
+ }
427
+
428
+ function onScopeChange(level) {
429
+ const v = (id) => document.getElementById(id).value;
430
+ if (level === 'org') scope = { org: v('scopeOrg'), project: '', product: '' };
431
+ if (level === 'project') scope = { ...scope, project: v('scopeProject'), product: '' };
432
+ if (level === 'product') scope = { ...scope, product: v('scopeProduct') };
433
+ syncScopeUrl();
434
+ closeDrawer && closeDrawer();
435
+ loadGraphData(activeRoleLens);
436
+ }
437
+
438
+ function clearScope() {
439
+ scope = { org: '', project: '', product: '' };
440
+ syncScopeUrl();
441
+ loadGraphData(activeRoleLens);
442
+ }
443
+
444
+ async function loadGraphData(role = null) {
445
+ const params = new URLSearchParams();
446
+ if (role) params.set('role', role);
447
+ if (scope.org) params.set('organization', scope.org);
448
+ if (scope.org && scope.project) params.set('project', scope.project);
449
+ if (scope.org && scope.project && scope.product) params.set('product', scope.product);
450
+ const qs = params.toString();
451
+ const url = qs ? `/api/v1/graph?${qs}` : '/api/v1/graph';
452
+ try {
453
+ const res = await fetch(url);
454
+ fullGraph = await res.json();
455
+ catalogFacets = fullGraph.catalog || [];
456
+ renderScopeBar();
457
+ graphData = { ...fullGraph, nodes: fullGraph.nodes, links: fullGraph.links };
458
+ buildTimelineOrder();
459
+ if (timelineIndex >= 0) applyTimeline(false);
460
+ else updateTimelineLabel();
461
+ updateStats();
462
+ initPositions();
463
+ initParticles();
464
+ fitToScreen();
465
+ } catch (err) {
466
+ console.error('Falha ao carregar grafo:', err);
467
+ }
468
+ }
469
+
470
+ function updateStats() {
471
+ const s = graphData.stats || {};
472
+ document.getElementById('statsBar').innerHTML = `
473
+ <span><b>${s.total_nodes || 0}</b> Nós</span>
474
+ <span><b>${s.total_links || 0}</b> Sinapses</span>
475
+ <span><b>${s.constraints_count || 0}</b> Restrições</span>
476
+ <span><b>${s.heuristics_count || 0}</b> Heurísticas</span>
477
+ <span class="text-pink-400 font-semibold"><b>${s.azure_jobs_count || 0}</b> Jobs Azure</span>
478
+ <span class="text-emerald-400 font-semibold"><b>${s.azure_events_count || 0}</b> Eventos Ingeridos</span>
479
+ `;
480
+ }
481
+
482
+ function initPositions() {
483
+ const cx = canvas.width / 2;
484
+ const cy = canvas.height / 2;
485
+
486
+ graphData.nodes.forEach((node, i) => {
487
+ if (node.x === undefined || isNaN(node.x) || Math.abs(node.x) > 5000) {
488
+ const angle = (i / Math.max(1, graphData.nodes.length)) * Math.PI * 2;
489
+ const radius = 120 + (i % 3) * 60;
490
+ node.x = cx + Math.cos(angle) * radius;
491
+ node.y = cy + Math.sin(angle) * radius;
492
+ node.vx = 0;
493
+ node.vy = 0;
494
+ }
495
+ });
496
+ }
497
+
498
+ function initParticles() {
499
+ particles = [];
500
+ const linkCount = graphData.links.length;
501
+ if (linkCount === 0) return;
502
+ for (let i = 0; i < MAX_PARTICLES; i++) {
503
+ particles.push({
504
+ linkIndex: Math.floor(Math.random() * linkCount),
505
+ progress: Math.random(),
506
+ speed: 0.006 + Math.random() * 0.012,
507
+ });
508
+ }
509
+ }
510
+
511
+ function fitToScreen() {
512
+ const nodes = graphData.nodes;
513
+ if (!nodes || nodes.length === 0) return;
514
+
515
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
516
+ nodes.forEach(n => {
517
+ if (isNaN(n.x) || isNaN(n.y)) return;
518
+ if (n.x < minX) minX = n.x;
519
+ if (n.x > maxX) maxX = n.x;
520
+ if (n.y < minY) minY = n.y;
521
+ if (n.y > maxY) maxY = n.y;
522
+ });
523
+
524
+ if (!isFinite(minX) || !isFinite(maxX)) return;
525
+
526
+ const graphCenterX = (minX + maxX) / 2;
527
+ const graphCenterY = (minY + maxY) / 2;
528
+ const graphWidth = Math.max(300, maxX - minX + 160);
529
+ const graphHeight = Math.max(300, maxY - minY + 160);
530
+
531
+ const scaleX = (canvas.width * 0.82) / graphWidth;
532
+ const scaleY = (canvas.height * 0.82) / graphHeight;
533
+ const targetZoom = Math.max(0.4, Math.min(1.4, Math.min(scaleX, scaleY)));
534
+
535
+ camera.zoom = targetZoom;
536
+ camera.x = canvas.width / 2 - graphCenterX * targetZoom;
537
+ camera.y = canvas.height / 2 - graphCenterY * targetZoom;
538
+ }
539
+
540
+ // Force simulation physics (Stable, bounded, action-reaction)
541
+ function stepPhysics() {
542
+ if (!physicsRunning) return;
543
+
544
+ const nodes = graphData.nodes;
545
+ const links = graphData.links;
546
+ if (!nodes || nodes.length === 0) return;
547
+
548
+ const kRepel = 1200;
549
+ const kAttract = 0.015;
550
+ const damping = 0.85;
551
+ const maxVelocity = 8;
552
+ const cx = canvas.width / 2;
553
+ const cy = canvas.height / 2;
554
+
555
+ // 1. Repulsion between node pairs
556
+ for (let i = 0; i < nodes.length; i++) {
557
+ for (let j = i + 1; j < nodes.length; j++) {
558
+ const a = nodes[i];
559
+ const b = nodes[j];
560
+ const dx = b.x - a.x;
561
+ const dy = b.y - a.y;
562
+ const distSq = Math.max(100, dx * dx + dy * dy);
563
+ const dist = Math.sqrt(distSq);
564
+ const force = Math.min(15, kRepel / distSq);
565
+
566
+ const fx = (dx / dist) * force;
567
+ const fy = (dy / dist) * force;
568
+
569
+ a.vx -= fx;
570
+ a.vy -= fy;
571
+ b.vx += fx;
572
+ b.vy += fy;
573
+ }
574
+ }
575
+
576
+ // 2. Attraction along links (Equal and Opposite Reaction)
577
+ links.forEach(link => {
578
+ const a = typeof link.source === 'object' ? link.source : nodes.find(n => n.id === link.source);
579
+ const b = typeof link.target === 'object' ? link.target : nodes.find(n => n.id === link.target);
580
+ if (a && b) {
581
+ const dx = b.x - a.x;
582
+ const dy = b.y - a.y;
583
+ const dist = Math.sqrt(dx * dx + dy * dy) || 1;
584
+ const targetDist = 110;
585
+ const force = Math.max(-10, Math.min(10, (dist - targetDist) * kAttract));
586
+
587
+ const fx = (dx / dist) * force;
588
+ const fy = (dy / dist) * force;
589
+
590
+ a.vx += fx;
591
+ a.vy += fy;
592
+ b.vx -= fx; // Action-reaction
593
+ b.vy -= fy;
594
+ }
595
+ });
596
+
597
+ // 3. Center gravity & velocity integration with strict sanity bounds
598
+ nodes.forEach(node => {
599
+ if (node === draggedNode) return;
600
+
601
+ // Auto-heal runaway nodes
602
+ if (isNaN(node.x) || isNaN(node.y) || Math.abs(node.x) > 8000 || Math.abs(node.y) > 8000) {
603
+ node.x = cx + (Math.random() - 0.5) * 150;
604
+ node.y = cy + (Math.random() - 0.5) * 150;
605
+ node.vx = 0;
606
+ node.vy = 0;
607
+ }
608
+
609
+ node.vx += (cx - node.x) * 0.002;
610
+ node.vy += (cy - node.y) * 0.002;
611
+
612
+ node.vx *= damping;
613
+ node.vy *= damping;
614
+
615
+ // Clamp velocity to avoid instability
616
+ node.vx = Math.max(-maxVelocity, Math.min(maxVelocity, node.vx));
617
+ node.vy = Math.max(-maxVelocity, Math.min(maxVelocity, node.vy));
618
+
619
+ node.x += node.vx;
620
+ node.y += node.vy;
621
+ });
622
+ }
623
+
624
+ function drawGrid() {
625
+ ctx.save();
626
+ const gridSize = 40;
627
+ const startX = -camera.x / camera.zoom;
628
+ const startY = -camera.y / camera.zoom;
629
+ const endX = startX + canvas.width / camera.zoom;
630
+ const endY = startY + canvas.height / camera.zoom;
631
+
632
+ ctx.strokeStyle = 'rgba(255, 255, 255, 0.03)';
633
+ ctx.lineWidth = 1 / camera.zoom;
634
+
635
+ const firstX = Math.floor(startX / gridSize) * gridSize;
636
+ const firstY = Math.floor(startY / gridSize) * gridSize;
637
+
638
+ ctx.beginPath();
639
+ for (let x = firstX; x <= endX; x += gridSize) {
640
+ ctx.moveTo(x, startY);
641
+ ctx.lineTo(x, endY);
642
+ }
643
+ for (let y = firstY; y <= endY; y += gridSize) {
644
+ ctx.moveTo(startX, y);
645
+ ctx.lineTo(endX, y);
646
+ }
647
+ ctx.stroke();
648
+ ctx.restore();
649
+ }
650
+
651
+ function draw() {
652
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
653
+
654
+ ctx.save();
655
+ ctx.translate(camera.x, camera.y);
656
+ ctx.scale(camera.zoom, camera.zoom);
657
+
658
+ drawGrid();
659
+
660
+ const nodes = graphData.nodes;
661
+ const links = graphData.links;
662
+
663
+ // 1. Draw Links
664
+ links.forEach(link => {
665
+ const a = typeof link.source === 'object' ? link.source : nodes.find(n => n.id === link.source);
666
+ const b = typeof link.target === 'object' ? link.target : nodes.find(n => n.id === link.target);
667
+ if (!a || !b) return;
668
+
669
+ const isHighlighted = (hoveredNode && (hoveredNode.id === a.id || hoveredNode.id === b.id));
670
+ const opacity = link.opacity !== undefined ? link.opacity : (isHighlighted ? 0.9 : 0.28);
671
+
672
+ ctx.beginPath();
673
+ ctx.moveTo(a.x, a.y);
674
+ ctx.lineTo(b.x, b.y);
675
+ ctx.strokeStyle = isHighlighted ? '#60A5FA' : `rgba(148, 163, 184, ${opacity})`;
676
+ ctx.lineWidth = isHighlighted ? 2.5 : 1.2;
677
+ ctx.stroke();
678
+ });
679
+
680
+ // 2. Draw Synapse Particles (Token Flow)
681
+ if (links.length > 0 && particles.length > 0) {
682
+ particles.forEach(p => {
683
+ p.progress += p.speed;
684
+ if (p.progress >= 1) {
685
+ p.progress = 0;
686
+ p.linkIndex = Math.floor(Math.random() * links.length);
687
+ }
688
+
689
+ const link = links[p.linkIndex];
690
+ if (!link) return;
691
+ const a = typeof link.source === 'object' ? link.source : nodes.find(n => n.id === link.source);
692
+ const b = typeof link.target === 'object' ? link.target : nodes.find(n => n.id === link.target);
693
+ if (!a || !b) return;
694
+
695
+ const px = a.x + (b.x - a.x) * p.progress;
696
+ const py = a.y + (b.y - a.y) * p.progress;
697
+
698
+ ctx.beginPath();
699
+ ctx.arc(px, py, 2.5, 0, Math.PI * 2);
700
+ ctx.fillStyle = activeRoleLens ? '#60A5FA' : '#38BDF8';
701
+ ctx.fill();
702
+ });
703
+ }
704
+
705
+ // 3. Draw Nodes
706
+ nodes.forEach(node => {
707
+ const isHovered = hoveredNode && hoveredNode.id === node.id;
708
+ const isSelected = selectedNode && selectedNode.id === node.id;
709
+ const isSearchMatch = searchQuery && node.name.toLowerCase().includes(searchQuery.toLowerCase());
710
+ const opacity = node.opacity !== undefined ? node.opacity : 1.0;
711
+ const verified = verifiedNodeStatuses[node.id];
712
+
713
+ ctx.save();
714
+ ctx.globalAlpha = opacity;
715
+
716
+ let radius = (node.val || 16);
717
+ if (node._bornAt) {
718
+ const t = Math.min(1, (performance.now() - node._bornAt) / 400);
719
+ if (t >= 1) node._bornAt = null;
720
+ radius *= 1 - Math.pow(1 - t, 3) + Math.sin(t * Math.PI) * 0.25; // pop-in
721
+ ctx.globalAlpha = opacity * t;
722
+ }
723
+
724
+ // Pulsing hazard ring on gate violation
725
+ if (verified && verified.status === 'violated') {
726
+ ctx.beginPath();
727
+ ctx.arc(node.x, node.y, radius + 12, 0, Math.PI * 2);
728
+ ctx.fillStyle = 'rgba(239, 68, 68, 0.45)';
729
+ ctx.fill();
730
+ ctx.lineWidth = 2.5;
731
+ ctx.strokeStyle = '#EF4444';
732
+ ctx.stroke();
733
+ } else if (isSelected || isHovered || isSearchMatch) {
734
+ ctx.beginPath();
735
+ ctx.arc(node.x, node.y, radius + 8, 0, Math.PI * 2);
736
+ ctx.fillStyle = node.color ? `${node.color}44` : 'rgba(59, 130, 246, 0.3)';
737
+ ctx.fill();
738
+ }
739
+
740
+ // Node Body
741
+ ctx.beginPath();
742
+ ctx.arc(node.x, node.y, radius, 0, Math.PI * 2);
743
+ ctx.fillStyle = (verified && verified.status === 'violated') ? '#EF4444' : (node.color || '#3B82F6');
744
+ ctx.fill();
745
+ ctx.lineWidth = isSelected ? 3 : 1.8;
746
+ ctx.strokeStyle = (verified && verified.status === 'violated') ? '#FEE2E2' : (isSelected ? '#FFFFFF' : '#0B0F19');
747
+ ctx.stroke();
748
+
749
+ // Node Label
750
+ ctx.font = 'bold 11px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
751
+ ctx.fillStyle = opacity < 0.5 ? '#64748B' : '#F8FAFC';
752
+ ctx.textAlign = 'center';
753
+ ctx.fillText(node.label || node.name, node.x, node.y + radius + 14);
754
+
755
+ // Warning Badge if violated
756
+ if (verified && verified.status === 'violated') {
757
+ ctx.font = 'bold 9px monospace';
758
+ ctx.fillStyle = '#EF4444';
759
+ ctx.fillText(`⚠️ VIOLADO`, node.x, node.y - radius - 6);
760
+ }
761
+
762
+ ctx.restore();
763
+ });
764
+
765
+ ctx.restore();
766
+ }
767
+
768
+ function animLoop() {
769
+ draw();
770
+ stepPhysics();
771
+ requestAnimationFrame(animLoop);
772
+ }
773
+
774
+ // Camera and interaction
775
+ canvas.addEventListener('mousedown', e => {
776
+ const rect = canvas.getBoundingClientRect();
777
+ const mouseX = (e.clientX - rect.left - camera.x) / camera.zoom;
778
+ const mouseY = (e.clientY - rect.top - camera.y) / camera.zoom;
779
+
780
+ const clicked = graphData.nodes.find(n => {
781
+ const dx = n.x - mouseX;
782
+ const dy = n.y - mouseY;
783
+ return Math.sqrt(dx * dx + dy * dy) <= (n.val || 14) + 6;
784
+ });
785
+
786
+ if (clicked) {
787
+ draggedNode = clicked;
788
+ selectNode(clicked);
789
+ } else {
790
+ isDragging = true;
791
+ dragStart = { x: e.clientX - camera.x, y: e.clientY - camera.y };
792
+ }
793
+ });
794
+
795
+ window.addEventListener('mousemove', e => {
796
+ if (draggedNode) {
797
+ const rect = canvas.getBoundingClientRect();
798
+ draggedNode.x = (e.clientX - rect.left - camera.x) / camera.zoom;
799
+ draggedNode.y = (e.clientY - rect.top - camera.y) / camera.zoom;
800
+ } else if (isDragging) {
801
+ camera.x = e.clientX - dragStart.x;
802
+ camera.y = e.clientY - dragStart.y;
803
+ } else {
804
+ const rect = canvas.getBoundingClientRect();
805
+ const mouseX = (e.clientX - rect.left - camera.x) / camera.zoom;
806
+ const mouseY = (e.clientY - rect.top - camera.y) / camera.zoom;
807
+
808
+ hoveredNode = graphData.nodes.find(n => {
809
+ const dx = n.x - mouseX;
810
+ const dy = n.y - mouseY;
811
+ return Math.sqrt(dx * dx + dy * dy) <= (n.val || 14) + 6;
812
+ }) || null;
813
+ }
814
+ });
815
+
816
+ window.addEventListener('mouseup', () => {
817
+ isDragging = false;
818
+ draggedNode = null;
819
+ });
820
+
821
+ canvas.addEventListener('wheel', e => {
822
+ e.preventDefault();
823
+ const zoomFactor = e.deltaY < 0 ? 1.08 : 0.92;
824
+ camera.zoom = Math.max(0.3, Math.min(3.5, camera.zoom * zoomFactor));
825
+ });
826
+
827
+ function selectNode(node) {
828
+ selectedNode = node;
829
+ const drawer = document.getElementById('inspectorDrawer');
830
+ const title = document.getElementById('drawerTitle');
831
+ const badge = document.getElementById('drawerBadge');
832
+ const body = document.getElementById('drawerBody');
833
+
834
+ drawer.classList.remove('translate-x-[420px]');
835
+ title.innerText = node.name;
836
+ badge.innerText = node.type;
837
+
838
+ let badgeBg = 'bg-blue-500/20 text-blue-400 border border-blue-500/30';
839
+ if (node.type === 'constraint') badgeBg = 'bg-red-500/20 text-red-400 border border-red-500/30';
840
+ if (node.type === 'heuristic') badgeBg = 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30';
841
+ if (node.type === 'principle') badgeBg = 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30';
842
+ if (node.type === 'tenant') badgeBg = 'bg-orange-500/20 text-orange-400 border border-orange-500/30';
843
+ if (node.type === 'production_job') badgeBg = 'bg-pink-500/20 text-pink-400 border border-pink-500/30';
844
+ if (node.type === 'telemetry_source') badgeBg = 'bg-sky-500/20 text-sky-400 border border-sky-500/30';
845
+ if (node.type === 'organization' || node.type === 'project') badgeBg = 'bg-slate-500/20 text-slate-200 border border-slate-500/30';
846
+ if (node.type === 'product') badgeBg = 'bg-teal-500/20 text-teal-300 border border-teal-500/30';
847
+ badge.className = `text-[10px] font-mono uppercase px-2 py-0.5 rounded font-bold ${badgeBg}`;
848
+
849
+ const d = node.details || {};
850
+ let html = '';
851
+
852
+ if (node.type === 'organization' || node.type === 'project' || node.type === 'product') {
853
+ const rows = Object.entries(d).filter(([k, v]) => k !== 'desc' && v !== null && v !== '' && !(Array.isArray(v) && !v.length));
854
+ html += `<div class="bg-slate-900/80 p-3 rounded-xl border border-slate-800 space-y-1.5">
855
+ <div class="text-[10px] text-teal-300 font-mono uppercase font-bold">Portfólio Synap-se</div>
856
+ ${rows.map(([k, v]) => `<div class="flex gap-2"><span class="text-slate-500 font-mono w-24 shrink-0">${escHtml(k)}</span><span class="text-slate-200">${escHtml(Array.isArray(v) ? v.join(', ') : v)}</span></div>`).join('')}
857
+ <button onclick="focusScopeFromNode()" class="mt-2 px-2.5 py-1 rounded-lg border border-teal-500/30 bg-teal-500/10 text-teal-300 text-[11px]">Filtrar o grafo por este ${node.type === 'organization' ? 'organização' : node.type === 'project' ? 'projeto' : 'produto'}</button>
858
+ </div>`;
859
+ const linkedCount = (fullGraph?.nodes || []).filter(n => !['organization', 'project', 'product'].includes(n.type) && (n.products || []).some(p => p.startsWith(node.id.replace(/^(org|project|product):/, 'product:')))).length;
860
+ html += `<p class="text-slate-400 text-[11px]">${linkedCount} nós de conhecimento vinculados.</p>`;
861
+ }
862
+
863
+ if (node.type === 'production_job') {
864
+ html += `<div class="bg-pink-950/30 border border-pink-800/40 p-3 rounded-xl space-y-2">
865
+ <div class="text-[10px] text-pink-300 font-mono font-bold uppercase">Job Real da Nuvem (Azure Container Apps)</div>
866
+ <p class="text-white font-medium text-xs leading-snug">${d.titulo || ''}</p>
867
+ <div class="text-[11px] text-slate-300 flex items-center justify-between pt-1">
868
+ <span>Status: <b class="text-emerald-400 font-mono">${d.estado || 'concluído'}</b></span>
869
+ <span>Eventos: <b class="text-white font-mono">${d.eventos_count || 0}</b></span>
870
+ </div>
871
+ <div class="text-[10px] text-slate-400 font-mono">Tenant / Cliente: <span class="text-orange-400 font-semibold">${d.cliente || 'diario_glp1'}</span></div>
872
+ </div>`;
873
+
874
+ if (Array.isArray(d.amostra_eventos) && d.amostra_eventos.length > 0) {
875
+ html += `<div class="space-y-1">
876
+ <div class="text-[10px] font-mono text-slate-400 uppercase">Trilha de Telemetria Auditada</div>
877
+ <div class="bg-slate-900/90 p-2.5 rounded-xl border border-slate-800 space-y-2 max-h-48 overflow-y-auto">`;
878
+ d.amostra_eventos.forEach(ev => {
879
+ html += `<div class="border-b border-slate-800/60 pb-1.5 last:border-0 text-[11px]">
880
+ <div class="flex items-center justify-between text-[10px] font-mono text-slate-500">
881
+ <span class="text-blue-400">@${ev.agente || 'agente'}</span>
882
+ <span>${ev.ts ? ev.ts.slice(11) : ''}</span>
883
+ </div>
884
+ <p class="text-slate-300 text-[11px] mt-0.5">${ev.resumo || ev.tipo || ''}</p>
885
+ ${ev.custo ? `<div class="text-[10px] font-mono text-yellow-400/90 mt-0.5">Modelo: ${ev.custo.modelo || ''} (${ev.custo.tokens_entrada || 0} in / ${ev.custo.tokens_saida || 0} out)</div>` : ''}
886
+ </div>`;
887
+ });
888
+ html += `</div></div>`;
889
+ }
890
+ } else if (node.type === 'telemetry_source') {
891
+ html += `<div class="bg-sky-950/30 border border-sky-800/40 p-3 rounded-xl space-y-2">
892
+ <div class="text-[10px] text-sky-300 font-mono font-bold uppercase">Origem de Telemetria em Produção</div>
893
+ <p class="text-white text-xs">${d.desc || ''}</p>
894
+ <div class="bg-black/40 p-2 rounded-lg font-mono text-[11px] text-sky-200 break-all">${d.url || ''}</div>
895
+ <div class="grid grid-cols-2 gap-2 text-[11px] text-slate-300 pt-1">
896
+ <div>Jobs na Nuvem: <b class="text-white">${d.total_azure_jobs || 0}</b></div>
897
+ <div>Eventos Ingeridos: <b class="text-emerald-400">${d.total_events_ingested || 0}</b></div>
898
+ </div>
899
+ <div class="text-[10px] text-slate-400 font-mono pt-1">Última Sincronização: ${new Date(d.synced_at || Date.now()).toLocaleTimeString()}</div>
900
+ </div>`;
901
+ } else if (node.type === 'role') {
902
+ html += `<p class="text-slate-300 leading-relaxed">${d.desc || ''}</p>`;
903
+ html += `<div class="bg-slate-900/80 p-3 rounded-xl border border-slate-800 space-y-1">
904
+ <div class="text-[10px] text-slate-500 font-mono">IDENTIFICADOR DE PAPEL</div>
905
+ <div class="font-mono text-blue-400 font-semibold">${node.role}</div>
906
+ </div>`;
907
+ } else if (node.type === 'constraint') {
908
+ html += `<div class="bg-slate-900/80 p-3 rounded-xl border border-slate-800 space-y-2">
909
+ <div class="text-[10px] text-red-400 font-mono uppercase font-bold">Enunciado da Restrição</div>
910
+ <p class="text-slate-200 text-xs leading-relaxed font-medium">${d.rule || ''}</p>
911
+ </div>`;
912
+ if (d.deterministic_gate_hint) {
913
+ html += `<div class="bg-red-950/30 border border-red-800/40 p-3 rounded-xl space-y-1">
914
+ <div class="text-[10px] text-red-300 font-mono">PORTÃO DETERMINÍSTICO (HINT)</div>
915
+ <code class="text-[11px] text-red-200 block font-mono bg-black/40 p-1.5 rounded">${d.deterministic_gate_hint}</code>
916
+ </div>`;
917
+ }
918
+ } else if (node.type === 'heuristic') {
919
+ html += `<div class="bg-slate-900/80 p-3 rounded-xl border border-slate-800 space-y-2">
920
+ <div class="text-[10px] text-yellow-400 font-mono uppercase font-bold">Condição (When)</div>
921
+ <p class="text-slate-300 text-xs">${d.when || ''}</p>
922
+ <div class="text-[10px] text-emerald-400 font-mono uppercase font-bold pt-1">Ação Prescrita (Then)</div>
923
+ <p class="text-slate-200 text-xs leading-relaxed font-medium">${d.then || ''}</p>
924
+ </div>`;
925
+ if (d.evidence_count) {
926
+ html += `<div class="text-xs text-slate-400">Comprovado em <b>${d.evidence_count}</b> execuções reais.</div>`;
927
+ }
928
+ } else if (node.type === 'experience') {
929
+ html += `<div class="bg-slate-900/80 p-3 rounded-xl border border-slate-800 space-y-2">
930
+ <div class="text-[10px] text-cyan-400 font-mono font-bold">SINTOMA</div>
931
+ <p class="text-slate-300 text-xs">${d.symptom || ''}</p>
932
+ <div class="text-[10px] text-emerald-400 font-mono font-bold pt-1">CAUSA RAIZ & ADOÇÃO</div>
933
+ <p class="text-slate-200 text-xs">${d.root_cause || ''}</p>
934
+ </div>`;
935
+ } else if (node.type === 'tenant') {
936
+ html += `<div class="bg-slate-900/80 p-3 rounded-xl border border-slate-800 space-y-2 max-h-64 overflow-y-auto">
937
+ <div class="text-[10px] text-orange-400 font-mono uppercase font-bold">Conteúdo do Vault</div>
938
+ <pre class="text-[11px] font-mono text-slate-300 whitespace-pre-wrap">${(d.content || '').slice(0, 800)}...</pre>
939
+ </div>`;
940
+ }
941
+
942
+ if (d.target_roles && d.target_roles.length > 0) {
943
+ html += `<div class="space-y-1.5">
944
+ <div class="text-[10px] font-mono text-slate-500 uppercase">Papéis-Alvo (Injeção JIT)</div>
945
+ <div class="flex flex-wrap gap-1">
946
+ ${d.target_roles.map(r => `<span class="bg-slate-800 text-slate-300 px-2 py-0.5 rounded text-[10px] font-mono">${r}</span>`).join('')}
947
+ </div>
948
+ </div>`;
949
+ }
950
+
951
+ body.innerHTML = html;
952
+ }
953
+
954
+ function closeDrawer() {
955
+ document.getElementById('inspectorDrawer').classList.add('translate-x-[420px]');
956
+ selectedNode = null;
957
+ }
958
+
959
+ function setRoleLens(role) {
960
+ activeRoleLens = role;
961
+ document.querySelectorAll('.lens-btn').forEach(btn => {
962
+ if (btn.getAttribute('data-role') === (role || '')) {
963
+ btn.className = 'lens-btn px-2.5 py-1 rounded-lg text-xs font-medium bg-blue-600 text-white transition-all shadow-sm';
964
+ } else {
965
+ btn.className = 'lens-btn px-2.5 py-1 rounded-lg text-xs font-medium text-slate-400 hover:text-white transition-all';
966
+ }
967
+ });
968
+
969
+ const meter = document.getElementById('tokenBudgetBox');
970
+ const label = document.getElementById('tokenCountLabel');
971
+ const bar = document.getElementById('tokenProgressBar');
972
+
973
+ if (role === 'roteirista') {
974
+ meter.classList.remove('hidden');
975
+ meter.classList.add('flex');
976
+ label.innerText = '164 / 600';
977
+ bar.style.width = '27%';
978
+ bar.className = 'h-full bg-emerald-500';
979
+ } else if (role === 'construtor_3d') {
980
+ meter.classList.remove('hidden');
981
+ meter.classList.add('flex');
982
+ label.innerText = '773 / 1200';
983
+ bar.style.width = '64%';
984
+ bar.className = 'h-full bg-blue-500';
985
+ } else {
986
+ meter.classList.add('hidden');
987
+ }
988
+
989
+ loadGraphData(role);
990
+ }
991
+
992
+ function focusScopeFromNode() {
993
+ const n = selectedNode;
994
+ if (!n) return;
995
+ scope = { org: n.organization || '', project: n.type !== 'organization' ? (n.project || '') : '', product: n.type === 'product' ? (n.product || '') : '' };
996
+ syncScopeUrl();
997
+ loadGraphData(activeRoleLens);
998
+ }
999
+
1000
+ function onSearch(val) {
1001
+ searchQuery = val.trim();
1002
+ }
1003
+
1004
+ function resetCamera() {
1005
+ camera = { x: 0, y: 0, zoom: 1 };
1006
+ fitToScreen();
1007
+ }
1008
+
1009
+ function togglePhysics() {
1010
+ physicsRunning = !physicsRunning;
1011
+ document.getElementById('btnPhysics').innerText = physicsRunning ? '⏸' : '▶';
1012
+ }
1013
+
1014
+ async function simulateJitForSelected() {
1015
+ if (!selectedNode) return;
1016
+ const role = selectedNode.type === 'role' ? selectedNode.role : (selectedNode.target_roles?.[0] || 'roteirista');
1017
+ const res = await fetch('/api/v1/resolve', {
1018
+ method: 'POST',
1019
+ headers: { 'Content-Type': 'application/json' },
1020
+ body: JSON.stringify({
1021
+ role,
1022
+ tenant: 'diario_glp1',
1023
+ squad: 'aquisicao',
1024
+ stacks: ['scientific_3d_stack'],
1025
+ max_tokens: role === 'construtor_3d' ? 1200 : 600
1026
+ })
1027
+ });
1028
+ const data = await res.json();
1029
+ showToast(`JIT Resolvido: ${data.token_count} tokens (SHA: ${data.digest_sha256.slice(0, 8)}...)`);
1030
+ }
1031
+
1032
+ // Linter Gate Testing
1033
+ function toggleLinterModal() {
1034
+ const modal = document.getElementById('linterModal');
1035
+ modal.classList.toggle('hidden');
1036
+ if (!modal.classList.contains('hidden')) {
1037
+ loadLinterPreset('roteiro_valido');
1038
+ }
1039
+ }
1040
+
1041
+ function setLinterStage(stage) {
1042
+ linterStage = stage;
1043
+ document.getElementById('btnStageRoteiro').className = stage === 'roteiro'
1044
+ ? 'flex-1 py-1.5 rounded-lg text-xs font-medium bg-blue-600 text-white'
1045
+ : 'flex-1 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-slate-300';
1046
+ document.getElementById('btnStage3D').className = stage === 'construcao_3d'
1047
+ ? 'flex-1 py-1.5 rounded-lg text-xs font-medium bg-blue-600 text-white'
1048
+ : 'flex-1 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-slate-300';
1049
+ }
1050
+
1051
+ function loadLinterPreset(preset) {
1052
+ const t = document.getElementById('linterDraftText');
1053
+ if (preset === 'roteiro_valido') {
1054
+ setLinterStage('roteiro');
1055
+ t.value = 'Neste episódio vamos entender como funcionam as canetas emagrecedoras de GLP-1 e sua ação no hipotálamo.';
1056
+ } else if (preset === 'roteiro_invalido') {
1057
+ setLinterStage('roteiro');
1058
+ t.value = 'As canetas como o Ozempic ajudam muito na saciedade e perda rápida de gordura.';
1059
+ } else if (preset === 'blender_valido') {
1060
+ setLinterStage('construcao_3d');
1061
+ t.value = 'stomach = za_baked("z_anatomy_digestive")\ncam_dist = 2.4\nlens = 85.0\nrender_clip(preview=True)';
1062
+ } else if (preset === 'blender_invalido') {
1063
+ setLinterStage('construcao_3d');
1064
+ t.value = 'stomach_organ = bpy.data.objects["z_anatomy_stomach"]\nstomach_organ.scale = (1.5, 1.5, 1.5)\nbpy.ops.render.render()';
1065
+ }
1066
+ }
1067
+
1068
+ async function runGateVerification() {
1069
+ const draftText = document.getElementById('linterDraftText').value;
1070
+ const draftPayload = linterStage === 'roteiro' ? { texto: draftText, titulo: draftText } : { code: draftText };
1071
+
1072
+ const res = await fetch('/api/v1/graph/verify', {
1073
+ method: 'POST',
1074
+ headers: { 'Content-Type': 'application/json' },
1075
+ body: JSON.stringify({
1076
+ stage: linterStage,
1077
+ draftPayload,
1078
+ })
1079
+ });
1080
+
1081
+ const data = await res.json();
1082
+ verifiedNodeStatuses = data.nodeStatuses || {};
1083
+
1084
+ const resultBox = document.getElementById('linterResult');
1085
+ resultBox.classList.remove('hidden');
1086
+
1087
+ if (data.passed) {
1088
+ resultBox.className = 'text-xs rounded-xl p-3 bg-emerald-950/40 border border-emerald-800 text-emerald-300 space-y-1';
1089
+ resultBox.innerHTML = `<b>✅ APROVADO NO CONTRACT GATE!</b><br>Nenhuma violação detectada. Todos os nós passaram.`;
1090
+ showToast('✅ Aprovado nos Gates!');
1091
+ } else {
1092
+ resultBox.className = 'text-xs rounded-xl p-3 bg-red-950/50 border border-red-800 text-red-200 space-y-1';
1093
+ let issuesHtml = `<b>❌ VIOLAÇÃO DETECTADA NO GRAFO (${data.issues.length}):</b><ul class="list-disc pl-4 space-y-1 mt-1">`;
1094
+ data.issues.forEach(i => {
1095
+ issuesHtml += `<li><b>[${i.id}]</b>: ${i.message}</li>`;
1096
+ });
1097
+ issuesHtml += `</ul>`;
1098
+ resultBox.innerHTML = issuesHtml;
1099
+ showToast(`❌ ${data.issues.length} violações no Grafo!`);
1100
+ }
1101
+ }
1102
+
1103
+ // Obsidian Export Trigger
1104
+ async function exportToObsidian() {
1105
+ try {
1106
+ const res = await fetch('/api/v1/graph/export/obsidian');
1107
+ const data = await res.json();
1108
+ showToast(`📂 Vault gerado: ${data.total_files} notas em store/obsidian-vault!`);
1109
+ } catch (err) {
1110
+ showToast('Erro ao exportar vault');
1111
+ }
1112
+ }
1113
+
1114
+ // Rule Creator
1115
+ function openRuleCreatorModal() {
1116
+ document.getElementById('ruleCreatorModal').classList.remove('hidden');
1117
+ }
1118
+ function closeRuleCreatorModal() {
1119
+ document.getElementById('ruleCreatorModal').classList.add('hidden');
1120
+ }
1121
+ async function submitNewRule() {
1122
+ const type = document.getElementById('newRuleType').value;
1123
+ const id = document.getElementById('newRuleId').value.trim();
1124
+ const roles = document.getElementById('newRuleRoles').value.split(',').map(r => r.trim()).filter(Boolean);
1125
+ const content = document.getElementById('newRuleContent').value.trim();
1126
+
1127
+ if (!id || !content) {
1128
+ alert('Preencha o ID e o conteúdo da regra.');
1129
+ return;
1130
+ }
1131
+
1132
+ const res = await fetch('/api/v1/graph/nodes', {
1133
+ method: 'POST',
1134
+ headers: { 'Content-Type': 'application/json' },
1135
+ body: JSON.stringify({
1136
+ type,
1137
+ id,
1138
+ rule: content,
1139
+ then: content,
1140
+ target_roles: roles,
1141
+ stack: 'scientific_3d_stack',
1142
+ })
1143
+ });
1144
+
1145
+ if (res.ok) {
1146
+ closeRuleCreatorModal();
1147
+ showToast(`Regra ${id} adicionada ao Grafo!`);
1148
+ loadGraphData(activeRoleLens);
1149
+ }
1150
+ }
1151
+
1152
+ function showToast(msg) {
1153
+ const toast = document.getElementById('toastNotification');
1154
+ const text = document.getElementById('toastMessage');
1155
+ text.innerText = msg;
1156
+ toast.classList.remove('hidden');
1157
+ setTimeout(() => {
1158
+ toast.classList.add('hidden');
1159
+ }, 3500);
1160
+ }
1161
+
1162
+ // Start
1163
+ resize();
1164
+ loadGraphData();
1165
+ animLoop();
1166
+ </script>
1167
+ </body>
1168
+ </html>