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.
Files changed (66) hide show
  1. package/LICENSE +70 -0
  2. package/README.md +99 -2
  3. package/SECURITY.md +29 -0
  4. package/TERMS_OF_SERVICE.md +55 -0
  5. package/bin/cbc-cloud-bootstrap.js +108 -0
  6. package/bin/cbc-seed-projects.js +29 -0
  7. package/bin/cbc-server.js +45 -0
  8. package/bin/cognitivebc.js +251 -0
  9. package/docs/ACCESS_CONTROL.md +111 -0
  10. package/docs/ARTIFACT_AUDIT.md +36 -0
  11. package/docs/CONNECT_CLIENTS.md +116 -0
  12. package/docs/DEPLOY_AZURE.md +136 -0
  13. package/docs/INGESTION.md +29 -0
  14. package/docs/OPERATIONS.md +85 -0
  15. package/docs/PROJECT_IDENTITY.md +35 -0
  16. package/docs/RESOLVER.md +86 -0
  17. package/docs/SDK.md +96 -0
  18. package/docs/STORAGE.md +63 -0
  19. package/docs/TECHNICAL_SPECIFICATION.md +365 -0
  20. package/docs/TELEMETRY.md +119 -0
  21. package/index.js +27 -0
  22. package/package.json +59 -4
  23. package/packages/cbc-compiler/index.js +357 -0
  24. package/packages/cbc-compiler/sanitizer.js +43 -0
  25. package/packages/cbc-identity/index.js +92 -0
  26. package/packages/cbc-mcp/http-backend.js +138 -0
  27. package/packages/cbc-mcp/http-route.js +64 -0
  28. package/packages/cbc-mcp/index.js +50 -0
  29. package/packages/cbc-mcp/tools.js +122 -0
  30. package/packages/cbc-resolver/catalog-linker.js +215 -0
  31. package/packages/cbc-resolver/graph-builder.js +533 -0
  32. package/packages/cbc-resolver/index.js +548 -0
  33. package/packages/cbc-resolver/obsidian-bridge.js +564 -0
  34. package/packages/cbc-schema/index.js +194 -0
  35. package/packages/cbc-sdk-js/client.js +162 -0
  36. package/services/cbc-api/access-policy.js +130 -0
  37. package/services/cbc-api/artifact-audit.js +167 -0
  38. package/services/cbc-api/cloud.js +56 -0
  39. package/services/cbc-api/context-service.js +48 -0
  40. package/services/cbc-api/ingestion-service.js +234 -0
  41. package/services/cbc-api/pg-store.js +172 -0
  42. package/services/cbc-api/project-registry.js +322 -0
  43. package/services/cbc-api/public/app.html +123 -0
  44. package/services/cbc-api/public/graph.html +1168 -0
  45. package/services/cbc-api/public/graph2.html +455 -0
  46. package/services/cbc-api/public/graph3.html +503 -0
  47. package/services/cbc-api/public/index.html +78 -0
  48. package/services/cbc-api/public/vendor/cbc-app.js +209 -0
  49. package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
  50. package/services/cbc-api/public/vendor/cbc-site.css +101 -0
  51. package/services/cbc-api/public/vendor/cose-base.js +3214 -0
  52. package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
  53. package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
  54. package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
  55. package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
  56. package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
  57. package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
  58. package/services/cbc-api/public/vendor/layout-base.js +5230 -0
  59. package/services/cbc-api/public/vendor/pf-graph.css +86 -0
  60. package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
  61. package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
  62. package/services/cbc-api/runtime-info.js +39 -0
  63. package/services/cbc-api/server.js +642 -0
  64. package/services/cbc-api/store-loader.js +269 -0
  65. package/services/cbc-api/telemetry.js +148 -0
  66. package/services/cbc-api/token-service.js +61 -0
