cognitivebc 0.0.0-stage → 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 +99 -2
- 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 -0
- package/package.json +59 -4
- 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,64 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createHttpBackend } = require('./http-backend');
|
|
4
|
+
const { TOOLS, SERVER_INSTRUCTIONS, registerTools, registerPrompts } = require('./tools');
|
|
5
|
+
|
|
6
|
+
const PKG = require('../../package.json');
|
|
7
|
+
const REMOTE_INSTRUCTIONS = `${SERVER_INSTRUCTIONS}\nThis is the remote (HTTP) endpoint: it cannot read your workspace. Call cbc_identify_project once with git_remote/root_commit (or project_id), then pass tenant/project_id from its answer to the other tools.`;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Remote MCP endpoint (Streamable HTTP, stateless JSON responses) at /mcp.
|
|
11
|
+
* Each request authenticates with the same bearer principal as the REST API
|
|
12
|
+
* and is executed through the REST contract on loopback, so authorization,
|
|
13
|
+
* tenant isolation and telemetry stay in one code path.
|
|
14
|
+
*/
|
|
15
|
+
function createMcpRoute({ path = '/mcp' } = {}) {
|
|
16
|
+
const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js');
|
|
17
|
+
const { StreamableHTTPServerTransport } = require('@modelcontextprotocol/sdk/server/streamableHttp.js');
|
|
18
|
+
return async function mcpRoute({ req, res, method, pathname, principal, parseBody, sendJson }) {
|
|
19
|
+
if (pathname !== path) return false;
|
|
20
|
+
if (principal.anonymous) {
|
|
21
|
+
res.setHeader('WWW-Authenticate', 'Bearer realm="cognitivebc"');
|
|
22
|
+
sendJson(401, { error: 'Authentication required' });
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
if (method !== 'POST') {
|
|
26
|
+
res.setHeader('Allow', 'POST');
|
|
27
|
+
sendJson(405, { jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed (stateless server: use POST)' }, id: null });
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
const body = await parseBody();
|
|
31
|
+
const port = req.socket.localPort;
|
|
32
|
+
if (!port) { sendJson(503, { error: 'MCP loopback unavailable' }); return true; }
|
|
33
|
+
const apiKey = /^Bearer (\S+)$/i.exec(req.headers.authorization || '')?.[1] || '';
|
|
34
|
+
let identity = { manifest: null, git_remotes: [], root_commits: [], path_hint: 'remote-mcp' };
|
|
35
|
+
const backend = () => createHttpBackend({ baseUrl: `http://127.0.0.1:${port}`, apiKey, identity });
|
|
36
|
+
let current = backend();
|
|
37
|
+
const invoke = async (name, args) => {
|
|
38
|
+
if (name === 'cbc_identify_project') {
|
|
39
|
+
const { normalizeGitRemote } = require('../cbc-identity');
|
|
40
|
+
identity = {
|
|
41
|
+
manifest: args.project_id ? { project_id: args.project_id } : null,
|
|
42
|
+
git_remotes: args.git_remote ? [normalizeGitRemote(args.git_remote)].filter(Boolean) : [],
|
|
43
|
+
root_commits: args.root_commit && /^[a-f0-9]{40}$/i.test(args.root_commit) ? [args.root_commit.toLowerCase()] : [],
|
|
44
|
+
path_hint: 'remote-mcp',
|
|
45
|
+
};
|
|
46
|
+
if (!identity.manifest && !identity.git_remotes.length && !identity.root_commits.length) {
|
|
47
|
+
return { status: 'unknown', hint: 'Pass git_remote, root_commit or project_id so the server can recognize the project.' };
|
|
48
|
+
}
|
|
49
|
+
current = backend();
|
|
50
|
+
}
|
|
51
|
+
return current.invoke(name, args);
|
|
52
|
+
};
|
|
53
|
+
const server = new McpServer({ name: 'cognitivebc', version: PKG.version }, { instructions: REMOTE_INSTRUCTIONS });
|
|
54
|
+
registerTools(server, invoke);
|
|
55
|
+
registerPrompts(server);
|
|
56
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
57
|
+
res.on('close', () => { transport.close().catch(() => {}); server.close().catch(() => {}); });
|
|
58
|
+
await server.connect(transport);
|
|
59
|
+
await transport.handleRequest(req, res, body);
|
|
60
|
+
return true;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = { createMcpRoute, TOOLS };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { verifyGateRules } = require('../cbc-compiler');
|
|
4
|
+
const { resolveAuthorizedContext } = require('../../services/cbc-api/context-service');
|
|
5
|
+
const { createAccessPolicy, authorize, assertTenant, createStoreView, selectMapSection, fail } = require('../../services/cbc-api/access-policy');
|
|
6
|
+
|
|
7
|
+
/** Principal belongs to the trusted transport context, never to tool arguments. */
|
|
8
|
+
function createMcpHandlers(store, options = {}) {
|
|
9
|
+
const policy = createAccessPolicy({ auth: options.auth });
|
|
10
|
+
const principal = policy.principalFromContext(options.principal);
|
|
11
|
+
if (policy.configured && !options.principal) fail(401, 'Authenticated MCP context required');
|
|
12
|
+
function view(scope = {}) {
|
|
13
|
+
authorize(principal, 'read');
|
|
14
|
+
if (!scope || typeof scope !== 'object' || Array.isArray(scope)) fail(400, 'Invalid scope');
|
|
15
|
+
assertTenant(principal, scope.tenant);
|
|
16
|
+
return createStoreView(store, principal, scope);
|
|
17
|
+
}
|
|
18
|
+
const handlers = {
|
|
19
|
+
cbc_get_context: async (params = {}) => resolveAuthorizedContext({ store, principal, params }),
|
|
20
|
+
cbc_pull_experience: async ({ scope = {}, topic } = {}) => {
|
|
21
|
+
const bytecodes = view(scope).getBytecodes();
|
|
22
|
+
if (topic !== undefined && typeof topic !== 'string') fail(400, 'Invalid topic');
|
|
23
|
+
if (scope.role !== undefined && (typeof scope.role !== 'string' || !scope.role.trim())) fail(400, 'Invalid role');
|
|
24
|
+
const matched = bytecodes.flatMap(b => (b.agent_heuristics || []).filter(h => {
|
|
25
|
+
const roles = h.target_roles;
|
|
26
|
+
const permittedRole = !scope.role || !Array.isArray(roles) || roles.length === 0 || roles.includes('*') || roles.includes(scope.role);
|
|
27
|
+
return permittedRole && (!topic || [h.when, h.then].some(text => typeof text === 'string' && text.toLowerCase().includes(topic.toLowerCase())));
|
|
28
|
+
}));
|
|
29
|
+
return { results: matched.slice(0, 5), count: matched.length };
|
|
30
|
+
},
|
|
31
|
+
cbc_read_tenant_map: async ({ tenant, section } = {}) => {
|
|
32
|
+
if (typeof tenant !== 'string' || !tenant.trim()) fail(400, 'Tenant required');
|
|
33
|
+
const content = view({ tenant }).getMap(tenant);
|
|
34
|
+
if (!content) return { error: 'Map not found' };
|
|
35
|
+
const selected = selectMapSection(content, section);
|
|
36
|
+
if (selected === null) return { error: 'Map section not found' };
|
|
37
|
+
return { tenant, ...(section ? { section } : {}), content: selected };
|
|
38
|
+
},
|
|
39
|
+
cbc_check_gate_rules: async ({ stage, draft_json = {}, scope = {}, tenant } = {}) => {
|
|
40
|
+
view(scope); // Validate the original object before merging a legacy tenant alias.
|
|
41
|
+
if (tenant && scope.tenant && tenant !== scope.tenant) fail(400, 'Conflicting tenant scope');
|
|
42
|
+
const selected = view({ ...scope, ...(tenant ? { tenant } : {}) });
|
|
43
|
+
return verifyGateRules({ stage, draftPayload: draft_json, bytecodes: selected.getBytecodes() });
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
handlers.get_context = handlers.cbc_get_context;
|
|
47
|
+
return handlers;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
module.exports = { createMcpHandlers };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { z } = require('zod');
|
|
4
|
+
|
|
5
|
+
const SERVER_INSTRUCTIONS = [
|
|
6
|
+
'CognitiveBC provides governed organizational context, experience and quality gates for this project.',
|
|
7
|
+
'1. At the START of every task call cbc_get_context with your role (e.g. "developer", "reviewer", "architect") and a short task description. Follow the returned constraints.',
|
|
8
|
+
'2. Use cbc_pull_experience for lessons learned on a specific topic and cbc_read_tenant_map for tenant-level structure.',
|
|
9
|
+
'3. BEFORE delivering a result, call cbc_check_gate_rules with the stage and your draft as JSON, and fix any violations.',
|
|
10
|
+
'4. When the user corrects you, or you correct yourself after several attempts, call cbc_report_learning. It only creates a reviewable candidate, never publishes directly.',
|
|
11
|
+
'If the project is unknown, call cbc_identify_project and suggest running `cognitivebc init`.',
|
|
12
|
+
].join('\n');
|
|
13
|
+
|
|
14
|
+
const TOOLS = [
|
|
15
|
+
{
|
|
16
|
+
name: 'cbc_identify_project',
|
|
17
|
+
title: 'Identify project',
|
|
18
|
+
description: 'Identify the current workspace project in CognitiveBC (by manifest, git remotes, root commits). Returns status known|probable|new|forbidden and the project (tenant, stack, squad) when known. Call this if context looks generic or a tenant is needed. Remote (HTTP) clients cannot read the workspace: pass git_remote (output of `git remote get-url origin`) and/or root_commit (`git rev-list --max-parents=0 HEAD`) or project_id from .cognitivebc.yaml.',
|
|
19
|
+
inputSchema: {
|
|
20
|
+
git_remote: z.string().optional().describe('Remote URL of the repository (remote clients only)'),
|
|
21
|
+
root_commit: z.string().optional().describe('Root commit SHA of the repository (remote clients only)'),
|
|
22
|
+
project_id: z.string().optional().describe('project_id from .cognitivebc.yaml (remote clients only)'),
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: 'cbc_get_context',
|
|
27
|
+
title: 'Get task context',
|
|
28
|
+
description: 'Fetch governed context (rules, constraints, heuristics) for your role and task. Call at the START of every task. Tenant, project and stack default to the identified project.',
|
|
29
|
+
inputSchema: {
|
|
30
|
+
role: z.string().min(1).describe('Your role, e.g. developer, reviewer, architect, qa'),
|
|
31
|
+
task: z.string().optional().describe('Short description of the task at hand'),
|
|
32
|
+
query: z.string().optional().describe('Free-text query to focus retrieval'),
|
|
33
|
+
stacks: z.array(z.string()).optional().describe('Technology stacks, e.g. ["node","postgres"]'),
|
|
34
|
+
max_tokens: z.number().int().min(100).max(2000).optional().describe('Context budget in tokens (100..2000)'),
|
|
35
|
+
tenant: z.string().optional().describe('Override tenant (defaults to the project tenant)'),
|
|
36
|
+
project_id: z.string().optional().describe('Override project id'),
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: 'cbc_pull_experience',
|
|
41
|
+
title: 'Pull experience',
|
|
42
|
+
description: 'Retrieve accumulated experience and heuristics (lessons learned, past corrections) on a topic. Use when facing a non-trivial decision.',
|
|
43
|
+
inputSchema: {
|
|
44
|
+
topic: z.string().optional().describe('Topic to look up'),
|
|
45
|
+
role: z.string().optional().describe('Role perspective (default specialist)'),
|
|
46
|
+
tenant: z.string().optional(),
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: 'cbc_read_tenant_map',
|
|
51
|
+
title: 'Read tenant map',
|
|
52
|
+
description: 'Read the tenant knowledge map (domains, systems, owners). Optionally restrict to one section.',
|
|
53
|
+
inputSchema: {
|
|
54
|
+
tenant: z.string().min(1),
|
|
55
|
+
section: z.string().optional(),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
name: 'cbc_check_gate_rules',
|
|
60
|
+
title: 'Check gate rules',
|
|
61
|
+
description: 'Verify a draft deliverable against the quality gates of a stage BEFORE delivering it. Fix every reported violation.',
|
|
62
|
+
inputSchema: {
|
|
63
|
+
stage: z.string().min(1).describe('Delivery stage, e.g. design, implementation, review'),
|
|
64
|
+
draft_json: z.record(z.string(), z.any()).describe('The draft deliverable as a JSON object'),
|
|
65
|
+
tenant: z.string().optional(),
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: 'cbc_report_learning',
|
|
70
|
+
title: 'Report learning',
|
|
71
|
+
description: 'Report a correction so the organization learns. kind=correction: the user corrected you (give issue and resolution). kind=self_correction: you iterated to fix your own mistake (give versions and reasoning_summaries). Creates a reviewable candidate only, never publishes.',
|
|
72
|
+
inputSchema: {
|
|
73
|
+
kind: z.enum(['correction', 'self_correction']),
|
|
74
|
+
issue: z.string().optional(),
|
|
75
|
+
resolution: z.string().optional(),
|
|
76
|
+
versions: z.array(z.string()).optional(),
|
|
77
|
+
reasoning_summaries: z.array(z.string()).optional(),
|
|
78
|
+
session_id: z.string().optional(),
|
|
79
|
+
tenant: z.string().optional(),
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
function toResult(result) {
|
|
85
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], structuredContent: result };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function registerTools(server, invoke) {
|
|
89
|
+
for (const tool of TOOLS) {
|
|
90
|
+
server.registerTool(tool.name, {
|
|
91
|
+
title: tool.title,
|
|
92
|
+
description: tool.description,
|
|
93
|
+
inputSchema: tool.inputSchema,
|
|
94
|
+
}, async (args) => {
|
|
95
|
+
try {
|
|
96
|
+
const result = await invoke(tool.name, args || {});
|
|
97
|
+
const obj = result && typeof result === 'object' && !Array.isArray(result) ? result : { result };
|
|
98
|
+
return toResult(obj);
|
|
99
|
+
} catch (err) {
|
|
100
|
+
return { content: [{ type: 'text', text: String((err && err.message) || err) }], isError: true };
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function registerPrompts(server) {
|
|
107
|
+
server.registerPrompt('cbc_start_task', {
|
|
108
|
+
title: 'Start a task with CognitiveBC context',
|
|
109
|
+
description: 'Fetch governed context before starting a task',
|
|
110
|
+
argsSchema: { role: z.string(), task: z.string() },
|
|
111
|
+
}, ({ role, task }) => ({
|
|
112
|
+
messages: [{
|
|
113
|
+
role: 'user',
|
|
114
|
+
content: {
|
|
115
|
+
type: 'text',
|
|
116
|
+
text: `Before doing anything, call cbc_get_context with role "${role}" and task "${task}". Follow the returned rules, check cbc_check_gate_rules before delivering, and report corrections with cbc_report_learning.\n\nTask: ${task}`,
|
|
117
|
+
},
|
|
118
|
+
}],
|
|
119
|
+
}));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { TOOLS, SERVER_INSTRUCTIONS, registerTools, registerPrompts };
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Vincula o catálogo de portfólio do Synap-se (~/.synap-se/catalogo.json: organização › projeto › produto)
|
|
5
|
+
* ao grafo semântico e permite recortar o grafo por organização, projeto e produto.
|
|
6
|
+
*
|
|
7
|
+
* Vínculo de conhecimento a produto (sem mexer nos artefatos):
|
|
8
|
+
* - tenant (MAP_<tenant>.md) -> produto cujo id, workspaceId, marketing.marca ou nome normalizado bate com o tenant,
|
|
9
|
+
* ou que declara o tenant em produto.cbc.tenants;
|
|
10
|
+
* - stack (bytecode) -> produto cujo id/marca bate com scope.squad ou scope.tenant, que declara a stack em
|
|
11
|
+
* produto.cbc.stacks, ou dono de um tenant listado em companion_artifacts.tenant_maps;
|
|
12
|
+
* - regras e casos -> herdam os produtos da stack;
|
|
13
|
+
* - jobs de telemetria -> produto cujo nome/id/marca bate com job.cliente, ou os do tenant do job;
|
|
14
|
+
* - papéis e origem cloud -> união dos produtos do que está ligado a eles.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const os = require('os');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
|
|
21
|
+
const DEFAULT_CATALOG_PATH = path.join(os.homedir(), '.synap-se', 'catalogo.json');
|
|
22
|
+
|
|
23
|
+
function norm(s) {
|
|
24
|
+
return String(s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function loadCatalog(options = {}) {
|
|
28
|
+
if (options.catalog === false) return null;
|
|
29
|
+
if (options.catalog && typeof options.catalog === 'object') return options.catalog;
|
|
30
|
+
const file = options.catalogPath || process.env.COGNITIVEBC_CATALOG || process.env.SYNAPSE_CATALOGO || DEFAULT_CATALOG_PATH;
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
33
|
+
} catch (_) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const orgId = (o) => `org:${o.id}`;
|
|
39
|
+
const projectId = (o, p) => `project:${o.id}/${p.id}`;
|
|
40
|
+
const productId = (o, p, d) => `product:${o.id}/${p.id}/${d.id}`;
|
|
41
|
+
|
|
42
|
+
/** Lista plana de produtos com aliases normalizados para casamento. */
|
|
43
|
+
function flattenCatalog(catalog) {
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const o of catalog?.clientes || []) {
|
|
46
|
+
for (const p of o.projetos || []) {
|
|
47
|
+
for (const d of p.produtos || []) {
|
|
48
|
+
const aliases = new Set([d.id, d.workspaceId, d.nome, d.marketing?.marca].filter(Boolean).map(norm));
|
|
49
|
+
out.push({
|
|
50
|
+
org: o, project: p, product: d,
|
|
51
|
+
orgNodeId: orgId(o), projectNodeId: projectId(o, p), productNodeId: productId(o, p, d),
|
|
52
|
+
aliases,
|
|
53
|
+
tenants: new Set((d.cbc?.tenants || []).map(norm)),
|
|
54
|
+
stacks: new Set((d.cbc?.stacks || []).map(norm)),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Facetas para os seletores da UI (sempre o catálogo inteiro, independente do filtro). */
|
|
63
|
+
function catalogFacets(catalog) {
|
|
64
|
+
return (catalog?.clientes || []).map(o => ({
|
|
65
|
+
id: o.id,
|
|
66
|
+
name: o.nome || o.id,
|
|
67
|
+
tipo: o.tipo || null,
|
|
68
|
+
projects: (o.projetos || []).map(p => ({
|
|
69
|
+
id: p.id,
|
|
70
|
+
name: p.nome || p.id,
|
|
71
|
+
products: (p.produtos || []).map(d => ({ id: d.id, name: d.nome || d.id, workspaceId: d.workspaceId || null })),
|
|
72
|
+
})),
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Adiciona os nós de organização/projeto/produto e os vínculos com o conhecimento já presente no grafo.
|
|
78
|
+
* Muta nodes/links via addNode/addLink e grava node.products = [productNodeId...] nos nós de conhecimento.
|
|
79
|
+
*/
|
|
80
|
+
function linkCatalog({ catalog, nodes, links, addNode, addLink, bytecodes, telemetry }) {
|
|
81
|
+
const flat = flattenCatalog(catalog);
|
|
82
|
+
if (!flat.length) return { flat, linked: 0 };
|
|
83
|
+
|
|
84
|
+
for (const o of catalog.clientes || []) {
|
|
85
|
+
addNode({
|
|
86
|
+
id: orgId(o), name: o.nome || o.id, label: `🏢 ${o.nome || o.id}`, type: 'organization',
|
|
87
|
+
organization: o.id, val: 30, color: '#F8FAFC',
|
|
88
|
+
details: { id: o.id, nome: o.nome, tipo: o.tipo || null, via: o.via || null, projetos: (o.projetos || []).length,
|
|
89
|
+
desc: 'Organização do portfólio Synap-se (catálogo).' },
|
|
90
|
+
});
|
|
91
|
+
for (const p of o.projetos || []) {
|
|
92
|
+
addNode({
|
|
93
|
+
id: projectId(o, p), name: p.nome || p.id, label: `📁 ${p.nome || p.id}`, type: 'project',
|
|
94
|
+
organization: o.id, project: p.id, val: 22, color: '#94A3B8',
|
|
95
|
+
details: { id: p.id, nome: p.nome, organizacao: o.nome, subPath: p.subPath || '', produtos: (p.produtos || []).length,
|
|
96
|
+
desc: 'Projeto do portfólio Synap-se (catálogo).' },
|
|
97
|
+
});
|
|
98
|
+
addLink(orgId(o), projectId(o, p), 'owns_project', 1.2);
|
|
99
|
+
for (const d of p.produtos || []) {
|
|
100
|
+
addNode({
|
|
101
|
+
id: productId(o, p, d), name: d.nome || d.id, label: `📦 ${d.nome || d.id}`, type: 'product',
|
|
102
|
+
organization: o.id, project: p.id, product: d.id, val: 18, color: '#14B8A6',
|
|
103
|
+
details: { id: d.id, nome: d.nome, descricao: d.descricao || '', organizacao: o.nome, projeto: p.nome,
|
|
104
|
+
workspaceId: d.workspaceId || null, hasBuilder: d.hasBuilder !== false, hasOps: d.hasOps === true,
|
|
105
|
+
features: d.features || [], desc: 'Produto do portfólio Synap-se (catálogo).' },
|
|
106
|
+
});
|
|
107
|
+
addLink(projectId(o, p), productId(o, p, d), 'has_product', 1.1);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const byId = new Map(nodes.map(n => [n.id, n]));
|
|
113
|
+
const attr = new Map(); // nodeId -> Set(productNodeId)
|
|
114
|
+
const give = (nodeId, prodIds) => {
|
|
115
|
+
if (!byId.has(nodeId) || !prodIds.size) return;
|
|
116
|
+
if (!attr.has(nodeId)) attr.set(nodeId, new Set());
|
|
117
|
+
prodIds.forEach(p => attr.get(nodeId).add(p));
|
|
118
|
+
};
|
|
119
|
+
const match = (key) => {
|
|
120
|
+
const k = norm(key), semParenteses = norm(String(key || '').replace(/\([^)]*\)/g, ''));
|
|
121
|
+
return new Set(flat.filter(f => f.aliases.has(k) || (semParenteses && f.aliases.has(semParenteses))).map(f => f.productNodeId));
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// Tenants
|
|
125
|
+
const tenantProducts = new Map();
|
|
126
|
+
for (const n of nodes.filter(x => x.type === 'tenant')) {
|
|
127
|
+
const k = norm(n.tenant);
|
|
128
|
+
const prods = new Set(flat.filter(f => f.aliases.has(k) || f.tenants.has(k)).map(f => f.productNodeId));
|
|
129
|
+
tenantProducts.set(n.tenant, prods);
|
|
130
|
+
give(n.id, prods);
|
|
131
|
+
prods.forEach(p => addLink(p, n.id, 'product_vault', 1));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Stacks e regras
|
|
135
|
+
for (const bc of bytecodes) {
|
|
136
|
+
const stackKey = bc.scope?.stack || 'general_stack';
|
|
137
|
+
const stackNodeId = `stack:${stackKey}`;
|
|
138
|
+
const prods = new Set(flat.filter(f => f.stacks.has(norm(stackKey))).map(f => f.productNodeId));
|
|
139
|
+
// Isolamento: se algum produto declara a stack em cbc.stacks, só os declarantes a possuem. Herança por
|
|
140
|
+
// tenant/squad vale apenas para stacks que ninguém declarou (evita que todo produto do tenant herde tudo).
|
|
141
|
+
const declared = flat.some(f => f.stacks.has(norm(stackKey)));
|
|
142
|
+
if (!declared) [bc.scope?.squad, bc.scope?.tenant].filter(Boolean).forEach(k => match(k).forEach(p => prods.add(p)));
|
|
143
|
+
if (!declared && bc.scope?.tenant && tenantProducts.has(bc.scope.tenant)) tenantProducts.get(bc.scope.tenant).forEach(p => prods.add(p));
|
|
144
|
+
if (!declared) Object.keys(bc.companion_artifacts?.tenant_maps || {}).forEach(t => (tenantProducts.get(t) || match(t)).forEach(p => prods.add(p)));
|
|
145
|
+
give(stackNodeId, prods);
|
|
146
|
+
prods.forEach(p => addLink(p, stackNodeId, 'uses_stack', 0.9));
|
|
147
|
+
}
|
|
148
|
+
for (const l of links) {
|
|
149
|
+
if ((l.type === 'contains_rule' || l.type === 'contains_case') && attr.has(l.source)) give(l.target, attr.get(l.source));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Jobs de telemetria: o produto cliente do job e o produto que executa (a origem, ex.: MktSquad)
|
|
153
|
+
const executor = new Set();
|
|
154
|
+
for (const n of nodes.filter(x => x.type === 'telemetry_source')) {
|
|
155
|
+
const m = /\(([^)]+)\)/.exec(n.name || '');
|
|
156
|
+
[m && m[1], n.details?.executor].filter(Boolean).forEach(k => match(k).forEach(p => executor.add(p)));
|
|
157
|
+
give(n.id, executor);
|
|
158
|
+
executor.forEach(p => addLink(p, n.id, 'operates_source', 0.9));
|
|
159
|
+
}
|
|
160
|
+
const squadJobs = new Set((telemetry?.jobs || []).filter(j => j.squad && match(j.squad).size).map(j => `job:${j.id}`));
|
|
161
|
+
for (const job of telemetry?.jobs || []) {
|
|
162
|
+
const jobNodeId = `job:${job.id}`;
|
|
163
|
+
// Squad do job (ex.: pricefy) identifica o produto com precisão; só sem ele cai no cliente/tenant.
|
|
164
|
+
const bySquad = job.squad ? match(job.squad) : new Set();
|
|
165
|
+
const prods = bySquad.size ? bySquad : match(job.cliente);
|
|
166
|
+
if (!prods.size && tenantProducts.has(job.cliente)) tenantProducts.get(job.cliente).forEach(p => prods.add(p));
|
|
167
|
+
give(jobNodeId, prods);
|
|
168
|
+
prods.forEach(p => addLink(p, jobNodeId, 'product_job', 0.7));
|
|
169
|
+
if (!bySquad.size) give(jobNodeId, executor);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Papéis e origem cloud herdam dos vizinhos atribuídos
|
|
173
|
+
for (const l of links) {
|
|
174
|
+
const s = byId.get(l.source), t = byId.get(l.target);
|
|
175
|
+
if (!s || !t) continue;
|
|
176
|
+
// Tenant compartilhado por vários produtos não diz a qual produto o papel pertence: o papel só entra no
|
|
177
|
+
// recorte por regra, caso ou job do próprio produto.
|
|
178
|
+
if (l.type === 'provides_vault' && (tenantProducts.get(s.tenant)?.size || 0) > 1) continue;
|
|
179
|
+
if (s.type === 'role' && attr.has(l.target)) give(s.id, attr.get(l.target));
|
|
180
|
+
if (t.type === 'role' && attr.has(l.source)) give(t.id, attr.get(l.source));
|
|
181
|
+
if (s.type === 'telemetry_source' && attr.has(l.target) && !squadJobs.has(l.target)) give(s.id, attr.get(l.target));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
for (const [id, set] of attr) byId.get(id).products = Array.from(set);
|
|
185
|
+
// nós de catálogo: o próprio escopo
|
|
186
|
+
for (const f of flat) {
|
|
187
|
+
byId.get(f.productNodeId).products = [f.productNodeId];
|
|
188
|
+
}
|
|
189
|
+
return { flat, linked: attr.size };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Recorte por organização/projeto/produto. Mantém: o caminho hierárquico do recorte, os produtos do recorte e
|
|
194
|
+
* todo nó de conhecimento atribuído a algum desses produtos. Conhecimento sem dono no catálogo sai do recorte.
|
|
195
|
+
*/
|
|
196
|
+
function filterByScope(nodes, links, flat, { organization, project, product } = {}) {
|
|
197
|
+
if (!organization && !project && !product) return null;
|
|
198
|
+
const sel = flat.filter(f =>
|
|
199
|
+
(!organization || f.org.id === organization) &&
|
|
200
|
+
(!project || f.project.id === project) &&
|
|
201
|
+
(!product || f.product.id === product));
|
|
202
|
+
const prodIds = new Set(sel.map(f => f.productNodeId));
|
|
203
|
+
const keep = new Set();
|
|
204
|
+
sel.forEach(f => { keep.add(f.orgNodeId); keep.add(f.projectNodeId); keep.add(f.productNodeId); });
|
|
205
|
+
for (const n of nodes) {
|
|
206
|
+
if ((n.products || []).some(p => prodIds.has(p))) keep.add(n.id);
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
nodes: nodes.filter(n => keep.has(n.id)),
|
|
210
|
+
links: links.filter(l => keep.has(l.source) && keep.has(l.target)),
|
|
211
|
+
selection: { organization: organization || null, project: project || null, product: product || null, products: sel.length },
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
module.exports = { DEFAULT_CATALOG_PATH, norm, loadCatalog, flattenCatalog, catalogFacets, linkCatalog, filterByScope };
|