cognitivebc 0.1.0 → 0.2.1

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 +142 -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 +343 -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,503 @@
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">
6
+ <title>CognitiveBC · Grafo (Sigma.js)</title>
7
+ <link rel="icon" href="data:,">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500;600&display=swap">
10
+ <link rel="stylesheet" href="/vendor/pf-graph.css">
11
+ <script src="/vendor/cbc-auth.js"></script>
12
+ <script src="/vendor/graphology.umd.min.js"></script>
13
+ <script src="/vendor/graphology-library.min.js"></script>
14
+ <script src="/vendor/sigma.min.js"></script>
15
+ <script src="/vendor/pf-telemetry.js"></script>
16
+ <style>
17
+ body { display:flex; flex-direction:column; overflow:hidden; }
18
+ header { flex:none; flex-wrap:wrap; overflow:visible; padding:10px 14px; }
19
+ header select, header input { max-width:100%; min-width:0; }
20
+ main { position:relative; top:auto; flex:1; min-height:0; }
21
+ #stage { min-width:0; }
22
+ #cy, #hulls { bottom:64px; }
23
+ aside { flex:none; overflow-wrap:anywhere; }
24
+ .timebar input { min-width:0; }
25
+ #graph-error { position:absolute; top:16px; left:16px; right:16px; z-index:3; padding:16px; border:1px solid var(--alert); border-radius:16px; background:var(--surface); }
26
+ #graph-error button { margin-left:12px; }
27
+ @media(max-width:800px) {
28
+ aside { width:240px; padding:12px; }
29
+ .legend { grid-template-columns:1fr; }
30
+ header .brand, header .sp, #stats, header > a { display:none; }
31
+ header { gap:5px; padding:6px; }
32
+ header select, header input { max-width:155px; }
33
+ .timebar { left:6px !important; gap:5px; padding:6px; }
34
+ .timebar .when { min-width:0; }
35
+ .timebar .eyebrow, .tag { display:none; }
36
+ }
37
+ @media(max-width:520px) { main { flex-direction:column; } #stage { flex:1; min-height:180px; } aside { width:100%; height:30%; border-top:1px solid var(--line); } }
38
+ #hulls { position:absolute; inset:0; pointer-events:none; }
39
+ .zoom { position:absolute; right:16px; bottom:16px; display:flex; flex-direction:column; gap:6px; z-index:2; }
40
+ .zoom button { width:34px; height:34px; padding:0; font:500 16px var(--font-body); }
41
+ .tag { position:absolute; left:16px; bottom:16px; font:600 10px var(--font-mono); letter-spacing:.14em; text-transform:uppercase; color:var(--txt-3); z-index:2; }
42
+ </style>
43
+ </head>
44
+ <body>
45
+ <header>
46
+ <div class="brand"><svg viewBox="-107.2 -122.8 214.3 245.6" aria-hidden="true"><path d="M0,-55.87L46.89,-28.8L0,-1.73L-46.89,-28.8Z" fill="#F5F5F5"/><path d="M48.39,-26.21L1.5,0.86L1.5,55.01L48.39,27.94Z" fill="#F5F5F5"/><path d="M-1.5,0.86L-48.39,-26.21L-48.39,27.94L-1.5,55.01Z" fill="#F5F5F5"/><path d="M87.3,2.02L87.3,50.4L45.39,74.59" fill="none" stroke="#A78BFA" stroke-width="8"/><path d="M-87.3,-2.02L-87.3,-50.4L-45.39,-74.59" fill="none" stroke="#A78BFA" stroke-width="8"/></svg>
47
+ <h1>CognitiveBC <span>/ grafo</span></h1></div>
48
+ <select id="org"></select><select id="project"></select><select id="product"></select>
49
+ <select id="role"><option value="">Lente: todos os papéis</option></select>
50
+ <input id="q" placeholder="Buscar nó…" size="16">
51
+ <span class="sp"></span>
52
+ <span id="stats"></span>
53
+ <button id="hullsBtn" class="on" title="Contorno de cada produto">Produtos</button>
54
+ <button id="live" class="livebadge" title="Atualiza a cada 4 s e pulsa o que foi usado">Ao vivo</button>
55
+ <button id="relayout">Reorganizar</button>
56
+ <a id="alternate" href="/graph2" style="margin-left:6px">versão Cytoscape ↗</a>
57
+ </header>
58
+ <main>
59
+ <div id="stage">
60
+ <canvas id="hulls"></canvas>
61
+ <div id="cy"></div>
62
+ <div id="graph-error" role="alert" hidden></div>
63
+ <div class="zoom"><button id="zin">+</button><button id="zout">−</button><button id="fit" title="Enquadrar">◻</button></div>
64
+ <div class="timebar" style="left:150px"><span class="eyebrow" style="margin:0">Tempo</span><input id="time" type="range" min="0" max="1000" value="1000"><span class="when" id="when">agora</span><button id="play">▶</button></div>
65
+ <div class="tag">Sigma.js · WebGL</div>
66
+ </div>
67
+ <aside>
68
+ <div class="eyebrow">Tamanho dos nós</div><div id="sizectl"></div>
69
+ <div class="eyebrow">Tipos</div><div class="legend" id="legend"></div>
70
+ <div class="eyebrow">Detalhes</div><div id="details" class="muted">Selecione um nó para ver a regra, os vínculos e os vizinhos.</div>
71
+ <div class="eyebrow">Atividade</div><div id="telsum"></div><div id="feed"></div>
72
+ </aside>
73
+ </main>
74
+ <script>
75
+ /* Mesma linguagem visual do /graph2 (PerformacIA DS): paleta restrita, sem ícones nem emoji.
76
+ Sigma desenha círculos em WebGL; o tipo é dado pela cor e pelo tamanho, e os produtos ganham um contorno. */
77
+ const TYPES = {
78
+ organization: { n:'Organização', c:'#F5F5F5', s:9, g:'square outline' },
79
+ project: { n:'Projeto', c:'#A3A3A3', s:8, g:'square outline' },
80
+ product: { n:'Produto', c:'#A78BFA', s:11, g:'square' },
81
+ stack: { n:'Stack', c:'#7C3AED', s:10, g:'hex' },
82
+ tenant: { n:'Tenant', c:'#C4B5FD', s:8, g:'square outline' },
83
+ agent: { n:'Agente observado', c:'#A78BFA', s:9, g:'diamond' },
84
+ role: { n:'Papel', c:'#34D399', s:8, g:'diamond' },
85
+ principle: { n:'Princípio', c:'#F5F5F5', s:5, g:'round' },
86
+ constraint: { n:'Restrição', c:'#FB923C', s:5, g:'round' },
87
+ heuristic: { n:'Heurística', c:'#A3A3A3', s:5, g:'round' },
88
+ experience: { n:'Caso', c:'#A78BFA', s:5, g:'round outline' },
89
+ telemetry_source:{ n:'Fonte cloud', c:'#8A8A91', s:7, g:'square outline' },
90
+ production_job: { n:'Job', c:'#5A5A62', s:3.5,g:'round' },
91
+ };
92
+ const STRONG = new Set(['organization','project','product','stack','tenant','agent','role']);
93
+ const EDGE_LABEL = { targets_role:'cobertura explícita', executed_by:'papel observado na sessão', executed_session:'executou sessão', performs_role:'exerceu papel', contains_rule:'contém', contains_case:'caso', dispatched_job:'registrou',
94
+ product_job:'job', provides_vault:'vocabulário', has_product:'produto', uses_stack:'usa', owns_project:'projeto',
95
+ belongs_to_tenant:'tenant', product_vault:'tenant', operates_source:'opera' };
96
+ const EDGE_COLOR = { targets_role:'#1F4D3E', executed_by:'#183A30', contains_rule:'#3D2F66', contains_case:'#3D2F66', uses_stack:'#3D2F66' };
97
+ const EDGE_DEFAULT = '#26262A', EDGE_FADE = '#121215';
98
+
99
+ const $ = (id) => document.getElementById(id);
100
+ const esc = (s) => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
101
+ const params = new URLSearchParams(location.search);
102
+ let state = { org: params.get('org')||'', project: params.get('project')||'', product: params.get('product')||'',
103
+ tenant: params.get('tenant')||'', projectId: params.get('project_id')||'',
104
+ role: params.get('role')||'', hulls: params.get('hulls') !== '0' };
105
+ let hidden = new Set(), catalog = [], data = null, graph = null, renderer = null;
106
+ let focus = null, hood = null, matches = null, hover = null, loadVersion = 0;
107
+ let labelBoxes = [], hullBoxes = [], nodeObstacles = [];
108
+ const L = window.graphologyLibrary;
109
+
110
+ function isVisible(k) {
111
+ if (!graph || !graph.hasNode(k)) return false;
112
+ const a = graph.getNodeAttributes(k);
113
+ return !hidden.has(a.type_) && a.created <= timeCut;
114
+ }
115
+ const intersects = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
116
+ function shortText(ctx, text, width) {
117
+ let s = String(text).slice(0, 160);
118
+ if (ctx.measureText(s).width <= width) return s;
119
+ while (s.length && ctx.measureText(s + '…').width > width) s = s.slice(0, -1);
120
+ return s + '…';
121
+ }
122
+ function labelFits(box) {
123
+ const {width, height} = renderer.getDimensions();
124
+ return box.x >= 2 && box.y >= 2 && box.x + box.w <= width - 2 && box.y + box.h <= height - 2 &&
125
+ ![...labelBoxes, ...hullBoxes, ...nodeObstacles].some(b => intersects(box, b));
126
+ }
127
+
128
+ function build(g) {
129
+ const G = new graphology.MultiGraph({ type: 'directed' });
130
+ for (const n of g.nodes) {
131
+ const t = TYPES[n.type] || { c: '#8A8A91', s: 5 };
132
+ G.addNode(n.id, { label: n.name || n.id, size: t.s, color: t.c, type_: n.type, raw: n, x: Math.random(), y: Math.random(),
133
+ created: Date.parse(n.created_at) || 0,
134
+ inactive: n.activeInRole === false, strong: STRONG.has(n.type) });
135
+ }
136
+ for (const l of g.links) {
137
+ if (!G.hasNode(l.source) || !G.hasNode(l.target)) continue;
138
+ const key = `${l.source}->${l.target}:${l.type}`;
139
+ if (G.hasEdge(key)) continue; // a API pode repetir o mesmo vínculo
140
+ G.addEdgeWithKey(key, l.source, l.target,
141
+ { rel: l.type, label: EDGE_LABEL[l.type] || l.type, color: EDGE_COLOR[l.type] || EDGE_DEFAULT, size: .6 });
142
+ }
143
+ return G;
144
+ }
145
+
146
+ function layout(G) {
147
+ if (!G.order) return;
148
+ // semente: agrupa por produto (círculo), depois ForceAtlas2 + remoção de sobreposição
149
+ const prods = [...new Set(G.mapNodes((k, a) => (a.raw.products || [])[0]).filter(Boolean))];
150
+ G.forEachNode((k, a) => {
151
+ const i = prods.indexOf((a.raw.products || [])[0]);
152
+ const ang = (i < 0 ? Math.random() * 6.28 : (i / Math.max(1, prods.length)) * 6.28);
153
+ const r = i < 0 ? 2 : 10;
154
+ G.mergeNodeAttributes(k, { x: Math.cos(ang) * r + Math.random(), y: Math.sin(ang) * r + Math.random() });
155
+ });
156
+ const fa2 = L.layoutForceAtlas2;
157
+ // ForceAtlas2 em modo linlog separa bem os grupos; a gravidade forte evita componentes soltos longe
158
+ const settings = { ...fa2.inferSettings(G), gravity: 3, strongGravityMode: true, scalingRatio: 14, barnesHutOptimize: false, linLogMode: true,
159
+ outboundAttractionDistribution: true, adjustSizes: false, edgeWeightInfluence: 1 };
160
+ fa2.assign(G, { iterations: 600, settings });
161
+ L.layoutNoverlap.assign(G, { maxIterations: 200, settings: { margin: 10, ratio: 1.3 } });
162
+ }
163
+
164
+ /* Contorno suave (casca convexa) de cada produto, desenhado num canvas abaixo do WebGL. */
165
+ function convexHull(pts) {
166
+ if (pts.length < 3) return pts;
167
+ pts = pts.slice().sort((a, b) => a.x - b.x || a.y - b.y);
168
+ const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
169
+ const lo = [], up = [];
170
+ for (const p of pts) { while (lo.length >= 2 && cross(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }
171
+ for (const p of pts.reverse()) { while (up.length >= 2 && cross(up[up.length - 2], up[up.length - 1], p) <= 0) up.pop(); up.push(p); }
172
+ return lo.slice(0, -1).concat(up.slice(0, -1));
173
+ }
174
+ function drawHulls() {
175
+ hullBoxes = [];
176
+ const cv = $('hulls'), st = $('cy'), dpr = devicePixelRatio || 1;
177
+ cv.width = st.clientWidth * dpr; cv.height = st.clientHeight * dpr; cv.style.width = st.clientWidth + 'px'; cv.style.height = st.clientHeight + 'px';
178
+ const ctx = cv.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, cv.width, cv.height);
179
+ if (!state.hulls || !renderer) return;
180
+ const groups = new Map();
181
+ graph.forEachNode((k, a) => {
182
+ if (!isVisible(k)) return;
183
+ const ps = a.raw.products || [];
184
+ const key = a.type_ === 'product' ? a.raw.id : (ps.length === 1 ? ps[0] : null);
185
+ if (!key) return;
186
+ const p = renderer.graphToViewport({ x: a.x, y: a.y });
187
+ (groups.get(key) || groups.set(key, []).get(key)).push(p);
188
+ });
189
+ const pad = 26 / Math.sqrt(renderer.getCamera().ratio);
190
+ for (const [key, pts] of groups) {
191
+ const ring = [];
192
+ for (const p of pts) for (let i = 0; i < 12; i++) ring.push({ x: p.x + Math.cos(i * Math.PI / 6) * pad, y: p.y + Math.sin(i * Math.PI / 6) * pad });
193
+ const h = convexHull(ring);
194
+ if (h.length < 3) continue;
195
+ const faded = focus && !(graph.getNodeAttribute(focus, 'raw').products || []).includes(key) && focus !== key;
196
+ ctx.beginPath();
197
+ h.forEach((p, i) => { const q = h[(i + 1) % h.length]; const m = { x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 };
198
+ i === 0 ? ctx.moveTo(m.x, m.y) : null; ctx.quadraticCurveTo(q.x, q.y, (q.x + h[(i + 2) % h.length].x) / 2, (q.y + h[(i + 2) % h.length].y) / 2); });
199
+ ctx.closePath();
200
+ ctx.fillStyle = faded ? 'rgba(124,58,237,.015)' : 'rgba(124,58,237,.06)'; ctx.fill();
201
+ ctx.strokeStyle = faded ? 'rgba(167,139,250,.10)' : 'rgba(167,139,250,.32)'; ctx.lineWidth = 1; ctx.stroke();
202
+ const top = h.reduce((a, b) => (b.y < a.y ? b : a));
203
+ const name = graph.hasNode(key) ? graph.getNodeAttribute(key, 'label') : key.split('/').pop();
204
+ ctx.font = '600 10px "IBM Plex Mono", ui-monospace, monospace'; ctx.fillStyle = faded ? 'rgba(167,139,250,.3)' : '#A78BFA';
205
+ const text = shortText(ctx, name.toUpperCase(), Math.min(200, st.clientWidth - 24));
206
+ const w = ctx.measureText(text).width + 4;
207
+ const box = {x:top.x - w / 2, y:top.y - 20, w, h:14};
208
+ if (labelFits(box)) { hullBoxes.push(box); ctx.textAlign = 'center'; ctx.fillText(text, top.x, top.y - 8); }
209
+ }
210
+ }
211
+
212
+ function drawLabel(ctx, d, settings) {
213
+ if (!d.label || !renderer) return;
214
+ const strong = d.strong, size = strong ? 12 : 10.5;
215
+ ctx.font = `${strong ? 600 : 500} ${size}px ${strong ? '"Space Grotesk"' : '"IBM Plex Sans"'}, sans-serif`;
216
+ const text = shortText(ctx, d.label, Math.min(170, renderer.getDimensions().width - 24));
217
+ const w = ctx.measureText(text).width + 4;
218
+ const box = {x:Math.max(3, Math.min(renderer.getDimensions().width - w - 3, d.x - w / 2)), y:d.y + d.size + 5, w, h:size + 4};
219
+ if (!labelFits(box)) return;
220
+ labelBoxes.push(box);
221
+ ctx.fillStyle = d.dim ? 'rgba(163,163,163,.25)' : (strong || d.highlighted ? '#F5F5F5' : '#A3A3A3');
222
+ ctx.textAlign = 'center';
223
+ ctx.fillText(text, box.x + w / 2, box.y + size);
224
+ }
225
+ function drawHover(ctx, d) {
226
+ if (!d.label) { ctx.beginPath(); ctx.arc(d.x, d.y, d.size + 4, 0, 6.283); ctx.strokeStyle = 'rgba(52,211,153,.7)'; ctx.lineWidth = 1.5; ctx.stroke(); return; }
227
+ const size = 12; ctx.font = `600 ${size}px "Space Grotesk", sans-serif`;
228
+ const {width, height} = renderer.getDimensions();
229
+ const text = shortText(ctx, d.label, width - 32);
230
+ const w = ctx.measureText(text).width + 16, h = 24;
231
+ const x = Math.max(4, Math.min(width - w - 4, d.x - w / 2));
232
+ const y = Math.max(4, Math.min(height - h - 4, d.y + d.size + 6));
233
+ ctx.fillStyle = '#101013'; ctx.strokeStyle = 'rgba(167,139,250,.55)'; ctx.lineWidth = 1;
234
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, 12); ctx.fill(); ctx.stroke();
235
+ ctx.fillStyle = '#F5F5F5'; ctx.textAlign = 'center'; ctx.fillText(text, x + w / 2, y + 16);
236
+ ctx.beginPath(); ctx.arc(d.x, d.y, d.size + 4, 0, 6.283); ctx.strokeStyle = 'rgba(167,139,250,.7)'; ctx.lineWidth = 1.5; ctx.stroke();
237
+ }
238
+
239
+ function separateNodes() {
240
+ if (!renderer || graph.order < 2) return;
241
+ // Sigma normalizes coordinates and scales radii with the camera. Feed the
242
+ // actual pixel geometry to Noverlap, then map its result back to graph space.
243
+ for (let pass = 0; pass < 3; pass++) {
244
+ L.layoutNoverlap.assign(graph, {maxIterations:300,
245
+ inputReducer:(k, a) => ({...renderer.graphToViewport(a), size:renderer.scaleSize(renderer.getNodeDisplayData(k).size)}),
246
+ outputReducer:(k, p) => renderer.viewportToGraph(p),
247
+ settings:{margin:8, ratio:1.2, expansion:1.1} });
248
+ renderer.refresh();
249
+ }
250
+ }
251
+
252
+ function mount() {
253
+ if (renderer) { renderer.kill(); renderer = null; }
254
+ renderer = new Sigma(graph, $('cy'), {
255
+ renderEdgeLabels: false, labelRenderedSizeThreshold: 0, defaultEdgeType: 'line', minCameraRatio: .08, maxCameraRatio: 4,
256
+ zIndex: true, labelDensity: 0.9, labelGridCellSize: 70, stagePadding: 40,
257
+ defaultDrawNodeLabel: drawLabel, defaultDrawNodeHover: drawHover,
258
+ nodeReducer: (k, a) => {
259
+ const r = { ...a, label: a.label, zIndex: a.strong ? 2 : 1 };
260
+ if (hidden.has(a.type_) || a.created > timeCut) { r.hidden = true; return r; }
261
+ if (PFTel.data) {
262
+ r.size = a.size * (sizes.get(k) || 1);
263
+ if (PFTel.isUnused(a.raw)) { r.color = '#2E2E34'; r.dim = true; }
264
+ }
265
+ if (pulses.has(k)) { r.highlighted = true; r.color = '#34D399'; r.size = (r.size || a.size) * 1.6; r.zIndex = 5; }
266
+ if (a.type_ === 'production_job') r.label = '';
267
+ else if (!a.strong && renderer && renderer.getCamera().ratio > .9 && !(hood && hood.has(k))) r.label = '';
268
+ if (a.inactive) { r.color = '#2A2A30'; r.dim = true; }
269
+ if (hood && !hood.has(k)) { r.color = '#1C1C21'; r.dim = true; r.zIndex = 0; }
270
+ if (hood && hood.has(k)) { r.highlighted = k === focus; r.zIndex = 3; r.dim = false; }
271
+ if (matches && matches.has(k)) { r.highlighted = true; r.zIndex = 4; }
272
+ return r;
273
+ },
274
+ edgeReducer: (k, a) => {
275
+ const r = { ...a };
276
+ const [s, t] = graph.extremities(k);
277
+ if (!isVisible(s) || !isVisible(t)) { r.hidden = true; return r; }
278
+ if (hood) {
279
+ if (s === focus || t === focus) { r.color = '#A78BFA'; r.size = 1.4; r.zIndex = 2; }
280
+ else { r.color = EDGE_FADE; }
281
+ }
282
+ return r;
283
+ },
284
+ });
285
+ renderer.on('clickNode', ({ node }) => select(node));
286
+ renderer.on('clickStage', () => select(null));
287
+ renderer.on('enterNode', () => { $('cy').style.cursor = 'pointer'; });
288
+ renderer.on('leaveNode', () => { $('cy').style.cursor = 'default'; });
289
+ renderer.on('beforeRender', () => {
290
+ labelBoxes = []; hullBoxes = []; nodeObstacles = [];
291
+ graph.forEachNode((k, a) => {
292
+ if (!isVisible(k)) return;
293
+ const d = renderer.getNodeDisplayData(k); if (!d) return;
294
+ const p = renderer.graphToViewport(a), r = renderer.scaleSize(d.size) + 2;
295
+ nodeObstacles.push({x:p.x-r, y:p.y-r, w:2*r, h:2*r});
296
+ });
297
+ });
298
+ renderer.on('afterRender', drawHulls);
299
+ // arrastar nós
300
+ let dragged = null;
301
+ renderer.on('downNode', (e) => { dragged = e.node; renderer.getCamera().disable(); });
302
+ renderer.getMouseCaptor().on('mousemovebody', (e) => {
303
+ if (!dragged) return;
304
+ const p = renderer.viewportToGraph(e); graph.mergeNodeAttributes(dragged, { x: p.x, y: p.y });
305
+ e.preventSigmaDefault(); e.original.preventDefault(); e.original.stopPropagation();
306
+ });
307
+ renderer.getMouseCaptor().on('mouseup', () => { dragged = null; renderer.getCamera().enable(); });
308
+ renderer.refresh();
309
+ separateNodes();
310
+ }
311
+
312
+ function select(k) {
313
+ if (!renderer || !graph) return;
314
+ if (k && !isVisible(k)) return;
315
+ focus = k; hood = k ? new Set([k, ...graph.neighbors(k)]) : null;
316
+ if (k) { details(k); const d = renderer.getNodeDisplayData(k); renderer.getCamera().animate({ x: d.x, y: d.y }, { duration: 350 }); }
317
+ else $('details').innerHTML = '<span class="muted">Selecione um nó para ver a regra, os vínculos e os vizinhos.</span>';
318
+ renderer.refresh();
319
+ }
320
+
321
+ function details(k) {
322
+ const r = graph.getNodeAttribute(k, 'raw'), d = r.details || {}, t = TYPES[r.type] || {};
323
+ const rows = [];
324
+ rows.push(`<div class="title"><span class="glyph ${t.g}" style="background:${t.c};color:${t.c}"></span>${esc(r.name || r.id)}</div>
325
+ <span class="chip brand">${esc(t.n || r.type)}</span>`);
326
+ const texto = d.rule || d.principle || (d.when ? `QUANDO ${d.when}\nENTÃO ${d.then}` : '') || d.symptom || d.descricao || d.desc;
327
+ if (texto) rows.push(`<div class="rule">${esc(texto)}</div>`);
328
+ if (r.type === 'agent') rows.push('<div class="kv"><b>Atividade observada</b> Identidade explícita registrada, não inferida do papel.</div>');
329
+ if (r.type === 'role') rows.push(`<div class="kv"><b>Atividade observada</b> ${r.observed ? 'Sim' : 'Sem observação nesta vista'}</div><div class="kv"><b>Cobertura de conhecimento</b> ${r.covered ? 'Vínculo explícito com regra' : 'Sem regra vinculada nesta vista'}</div>`);
330
+ if ((r.target_roles || []).length) rows.push(`<div class="kv"><b>Papéis</b> ${r.target_roles.map(x => `<span class="chip">${esc(x)}</span>`).join('')}</div>`);
331
+ if ((r.products || []).length) rows.push(`<div class="kv"><b>Produtos</b> ${r.products.map(x => `<span class="chip">${esc(x.replace('product:', ''))}</span>`).join('')}</div>`);
332
+ for (const f of ['scope', 'stack', 'tenant', 'trigger_regime', 'cliente', 'estado', 'eventos_count', 'agentes']) {
333
+ if (d[f] != null && d[f] !== '') rows.push(`<div class="kv"><b>${f.replace(/_/g, ' ')}</b> ${esc(Array.isArray(d[f]) ? d[f].join(', ') : d[f])}</div>`);
334
+ }
335
+ const nb = [];
336
+ graph.forEachEdge(k, (e, a, s, tt) => {
337
+ const o = s === k ? tt : s;
338
+ if (!isVisible(o)) return;
339
+ nb.push(`<div><span class="rel">${esc(a.label)}</span><a data-id="${esc(o)}">${esc(graph.getNodeAttribute(o, 'label'))}</a></div>`);
340
+ });
341
+ rows.push(`<div class="eyebrow">Vizinhos · ${nb.length}</div><div id="nb">${nb.join('') || '<span class="muted">nenhum</span>'}</div>`);
342
+ rows.splice(rows.length - 1, 0, PFTel.panel(r));
343
+ $('details').innerHTML = rows.join('');
344
+ $('details').querySelectorAll('#nb a').forEach(a => a.onclick = () => select(a.dataset.id));
345
+ }
346
+
347
+ function legend() {
348
+ const present = new Set(data.nodes.map(n => n.type));
349
+ $('legend').innerHTML = Object.entries(TYPES).filter(([k]) => present.has(k)).map(([k, t]) =>
350
+ `<label class="${hidden.has(k)?'off':''}"><input type="checkbox" data-t="${k}" ${hidden.has(k)?'':'checked'}><span class="glyph ${t.g}" style="background:${t.c};color:${t.c}"></span>${t.n}
351
+ <span class="n">${data.nodes.filter(n => n.type === k).length}</span></label>`).join('');
352
+ $('legend').querySelectorAll('input').forEach(i => i.onchange = () => {
353
+ i.checked ? hidden.delete(i.dataset.t) : hidden.add(i.dataset.t); i.parentElement.classList.toggle('off', !i.checked);
354
+ if (focus && !isVisible(focus)) select(null);
355
+ renderer.refresh(); });
356
+ }
357
+
358
+ $('q').oninput = () => {
359
+ if (!graph || !renderer) { matches = null; return; }
360
+ const q = $('q').value.trim().toLowerCase();
361
+ matches = q ? new Set(graph.filterNodes((k, a) => isVisible(k) && String(a.label).toLowerCase().includes(q))) : null;
362
+ if (matches && matches.size) {
363
+ const first = renderer.getNodeDisplayData([...matches][0]); renderer.getCamera().animate({ x:first.x, y:first.y, ratio: .6 }, { duration: 300 });
364
+ }
365
+ renderer.refresh();
366
+ };
367
+ $('zin').onclick = () => renderer && renderer.getCamera().animatedZoom({ duration: 250 });
368
+ $('zout').onclick = () => renderer && renderer.getCamera().animatedUnzoom({ duration: 250 });
369
+ $('fit').onclick = () => renderer && renderer.getCamera().animatedReset({ duration: 300 });
370
+ $('relayout').onclick = () => { if (!graph || !renderer) return; layout(graph); renderer.getCamera().setState({x:.5, y:.5, ratio:1, angle:0}); renderer.refresh(); separateNodes(); };
371
+ $('hullsBtn').onclick = () => { state.hulls = !state.hulls; $('hullsBtn').classList.toggle('on', state.hulls); sync(); drawHulls(); };
372
+ let resizeT = null;
373
+ new ResizeObserver(() => {
374
+ if (!renderer) return;
375
+ renderer.resize(); renderer.refresh();
376
+ clearTimeout(resizeT); resizeT = setTimeout(separateNodes, 80);
377
+ }).observe($('cy'));
378
+
379
+ function fillScope() {
380
+ const opt = (v, t, sel) => `<option value="${esc(v)}" ${v === sel ? 'selected' : ''}>${esc(t)}</option>`;
381
+ const org = catalog.find(o => o.id === state.org), proj = org?.projects.find(p => p.id === state.project);
382
+ $('org').innerHTML = opt('', 'Todas as organizações', state.org) + catalog.map(o => opt(o.id, o.name, state.org)).join('');
383
+ $('project').innerHTML = opt('', org ? 'Todos os projetos' : '—', state.project) + (org?.projects || []).map(p => opt(p.id, p.name, state.project)).join('');
384
+ $('product').innerHTML = opt('', proj ? 'Todos os produtos' : '—', state.product) + (proj?.products || []).map(p => opt(p.id, p.name, state.product)).join('');
385
+ $('project').disabled = !org; $('product').disabled = !proj;
386
+ }
387
+ $('org').onchange = () => { state.org = $('org').value; state.project = state.product = ''; load(); };
388
+ $('project').onchange = () => { state.project = $('project').value; state.product = ''; load(); };
389
+ $('product').onchange = () => { state.product = $('product').value; load(); };
390
+ $('role').onchange = () => { state.role = $('role').value; load(); };
391
+ function sync() {
392
+ const p = new URLSearchParams();
393
+ for (const k of ['org', 'project', 'product', 'role']) if (state[k]) p.set(k, state[k]);
394
+ if (state.tenant) p.set('tenant', state.tenant);
395
+ if (state.projectId) p.set('project_id', state.projectId);
396
+ if (!state.hulls) p.set('hulls', '0');
397
+ PFTel.writeParams(p);
398
+ history.replaceState(null, '', location.pathname + (p.toString() ? '?' + p : ''));
399
+ $('alternate').href = '/graph2' + (p.toString() ? '?' + p : '');
400
+ }
401
+
402
+ /* ---- Telemetria ---- */
403
+ let timeCut = Infinity, pulses = new Set(), playing = null, sizes = new Map();
404
+ const recomputeSizes = () => { sizes = PFTel.data && data ? PFTel.sizeMap(data.nodes, data.links) : new Map(); };
405
+ function telemetryUi() {
406
+ recomputeSizes();
407
+ $('telsum').textContent = PFTel.summary();
408
+ $('feed').innerHTML = PFTel.feed((PFTel.data || {}).recent);
409
+ applyTime();
410
+ }
411
+ function applyTime() {
412
+ if (!data) { timeCut = Infinity; return; }
413
+ const b = PFTel.timeBounds(data); if (!b) { timeCut = Infinity; return; }
414
+ const v = +$('time').value;
415
+ timeCut = v >= 1000 ? Infinity : b.min + (b.max - b.min) * v / 1000;
416
+ $('when').textContent = v >= 1000 ? 'agora' : PFTel.fmt(timeCut);
417
+ if (focus && !isVisible(focus)) select(null);
418
+ renderer && renderer.refresh();
419
+ }
420
+ $('time').oninput = applyTime;
421
+ $('play').onclick = () => {
422
+ if (playing) { clearInterval(playing); playing = null; $('play').textContent = '▶'; return; }
423
+ if (+$('time').value >= 1000) $('time').value = 0;
424
+ $('play').textContent = '❚❚';
425
+ playing = setInterval(() => { const v = Math.min(1000, +$('time').value + 12); $('time').value = v; applyTime(); if (v >= 1000) $('play').onclick(); }, 60);
426
+ };
427
+ let spaceT = null;
428
+ PFTel.mountSizeControls($('sizectl'), () => {
429
+ recomputeSizes(); renderer && renderer.refresh(); sync();
430
+ // nós maiores: afasta para não sobrepor (noverlap usa o tamanho efetivo)
431
+ clearTimeout(spaceT);
432
+ spaceT = setTimeout(() => {
433
+ separateNodes();
434
+ }, 300);
435
+ });
436
+ $('live').onclick = () => {
437
+ const on = !PFTel.live; $('live').classList.toggle('on', on);
438
+ PFTel.setLive(on, (events, ids) => {
439
+ if (!data || !renderer) return;
440
+ telemetryUi();
441
+ PFTel.matchNodes(data.nodes, ids).forEach(id => { pulses.add(id); setTimeout(() => { pulses.delete(id); if (renderer) renderer.refresh(); }, 2200); });
442
+ renderer.refresh();
443
+ if (focus) details(focus);
444
+ });
445
+ };
446
+
447
+ function clearGraphView() {
448
+ if (renderer) renderer.kill();
449
+ renderer = graph = data = null;
450
+ focus = hood = matches = null;
451
+ sizes = new Map(); pulses.clear();
452
+ if (playing) { clearInterval(playing); playing = null; $('play').textContent = '▶'; }
453
+ $('hulls').getContext('2d').clearRect(0, 0, $('hulls').width, $('hulls').height);
454
+ for (const id of ['legend', 'stats', 'telsum', 'feed']) $(id).textContent = '';
455
+ $('details').textContent = 'Nenhum grafo carregado.';
456
+ }
457
+
458
+ async function load() {
459
+ const version = ++loadVersion;
460
+ clearGraphView(); catalog = []; fillScope();
461
+ $('role').innerHTML = '<option value="">Lente: todos os papéis</option>';
462
+ $('graph-error').hidden = true;
463
+ try {
464
+ const p = new URLSearchParams();
465
+ if (state.org) p.set('organization', state.org);
466
+ if (state.org && state.project) p.set('project', state.project);
467
+ if (state.org && state.project && state.product) p.set('product', state.product);
468
+ if (state.role) p.set('role', state.role);
469
+ if (state.tenant) p.set('tenant', state.tenant);
470
+ if (state.projectId) p.set('project_id', state.projectId);
471
+ const response = await fetch('/api/v1/graph?' + p);
472
+ if (!response.ok) throw new Error(response.status === 401 ? 'Autenticação necessária (HTTP 401).' :
473
+ response.status === 403 ? 'Acesso negado (HTTP 403).' : `Não foi possível carregar o grafo (HTTP ${response.status}).`);
474
+ let next;
475
+ try { next = await response.json(); } catch { throw new Error('Resposta JSON inválida do servidor.'); }
476
+ if (!next || !Array.isArray(next.nodes) || !Array.isArray(next.links)) throw new Error('Resposta de grafo inválida do servidor.');
477
+ await PFTel.load().catch(() => null);
478
+ if (version !== loadVersion) return;
479
+ data = next;
480
+ catalog = data.catalog || catalog;
481
+ const roles = [...new Set((data.roles || []).map(r => r.role || r.id?.replace('role:', '')).filter(Boolean))].sort();
482
+ $('role').innerHTML = '<option value="">Lente: todos os papéis</option>' + roles.map(r => `<option ${r === state.role ? 'selected' : ''}>${esc(r)}</option>`).join('');
483
+ await document.fonts.ready;
484
+ if (version !== loadVersion) return;
485
+ fillScope(); sync();
486
+ focus = hood = matches = null;
487
+ graph = build(data); layout(graph); mount(); legend(); telemetryUi();
488
+ select(null);
489
+ if ($('q').value.trim()) $('q').oninput();
490
+ $('stats').textContent = `${data.nodes.length} nós · ${data.links.length} arestas`;
491
+ $('hullsBtn').classList.toggle('on', state.hulls);
492
+ } catch (error) {
493
+ if (version !== loadVersion) return;
494
+ clearGraphView(); catalog = []; fillScope(); sync();
495
+ $('graph-error').textContent = error.message || 'Não foi possível carregar o grafo.';
496
+ const retry = document.createElement('button'); retry.textContent = 'Tentar novamente'; retry.onclick = load;
497
+ $('graph-error').append(retry); $('graph-error').hidden = false;
498
+ }
499
+ }
500
+ load();
501
+ </script>
502
+ </body>
503
+ </html>
@@ -0,0 +1,78 @@
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">
6
+ <title>CognitiveBC · Memória organizacional governada para agentes de IA</title>
7
+ <meta name="description" content="Cognitive Bytecode: a memória organizacional governada para agentes de IA. Compila correções, decisões e gates em bytecodes revisáveis e versionados, servidos via MCP.">
8
+ <link rel="icon" href="data:,">
9
+ <link rel="preconnect" href="https://fonts.googleapis.com">
10
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500;600&display=swap">
11
+ <link rel="stylesheet" href="/vendor/cbc-site.css">
12
+ </head>
13
+ <body class="site">
14
+ <a class="skip" href="#conteudo">Pular para o conteúdo</a>
15
+ <header class="topbar" role="banner">
16
+ <a class="logo" href="/" aria-label="CognitiveBC, início">
17
+ <svg viewBox="0 0 20 22" aria-hidden="true"><path d="M10 1 19 6v10l-9 5-9-5V6z" fill="none" stroke="currentColor" stroke-width="1.6"/><circle cx="10" cy="11" r="3" fill="currentColor"/></svg>
18
+ <span>CognitiveBC</span>
19
+ </a>
20
+ <nav aria-label="Principal" class="topnav">
21
+ <a href="#como-funciona">Como funciona</a>
22
+ <a href="#conectar">Conectar</a>
23
+ <a class="btn ghost" href="/app">Entrar</a>
24
+ </nav>
25
+ </header>
26
+
27
+ <main id="conteudo">
28
+ <section class="hero" aria-labelledby="hero-title">
29
+ <p class="eyebrow">Cognitive Bytecode</p>
30
+ <h1 id="hero-title">A memória organizacional governada para agentes de IA</h1>
31
+ <p class="lead">O CognitiveBC compila a experiência das sessões dos seus agentes (correções, decisões e gates) em <strong>bytecodes</strong> revisáveis e versionados, e os entrega como contexto a qualquer agente via MCP.</p>
32
+ <div class="cta">
33
+ <a class="btn primary" href="mailto:contato@performacia.com.br?subject=Acesso%20ao%20CognitiveBC">Solicitar acesso</a>
34
+ <a class="btn ghost" href="/app">Entrar</a>
35
+ </div>
36
+ <p class="clients" aria-label="Clientes compatíveis">Claude Code · Claude Desktop · Codex · Cursor · Antigravity · ChatGPT <span class="tag">em breve</span></p>
37
+ </section>
38
+
39
+ <section id="como-funciona" class="block" aria-labelledby="fluxo-title">
40
+ <p class="eyebrow">Como funciona</p>
41
+ <h2 id="fluxo-title">Da sessão do agente ao contexto governado</h2>
42
+ <ol class="steps">
43
+ <li><span class="n">01</span><h3>Captura</h3><p>Correções, decisões e gates surgem nas sessões dos agentes e são ingeridos como evidência.</p></li>
44
+ <li><span class="n">02</span><h3>Compilação</h3><p>A experiência vira bytecodes candidatos: estruturados, versionados e com origem rastreável.</p></li>
45
+ <li><span class="n">03</span><h3>Revisão humana</h3><p>Nada é publicado sozinho. Candidatos são revisados e promovidos por quem tem permissão.</p></li>
46
+ <li><span class="n">04</span><h3>Entrega via MCP</h3><p>Os bytecodes publicados chegam como contexto a qualquer agente compatível com MCP.</p></li>
47
+ </ol>
48
+ </section>
49
+
50
+ <section class="block" aria-labelledby="pilares-title">
51
+ <p class="eyebrow">Governança</p>
52
+ <h2 id="pilares-title">Feito para equipes, não para um único prompt</h2>
53
+ <div class="grid">
54
+ <article class="card"><h3>Isolamento multi-tenant</h3><p>Cada token enxerga apenas os tenants e permissões que lhe foram delegados.</p></article>
55
+ <article class="card"><h3>Revisão antes de publicar</h3><p>Fluxo de candidatos → promoção, com aprovador registrado.</p></article>
56
+ <article class="card"><h3>Projeto reconhecido em qualquer máquina</h3><p>O projeto é identificado pelo git remote e pelo commit raiz, não pelo caminho local.</p></article>
57
+ <article class="card"><h3>Gates antes da entrega</h3><p>Regras de verificação são checadas antes que o agente entregue o trabalho.</p></article>
58
+ </div>
59
+ </section>
60
+
61
+ <section id="conectar" class="block" aria-labelledby="conectar-title">
62
+ <p class="eyebrow">Como conectar</p>
63
+ <h2 id="conectar-title">Em dois comandos</h2>
64
+ <ol class="cmds">
65
+ <li><p>Autentique com seu token pessoal:</p><pre><code>npx -y cognitivebc login</code></pre></li>
66
+ <li><p>Registre o servidor MCP no seu cliente (exemplo: Claude Code):</p><pre><code>npx -y cognitivebc setup claude-code --apply</code></pre></li>
67
+ <li><p>Ou use o MCP remoto diretamente:</p><pre><code>URL: https://api.cognitivebc.io/mcp
68
+ Header: Authorization: Bearer cbc_…</code></pre></li>
69
+ </ol>
70
+ </section>
71
+ </main>
72
+
73
+ <footer class="foot" role="contentinfo">
74
+ <span>© CognitiveBC · PerformacIA</span>
75
+ <nav aria-label="Rodapé"><a href="https://github.com/performacia/cognitivebc" rel="noopener">GitHub</a><a href="mailto:contato@performacia.com.br">Contato</a><a href="/app">Entrar</a></nav>
76
+ </footer>
77
+ </body>
78
+ </html>