@@ -0,0 +1,642 @@
1
+ 'use strict';
2
+
3
+ const http = require('http');
4
+ const crypto = require('crypto');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const packageInfo = require('../../package.json');
8
+ const { CognitiveStore } = require('./store-loader');
9
+ const { resolveContextForRole } = require('../../packages/cbc-resolver');
10
+ const { buildSemanticGraph } = require('../../packages/cbc-resolver/graph-builder');
11
+ const { exportToObsidianVault } = require('../../packages/cbc-resolver/obsidian-bridge');
12
+ const { compileExperience, verifyGateRules } = require('../../packages/cbc-compiler');
13
+ const { createIngestionService } = require('./ingestion-service');
14
+ const { captureRuntimeInfo } = require('./runtime-info');
15
+ const { resolveAuthorizedContext } = require('./context-service');
16
+ const telemetry = require('./telemetry');
17
+ const { createAccessPolicy, authorize, allowsTenant, assertTenant, canReadArtifact, createStoreView, selectMapSection, fail } = require('./access-policy');
18
+
19
+ const HTML_SECURITY_HEADERS = {
20
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com data:; img-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'",
21
+ 'X-Frame-Options': 'SAMEORIGIN',
22
+ 'Referrer-Policy': 'no-referrer',
23
+ 'X-Content-Type-Options': 'nosniff',
24
+ };
25
+
26
+ /**
27
+ * Optional host split (production): marketing site, user app and API on separate
28
+ * origins served by the same process. Without `options.origins` every route is
29
+ * available on every host (local development).
30
+ */
31
+ function originRoles(origins) {
32
+ if (!origins) return null;
33
+ const role = new Map();
34
+ for (const kind of ['site', 'app', 'api']) for (const o of [].concat(origins[kind] || [])) role.set(new URL(o).host, kind);
35
+ const first = kind => [].concat(origins[kind] || [])[0] || null;
36
+ return { role, site: first('site'), app: first('app'), api: first('api') };
37
+ }
38
+ function injectApiBase(html, apiBase) {
39
+ if (!apiBase) return html;
40
+ // Must precede cbc-auth.js, which reads the tag synchronously.
41
+ return html.replace(/<head>/i, `<head>\n<meta name="cbc-api" content="${apiBase.replace(/"/g, '')}">`);
42
+ }
43
+
44
+ function createServer(options = {}) {
45
+ const policy = createAccessPolicy({ auth: options.auth, tokenLookup: options.tokenLookup });
46
+ const hosts = originRoles(options.origins);
47
+ const corsOrigins = [...(options.corsOrigins || []), ...(hosts ? [hosts.site, hosts.app].filter(Boolean) : [])];
48
+ const htmlHeaders = { ...HTML_SECURITY_HEADERS };
49
+ if (hosts?.api) htmlHeaders['Content-Security-Policy'] = htmlHeaders['Content-Security-Policy'].replace("connect-src 'self'", `connect-src 'self' ${hosts.api}`);
50
+ const store = options.store || new CognitiveStore(options.storeDir);
51
+ store.loadAll();
52
+ const ingestionService = options.ingestionService || createIngestionService({ store, receiptDir: options.receiptDir });
53
+ const runtimeInfo = captureRuntimeInfo({ publicExports: { createServer, compileExperience, verifyGateRules, createIngestionService, resolveAuthorizedContext, resolveContextForRole, buildSemanticGraph, createMcpHandlers: require('../../packages/cbc-mcp').createMcpHandlers } });
54
+
55
+ // In-memory sliding-window rate limiter (Anti-Scraping / IP protection)
56
+ const rateLimitMap = new Map();
57
+ const RATE_LIMIT_WINDOW_MS = 60 * 1000;
58
+ const RATE_LIMIT_MAX_REQUESTS = options.rateLimitMaxRequests || 180; // 180 req/min
59
+
60
+ const server = http.createServer(async (req, res) => {
61
+ // Enable CORS and IP protection headers
62
+ const origin = req.headers.origin;
63
+ const sameOrigin = origin === `http://${req.headers.host}` || origin === `https://${req.headers.host}`;
64
+ const allowedOrigin = !origin || sameOrigin || corsOrigins.includes(origin);
65
+ if (origin && allowedOrigin) {
66
+ res.setHeader('Access-Control-Allow-Origin', origin);
67
+ res.setHeader('Vary', 'Origin');
68
+ }
69
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
70
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
71
+ res.setHeader('X-Content-Type-Options', 'nosniff');
72
+ // Authorized representations must never be reused across identities.
73
+ res.setHeader('Cache-Control', 'no-store');
74
+ res.setHeader('X-CognitiveBC-Version', '0.2.0');
75
+ res.setHeader('X-CognitiveBC-License', packageInfo.license);
76
+
77
+ if (!allowedOrigin) {
78
+ res.writeHead(403, { 'Content-Type': 'application/json' });
79
+ return res.end(JSON.stringify({ error: 'Origin not permitted' }));
80
+ }
81
+ if (req.method === 'OPTIONS') {
82
+ res.writeHead(204);
83
+ return res.end();
84
+ }
85
+
86
+ // Authenticated callers are limited per credential (offices share NAT IPs and the
87
+ // remote MCP endpoint loops back); anonymous callers are limited per IP.
88
+ const credential = /^Bearer (\S+)$/i.exec(req.headers.authorization || '')?.[1];
89
+ const clientIp = credential ? `token:${crypto.createHash('sha256').update(credential).digest('hex')}` : (req.socket.remoteAddress || '');
90
+ const now = Date.now();
91
+ const clientWindow = rateLimitMap.get(clientIp) || { count: 0, resetAt: now + RATE_LIMIT_WINDOW_MS };
92
+
93
+ if (now > clientWindow.resetAt) {
94
+ clientWindow.count = 0;
95
+ clientWindow.resetAt = now + RATE_LIMIT_WINDOW_MS;
96
+ }
97
+ clientWindow.count++;
98
+ rateLimitMap.set(clientIp, clientWindow);
99
+
100
+ if (clientWindow.count > RATE_LIMIT_MAX_REQUESTS && !options.disableRateLimit) {
101
+ res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After': '60' });
102
+ return res.end(JSON.stringify({
103
+ error: 'Too Many Requests: Rate limit exceeded to prevent mass bytecode scraping.',
104
+ window_reset_in_seconds: Math.ceil((clientWindow.resetAt - now) / 1000),
105
+ }));
106
+ }
107
+
108
+ let parsedUrl;
109
+ try { parsedUrl = new URL(req.url, 'http://localhost'); }
110
+ catch {
111
+ res.writeHead(400, { 'Content-Type': 'application/json' });
112
+ return res.end(JSON.stringify({ error: 'Invalid request URL' }));
113
+ }
114
+ const pathname = parsedUrl.pathname;
115
+
116
+ const sendJson = (statusCode, data) => {
117
+ res.writeHead(statusCode, { 'Content-Type': 'application/json' });
118
+ res.end(JSON.stringify(data));
119
+ };
120
+ const checkLocalHost = identity => {
121
+ if (!identity?.trustedLocal) return;
122
+ let hostname;
123
+ try { hostname = new URL(`http://${req.headers.host || 'localhost'}`).hostname; }
124
+ catch { fail(400, 'Invalid Host'); }
125
+ if (!['localhost', '127.0.0.1', '[::1]', '::1'].includes(hostname) && !(options.allowedHosts || []).includes(hostname)) fail(403, 'Local Host not permitted');
126
+ };
127
+
128
+ const parseBody = () => new Promise((resolve, reject) => {
129
+ const chunks = [];
130
+ let bytes = 0, exceeded = false;
131
+ const limit = options.maxBodyBytes || 10 * 1024 * 1024;
132
+ req.on('data', chunk => {
133
+ bytes += chunk.length;
134
+ if (bytes > limit) {
135
+ exceeded = true;
136
+ chunks.length = 0;
137
+ reject(Object.assign(new Error('Body payload too large'), { status: 413 }));
138
+ } else if (!exceeded) {
139
+ chunks.push(chunk);
140
+ }
141
+ });
142
+ req.on('end', () => {
143
+ if (exceeded) return;
144
+ try {
145
+ const body = Buffer.concat(chunks).toString('utf8');
146
+ const value = body ? JSON.parse(body) : {};
147
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('object required');
148
+ resolve(value);
149
+ } catch (err) {
150
+ reject(Object.assign(new Error('Invalid JSON object'), { status: 400 }));
151
+ }
152
+ });
153
+ req.on('error', reject);
154
+ req.on('aborted', () => reject(Object.assign(new Error('Request aborted'), { status: 400 })));
155
+ });
156
+
157
+ try {
158
+ // 1. Health check
159
+ if ((pathname === '/health' || pathname === '/api/v1/health') && (req.method === 'GET' || req.method === 'HEAD')) {
160
+ let details = !policy.configured;
161
+ let identity;
162
+ if (req.headers.authorization) {
163
+ identity = await policy.authenticate(req);
164
+ authorize(identity, 'read');
165
+ details = true;
166
+ } else if (!policy.configured) {
167
+ identity = await policy.authenticate(req);
168
+ details = Boolean(identity.trustedLocal);
169
+ }
170
+ checkLocalHost(identity);
171
+ const healthView = details ? createStoreView(store, identity) : null;
172
+ const ready = !(store.loadErrors?.length);
173
+ res.writeHead(ready ? 200 : 503, { 'Content-Type': 'application/json' });
174
+ if (req.method === 'HEAD') return res.end();
175
+ return res.end(JSON.stringify({
176
+ status: ready ? 'ok' : 'degraded',
177
+ service: 'cognitivebc-api',
178
+ ...(details ? {
179
+ version: runtimeInfo.version,
180
+ readiness: { ready, load_error_count: store.loadErrors?.length || 0 },
181
+ runtime: runtimeInfo,
182
+ schema: 'cognitivebc/v1',
183
+ uptime: process.uptime(),
184
+ loaded_artifacts: {
185
+ bytecodes: healthView.getBytecodes().length,
186
+ skills: [...store.skills].filter(([id, item]) => canReadArtifact(identity, 'skill', id, item)).length,
187
+ maps: Object.keys(healthView.getMapsDict()).length,
188
+ },
189
+ } : {}),
190
+ }));
191
+ }
192
+
193
+ // 0. Páginas e assets estáticos públicos (sem dados; os dados vêm das APIs autenticadas).
194
+ // Com origins configurados: site em cognitivebc.io, app em app.*, API sem HTML.
195
+ const hostRole = hosts ? hosts.role.get(String(req.headers.host || '').toLowerCase()) || null : null;
196
+ const isPage = method => method === 'GET' || method === 'HEAD';
197
+ if (hosts && hostRole === 'api' && isPage(req.method) && !pathname.startsWith('/api/') && pathname !== '/mcp' && !pathname.startsWith('/vendor/')) {
198
+ if (pathname === '/' && hosts.site) { res.writeHead(302, { Location: hosts.site }); return res.end(); }
199
+ if (pathname === '/app' || pathname.startsWith('/app/')) { res.writeHead(301, { Location: hosts.app + pathname.replace(/^\/app/, '') + parsedUrl.search }); return res.end(); }
200
+ }
201
+ if (hosts && hostRole === 'site' && isPage(req.method) && (pathname === '/app' || pathname.startsWith('/app/'))) {
202
+ res.writeHead(301, { Location: hosts.app + (pathname.replace(/^\/app/, '') || '/') + parsedUrl.search }); return res.end();
203
+ }
204
+ if (hosts && (hostRole === 'site' || hostRole === 'app') && pathname.startsWith('/api/')) {
205
+ // Data lives only on the API origin.
206
+ return sendJson(404, { error: `Use ${hosts.api}${pathname}` });
207
+ }
208
+ const sitePages = { '/': 'index.html' };
209
+ const appPages = { '/': 'app.html', '/app': 'app.html', '/graph': 'graph3.html', '/app/graph': 'graph3.html', '/graph2': 'graph2.html', '/graph3': 'graph3.html', '/canvas': 'graph.html' };
210
+ const allPages = { '/': 'index.html', '/app': 'app.html', '/app/': 'app.html', '/app/graph': 'graph3.html',
211
+ '/graph': 'graph.html', '/canvas': 'graph.html', '/graph2': 'graph2.html', '/graph3': 'graph3.html' };
212
+ const pages = !hosts || !hostRole ? (hosts ? {} : allPages) : hostRole === 'site' ? sitePages : hostRole === 'app' ? appPages : {};
213
+ if (pages[pathname] && isPage(req.method)) {
214
+ const htmlPath = path.join(__dirname, 'public', pages[pathname]);
215
+ if (fs.existsSync(htmlPath)) {
216
+ const headers = { 'Content-Type': 'text/html; charset=utf-8', ...htmlHeaders };
217
+ // Legado: graph.html ainda depende do Tailwind CDN; exceção restrita a essa página.
218
+ if (pages[pathname] === 'graph.html') headers['Content-Security-Policy'] = headers['Content-Security-Policy'].replace("script-src 'self' 'unsafe-inline'", "script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com");
219
+ res.writeHead(200, headers);
220
+ if (req.method === 'HEAD') return res.end();
221
+ let html = fs.readFileSync(htmlPath, 'utf8');
222
+ if (hosts) html = injectApiBase(html, hosts.api).replaceAll('href="/app"', `href="${hosts.app}"`);
223
+ return res.end(html);
224
+ }
225
+ }
226
+ if (pathname.startsWith('/vendor/') && (req.method === 'GET' || req.method === 'HEAD')) {
227
+ const name = path.basename(pathname);
228
+ const file = path.join(__dirname, 'public/vendor', name);
229
+ const m = /^[\w.-]+\.(js|css)$/.exec(name);
230
+ if (m && fs.existsSync(file)) {
231
+ res.writeHead(200, { 'Content-Type': (m[1] === 'css' ? 'text/css' : 'text/javascript') + '; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
232
+ return req.method === 'HEAD' ? res.end() : res.end(fs.readFileSync(file));
233
+ }
234
+ }
235
+
236
+ const principal = await policy.authenticate(req);
237
+ checkLocalHost(principal);
238
+ if (options.extraRoutes) {
239
+ for (const route of options.extraRoutes) {
240
+ const handled = await route({ req, res, method: req.method, pathname, parsedUrl, principal, parseBody, sendJson, store });
241
+ if (handled) return;
242
+ }
243
+ }
244
+ const operation = pathname.endsWith('/promote') ? 'approve'
245
+ : pathname === '/api/v1/compile' ? 'compile'
246
+ : pathname === '/api/v1/streams/ingest' ? 'ingest'
247
+ : pathname === '/api/v1/graph/nodes' ? 'write'
248
+ : pathname === '/api/v1/graph/export/obsidian' ? 'export' : 'read';
249
+ authorize(principal, operation);
250
+ const queryTenant = parsedUrl.searchParams.get('tenant');
251
+ assertTenant(principal, queryTenant);
252
+ const viewStore = createStoreView(store, principal, { tenant: queryTenant });
253
+ const bodyView = body => {
254
+ if (Object.hasOwn(body, 'scope') && (!body.scope || typeof body.scope !== 'object' || Array.isArray(body.scope))) fail(400, 'Invalid scope');
255
+ if (Object.hasOwn(body, 'tenant') && (typeof body.tenant !== 'string' || !body.tenant.trim())) fail(400, 'Invalid tenant');
256
+ assertTenant(principal, body.scope?.tenant);
257
+ if (body.tenant && body.scope?.tenant && body.tenant !== body.scope.tenant) fail(400, 'Conflicting tenant scope');
258
+ if (queryTenant && (body.tenant || body.scope?.tenant) && queryTenant !== (body.tenant || body.scope?.tenant)) fail(400, 'Conflicting query tenant scope');
259
+ return createStoreView(store, principal, { ...body.scope, tenant: body.tenant || body.scope?.tenant || queryTenant });
260
+ };
261
+ const originScope = body => {
262
+ bodyView(body);
263
+ const tenant = body.scope?.tenant || body.tenant;
264
+ assertTenant(principal, tenant, { required: true });
265
+ return { ...body.scope, level: 'tenant', tenant };
266
+ };
267
+ const originEvidence = body => {
268
+ const evidence = body.evidence;
269
+ if (!evidence || typeof evidence !== 'object' || !Object.keys(evidence).length) fail(400, 'Origin evidence required');
270
+ return evidence;
271
+ };
272
+ const allowTelemetryTenant = tenant => Boolean(tenant && (!queryTenant || tenant === queryTenant) &&
273
+ (principal.trustedLocal || (!principal.anonymous && allowsTenant(principal, tenant))));
274
+ const scopedLedger = async () => {
275
+ let ledger = options.graphTelemetry || { jobs: [] };
276
+ if (!options.graphTelemetry) {
277
+ try { ledger = JSON.parse(fs.readFileSync(options.ledgerPath || path.join(store.storeDir, 'telemetry/ledger.json'), 'utf8')); }
278
+ catch { /* Missing or malformed telemetry is not public data. */ }
279
+ }
280
+ const jobsById = new Map((Array.isArray(ledger.jobs) ? ledger.jobs : []).filter(job => allowTelemetryTenant(job.tenant)).map(job => {
281
+ const normalized = { ...job };
282
+ return [JSON.stringify([normalized.tenant, normalized.id]), normalized];
283
+ }));
284
+ for (const job of (await ingestionService.listJobs?.({ allowTenant: allowTelemetryTenant, tenant: queryTenant, project_id: parsedUrl.searchParams.get('project_id') })) || []) {
285
+ jobsById.set(JSON.stringify([job.tenant, job.id]), job);
286
+ }
287
+ const jobs = [...jobsById.values()];
288
+ return { jobs, source: 'cognitivebc', provider: 'CognitiveBC', total_events_ingested: jobs.reduce((n, j) => n + (Number(j.eventos_count) || 0), 0) };
289
+ };
290
+
291
+ // 1.2. GET /api/v1/graph (Semantic Graph API for visualizers and tooling)
292
+ if (pathname === '/api/v1/graph' && req.method === 'GET') {
293
+ const role = parsedUrl.searchParams.get('role');
294
+ const tenant = parsedUrl.searchParams.get('tenant');
295
+ const q = (k) => parsedUrl.searchParams.get(k) || null;
296
+ const graph = buildSemanticGraph(viewStore, {
297
+ role, tenant,
298
+ organization: q('organization') || q('org'),
299
+ project: q('project'),
300
+ product: q('product'),
301
+ catalog: principal.trustedLocal ? options.catalog : false,
302
+ catalogPath: options.catalogPath,
303
+ telemetry: await scopedLedger(),
304
+ });
305
+ return sendJson(200, graph);
306
+ }
307
+
308
+ if (pathname === '/api/v1/me' && req.method === 'GET') {
309
+ // Lets clients adapt the UI without probing privileged routes.
310
+ return sendJson(200, { id: principal.id, tenants: principal.tenants, permissions: principal.permissions, anonymous: Boolean(principal.anonymous), trusted_local: Boolean(principal.trustedLocal) });
311
+ }
312
+ if (pathname === '/api/v1/candidates' && req.method === 'GET') {
313
+ if (principal.anonymous) fail(403, 'Candidate access not permitted');
314
+ if (typeof store.listCandidates !== 'function') return sendJson(200, { candidates: [], supported: false });
315
+ const status = parsedUrl.searchParams.get('status') || 'candidate';
316
+ if (!['candidate', 'promoted'].includes(status)) fail(400, 'Invalid status');
317
+ const all = principal.trustedLocal || allowsTenant(principal, '*');
318
+ const tenants = all ? (queryTenant ? [queryTenant] : null) : principal.tenants.filter(t => !queryTenant || t === queryTenant);
319
+ const records = tenants && !tenants.length ? [] : await store.listCandidates({ tenants, status, limit: 200 });
320
+ return sendJson(200, { supported: true, candidates: records.map(r => ({ id: r.id, status: r.status, tenant: r.scope?.tenant, regime: r.regime, created_at: r.createdAt, bytecode_id: r.artifacts?.bytecode_artifact?.id, scope: r.scope, evidence: { producer: r.evidence?.producer, session_id: r.evidence?.session_id, validation_status: r.evidence?.validation_status }, history: r.history })) });
321
+ }
322
+
323
+ if (pathname === '/api/v1/jobs' && req.method === 'GET') {
324
+ if (typeof ingestionService.listJobs !== 'function') fail(503, 'Durable job listing unavailable');
325
+ const jobs = await ingestionService.listJobs({ allowTenant: allowTelemetryTenant, tenant: queryTenant, project_id: parsedUrl.searchParams.get('project_id') });
326
+ return sendJson(200, { jobs, count: jobs.length });
327
+ }
328
+
329
+ // 1.25. GET /api/v1/telemetry (uso agregado por regra/papel/job) e /api/v1/telemetry/events?since= (feed ao vivo)
330
+ if ((pathname === '/api/v1/telemetry' || pathname === '/api/v1/telemetry/events') && req.method === 'GET') {
331
+ const since = parsedUrl.searchParams.get('since');
332
+ const recs = await telemetry.load({ allowTenant: allowTelemetryTenant, since }, options);
333
+ if (pathname.endsWith('/events')) return sendJson(200, { now: new Date().toISOString(), events: telemetry.recent(recs, 200) });
334
+ const days = Math.min(Math.max(parseInt(parsedUrl.searchParams.get('days') || '30', 10) || 30, 1), 365);
335
+ return sendJson(200, { ...telemetry.aggregate(recs, { days }), recent: telemetry.recent(recs, 40) });
336
+ }
337
+
338
+ // 1.3. GET /api/v1/graph/export/obsidian (Export to native Obsidian Vault)
339
+ if (pathname === '/api/v1/graph/export/obsidian' && req.method === 'GET') {
340
+ const exportRoot = options.exportDir || path.join(store.storeDir, 'obsidian-vault');
341
+ fs.mkdirSync(exportRoot, { recursive: true, mode: 0o700 });
342
+ const vaultDir = fs.mkdtempSync(path.join(exportRoot, 'export-'));
343
+ const exportRes = exportToObsidianVault(viewStore, vaultDir, { telemetry: await scopedLedger(), catalog: false });
344
+ return sendJson(200, exportRes);
345
+ }
346
+
347
+ // 1.4. POST /api/v1/graph/verify (Interactive Gate Linter for Graph Canvas)
348
+ if (pathname === '/api/v1/graph/verify' && req.method === 'POST') {
349
+ const body = await parseBody();
350
+ const selectedStore = bodyView(body);
351
+ const stage = body.stage || 'roteiro';
352
+ const draftPayload = body.draftPayload || body.draft || {};
353
+ const verifyRes = verifyGateRules({
354
+ stage,
355
+ draftPayload,
356
+ bytecodes: selectedStore.getBytecodes(),
357
+ });
358
+
359
+ // Map declarative gate issues to visual graph node IDs
360
+ const nodeStatuses = {};
361
+ const gateToNodeMap = {
362
+ 'GATE-ANCHOR-01': 'constraint:AC-ED-01',
363
+ 'GATE-BRAND-01': 'constraint:AC-ED-01',
364
+ 'GATE-3D-SCALE-01': 'constraint:AC-3D-01',
365
+ 'GATE-3D-PREVIEW-01': 'principle:DP-3D-01',
366
+ };
367
+
368
+ for (const issue of verifyRes.issues || []) {
369
+ const mappedNode = gateToNodeMap[issue.id] || `constraint:${issue.id}`;
370
+ nodeStatuses[mappedNode] = {
371
+ status: 'violated',
372
+ severity: issue.severity,
373
+ message: issue.message,
374
+ field: issue.field,
375
+ };
376
+ }
377
+
378
+ return sendJson(200, {
379
+ passed: verifyRes.passed,
380
+ issues: verifyRes.issues,
381
+ nodeStatuses,
382
+ });
383
+ }
384
+
385
+ // 1.5. POST /api/v1/graph/nodes (Visual Rule / Node Creator)
386
+ if (pathname === '/api/v1/graph/nodes' && req.method === 'POST') {
387
+ const body = await parseBody();
388
+ const { type, id, stack, rule, when, then, principle, target_roles = [] } = body;
389
+ if (!['constraint', 'heuristic', 'principle'].includes(type) || typeof id !== 'string' || !id.trim() || typeof stack !== 'string' || !stack.trim()) {
390
+ return sendJson(400, { error: 'type and id are required' });
391
+ }
392
+ if (!Array.isArray(target_roles) || target_roles.some(role => typeof role !== 'string')) fail(400, 'Invalid target_roles');
393
+ const evidence = originEvidence(body);
394
+ const texts = type === 'heuristic' ? [when, then] : type === 'principle' ? [principle, rule] : [rule];
395
+ if (texts.some(value => typeof value !== 'string' || !value.trim())) fail(400, 'Explicit rule content required');
396
+ const scope = originScope(body);
397
+ const bytecodes = bodyView({ ...body, scope }).getBytecodes();
398
+ const source = bytecodes.find(b => b.scope?.stack === stack && b.scope.tenant === scope.tenant)
399
+ || bytecodes.find(b => b.scope?.stack === stack && !b.scope.tenant);
400
+ if (!source) return sendJson(404, { error: 'Authorized stack not found' });
401
+ const bc = structuredClone(source);
402
+ bc.scope = { ...bc.scope, ...scope, stack };
403
+ // A tenant edit cannot overwrite a public/global artifact on later promotion.
404
+ bc.id = `cbc:tenant:${scope.tenant}:${stack}`;
405
+ const created_at = new Date().toISOString();
406
+ if (type === 'constraint') {
407
+ bc.agent_constraints = bc.agent_constraints || [];
408
+ bc.agent_constraints.push({
409
+ id,
410
+ type: 'avoid',
411
+ rule: rule || id,
412
+ target_roles,
413
+ graduation_candidate: true,
414
+ trigger_regime: 'external_corrective',
415
+ created_at,
416
+ });
417
+ } else if (type === 'heuristic') {
418
+ bc.agent_heuristics = bc.agent_heuristics || [];
419
+ bc.agent_heuristics.push({
420
+ id,
421
+ when: when || 'Condição de disparo',
422
+ then: then || rule || id,
423
+ target_roles,
424
+ evidence_count: 1,
425
+ trigger_regime: 'silent_multimodal',
426
+ created_at,
427
+ });
428
+ } else if (type === 'principle') {
429
+ bc.decision_principles = bc.decision_principles || [];
430
+ bc.decision_principles.push({
431
+ id,
432
+ principle: principle || id,
433
+ rule: rule || id,
434
+ target_roles,
435
+ created_at,
436
+ });
437
+ }
438
+ if (typeof store.saveCandidate !== 'function') fail(503, 'Candidate persistence unavailable');
439
+ const candidate = await store.saveCandidate({ artifacts: { bytecode_artifact: bc }, scope: bc.scope, evidence, regime: 'graph_edit' });
440
+
441
+ return sendJson(201, {
442
+ success: true,
443
+ node_id: `${type}:${id}`,
444
+ type,
445
+ id,
446
+ stack,
447
+ created_at,
448
+ candidate,
449
+ published: false,
450
+ });
451
+ }
452
+
453
+ // 2. POST /api/v1/resolve
454
+ if (pathname === '/api/v1/resolve' && req.method === 'POST') {
455
+ const body = await parseBody();
456
+ const requestedTenant = body.tenant ?? body.scope?.tenant;
457
+ if (queryTenant && requestedTenant != null && queryTenant !== requestedTenant) fail(400, 'Conflicting query tenant scope');
458
+ const resolved = resolveAuthorizedContext({ store, principal, params: { ...body, tenant: requestedTenant ?? queryTenant } });
459
+
460
+ res.setHeader('X-CognitiveBC-Digest', resolved.digest_sha256 || '');
461
+ if (options.telemetry !== false) {
462
+ const h = (k) => { try { return req.headers[k] ? decodeURIComponent(String(req.headers[k])) : undefined; } catch { return undefined; } };
463
+ telemetry.recordResolve({ ...body, tenant: body.tenant ?? body.scope?.tenant ?? queryTenant, agent: body.agent || h('x-cbc-agent'), team: body.team || h('x-cbc-team'), client: body.client || h('x-cbc-client') }, resolved, options);
464
+ }
465
+ return sendJson(200, resolved);
466
+ }
467
+
468
+ // 3. POST /api/v1/streams/ingest
469
+ if (pathname === '/api/v1/streams/ingest' && req.method === 'POST') {
470
+ const body = await parseBody();
471
+ const scope = originScope(body);
472
+ const sessionId = body.session_id || body.sessionId;
473
+ const tenant = scope.tenant;
474
+ const events = body.events || [];
475
+ if (!Array.isArray(events)) fail(400, 'Invalid events');
476
+ for (const event of events) {
477
+ if (!event || typeof event !== 'object') fail(400, 'Invalid event');
478
+ if (event.tenant && event.tenant !== tenant) fail(403, 'Event tenant outside origin scope');
479
+ }
480
+ const result = await ingestionService.ingest({ ...body, tenant, session_id: sessionId }, { principal });
481
+ // Receipt persistence is authoritative. Optional telemetry cannot turn a
482
+ // durable acceptance into a failure. Record each newly persisted ID once.
483
+ if (options.telemetry !== false && result.newly_accepted > 0) {
484
+ const pending = new Set(result.new_event_ids || []);
485
+ const newlyRecordedEvents = events.filter(event => pending.delete(event.event_id || event.id));
486
+ try { telemetry.recordIngest({ ...body, tenant }, newlyRecordedEvents, options); }
487
+ catch { /* Durable receipt remains the delivery acknowledgement. */ }
488
+ }
489
+ return sendJson(200, result);
490
+ }
491
+
492
+ // 4. POST /api/v1/compile
493
+ if (pathname === '/api/v1/compile' && req.method === 'POST') {
494
+ const body = await parseBody();
495
+ const scope = originScope(body);
496
+ const evidence = originEvidence(body);
497
+ const regime = body.regime;
498
+ if (!['external_corrective', 'silent_multimodal', 'pioneer_discovery'].includes(regime)) {
499
+ return sendJson(400, { error: 'Invalid compilation regime' });
500
+ }
501
+
502
+ const compiled = compileExperience({
503
+ regime: body.regime,
504
+ scope,
505
+ inputPayload: body.input_payload || body.inputPayload || {},
506
+ options: body.options === undefined ? {} : body.options,
507
+ });
508
+
509
+ if (typeof store.saveCandidate !== 'function') fail(503, 'Candidate persistence unavailable');
510
+ const candidate = await store.saveCandidate({ artifacts: compiled, scope, evidence, regime: body.regime });
511
+
512
+ return sendJson(200, { ...compiled, candidate, published: false });
513
+ }
514
+
515
+ const candidateRoute = /^\/api\/v1\/candidates\/([^/]+)(\/promote)?$/.exec(pathname);
516
+ if (candidateRoute && (req.method === 'GET' || req.method === 'POST')) {
517
+ if (typeof store.getCandidate !== 'function') fail(503, 'Candidate persistence unavailable');
518
+ const candidateId = decodeURIComponent(candidateRoute[1]);
519
+ if (!/^candidate_[a-f0-9]{64}$/.test(candidateId)) fail(400, 'Invalid candidate ID');
520
+ let candidate;
521
+ try { candidate = await store.getCandidate(candidateId); }
522
+ catch (err) { if (err.code === 'ENOENT') return sendJson(404, { error: 'Candidate not found' }); throw err; }
523
+ if (!candidate) return sendJson(404, { error: 'Candidate not found' });
524
+ assertTenant(principal, candidate.scope?.tenant, { required: true });
525
+ if (principal.anonymous) fail(403, 'Candidate access not permitted');
526
+ if (!candidateRoute[2] && req.method === 'GET') return sendJson(200, candidate);
527
+ if (candidateRoute[2] && req.method === 'POST') {
528
+ authorize(principal, 'approve');
529
+ const body = await parseBody();
530
+ const scope = originScope({ ...body, scope: body.scope || candidate.scope });
531
+ if (!allowsTenant(principal, '*') && scope.tenant !== candidate.scope.tenant) fail(403, 'Promotion scope not permitted');
532
+ const promoted = await store.promoteCandidate(candidate.id, { ...body, approvedBy: principal.id, scope });
533
+ return sendJson(200, promoted);
534
+ }
535
+ }
536
+
537
+ // 5. POST /api/v1/gates/verify
538
+ if (pathname === '/api/v1/gates/verify' && req.method === 'POST') {
539
+ const body = await parseBody();
540
+ const selectedStore = bodyView(body);
541
+ const stage = body.stage;
542
+ const draftPayload = body.draft_payload || body.draftPayload || {};
543
+ if (body.rules !== undefined && !Array.isArray(body.rules)) fail(400, 'Invalid gate rules');
544
+ if (body.rules?.length) authorize(principal, 'write');
545
+ const rules = body.rules?.length ? [...selectedStore.getBytecodes().flatMap(b => b.gate_rules || []), ...body.rules] : [];
546
+
547
+ const result = verifyGateRules({
548
+ stage,
549
+ draftPayload,
550
+ rules,
551
+ bytecodes: selectedStore.getBytecodes(),
552
+ });
553
+ return sendJson(200, result);
554
+ }
555
+
556
+ // 6. GET /api/v1/artifacts/:type/:id
557
+ if (pathname.startsWith('/api/v1/artifacts/') && req.method === 'GET') {
558
+ const parts = pathname.replace('/api/v1/artifacts/', '').split('/');
559
+ const type = decodeURIComponent(parts[0]);
560
+ const id = decodeURIComponent(parts.slice(1).join('/'));
561
+
562
+ if (!type || !id) {
563
+ return sendJson(400, { error: 'Usage: /api/v1/artifacts/{type}/{id}' });
564
+ }
565
+
566
+ if (type === 'bytecode') {
567
+ const item = store.getBytecode(id);
568
+ if (!item) return sendJson(404, { error: 'Artifact not found' });
569
+ if (!canReadArtifact(principal, type, id, item)) {
570
+ return sendJson(principal.anonymous ? 404 : 403, { error: 'Artifact not permitted' });
571
+ }
572
+ return sendJson(200, {
573
+ id,
574
+ type: 'bytecode',
575
+ sha256: item.sha256,
576
+ artifact: viewStore.getBytecode(id),
577
+ });
578
+ }
579
+
580
+ if (type === 'skill') {
581
+ const item = store.getSkill(id);
582
+ if (!item) return sendJson(404, { error: 'Artifact not found' });
583
+ if (!canReadArtifact(principal, type, id, item)) return sendJson(principal.anonymous ? 404 : 403, { error: 'Artifact not permitted' });
584
+ return sendJson(200, {
585
+ id,
586
+ type: 'skill',
587
+ sha256: item.sha256,
588
+ artifact: item.content,
589
+ });
590
+ }
591
+
592
+ if (type === 'map') {
593
+ const content = store.getMap(id);
594
+ if (!content) return sendJson(404, { error: 'Artifact not found' });
595
+ if (!canReadArtifact(principal, type, id, { private: store.isPrivate('map', id) })) return sendJson(principal.anonymous ? 404 : 403, { error: 'Artifact not permitted' });
596
+ const selected = selectMapSection(content, parsedUrl.searchParams.get('section'));
597
+ if (selected === null) return sendJson(404, { error: 'Map section not found' });
598
+ return sendJson(200, {
599
+ id,
600
+ type: 'map',
601
+ artifact: selected,
602
+ });
603
+ }
604
+
605
+ return sendJson(400, { error: `Unknown artifact type: ${type}` });
606
+ }
607
+
608
+ // 404
609
+ return sendJson(404, { error: `Route not found: ${req.method} ${pathname}` });
610
+ } catch (err) {
611
+ const status = err instanceof URIError ? 400 : Number.isInteger(err.status) && err.status >= 400 && err.status < 600 ? err.status : 500;
612
+ // Never log request payloads, credentials or stack traces containing private data.
613
+ if (status >= 500 && options.onError) options.onError({ method: req.method, status });
614
+ if (res.destroyed) return;
615
+ if (status === 413) res.setHeader('Connection', 'close');
616
+ return sendJson(status, { error: status === 500 ? 'Internal server error' : err.message });
617
+ }
618
+ });
619
+
620
+ return { server, store };
621
+ }
622
+
623
+ function startServer(port = 4780, host = '127.0.0.1', options = {}) {
624
+ const { server, store } = createServer(options);
625
+ return new Promise((resolve) => {
626
+ server.listen(port, host, () => {
627
+ console.log(`[CognitiveBC] API server listening on http://${host}:${port}`);
628
+ console.log(`[CognitiveBC] Initial store loaded: ${store.bytecodes.size} bytecodes, ${store.skills.size} skills, ${store.maps.size} maps`);
629
+ resolve({ server, store, port, host });
630
+ });
631
+ });
632
+ }
633
+
634
+ if (require.main === module) {
635
+ const port = parseInt(process.env.PORT || process.env.COGNITIVEBC_PORT || '4780', 10);
636
+ startServer(port);
637
+ }
638
+
639
+ module.exports = {
640
+ createServer,
641
+ startServer,
642
+ };