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.
- package/LICENSE +70 -0
- package/README.md +98 -4
- package/SECURITY.md +29 -0
- package/TERMS_OF_SERVICE.md +55 -0
- package/bin/cbc-cloud-bootstrap.js +108 -0
- package/bin/cbc-seed-projects.js +29 -0
- package/bin/cbc-server.js +45 -0
- package/bin/cognitivebc.js +251 -0
- package/docs/ACCESS_CONTROL.md +111 -0
- package/docs/ARTIFACT_AUDIT.md +36 -0
- package/docs/CONNECT_CLIENTS.md +116 -0
- package/docs/DEPLOY_AZURE.md +136 -0
- package/docs/INGESTION.md +29 -0
- package/docs/OPERATIONS.md +85 -0
- package/docs/PROJECT_IDENTITY.md +35 -0
- package/docs/RESOLVER.md +86 -0
- package/docs/SDK.md +96 -0
- package/docs/STORAGE.md +63 -0
- package/docs/TECHNICAL_SPECIFICATION.md +365 -0
- package/docs/TELEMETRY.md +119 -0
- package/index.js +27 -2
- package/package.json +45 -5
- package/packages/cbc-compiler/index.js +357 -0
- package/packages/cbc-compiler/sanitizer.js +43 -0
- package/packages/cbc-identity/index.js +92 -0
- package/packages/cbc-mcp/http-backend.js +142 -0
- package/packages/cbc-mcp/http-route.js +64 -0
- package/packages/cbc-mcp/index.js +50 -0
- package/packages/cbc-mcp/tools.js +122 -0
- package/packages/cbc-resolver/catalog-linker.js +215 -0
- package/packages/cbc-resolver/graph-builder.js +533 -0
- package/packages/cbc-resolver/index.js +548 -0
- package/packages/cbc-resolver/obsidian-bridge.js +564 -0
- package/packages/cbc-schema/index.js +194 -0
- package/packages/cbc-sdk-js/client.js +162 -0
- package/services/cbc-api/access-policy.js +130 -0
- package/services/cbc-api/artifact-audit.js +167 -0
- package/services/cbc-api/cloud.js +56 -0
- package/services/cbc-api/context-service.js +48 -0
- package/services/cbc-api/ingestion-service.js +234 -0
- package/services/cbc-api/pg-store.js +172 -0
- package/services/cbc-api/project-registry.js +343 -0
- package/services/cbc-api/public/app.html +123 -0
- package/services/cbc-api/public/graph.html +1168 -0
- package/services/cbc-api/public/graph2.html +455 -0
- package/services/cbc-api/public/graph3.html +503 -0
- package/services/cbc-api/public/index.html +78 -0
- package/services/cbc-api/public/vendor/cbc-app.js +209 -0
- package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
- package/services/cbc-api/public/vendor/cbc-site.css +101 -0
- package/services/cbc-api/public/vendor/cose-base.js +3214 -0
- package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
- package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
- package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
- package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
- package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
- package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
- package/services/cbc-api/public/vendor/layout-base.js +5230 -0
- package/services/cbc-api/public/vendor/pf-graph.css +86 -0
- package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
- package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
- package/services/cbc-api/runtime-info.js +39 -0
- package/services/cbc-api/server.js +642 -0
- package/services/cbc-api/store-loader.js +269 -0
- package/services/cbc-api/telemetry.js +148 -0
- package/services/cbc-api/token-service.js +61 -0
|
@@ -0,0 +1,455 @@
|
|
|
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 (Cytoscape)</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
|
+
<script src="/vendor/cbc-auth.js"></script>
|
|
11
|
+
<script src="/vendor/cytoscape.min.js"></script>
|
|
12
|
+
<script src="/vendor/layout-base.js"></script>
|
|
13
|
+
<script src="/vendor/cose-base.js"></script>
|
|
14
|
+
<script src="/vendor/cytoscape-fcose.js"></script>
|
|
15
|
+
<script src="/vendor/dagre.min.js"></script>
|
|
16
|
+
<script src="/vendor/cytoscape-dagre.js"></script>
|
|
17
|
+
<script src="/vendor/pf-telemetry.js"></script>
|
|
18
|
+
<link rel="stylesheet" href="/vendor/pf-graph.css">
|
|
19
|
+
<style>
|
|
20
|
+
body { display:flex; flex-direction:column; overflow:hidden; }
|
|
21
|
+
header { flex:none; flex-wrap:wrap; overflow:visible; padding:10px 14px; }
|
|
22
|
+
header select, header input { max-width:100%; min-width:0; }
|
|
23
|
+
main { position:relative; top:auto; flex:1; min-height:0; }
|
|
24
|
+
#stage { min-width:0; }
|
|
25
|
+
#cy { bottom:64px; }
|
|
26
|
+
aside { flex:none; overflow-wrap:anywhere; }
|
|
27
|
+
.timebar { right:16px; }
|
|
28
|
+
.timebar input { min-width:0; }
|
|
29
|
+
@media(max-width:800px) {
|
|
30
|
+
aside { width:240px; padding:12px; }
|
|
31
|
+
.legend { grid-template-columns:1fr; }
|
|
32
|
+
header .brand, header .sp, #stats, header > a { display:none; }
|
|
33
|
+
header { gap:5px; padding:6px; }
|
|
34
|
+
header select, header input { max-width:155px; }
|
|
35
|
+
.timebar { gap:5px; left:6px; right:6px; padding:6px; }
|
|
36
|
+
.timebar .when { min-width:0; }
|
|
37
|
+
.timebar .eyebrow { display:none; }
|
|
38
|
+
}
|
|
39
|
+
@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); } }
|
|
40
|
+
</style>
|
|
41
|
+
</head>
|
|
42
|
+
<body>
|
|
43
|
+
<header>
|
|
44
|
+
<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>
|
|
45
|
+
<h1>CognitiveBC <span>/ grafo</span></h1></div>
|
|
46
|
+
<select id="org"></select><select id="project"></select><select id="product"></select>
|
|
47
|
+
<select id="role"><option value="">Lente: todos os papéis</option></select>
|
|
48
|
+
<input id="q" placeholder="Buscar nó…" size="16">
|
|
49
|
+
<span class="sp"></span>
|
|
50
|
+
<span id="stats"></span>
|
|
51
|
+
<span class="seg" id="layouts">
|
|
52
|
+
<button data-l="fcose" class="on">Forças</button><button data-l="dagre">Hierarquia</button><button data-l="concentric">Camadas</button>
|
|
53
|
+
</span>
|
|
54
|
+
<button id="group" class="on" title="Caixas org › projeto › produto">Agrupar</button>
|
|
55
|
+
<button id="live" class="livebadge" title="Atualiza a cada 4 s e pulsa o que foi usado">Ao vivo</button>
|
|
56
|
+
<button id="fit">Enquadrar</button>
|
|
57
|
+
<button id="refresh">Atualizar</button>
|
|
58
|
+
<a id="alternate" href="/graph3" style="margin-left:6px">versão Sigma ↗</a>
|
|
59
|
+
</header>
|
|
60
|
+
<main>
|
|
61
|
+
<div id="stage"><div id="cy"></div>
|
|
62
|
+
<div class="timebar"><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>
|
|
63
|
+
</div>
|
|
64
|
+
<aside>
|
|
65
|
+
<div class="eyebrow">Atividade observada</div><div id="observed-summary" aria-live="polite"></div>
|
|
66
|
+
<p class="muted">Agentes e papéis aparecem pela atividade registrada, mesmo sem regra própria.</p>
|
|
67
|
+
<div class="eyebrow">Cobertura de conhecimento</div><div id="coverage-summary" aria-live="polite"></div>
|
|
68
|
+
<p class="muted">Cobertura indica vínculos explícitos com regras. Atividade não comprova cobertura nem sucesso.</p>
|
|
69
|
+
<div class="eyebrow">Tamanho dos nós</div><div id="sizectl"></div>
|
|
70
|
+
<div class="eyebrow">Tipos</div><div class="legend" id="legend"></div>
|
|
71
|
+
<div class="eyebrow">Detalhes</div><div id="details" class="muted">Selecione um nó para ver a regra, os vínculos e os vizinhos.</div>
|
|
72
|
+
<div class="eyebrow">Telemetria de uso · janela</div><div id="telsum"></div><div id="feed"></div>
|
|
73
|
+
</aside>
|
|
74
|
+
</main>
|
|
75
|
+
<script>
|
|
76
|
+
/* Marcas geométricas pequenas: losango = identidade explícita de agente, hexágono verde = papel.
|
|
77
|
+
Paleta restrita: roxo = identidade/estrutura, verde = ação/
|
|
78
|
+
aplicação, âmbar = alerta (restrição), neutros para o resto. Contorno fino = estrutura, preenchido = conhecimento. */
|
|
79
|
+
const TYPES = {
|
|
80
|
+
organization: { n:'Organização', c:'#F5F5F5', shape:'round-rectangle', s:18, fill:false, g:'square outline' },
|
|
81
|
+
project: { n:'Projeto', c:'#A3A3A3', shape:'round-rectangle', s:16, fill:false, g:'square outline' },
|
|
82
|
+
product: { n:'Produto', c:'#A78BFA', shape:'round-rectangle', s:18, fill:true, g:'square' },
|
|
83
|
+
stack: { n:'Stack', c:'#A78BFA', shape:'hexagon', s:20, fill:false, g:'hex' },
|
|
84
|
+
tenant: { n:'Tenant', c:'#C4B5FD', shape:'round-rectangle', s:16, fill:false, g:'square outline' },
|
|
85
|
+
agent: { n:'Agente observado', c:'#A78BFA', shape:'diamond', s:18, fill:true, g:'diamond' },
|
|
86
|
+
role: { n:'Papel', c:'#34D399', shape:'hexagon', s:16, fill:true, g:'hex' },
|
|
87
|
+
principle: { n:'Princípio', c:'#F5F5F5', shape:'ellipse', s:11, fill:true, g:'round' },
|
|
88
|
+
constraint: { n:'Restrição', c:'#FB923C', shape:'ellipse', s:11, fill:true, g:'round' },
|
|
89
|
+
heuristic: { n:'Heurística', c:'#A3A3A3', shape:'ellipse', s:11, fill:true, g:'round' },
|
|
90
|
+
experience: { n:'Caso', c:'#A78BFA', shape:'ellipse', s:11, fill:false, g:'round outline' },
|
|
91
|
+
telemetry_source:{ n:'Fonte de atividade', c:'#8A8A91', shape:'round-rectangle', s:14, fill:false, g:'square outline' },
|
|
92
|
+
production_job: { n:'Sessão / job', c:'#8A8A91', shape:'ellipse', s:7, fill:true, g:'round' },
|
|
93
|
+
};
|
|
94
|
+
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',
|
|
95
|
+
product_job:'job', provides_vault:'vocabulário', has_product:'produto', uses_stack:'usa', owns_project:'projeto',
|
|
96
|
+
belongs_to_tenant:'tenant', product_vault:'tenant', operates_source:'opera' };
|
|
97
|
+
const STRUCT = new Set(['owns_project','has_product']);
|
|
98
|
+
|
|
99
|
+
const $ = (id) => document.getElementById(id);
|
|
100
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[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')||'', layout: params.get('layout')||'fcose', group: params.get('group') !== '0' };
|
|
105
|
+
let hidden = new Set(), catalog = [], graph = null;
|
|
106
|
+
|
|
107
|
+
cytoscape.use(cytoscapeFcose); cytoscape.use(cytoscapeDagre);
|
|
108
|
+
const cy = cytoscape({
|
|
109
|
+
container: $('cy'), wheelSensitivity: 0.25, minZoom: 0.01, maxZoom: 1.5,
|
|
110
|
+
style: [
|
|
111
|
+
{ selector: 'node', style: {
|
|
112
|
+
'shape': 'data(shape)', 'width': 'data(size)', 'height': 'data(size)',
|
|
113
|
+
'background-color': 'data(color)', 'background-opacity': 'data(fillOpacity)',
|
|
114
|
+
'border-width': 1.5, 'border-color': 'data(color)', 'border-opacity': .9,
|
|
115
|
+
'label': 'data(label)', 'color': '#A3A3A3', 'font-family': 'IBM Plex Sans, sans-serif', 'font-size': 11, 'font-weight': 500,
|
|
116
|
+
'text-valign': 'bottom', 'text-margin-y': 6, 'text-wrap': 'ellipsis', 'text-max-width': 110, 'min-zoomed-font-size': 5,
|
|
117
|
+
'transition-property': 'opacity, border-width, background-opacity', 'transition-duration': 150 } },
|
|
118
|
+
{ selector: 'node[type="product"],node[type="stack"],node[type="tenant"],node[type="role"],node[type="agent"],node[type="organization"],node[type="project"]',
|
|
119
|
+
style: { 'color': '#F5F5F5', 'font-family': 'Space Grotesk, sans-serif', 'font-size': 11.5, 'font-weight': 600, 'min-zoomed-font-size': 0 } },
|
|
120
|
+
{ selector: 'node[type="production_job"]', style: { 'label': '', 'border-width': 0 } },
|
|
121
|
+
{ selector: 'node.inactive', style: { 'opacity': .18 } },
|
|
122
|
+
{ selector: 'node.observed-uncovered', style: { 'border-style': 'dashed', 'border-width': 2.5 } },
|
|
123
|
+
{ selector: 'node.unused', style: { 'background-opacity': .12, 'border-style': 'dashed', 'color': '#5A5A62' } },
|
|
124
|
+
{ selector: 'node.future, node.typeoff', style: { 'display': 'none' } },
|
|
125
|
+
{ selector: 'node.pulse', style: { 'underlay-color': '#34D399', 'underlay-opacity': .45, 'underlay-padding': 12, 'underlay-shape': 'ellipse' } },
|
|
126
|
+
{ selector: ':parent', style: {
|
|
127
|
+
'shape': 'round-rectangle', 'corner-radius': 22, 'background-color': '#101013', 'background-opacity': .55,
|
|
128
|
+
'border-width': 1, 'border-color': '#26262A', 'border-opacity': 1, 'padding': 32,
|
|
129
|
+
'compound-sizing-wrt-labels': 'include',
|
|
130
|
+
'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center', 'text-margin-x': 0, 'text-margin-y': 8,
|
|
131
|
+
'font-family': 'IBM Plex Mono, ui-monospace, monospace', 'font-size': 10, 'font-weight': 600, 'text-transform': 'uppercase',
|
|
132
|
+
'color': '#8A8A91', 'min-zoomed-font-size': 0 } },
|
|
133
|
+
{ selector: ':parent[kind="org"]', style: { 'background-opacity': 0, 'border-color': 'rgba(255,255,255,.08)', 'color': '#A3A3A3', 'font-size': 11 } },
|
|
134
|
+
{ selector: ':parent[kind="product"]', style: { 'background-color': '#7C3AED', 'background-opacity': .06, 'border-color': 'rgba(167,139,250,.35)', 'color': '#A78BFA' } },
|
|
135
|
+
{ selector: 'edge', style: {
|
|
136
|
+
'width': .8, 'line-color': '#3A3A40', 'curve-style': 'bezier', 'opacity': .7,
|
|
137
|
+
'target-arrow-shape': 'none', 'font-family': 'IBM Plex Mono, monospace', 'font-size': 8.5, 'color': '#A3A3A3', 'text-rotation': 'autorotate',
|
|
138
|
+
'text-background-color': '#060606', 'text-background-opacity': 1, 'text-background-padding': 2 } },
|
|
139
|
+
{ selector: 'edge[type="targets_role"],edge[type="executed_by"],edge[type="performs_role"]', style: { 'line-color': 'rgba(52,211,153,.28)' } },
|
|
140
|
+
{ selector: 'edge[type="executed_session"]', style: { 'line-color': 'rgba(167,139,250,.55)' } },
|
|
141
|
+
{ selector: 'edge[type="contains_rule"],edge[type="contains_case"],edge[type="uses_stack"]', style: { 'line-color': 'rgba(167,139,250,.32)' } },
|
|
142
|
+
{ selector: 'edge[struct]', style: { 'line-style': 'dashed', 'opacity': .4 } },
|
|
143
|
+
{ selector: '.faded', style: { 'opacity': .1 } },
|
|
144
|
+
{ selector: 'node.hl', style: { 'border-width': 3, 'background-opacity': 1, 'color': '#F5F5F5', 'z-index': 10 } },
|
|
145
|
+
{ selector: 'node.focus', style: { 'underlay-color': '#A78BFA', 'underlay-opacity': .22, 'underlay-padding': 7, 'underlay-shape': 'ellipse' } },
|
|
146
|
+
{ selector: 'edge.hl', style: { 'line-color': '#A78BFA', 'width': 1.6, 'opacity': 1, 'label': '',
|
|
147
|
+
'target-arrow-shape': 'triangle', 'target-arrow-color': '#A78BFA', 'arrow-scale': .6 } },
|
|
148
|
+
{ selector: 'node.match', style: { 'underlay-color': '#34D399', 'underlay-opacity': .28, 'underlay-padding': 8 } },
|
|
149
|
+
],
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
function legend() {
|
|
153
|
+
const present = new Set((graph?.nodes||[]).map(n => n.type));
|
|
154
|
+
$('legend').innerHTML = Object.entries(TYPES).filter(([k]) => present.has(k)).map(([k, t]) =>
|
|
155
|
+
`<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}
|
|
156
|
+
<span class="n">${graph.nodes.filter(n=>n.type===k).length}</span></label>`).join('');
|
|
157
|
+
$('legend').querySelectorAll('input').forEach(i => i.onchange = () => { i.checked ? hidden.delete(i.dataset.t) : hidden.add(i.dataset.t); i.parentElement.classList.toggle('off', !i.checked); applyHidden(); });
|
|
158
|
+
}
|
|
159
|
+
function applyHidden() {
|
|
160
|
+
cy.batch(() => cy.nodes().forEach(n => n.toggleClass('typeoff', hidden.has(n.data('type')))));
|
|
161
|
+
runLayout();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function toElements(g) {
|
|
165
|
+
const els = [], parents = new Set();
|
|
166
|
+
const byId = new Map(g.nodes.map(n => [n.id, n]));
|
|
167
|
+
const parentOf = (n) => {
|
|
168
|
+
if (!state.group) return undefined;
|
|
169
|
+
if (n.type === 'organization') return undefined;
|
|
170
|
+
if (n.type === 'project') return 'grp:org:' + n.organization;
|
|
171
|
+
if (n.type === 'product') return 'grp:project:' + n.organization + '/' + n.project;
|
|
172
|
+
const ps = n.products || [];
|
|
173
|
+
return ps.length === 1 ? 'grp:' + ps[0] : undefined; // conhecimento de um único produto fica dentro da caixa dele
|
|
174
|
+
};
|
|
175
|
+
for (const n of g.nodes) {
|
|
176
|
+
const t = TYPES[n.type] || { c: n.color || '#8A8A91', shape: 'ellipse', s: 11, fill: true };
|
|
177
|
+
let parent = parentOf(n);
|
|
178
|
+
if (n.type === 'product' && state.group) { parent = 'grp:' + n.id; }
|
|
179
|
+
els.push({ data: { id: n.id, parent, type: n.type, label: n.name || n.id, color: t.c, shape: t.shape,
|
|
180
|
+
size: t.s, fillOpacity: t.fill ? .95 : .08, raw: n }, classes: [n.activeInRole === false ? 'inactive' : '',
|
|
181
|
+
n.type === 'role' && n.observed && !n.covered ? 'observed-uncovered' : ''].filter(Boolean).join(' ') });
|
|
182
|
+
if (parent) parents.add(parent);
|
|
183
|
+
}
|
|
184
|
+
if (state.group) {
|
|
185
|
+
// caixas: org > projeto > produto (a caixa do produto contém o nó do produto e o conhecimento exclusivo dele)
|
|
186
|
+
const made = new Set();
|
|
187
|
+
const makeGroup = (p) => {
|
|
188
|
+
if (made.has(p)) return; made.add(p);
|
|
189
|
+
const m = /^grp:(org|project|product):(.+)$/.exec(p); if (!m) return;
|
|
190
|
+
const [, kind, key] = m;
|
|
191
|
+
let label = key, color = '#94a3b8', parent;
|
|
192
|
+
if (kind === 'org') { label = byId.get('org:' + key)?.name || key; color = '#e2e8f0'; }
|
|
193
|
+
if (kind === 'project') { label = byId.get('project:' + key)?.name || key; parent = 'grp:org:' + key.split('/')[0]; }
|
|
194
|
+
if (kind === 'product') { label = byId.get('product:' + key)?.name || key; color = '#14b8a6';
|
|
195
|
+
parent = 'grp:project:' + key.split('/').slice(0, 2).join('/'); }
|
|
196
|
+
els.push({ data: { id: p, label, color, parent, group: true, kind } });
|
|
197
|
+
if (parent) makeGroup(parent);
|
|
198
|
+
};
|
|
199
|
+
[...parents].forEach(makeGroup);
|
|
200
|
+
}
|
|
201
|
+
for (const l of g.links) {
|
|
202
|
+
if (!byId.has(l.source) || !byId.has(l.target)) continue;
|
|
203
|
+
if (state.group && STRUCT.has(l.type)) continue; // já representado pelas caixas
|
|
204
|
+
els.push({ data: { id: `${l.source}->${l.target}:${l.type}`, source: l.source, target: l.target, type: l.type,
|
|
205
|
+
label: EDGE_LABEL[l.type] || l.type, struct: STRUCT.has(l.type) || undefined } });
|
|
206
|
+
}
|
|
207
|
+
// nós org/projeto viram redundantes dentro das caixas (e qualquer aresta que aponte para eles sai junto)
|
|
208
|
+
if (!state.group) return els;
|
|
209
|
+
const drop = new Set(els.filter(e => e.data.type === 'organization' || e.data.type === 'project').map(e => e.data.id));
|
|
210
|
+
return els.filter(e => !drop.has(e.data.id) && !drop.has(e.data.source) && !drop.has(e.data.target));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function fitGraph(eles = cy.elements(':visible')) {
|
|
214
|
+
if (eles.empty()) return;
|
|
215
|
+
cy.stop();
|
|
216
|
+
cy.fit(eles, 32);
|
|
217
|
+
// Sparse graphs must not inflate typography to fill the viewport.
|
|
218
|
+
if (cy.zoom() > 1.25) cy.zoom(1.25);
|
|
219
|
+
cy.center(eles);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Resolve label collisions using model bounds, independent of viewport zoom.
|
|
223
|
+
function separateLabels() {
|
|
224
|
+
// Pack siblings bottom-up. Moving a compound moves its descendants together,
|
|
225
|
+
// so resolving outer boxes cannot reintroduce collisions inside a product.
|
|
226
|
+
const containers = cy.nodes(':visible').filter(':parent').toArray()
|
|
227
|
+
.sort((a, b) => b.ancestors().length - a.ancestors().length);
|
|
228
|
+
const levels = containers.map(p => p.children(':visible').toArray());
|
|
229
|
+
levels.push(cy.nodes(':visible').filter(n => n.parent().empty()).toArray());
|
|
230
|
+
for (const nodes of levels) separateSiblings(nodes);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function separateSiblings(nodes) {
|
|
234
|
+
const bounds = n => n.boundingBox({ includeLabels: true, includeOverlays: false });
|
|
235
|
+
for (let pass = 0; pass < 80; pass++) {
|
|
236
|
+
let moved = false;
|
|
237
|
+
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
|
|
238
|
+
const a = bounds(nodes[i]), b = bounds(nodes[j]);
|
|
239
|
+
const dx = Math.min(a.x2, b.x2) - Math.max(a.x1, b.x1) + 12;
|
|
240
|
+
const dy = Math.min(a.y2, b.y2) - Math.max(a.y1, b.y1) + 12;
|
|
241
|
+
if (dx <= 0 || dy <= 0) continue;
|
|
242
|
+
const axis = dx < dy ? 'x' : 'y';
|
|
243
|
+
const delta = (axis === 'x' ? dx : dy) / 2 + 1;
|
|
244
|
+
const sign = nodes[i].position(axis) <= nodes[j].position(axis) ? -1 : 1;
|
|
245
|
+
nodes[i].position(axis, nodes[i].position(axis) + sign * delta);
|
|
246
|
+
nodes[j].position(axis, nodes[j].position(axis) - sign * delta);
|
|
247
|
+
moved = true;
|
|
248
|
+
}
|
|
249
|
+
if (!moved) break;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function compactOverview() {
|
|
254
|
+
const leaves = cy.nodes(':visible').not(':parent').filter(n => !!n.style('label'));
|
|
255
|
+
if (leaves.empty()) return;
|
|
256
|
+
const minFont = Math.min(...cy.nodes(':visible').filter(n => !!n.style('label')).map(n => parseFloat(n.style('font-size'))));
|
|
257
|
+
// Preserve the chosen layout unless fitting a modest graph makes its labels
|
|
258
|
+
// unreadable. Repack siblings, not the viewport: no zoom inflation/clipping.
|
|
259
|
+
if (cy.zoom() * minFont >= 7 || leaves.length > 100) return;
|
|
260
|
+
const parents = cy.nodes(':visible').filter(':parent').toArray()
|
|
261
|
+
.sort((a, b) => b.ancestors().length - a.ancestors().length);
|
|
262
|
+
const levels = parents.map(p => p.children(':visible').toArray());
|
|
263
|
+
levels.push(cy.nodes(':visible').filter(n => n.parent().empty()).toArray());
|
|
264
|
+
const aspect = Math.max(.6, Math.min(1.8, cy.width() / cy.height()));
|
|
265
|
+
for (const nodes of levels) {
|
|
266
|
+
if (nodes.length < 2) continue;
|
|
267
|
+
const items = nodes.map(n => ({n, b:n.boundingBox({includeLabels:true, includeOverlays:false})}));
|
|
268
|
+
// Retain the layout's vertical ordering within comparable rectangles.
|
|
269
|
+
items.sort((a, b) => b.b.h - a.b.h || a.n.position('y') - b.n.position('y') || a.n.position('x') - b.n.position('x'));
|
|
270
|
+
const area = items.reduce((sum, {b}) => sum + (b.w + 16) * (b.h + 16), 0);
|
|
271
|
+
const width = Math.max(...items.map(({b}) => b.w), Math.sqrt(area * aspect));
|
|
272
|
+
let x = 0, y = 0, rowHeight = 0;
|
|
273
|
+
for (const {n, b} of items) {
|
|
274
|
+
if (x && x + b.w > width) { x = 0; y += rowHeight + 16; rowHeight = 0; }
|
|
275
|
+
n.position({x:n.position('x') + x - b.x1, y:n.position('y') + y - b.y1});
|
|
276
|
+
x += b.w + 16; rowHeight = Math.max(rowHeight, b.h);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
separateLabels();
|
|
280
|
+
fitGraph();
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function runLayout() {
|
|
284
|
+
const vis = cy.elements(':visible');
|
|
285
|
+
const opts = {
|
|
286
|
+
fcose: { name: 'fcose', quality: 'proof', animate: true, animationDuration: 500, randomize: true, nodeRepulsion: 9000,
|
|
287
|
+
idealEdgeLength: 90, edgeElasticity: .35, nestingFactor: .6, gravity: .3, gravityCompound: 1.2, packComponents: true, nodeSeparation: 90, tile: true },
|
|
288
|
+
dagre: { name: 'dagre', rankDir: 'TB', nodeSep: 14, rankSep: 70, ranker: 'tight-tree', animate: true, animationDuration: 400 },
|
|
289
|
+
concentric: { name: 'concentric', animate: true, minNodeSpacing: 22, concentric: n => {
|
|
290
|
+
const order = ['product','stack','tenant','agent','role','principle','constraint','heuristic','experience','telemetry_source','production_job'];
|
|
291
|
+
return 20 - Math.max(0, order.indexOf(n.data('type'))); }, levelWidth: () => 1 },
|
|
292
|
+
}[state.layout];
|
|
293
|
+
vis.layout({ ...opts, animate: false, nodeDimensionsIncludeLabels: true,
|
|
294
|
+
fit: false, padding: 40, stop: () => { separateLabels(); fitGraph(); compactOverview(); } }).run();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function details(n) {
|
|
298
|
+
const r = n.data('raw'), d = r.details || {}, t = TYPES[r.type] || {};
|
|
299
|
+
const rows = [];
|
|
300
|
+
rows.push(`<div class="title"><span class="glyph ${t.g}" style="background:${t.c};color:${t.c}"></span>${esc(r.name || r.id)}</div>
|
|
301
|
+
<span class="chip brand">${esc(t.n || r.type)}</span>`);
|
|
302
|
+
const texto = d.rule || d.principle || (d.when ? `QUANDO ${d.when}\nENTÃO ${d.then}` : '') || d.symptom || d.descricao || d.desc;
|
|
303
|
+
if (texto) rows.push(`<div class="rule">${esc(texto)}</div>`);
|
|
304
|
+
if (r.type === 'role') rows.push(`<div class="kv"><b>Atividade observada</b> ${r.observed ? 'Sim' : 'Sem observação nesta vista'}</div>
|
|
305
|
+
<div class="kv"><b>Cobertura de conhecimento</b> ${r.covered ? 'Vínculo explícito com regra' : 'Sem regra vinculada nesta vista'}</div>`);
|
|
306
|
+
if (r.type === 'agent') rows.push('<div class="kv"><b>Atividade observada</b> Identidade explícita registrada, não inferida do papel.</div>');
|
|
307
|
+
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>`);
|
|
308
|
+
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>`);
|
|
309
|
+
for (const k of ['scope', 'stack', 'tenant', 'agent_id', 'roles', 'project_id', 'project_ids', 'session_ids', 'trigger_regime', 'cliente', 'estado', 'eventos_count', 'agentes']) {
|
|
310
|
+
if (d[k] != null && d[k] !== '') rows.push(`<div class="kv"><b>${k.replace(/_/g, ' ')}</b> ${esc(Array.isArray(d[k]) ? d[k].join(', ') : d[k])}</div>`);
|
|
311
|
+
}
|
|
312
|
+
const nb = n.connectedEdges(':visible').map(e => {
|
|
313
|
+
const o = e.source().same(n) ? e.target() : e.source();
|
|
314
|
+
return `<div><span class="rel">${esc(e.data('label'))}</span><a data-id="${esc(o.id())}">${esc(o.data('label'))}</a></div>`;
|
|
315
|
+
});
|
|
316
|
+
rows.push(`<div class="eyebrow">Vizinhos · ${nb.length}</div><div id="nb">${nb.join('') || '<span class="muted">nenhum</span>'}</div>`);
|
|
317
|
+
rows.splice(rows.length - 1, 0, PFTel.panel(r));
|
|
318
|
+
$('details').innerHTML = rows.join('');
|
|
319
|
+
$('details').querySelectorAll('#nb a').forEach(a => a.onclick = () => focusNode(cy.getElementById(a.dataset.id)));
|
|
320
|
+
}
|
|
321
|
+
function focusNode(n) {
|
|
322
|
+
if (!n || n.empty() || n.data('group')) return;
|
|
323
|
+
cy.elements().removeClass('faded hl focus');
|
|
324
|
+
n.addClass('focus');
|
|
325
|
+
const hood = n.closedNeighborhood();
|
|
326
|
+
cy.elements().not(hood).not(hood.ancestors()).addClass('faded');
|
|
327
|
+
hood.addClass('hl');
|
|
328
|
+
details(n);
|
|
329
|
+
// Focus is readable even in a dense overview, but never inflates text.
|
|
330
|
+
cy.stop();
|
|
331
|
+
cy.zoom(Math.min(1.25, Math.max(cy.zoom(), 1)));
|
|
332
|
+
cy.center(n);
|
|
333
|
+
}
|
|
334
|
+
cy.on('tap', 'node', e => focusNode(e.target));
|
|
335
|
+
function clearFocus() {
|
|
336
|
+
cy.elements().removeClass('faded hl focus');
|
|
337
|
+
$('details').innerHTML = '<span class="muted">Clique num nó para ver regras, vínculos e vizinhos.</span>';
|
|
338
|
+
}
|
|
339
|
+
cy.on('tap', e => { if (e.target === cy) clearFocus(); });
|
|
340
|
+
// Relationship labels remain in Details, never rotated across canvas nodes.
|
|
341
|
+
|
|
342
|
+
$('q').oninput = () => {
|
|
343
|
+
const q = $('q').value.trim().toLowerCase();
|
|
344
|
+
cy.nodes().removeClass('match');
|
|
345
|
+
if (!q) return;
|
|
346
|
+
const m = cy.nodes(':visible').filter(n => !n.data('group') && String(n.data('label')).toLowerCase().includes(q));
|
|
347
|
+
m.addClass('match');
|
|
348
|
+
if (m.nonempty()) fitGraph(m);
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
function fillScope() {
|
|
352
|
+
const opt = (v, t, sel) => `<option value="${esc(v)}" ${v === sel ? 'selected' : ''}>${esc(t)}</option>`;
|
|
353
|
+
const org = catalog.find(o => o.id === state.org), proj = org?.projects.find(p => p.id === state.project);
|
|
354
|
+
$('org').innerHTML = opt('', 'Todas as organizações', state.org) + catalog.map(o => opt(o.id, o.name, state.org)).join('');
|
|
355
|
+
$('project').innerHTML = opt('', org ? 'Todos os projetos' : '—', state.project) + (org?.projects || []).map(p => opt(p.id, p.name, state.project)).join('');
|
|
356
|
+
$('product').innerHTML = opt('', proj ? 'Todos os produtos' : '—', state.product) + (proj?.products || []).map(p => opt(p.id, p.name, state.product)).join('');
|
|
357
|
+
$('project').disabled = !org; $('product').disabled = !proj;
|
|
358
|
+
}
|
|
359
|
+
$('org').onchange = () => { state.org = $('org').value; state.project = state.product = ''; load(); };
|
|
360
|
+
$('project').onchange = () => { state.project = $('project').value; state.product = ''; load(); };
|
|
361
|
+
$('product').onchange = () => { state.product = $('product').value; load(); };
|
|
362
|
+
$('role').onchange = () => { state.role = $('role').value; load(); };
|
|
363
|
+
$('layouts').querySelectorAll('button').forEach(b => b.onclick = () => { state.layout = b.dataset.l; syncUi(); runLayout(); });
|
|
364
|
+
$('group').onclick = () => { state.group = !state.group; syncUi(); render(); };
|
|
365
|
+
$('fit').onclick = () => { clearFocus(); fitGraph(); };
|
|
366
|
+
new ResizeObserver(() => { cy.resize(); fitGraph(); compactOverview(); }).observe($('cy'));
|
|
367
|
+
$('refresh').onclick = () => load();
|
|
368
|
+
|
|
369
|
+
function syncUi() {
|
|
370
|
+
$('layouts').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.l === state.layout));
|
|
371
|
+
$('group').classList.toggle('on', state.group);
|
|
372
|
+
const p = new URLSearchParams();
|
|
373
|
+
for (const k of ['org', 'project', 'product', 'role']) if (state[k]) p.set(k, state[k]);
|
|
374
|
+
if (state.tenant) p.set('tenant', state.tenant);
|
|
375
|
+
if (state.projectId) p.set('project_id', state.projectId);
|
|
376
|
+
if (state.layout !== 'fcose') p.set('layout', state.layout);
|
|
377
|
+
if (!state.group) p.set('group', '0');
|
|
378
|
+
PFTel.writeParams(p);
|
|
379
|
+
history.replaceState(null, '', '/graph2' + (p.toString() ? '?' + p : ''));
|
|
380
|
+
$('alternate').href = '/graph3' + (p.toString() ? '?' + p : '');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function render() {
|
|
384
|
+
cy.elements().remove();
|
|
385
|
+
cy.add(toElements(graph));
|
|
386
|
+
cy.nodes().forEach(n => n.toggleClass('typeoff', hidden.has(n.data('type'))));
|
|
387
|
+
const s = graph.stats || {};
|
|
388
|
+
$('stats').textContent = `${s.visible_nodes ?? graph.nodes.length} nós · ${s.visible_links ?? graph.links.length} arestas`;
|
|
389
|
+
$('observed-summary').textContent = `${s.observed_agents_count ?? 0} agentes explícitos · ${s.observed_roles_count ?? 0} papéis observados · ${s.jobs_count ?? 0} sessões · ${s.events_count ?? 0} eventos`;
|
|
390
|
+
const rules = (s.constraints_count || 0) + (s.heuristics_count || 0) + (s.principles_count || 0) + (s.experience_cases_count || 0);
|
|
391
|
+
$('coverage-summary').textContent = `${s.covered_roles_count ?? 0} papéis com vínculo explícito · ${rules} regras / casos visíveis`;
|
|
392
|
+
applyUsage(); applyTime();
|
|
393
|
+
legend(); runLayout();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/* ---- Telemetria ---- */
|
|
397
|
+
function applyUsage() {
|
|
398
|
+
if (!PFTel.data) return;
|
|
399
|
+
const sizes = PFTel.sizeMap(graph.nodes, graph.links);
|
|
400
|
+
cy.batch(() => cy.nodes().forEach(n => {
|
|
401
|
+
const raw = n.data('raw'); if (!raw) return;
|
|
402
|
+
const base = (TYPES[raw.type] || {}).s || 11;
|
|
403
|
+
n.data('size', base * (sizes.get(raw.id) || 1));
|
|
404
|
+
n.toggleClass('unused', PFTel.isUnused(raw));
|
|
405
|
+
}));
|
|
406
|
+
$('telsum').textContent = PFTel.summary();
|
|
407
|
+
$('feed').innerHTML = PFTel.feed(PFTel.data.recent);
|
|
408
|
+
}
|
|
409
|
+
const tb = () => PFTel.timeBounds(graph);
|
|
410
|
+
function applyTime() {
|
|
411
|
+
const b = tb(); if (!b) return;
|
|
412
|
+
const v = +$('time').value, t = b.min + (b.max - b.min) * v / 1000;
|
|
413
|
+
$('when').textContent = v >= 1000 ? 'agora' : PFTel.fmt(t);
|
|
414
|
+
cy.batch(() => cy.nodes().forEach(n => { const r = n.data('raw'); if (r) n.toggleClass('future', Date.parse(r.created_at) > t); }));
|
|
415
|
+
}
|
|
416
|
+
$('time').oninput = applyTime;
|
|
417
|
+
let playing = null;
|
|
418
|
+
$('play').onclick = () => {
|
|
419
|
+
if (playing) { clearInterval(playing); playing = null; $('play').textContent = '▶'; return; }
|
|
420
|
+
if (+$('time').value >= 1000) $('time').value = 0;
|
|
421
|
+
$('play').textContent = '❚❚';
|
|
422
|
+
playing = setInterval(() => { const v = Math.min(1000, +$('time').value + 12); $('time').value = v; applyTime(); if (v >= 1000) $('play').onclick(); }, 60);
|
|
423
|
+
};
|
|
424
|
+
let relayoutT = null;
|
|
425
|
+
PFTel.mountSizeControls($('sizectl'), () => { applyUsage(); syncUi(); clearTimeout(relayoutT); relayoutT = setTimeout(runLayout, 350); });
|
|
426
|
+
$('live').onclick = () => {
|
|
427
|
+
const on = !PFTel.live; $('live').classList.toggle('on', on);
|
|
428
|
+
PFTel.setLive(on, async (events, ids) => {
|
|
429
|
+
await load();
|
|
430
|
+
const hit = PFTel.matchNodes(graph.nodes, ids);
|
|
431
|
+
hit.forEach(id => { const n = cy.getElementById(id); n.addClass('pulse'); setTimeout(() => n.removeClass('pulse'), 2200); });
|
|
432
|
+
const sel = cy.nodes('.focus'); if (sel.nonempty()) details(sel[0]);
|
|
433
|
+
});
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
async function load() {
|
|
437
|
+
const p = new URLSearchParams();
|
|
438
|
+
if (state.org) p.set('organization', state.org);
|
|
439
|
+
if (state.org && state.project) p.set('project', state.project);
|
|
440
|
+
if (state.org && state.project && state.product) p.set('product', state.product);
|
|
441
|
+
if (state.role) p.set('role', state.role);
|
|
442
|
+
if (state.tenant) p.set('tenant', state.tenant);
|
|
443
|
+
if (state.projectId) p.set('project_id', state.projectId);
|
|
444
|
+
graph = await (await fetch('/api/v1/graph?' + p)).json();
|
|
445
|
+
await PFTel.load().catch(() => null);
|
|
446
|
+
catalog = graph.catalog || catalog;
|
|
447
|
+
const roles = [...new Set((graph.roles || []).map(r => r.role || r.id?.replace('role:', '')).filter(Boolean))].sort();
|
|
448
|
+
$('role').innerHTML = '<option value="">Lente: todos os papéis</option>' + roles.map(r => `<option ${r === state.role ? 'selected' : ''}>${esc(r)}</option>`).join('');
|
|
449
|
+
await document.fonts.ready;
|
|
450
|
+
fillScope(); syncUi(); render();
|
|
451
|
+
}
|
|
452
|
+
load();
|
|
453
|
+
</script>
|
|
454
|
+
</body>
|
|
455
|
+
</html>
|