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.
- 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 +138 -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 +322 -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,533 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { loadCatalog, linkCatalog, filterByScope, catalogFacets } = require('./catalog-linker');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Builds an advanced semantic Force-Directed Graph from CognitiveStore artifacts
|
|
9
|
+
* and connects an optional tenant-authorized telemetry ledger.
|
|
10
|
+
*/
|
|
11
|
+
function buildSemanticGraph(store, options = {}) {
|
|
12
|
+
const permitted = tenant => {
|
|
13
|
+
const authorized = !options.allowTenant || options.allowTenant(tenant ?? null);
|
|
14
|
+
return authorized && (!options.tenant || tenant === options.tenant);
|
|
15
|
+
};
|
|
16
|
+
const bytecodes = store.getBytecodes().filter(bc => permitted(bc.scope?.tenant ?? null));
|
|
17
|
+
const mapsDict = Object.fromEntries(Object.entries(store.getMapsDict()).filter(([tenant]) => permitted(tenant)));
|
|
18
|
+
const filterRole = options.role || null;
|
|
19
|
+
const restricted = Boolean(options.allowTenant || options.tenant);
|
|
20
|
+
// Keep legacy IDs where unambiguous. Namespace collisions instead of merging rules.
|
|
21
|
+
const owners = new Map();
|
|
22
|
+
const claim = (key, owner) => {
|
|
23
|
+
if (!owners.has(key)) owners.set(key, new Set());
|
|
24
|
+
owners.get(key).add(owner);
|
|
25
|
+
};
|
|
26
|
+
for (const bc of bytecodes) {
|
|
27
|
+
const namespace = JSON.stringify([bc.scope?.tenant ?? null, bc.id]);
|
|
28
|
+
claim(`stack:${bc.scope?.stack || 'general_stack'}`, JSON.stringify(bc.scope?.tenant ?? null));
|
|
29
|
+
for (const [type, field, id] of [['constraint', 'agent_constraints', 'id'], ['heuristic', 'agent_heuristics', 'id'],
|
|
30
|
+
['principle', 'decision_principles', 'id'], ['experience', 'experience_graph', 'problem_id']]) {
|
|
31
|
+
for (const rule of bc[field] || []) claim(`${type}:${rule[id]}`, namespace);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const artifactId = (type, id, namespace) => owners.get(`${type}:${id}`)?.size > 1
|
|
35
|
+
? `${type}:${namespace}:${id}` : `${type}:${id}`;
|
|
36
|
+
|
|
37
|
+
const nodes = [];
|
|
38
|
+
const links = [];
|
|
39
|
+
const nodeMap = new Map();
|
|
40
|
+
const linkKeys = new Set();
|
|
41
|
+
|
|
42
|
+
function addNode(node) {
|
|
43
|
+
if (!nodeMap.has(node.id)) {
|
|
44
|
+
nodeMap.set(node.id, node);
|
|
45
|
+
nodes.push(node);
|
|
46
|
+
}
|
|
47
|
+
return nodeMap.get(node.id);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function addLink(source, target, type, strength = 1) {
|
|
51
|
+
if (source && target && nodeMap.has(source) && nodeMap.has(target)) {
|
|
52
|
+
const key = JSON.stringify([source, target, type]);
|
|
53
|
+
if (linkKeys.has(key)) return;
|
|
54
|
+
linkKeys.add(key);
|
|
55
|
+
links.push({
|
|
56
|
+
source,
|
|
57
|
+
target,
|
|
58
|
+
type,
|
|
59
|
+
strength,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 1. Roles Centrais (Descobertos dinamicamente dos bytecodes carregados)
|
|
65
|
+
const discoveredRoleSet = new Set();
|
|
66
|
+
for (const bc of bytecodes) {
|
|
67
|
+
(bc.scope?.roles || []).forEach(r => discoveredRoleSet.add(r));
|
|
68
|
+
(bc.agent_constraints || []).forEach(c => (c.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
69
|
+
(bc.agent_heuristics || []).forEach(h => (h.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
70
|
+
(bc.decision_principles || []).forEach(p => (p.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
71
|
+
(bc.experience_graph || []).forEach(eg => (eg.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const roles = Array.from(discoveredRoleSet).map(roleKey => ({
|
|
75
|
+
id: `role:${roleKey}`,
|
|
76
|
+
name: roleKey.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
|
|
77
|
+
role: roleKey,
|
|
78
|
+
icon: '🤖',
|
|
79
|
+
desc: `Papel operacional de agente (${roleKey})`,
|
|
80
|
+
}));
|
|
81
|
+
|
|
82
|
+
roles.forEach(r => {
|
|
83
|
+
addNode({
|
|
84
|
+
id: r.id,
|
|
85
|
+
name: r.name,
|
|
86
|
+
label: `${r.icon} ${r.name}`,
|
|
87
|
+
type: 'role',
|
|
88
|
+
role: r.role,
|
|
89
|
+
val: 24,
|
|
90
|
+
color: '#3B82F6', // Blue
|
|
91
|
+
details: r,
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// 2. Tenants (Vaults)
|
|
96
|
+
for (const tenantKey of Object.keys(mapsDict)) {
|
|
97
|
+
const tenantId = `tenant:${tenantKey}`;
|
|
98
|
+
addNode({
|
|
99
|
+
id: tenantId,
|
|
100
|
+
name: `Vault: ${tenantKey}`,
|
|
101
|
+
label: `🟠 ${tenantKey}`,
|
|
102
|
+
type: 'tenant',
|
|
103
|
+
tenant: tenantKey,
|
|
104
|
+
val: 20,
|
|
105
|
+
color: '#F97316', // Orange
|
|
106
|
+
details: {
|
|
107
|
+
tenant: tenantKey,
|
|
108
|
+
content: mapsDict[tenantKey],
|
|
109
|
+
desc: 'Cofre semântico de fatos auditados e ontologias do tenant',
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// Conecta o tenant aos papéis que o mapa declara (<!-- roles: ... -->); sem anotação, a todos.
|
|
114
|
+
const declared = new Set();
|
|
115
|
+
for (const m of String(mapsDict[tenantKey] || '').matchAll(/<!--\s*roles:\s*([^>]+?)\s*-->/gi)) {
|
|
116
|
+
m[1].split(',').map(r => r.trim()).filter(Boolean).forEach(r => declared.add(r));
|
|
117
|
+
}
|
|
118
|
+
// '*' numa seção (ex.: vocabulário) não liga o tenant a papéis de outros tenants: vale só se for a única anotação.
|
|
119
|
+
const specific = new Set([...declared].filter(r => r !== '*'));
|
|
120
|
+
const tenantRoles = specific.size ? roles.filter(r => specific.has(r.role)) : roles;
|
|
121
|
+
tenantRoles.forEach(r => {
|
|
122
|
+
addLink(tenantId, r.id, 'provides_vault', 0.8);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 3. Stacks & Bytecodes
|
|
127
|
+
for (const bc of bytecodes) {
|
|
128
|
+
const namespace = JSON.stringify([bc.scope?.tenant ?? null, bc.id]);
|
|
129
|
+
const stackKey = bc.scope?.stack || 'general_stack';
|
|
130
|
+
const stackId = artifactId('stack', stackKey, JSON.stringify(bc.scope?.tenant ?? null));
|
|
131
|
+
// Nascimento do artefato para a linha do tempo: proveniência declarada, senão data do arquivo.
|
|
132
|
+
const bornAt = bc.provenance?.compiled_at || bc.provenance?.created_at || bc._file_mtime || undefined;
|
|
133
|
+
|
|
134
|
+
addNode({
|
|
135
|
+
id: stackId,
|
|
136
|
+
name: stackKey,
|
|
137
|
+
label: `🟣 ${stackKey}`,
|
|
138
|
+
type: 'stack',
|
|
139
|
+
stack: stackKey,
|
|
140
|
+
val: 22,
|
|
141
|
+
color: '#A855F7', // Purple
|
|
142
|
+
details: {
|
|
143
|
+
id: bc.id,
|
|
144
|
+
scope: bc.scope,
|
|
145
|
+
schema: bc.schema,
|
|
146
|
+
created_at: bornAt,
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// 3.1. Restrições Rígidas (agent_constraints)
|
|
151
|
+
if (Array.isArray(bc.agent_constraints)) {
|
|
152
|
+
for (const c of bc.agent_constraints) {
|
|
153
|
+
const cId = artifactId('constraint', c.id, namespace);
|
|
154
|
+
addNode({
|
|
155
|
+
id: cId,
|
|
156
|
+
name: c.id,
|
|
157
|
+
label: `🛑 ${c.id}`,
|
|
158
|
+
type: 'constraint',
|
|
159
|
+
val: c.graduation_candidate ? 16 : 14,
|
|
160
|
+
color: '#EF4444', // Red
|
|
161
|
+
target_roles: c.target_roles || [],
|
|
162
|
+
details: {
|
|
163
|
+
...c,
|
|
164
|
+
kind: 'agent_constraint',
|
|
165
|
+
created_at: c.created_at || bornAt,
|
|
166
|
+
stack: stackKey,
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
addLink(stackId, cId, 'contains_rule', 1);
|
|
170
|
+
|
|
171
|
+
// Conecta aos papéis-alvo
|
|
172
|
+
(c.target_roles || []).forEach(r => {
|
|
173
|
+
addLink(`role:${r}`, cId, 'targets_role', 1.2);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// 3.2. Heurísticas Operacionais (agent_heuristics)
|
|
179
|
+
if (Array.isArray(bc.agent_heuristics)) {
|
|
180
|
+
for (const h of bc.agent_heuristics) {
|
|
181
|
+
const hId = artifactId('heuristic', h.id, namespace);
|
|
182
|
+
const evidenceCount = h.evidence_count || 1;
|
|
183
|
+
addNode({
|
|
184
|
+
id: hId,
|
|
185
|
+
name: h.id,
|
|
186
|
+
label: `💡 ${h.id}`,
|
|
187
|
+
type: 'heuristic',
|
|
188
|
+
val: 12 + evidenceCount * 2,
|
|
189
|
+
color: '#EAB308', // Yellow
|
|
190
|
+
target_roles: h.target_roles || [],
|
|
191
|
+
details: {
|
|
192
|
+
...h,
|
|
193
|
+
kind: 'agent_heuristic',
|
|
194
|
+
created_at: h.created_at || bornAt,
|
|
195
|
+
stack: stackKey,
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
addLink(stackId, hId, 'contains_rule', 1);
|
|
199
|
+
|
|
200
|
+
(h.target_roles || []).forEach(r => {
|
|
201
|
+
addLink(`role:${r}`, hId, 'targets_role', 1.0);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 3.3. Princípios Decisórios (decision_principles)
|
|
207
|
+
if (Array.isArray(bc.decision_principles)) {
|
|
208
|
+
for (const p of bc.decision_principles) {
|
|
209
|
+
const pId = artifactId('principle', p.id, namespace);
|
|
210
|
+
addNode({
|
|
211
|
+
id: pId,
|
|
212
|
+
name: p.id,
|
|
213
|
+
label: `🟢 ${p.principle || p.id}`,
|
|
214
|
+
type: 'principle',
|
|
215
|
+
val: 15,
|
|
216
|
+
color: '#10B981', // Green
|
|
217
|
+
target_roles: p.target_roles || [],
|
|
218
|
+
details: {
|
|
219
|
+
...p,
|
|
220
|
+
kind: 'decision_principle',
|
|
221
|
+
created_at: p.created_at || bornAt,
|
|
222
|
+
stack: stackKey,
|
|
223
|
+
},
|
|
224
|
+
});
|
|
225
|
+
addLink(stackId, pId, 'contains_rule', 1);
|
|
226
|
+
|
|
227
|
+
(p.target_roles || []).forEach(r => {
|
|
228
|
+
addLink(`role:${r}`, pId, 'targets_role', 1.1);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 3.4. Casos do Grafo de Experiência (experience_graph)
|
|
234
|
+
if (Array.isArray(bc.experience_graph)) {
|
|
235
|
+
for (const eg of bc.experience_graph) {
|
|
236
|
+
const egId = artifactId('experience', eg.problem_id, namespace);
|
|
237
|
+
addNode({
|
|
238
|
+
id: egId,
|
|
239
|
+
name: eg.problem_id,
|
|
240
|
+
label: `🔵 ${eg.problem_id}`,
|
|
241
|
+
type: 'experience',
|
|
242
|
+
val: 17,
|
|
243
|
+
color: '#06B6D4', // Cyan
|
|
244
|
+
target_roles: eg.target_roles || [],
|
|
245
|
+
details: {
|
|
246
|
+
...eg,
|
|
247
|
+
kind: 'experience_graph_case',
|
|
248
|
+
created_at: eg.created_at || bornAt,
|
|
249
|
+
stack: stackKey,
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
addLink(stackId, egId, 'contains_case', 1);
|
|
253
|
+
|
|
254
|
+
(eg.target_roles || []).forEach(r => {
|
|
255
|
+
addLink(`role:${r}`, egId, 'targets_role', 1.0);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// 4. Optional deployment-neutral ledger, local to this store.
|
|
262
|
+
const telemetryFile = options.telemetryFile || (store.storeDir && path.join(store.storeDir, 'telemetry', 'ledger.json'));
|
|
263
|
+
let telemetry = options.telemetry && typeof options.telemetry === 'object' ? options.telemetry : null;
|
|
264
|
+
if (options.telemetry !== false && !telemetry && telemetryFile && fs.existsSync(telemetryFile)) {
|
|
265
|
+
try {
|
|
266
|
+
telemetry = JSON.parse(fs.readFileSync(telemetryFile, 'utf8'));
|
|
267
|
+
} catch (_) {}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const jobTenant = job => job.tenant ?? (options.telemetryTenantField === 'cliente' ? job.cliente : null);
|
|
271
|
+
if (telemetry) telemetry = { jobs: (Array.isArray(telemetry.jobs) ? telemetry.jobs : [])
|
|
272
|
+
.filter(job => job && permitted(jobTenant(job))).map(job => ({ ...job, tenant: jobTenant(job) })) };
|
|
273
|
+
for (const job of telemetry?.jobs || []) claim(`job:${job.id}`, JSON.stringify(job.tenant ?? null));
|
|
274
|
+
|
|
275
|
+
if (telemetry && telemetry.jobs.length > 0) {
|
|
276
|
+
const telemetrySourceId = 'source:telemetry';
|
|
277
|
+
addNode({
|
|
278
|
+
id: telemetrySourceId,
|
|
279
|
+
name: 'Observed activity',
|
|
280
|
+
label: 'Observed activity',
|
|
281
|
+
type: 'telemetry_source',
|
|
282
|
+
val: 28,
|
|
283
|
+
color: '#0284C7', // Sky Blue
|
|
284
|
+
details: {
|
|
285
|
+
jobs_count: telemetry.jobs.length,
|
|
286
|
+
desc: 'Authorized observed sessions, independent of knowledge coverage.',
|
|
287
|
+
},
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const rolesByName = new Map(roles.map(role => [role.role, role]));
|
|
291
|
+
const observeRole = role => {
|
|
292
|
+
if (typeof role !== 'string' || !role.trim()) return null;
|
|
293
|
+
let known = rolesByName.get(role);
|
|
294
|
+
if (!known) {
|
|
295
|
+
const name = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
|
|
296
|
+
known = { id: `role:${role}`, role, name, icon: '🤖' };
|
|
297
|
+
roles.push(known);
|
|
298
|
+
rolesByName.set(role, known);
|
|
299
|
+
addNode({ id: known.id, name, label: `🤖 ${name}`, type: 'role', role,
|
|
300
|
+
val: 24, color: '#3B82F6', details: { role, desc: 'Observed role, not an inferred agent identity.' } });
|
|
301
|
+
}
|
|
302
|
+
return known.id;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
for (const job of telemetry.jobs) {
|
|
306
|
+
const jobId = artifactId('job', job.id, JSON.stringify(job.tenant ?? null));
|
|
307
|
+
const rawTitle = String(job.titulo || job.id || 'Untitled job');
|
|
308
|
+
const shortTitle = rawTitle.length > 22 ? rawTitle.slice(0, 21) + '…' : rawTitle;
|
|
309
|
+
const observations = (Array.isArray(job.observations) ? job.observations : []).filter(o => o && typeof o === 'object')
|
|
310
|
+
.map(o => ({ agent_id: typeof o.agent_id === 'string' && o.agent_id.trim() ? o.agent_id : null,
|
|
311
|
+
role: typeof o.role === 'string' && o.role.trim() ? o.role : null,
|
|
312
|
+
project_id: typeof o.project_id === 'string' ? o.project_id : null,
|
|
313
|
+
timestamp: toIso(o.timestamp), event_id: typeof o.event_id === 'string' ? o.event_id : null }));
|
|
314
|
+
|
|
315
|
+
addNode({
|
|
316
|
+
id: jobId,
|
|
317
|
+
name: rawTitle,
|
|
318
|
+
label: `🎬 ${shortTitle}`,
|
|
319
|
+
type: 'production_job',
|
|
320
|
+
val: 16,
|
|
321
|
+
color: '#EC4899', // Pink
|
|
322
|
+
details: {
|
|
323
|
+
id: job.id,
|
|
324
|
+
tenant: jobTenant(job),
|
|
325
|
+
project_id: job.project_id || null,
|
|
326
|
+
observations,
|
|
327
|
+
created_at: job.created_at || job.last_seen,
|
|
328
|
+
titulo: rawTitle,
|
|
329
|
+
cliente: job.cliente,
|
|
330
|
+
estado: job.estado,
|
|
331
|
+
eventos_count: job.eventos_count,
|
|
332
|
+
agentes: job.agentes,
|
|
333
|
+
amostra_eventos: job.amostra_eventos,
|
|
334
|
+
desc: `Production job with ${job.eventos_count || 0} reported events`,
|
|
335
|
+
},
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
addLink(telemetrySourceId, jobId, 'dispatched_job', 0.9);
|
|
339
|
+
|
|
340
|
+
// Link to tenant dynamically
|
|
341
|
+
const defaultTenantKey = jobTenant(job);
|
|
342
|
+
if (defaultTenantKey) {
|
|
343
|
+
addLink(jobId, `tenant:${defaultTenantKey}`, 'belongs_to_tenant', 0.8);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Legacy agentes are declared roles, never evidence of an agent identity.
|
|
347
|
+
const observedRoles = new Set([...(Array.isArray(job.agentes) ? job.agentes : []), ...observations.map(o => o.role)]);
|
|
348
|
+
for (const role of observedRoles) addLink(observeRole(role), jobId, 'executed_by', 0.7);
|
|
349
|
+
|
|
350
|
+
for (const observation of observations) {
|
|
351
|
+
if (!observation.agent_id) continue;
|
|
352
|
+
const agentId = `agent:${JSON.stringify([job.tenant ?? null, observation.agent_id])}`;
|
|
353
|
+
const agent = addNode({ id: agentId, name: observation.agent_id, label: observation.agent_id,
|
|
354
|
+
type: 'agent', agent_id: observation.agent_id, tenant: job.tenant ?? null, observed: true,
|
|
355
|
+
val: 18, color: '#A78BFA', details: { agent_id: observation.agent_id, tenant: job.tenant ?? null,
|
|
356
|
+
roles: [], project_ids: [], session_ids: [], observations: [], created_at: null, last_seen: null,
|
|
357
|
+
desc: 'Explicitly observed agent identity, separate from its operational roles.' } });
|
|
358
|
+
const detail = agent.details;
|
|
359
|
+
detail.observations.push({ ...observation, session_id: job.id });
|
|
360
|
+
if (observation.role && !detail.roles.includes(observation.role)) detail.roles.push(observation.role);
|
|
361
|
+
if (observation.project_id && !detail.project_ids.includes(observation.project_id)) detail.project_ids.push(observation.project_id);
|
|
362
|
+
if (!detail.session_ids.includes(job.id)) detail.session_ids.push(job.id);
|
|
363
|
+
const ts = observation.timestamp;
|
|
364
|
+
if (ts && (!detail.created_at || ts < detail.created_at)) detail.created_at = ts;
|
|
365
|
+
if (ts && (!detail.last_seen || ts > detail.last_seen)) detail.last_seen = ts;
|
|
366
|
+
addLink(agentId, jobId, 'executed_session', 0.9);
|
|
367
|
+
addLink(agentId, observeRole(observation.role), 'performs_role', 0.8);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Restricted graphs never consult a global portfolio catalog.
|
|
373
|
+
const catalog = restricted ? null : loadCatalog(options);
|
|
374
|
+
const linked = catalog
|
|
375
|
+
? linkCatalog({ catalog, nodes, links, addNode, addLink, bytecodes, telemetry })
|
|
376
|
+
: { flat: [], linked: 0 };
|
|
377
|
+
|
|
378
|
+
// Recorte opcional por organização / projeto / produto
|
|
379
|
+
const scoped = filterByScope(nodes, links, linked.flat, {
|
|
380
|
+
organization: options.organization, project: options.project, product: options.product,
|
|
381
|
+
});
|
|
382
|
+
const scopeNodes = scoped ? scoped.nodes : nodes;
|
|
383
|
+
const scopeLinks = scoped ? scoped.links : links;
|
|
384
|
+
|
|
385
|
+
// Filtragem opcional de subgrafo por papel (Role Lens)
|
|
386
|
+
let filteredNodes = scopeNodes;
|
|
387
|
+
let filteredLinks = scopeLinks;
|
|
388
|
+
|
|
389
|
+
if (filterRole) {
|
|
390
|
+
const roleId = `role:${filterRole}`;
|
|
391
|
+
const connectedNodeIds = new Set([roleId]);
|
|
392
|
+
|
|
393
|
+
// Encontra todos os nós conectados diretamente ao papel ou que têm esse papel nos target_roles
|
|
394
|
+
scopeLinks.forEach(l => {
|
|
395
|
+
if (l.source === roleId) connectedNodeIds.add(l.target);
|
|
396
|
+
if (l.target === roleId) connectedNodeIds.add(l.source);
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
scopeNodes.forEach(n => {
|
|
400
|
+
if (n.target_roles && n.target_roles.includes(filterRole)) {
|
|
401
|
+
connectedNodeIds.add(n.id);
|
|
402
|
+
}
|
|
403
|
+
if (['stack', 'tenant', 'telemetry_source', 'organization', 'project', 'product'].includes(n.type)) {
|
|
404
|
+
connectedNodeIds.add(n.id);
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
filteredNodes = scopeNodes.map(n => ({
|
|
409
|
+
...n,
|
|
410
|
+
activeInRole: connectedNodeIds.has(n.id),
|
|
411
|
+
opacity: connectedNodeIds.has(n.id) ? 1.0 : 0.15,
|
|
412
|
+
}));
|
|
413
|
+
|
|
414
|
+
filteredLinks = scopeLinks.map(l => ({
|
|
415
|
+
...l,
|
|
416
|
+
activeInRole: connectedNodeIds.has(l.source) && connectedNodeIds.has(l.target),
|
|
417
|
+
opacity: (connectedNodeIds.has(l.source) && connectedNodeIds.has(l.target)) ? 1.0 : 0.08,
|
|
418
|
+
}));
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
assignTimestamps(filteredNodes, filteredLinks, telemetry);
|
|
422
|
+
const count = type => filteredNodes.filter(n => n.type === type).length;
|
|
423
|
+
for (const node of filteredNodes) {
|
|
424
|
+
if (node.type === 'telemetry_source') node.details.jobs_count = count('production_job');
|
|
425
|
+
}
|
|
426
|
+
const visibleRoles = filteredNodes.filter(n => n.type === 'role');
|
|
427
|
+
const coveredRoles = new Set(filteredLinks.filter(l => l.type === 'targets_role').map(l => l.source));
|
|
428
|
+
const observedRoles = new Set(filteredLinks.filter(l => l.type === 'executed_by').map(l => l.source));
|
|
429
|
+
for (const role of visibleRoles) {
|
|
430
|
+
role.observed = observedRoles.has(role.id);
|
|
431
|
+
role.covered = coveredRoles.has(role.id);
|
|
432
|
+
}
|
|
433
|
+
const eventsCount = filteredNodes.filter(n => n.type === 'production_job').reduce((total, n) => {
|
|
434
|
+
const v = n.details.eventos_count;
|
|
435
|
+
return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? Math.min(Number.MAX_SAFE_INTEGER, total + v) : total;
|
|
436
|
+
}, 0);
|
|
437
|
+
const stats = {
|
|
438
|
+
total_nodes: filteredNodes.length,
|
|
439
|
+
total_links: filteredLinks.length,
|
|
440
|
+
constraints_count: count('constraint'),
|
|
441
|
+
heuristics_count: count('heuristic'),
|
|
442
|
+
principles_count: count('principle'),
|
|
443
|
+
experience_cases_count: count('experience'),
|
|
444
|
+
roles_count: visibleRoles.length,
|
|
445
|
+
agents_count: count('agent'),
|
|
446
|
+
observed_agents_count: count('agent'),
|
|
447
|
+
observed_roles_count: observedRoles.size,
|
|
448
|
+
covered_roles_count: coveredRoles.size,
|
|
449
|
+
tenants_count: count('tenant'),
|
|
450
|
+
jobs_count: count('production_job'),
|
|
451
|
+
events_count: eventsCount,
|
|
452
|
+
// Legacy names retained as aliases, not provider claims or global ledger totals.
|
|
453
|
+
azure_jobs_count: count('production_job'),
|
|
454
|
+
azure_events_count: eventsCount,
|
|
455
|
+
azure_source: null,
|
|
456
|
+
organizations_count: count('organization'),
|
|
457
|
+
projects_count: count('project'),
|
|
458
|
+
products_count: count('product'),
|
|
459
|
+
linked_knowledge_count: filteredNodes.filter(n => n.products?.length && !['organization', 'project', 'product'].includes(n.type)).length,
|
|
460
|
+
visible_nodes: filteredNodes.length,
|
|
461
|
+
visible_links: filteredLinks.length,
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
return {
|
|
465
|
+
nodes: filteredNodes,
|
|
466
|
+
links: filteredLinks,
|
|
467
|
+
stats,
|
|
468
|
+
timeline: (() => {
|
|
469
|
+
const t = filteredNodes.map(n => n.created_at).filter(Boolean).sort();
|
|
470
|
+
return { start: t[0] || null, end: t[t.length - 1] || null };
|
|
471
|
+
})(),
|
|
472
|
+
roles: visibleRoles.map(r => ({ id: r.role, name: r.name, icon: '🤖',
|
|
473
|
+
observed: observedRoles.has(r.id), covered: coveredRoles.has(r.id) })),
|
|
474
|
+
catalog: catalog ? catalogFacets(catalog) : [],
|
|
475
|
+
scope: scoped ? scoped.selection : null,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function toIso(v) {
|
|
480
|
+
if (!v) return null;
|
|
481
|
+
const d = new Date(v);
|
|
482
|
+
return isNaN(d.getTime()) ? null : d.toISOString();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Atribui created_at a cada nó e link (para animação temporal de construção).
|
|
487
|
+
* Ordem de prioridade: created_at explícito > primeiro evento (jobs) > origem inferida.
|
|
488
|
+
* created_at_source: 'explicit' | 'events' | 'inferred'
|
|
489
|
+
*/
|
|
490
|
+
function assignTimestamps(nodes, links, telemetry) {
|
|
491
|
+
const byId = new Map(nodes.map(n => [n.id, n]));
|
|
492
|
+
const jobsById = new Map();
|
|
493
|
+
for (const job of telemetry?.jobs || []) {
|
|
494
|
+
jobsById.set(`job:${JSON.stringify(job.tenant ?? null)}:${job.id}`, job);
|
|
495
|
+
// Legacy externally supplied nodes still use job:<id>.
|
|
496
|
+
jobsById.set(`job:${job.id}`, job);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
for (const n of nodes) {
|
|
500
|
+
const d = n.details || {};
|
|
501
|
+
let ts = toIso(d.created_at);
|
|
502
|
+
let src = ts ? 'explicit' : null;
|
|
503
|
+
if (!ts && n.type === 'production_job') {
|
|
504
|
+
const evTs = (Array.isArray(d.amostra_eventos) ? d.amostra_eventos : []).map(e => toIso(e && (e.ts || e.timestamp))).filter(Boolean).sort();
|
|
505
|
+
const job = jobsById.get(n.id) || {};
|
|
506
|
+
ts = evTs[0] || toIso(job.created_at) || toIso(job.last_seen);
|
|
507
|
+
if (ts) src = 'events';
|
|
508
|
+
}
|
|
509
|
+
n.created_at = ts;
|
|
510
|
+
n.created_at_source = src;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const known = nodes.map(n => n.created_at).filter(Boolean).sort();
|
|
514
|
+
const origin = known[0]
|
|
515
|
+
? new Date(new Date(known[0]).getTime() - 60 * 60 * 1000).toISOString()
|
|
516
|
+
: new Date().toISOString();
|
|
517
|
+
|
|
518
|
+
// Fonte de telemetria nasce junto com o primeiro job
|
|
519
|
+
const firstJob = nodes.filter(n => n.type === 'production_job' && n.created_at).map(n => n.created_at).sort()[0];
|
|
520
|
+
for (const n of nodes) {
|
|
521
|
+
if (n.created_at) continue;
|
|
522
|
+
n.created_at = (n.type === 'telemetry_source' && firstJob) ? firstJob : origin;
|
|
523
|
+
n.created_at_source = 'inferred';
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
for (const l of links) {
|
|
527
|
+
const a = byId.get(l.source)?.created_at || origin;
|
|
528
|
+
const b = byId.get(l.target)?.created_at || origin;
|
|
529
|
+
l.created_at = a > b ? a : b;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
module.exports = { buildSemanticGraph, assignTimestamps };
|