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.
Files changed (66) hide show
  1. package/LICENSE +70 -0
  2. package/README.md +98 -4
  3. package/SECURITY.md +29 -0
  4. package/TERMS_OF_SERVICE.md +55 -0
  5. package/bin/cbc-cloud-bootstrap.js +108 -0
  6. package/bin/cbc-seed-projects.js +29 -0
  7. package/bin/cbc-server.js +45 -0
  8. package/bin/cognitivebc.js +251 -0
  9. package/docs/ACCESS_CONTROL.md +111 -0
  10. package/docs/ARTIFACT_AUDIT.md +36 -0
  11. package/docs/CONNECT_CLIENTS.md +116 -0
  12. package/docs/DEPLOY_AZURE.md +136 -0
  13. package/docs/INGESTION.md +29 -0
  14. package/docs/OPERATIONS.md +85 -0
  15. package/docs/PROJECT_IDENTITY.md +35 -0
  16. package/docs/RESOLVER.md +86 -0
  17. package/docs/SDK.md +96 -0
  18. package/docs/STORAGE.md +63 -0
  19. package/docs/TECHNICAL_SPECIFICATION.md +365 -0
  20. package/docs/TELEMETRY.md +119 -0
  21. package/index.js +27 -2
  22. package/package.json +45 -5
  23. package/packages/cbc-compiler/index.js +357 -0
  24. package/packages/cbc-compiler/sanitizer.js +43 -0
  25. package/packages/cbc-identity/index.js +92 -0
  26. package/packages/cbc-mcp/http-backend.js +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
package/LICENSE ADDED
@@ -0,0 +1,70 @@
1
+ # CognitiveBC Licensing Agreement
2
+
3
+ CognitiveBC (`cognitivebc.io`) uses an **Open Core** licensing model to provide frictionless integration for developers while protecting core compilation and runtime infrastructure.
4
+
5
+ ---
6
+
7
+ ## 1. Client SDK, Schemas, and Connectors: Apache License 2.0
8
+
9
+ The following components located in this repository:
10
+ - `packages/cbc-sdk-js/` (Client SDK for JavaScript/TypeScript)
11
+ - `packages/cbc-schema/` (Canonical Schema Specifications, e.g. `cognitivebc/v1`)
12
+ - `packages/cbc-mcp/` (Model Context Protocol connectors)
13
+ - Type definitions and sample fixtures
14
+
15
+ are licensed under the **Apache License, Version 2.0**:
16
+
17
+ ```
18
+ Copyright 2026 PerformacIA
19
+
20
+ Licensed under the Apache License, Version 2.0 (the "License");
21
+ you may not use this file except in compliance with the License.
22
+ You may obtain a copy of the License at
23
+
24
+ http://www.apache.org/licenses/LICENSE-2.0
25
+
26
+ Unless required by applicable law or agreed to in writing, software
27
+ distributed under the License is distributed on an "AS IS" BASIS,
28
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ See the License for the specific language governing permissions and
30
+ limitations under the License.
31
+ ```
32
+
33
+ ---
34
+
35
+ ## 2. Server, Compiler Engine & Decision Infrastructure: Business Source License (BSL 1.1)
36
+
37
+ The following core infrastructure components:
38
+ - `packages/cbc-compiler/` (Three-Regime Cognitive Compiler, Cycle Ingestion, IP Sanitizer)
39
+ - `packages/cbc-resolver/` (JIT Context Filtering & Token Budget Engine)
40
+ - `services/cbc-api/` (API Server & Decision Gate Verifier)
41
+ - `bin/cbc-server.js` and `bin/cbc-daemon.sh`
42
+
43
+ are licensed under the **Business Source License 1.1 (BSL 1.1)**:
44
+
45
+ ```
46
+ Parameters:
47
+ Licensor: PerformacIA (https://performacia.com.br / https://cognitivebc.io)
48
+ Licensed Work: CognitiveBC Server & Cognitive Compilation Engine v0.2.0+
49
+ Change Date: 2030-01-01
50
+ Change License: Apache License, Version 2.0
51
+
52
+ Use Grant:
53
+ You may use the Licensed Work for non-production development, local testing,
54
+ internal evaluation, and within autonomous agents running on local machines.
55
+
56
+ Additional Use Grant:
57
+ You may execute this software in production solely to support your own internal
58
+ business operations.
59
+
60
+ Prohibited Commercial Use:
61
+ You may NOT make the functionality of the Licensed Work available to third
62
+ parties as a hosted service, managed service, API platform, or commercial
63
+ "Agent-as-a-Service" (AaaS) platform competing with CognitiveBC or PerformacIA
64
+ without a separate Commercial License Agreement from the Licensor.
65
+
66
+ On the Change Date, the Licensed Work converts automatically to Apache License 2.0.
67
+ ```
68
+
69
+ For enterprise licenses, custom deployment agreements, or inquiries, contact:
70
+ `licensing@cognitivebc.io` / `contato@performacia.com.br`.
package/README.md CHANGED
@@ -1,6 +1,100 @@
1
- # cognitivebc
1
+ # cognitivebc (`cognitivebc.io`)
2
2
 
3
- Cognitive Bytecode (CBC) runtime & compiler for autonomous AI agent squads.
3
+ **Infraestrutura de Compilação de Experiência Operacional, Decisória e Bytecode Cognitivo para Sistemas de Agentes**
4
4
 
5
- Website: https://cognitivebc.io
6
- GitHub: https://github.com/performacia/cognitivebc
5
+ SDK oficial no npm (`cognitivebc`) e serviço de API (`api.cognitivebc.io` ou localmente em `http://localhost:4780`).
6
+
7
+ ---
8
+
9
+ ## 🚀 Como Servir a API Localmente
10
+
11
+ ### Modo Interativo (Terminal)
12
+
13
+ ```bash
14
+ # Inicia na porta padrão 4780
15
+ npm start
16
+
17
+ # Ou especificando porta customizada
18
+ PORT=4780 npm start
19
+ ```
20
+
21
+ ### Modo Daemon Permanente (macOS `launchd`)
22
+
23
+ O serviço roda silenciosamente em segundo plano, sobrevive a reinicializações e reinicia automaticamente se necessário:
24
+
25
+ ```bash
26
+ # Gerenciamento simples via npm:
27
+ npm run daemon:status # Verifica se está rodando e testa o endpoint HTTP
28
+ npm run daemon:restart # Reinicia o daemon
29
+ npm run daemon:logs # Exibe os últimos logs (stdout e stderr)
30
+ npm run daemon:stop # Para o daemon
31
+ npm run daemon:start # Inicia o daemon
32
+
33
+ # Ou diretamente pelo script:
34
+ ./bin/cbc-daemon.sh status
35
+ ```
36
+
37
+ ### Endpoints Canônicos Disponíveis
38
+
39
+ | Método | Rota | Descrição |
40
+ | :--- | :--- | :--- |
41
+ | `GET` | `/health` | Status do serviço e contagem de artefatos carregados |
42
+ | `POST` | `/api/v1/resolve` | Resolução JIT de contexto filtrado por papel com teto de tokens |
43
+ | `POST` | `/api/v1/streams/ingest` | Ingestão de telemetria e detector de `SilentSelfCorrectionCycle` |
44
+ | `POST` | `/api/v1/compile` | Compilador dos 3 Regimes (Corretivo Externo, Autocorreção Multimodal, Pioneiro) |
45
+ | `POST` | `/api/v1/gates/verify` | Validação determinística de contratos (`ContractGate`) |
46
+ | `GET` | `/api/v1/artifacts/:type/:id` | Consulta de artefatos versionados (`bytecode`, `skill`, `map`) com SHA-256 |
47
+
48
+ ---
49
+
50
+ ## 📦 Como Usar o SDK no Synap-se e BUs
51
+
52
+ ```javascript
53
+ const { CognitiveBCClient } = require('cognitivebc');
54
+
55
+ const cbc = new CognitiveBCClient({
56
+ baseUrl: process.env.COGNITIVEBC_URL || 'http://localhost:4780',
57
+ apiKey: process.env.COGNITIVEBC_API_KEY,
58
+ localFallbackDir: './.cbc-cache', // Cache offline-first
59
+ });
60
+
61
+ // 1. Resolução JIT por Papel (Roteirista, Construtor 3D, Revisor, etc.)
62
+ const packet = await cbc.resolve({
63
+ tenant: 'diario_glp1',
64
+ squad: 'mktsquad',
65
+ area: 'midias-organico',
66
+ role: 'construtor_3d',
67
+ stacks: ['scientific_3d_stack'],
68
+ maxTokens: 600,
69
+ });
70
+
71
+ console.log(packet.push_markdown);
72
+ console.log('Tokens estimados:', packet.token_count);
73
+ console.log('Digest SHA-256:', packet.digest_sha256);
74
+
75
+ // 2. Verificação de Portão Determinístico (ContractGate)
76
+ const gate = await cbc.verifyGate({
77
+ stage: 'roteiro',
78
+ draftPayload: {
79
+ titulo: 'Como as canetas de GLP-1 funcionam',
80
+ texto: 'As canetas de GLP-1 auxiliam no equilíbrio metabólico...',
81
+ },
82
+ });
83
+ console.log('Gate passou?', gate.passed);
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 🧪 Testes Automatizados
89
+
90
+ Executa a suíte de testes com validação completa de esquemas, motor de resolução JIT, 3 regimes de compilação e chamadas HTTP na API local:
91
+
92
+ ```bash
93
+ npm test
94
+ ```
95
+
96
+ ---
97
+
98
+ ## 📚 Documentação Técnica
99
+
100
+ Consulte a especificação canônica detalhada em [`docs/TECHNICAL_SPECIFICATION.md`](docs/TECHNICAL_SPECIFICATION.md).
package/SECURITY.md ADDED
@@ -0,0 +1,29 @@
1
+ # CognitiveBC — Security & Trade Secret Policy
2
+
3
+ ## 1. Information Security & Vulnerability Reporting
4
+
5
+ Security is fundamental to autonomous agent operations. If you discover a security vulnerability in CognitiveBC, please report it privately:
6
+
7
+ - **Email:** `security@cognitivebc.io`
8
+ - **PGP Key:** Available upon request.
9
+ - **Policy:** We appreciate responsible disclosure and ask that you give us reasonable time to remediate issues before making them public.
10
+
11
+ ---
12
+
13
+ ## 2. Trade Secret Protection Policy (Segredo de Negócio)
14
+
15
+ In accordance with Brazilian Industrial Property Law (Lei 9.279/1996, Arts. 195 and 207), the US Defend Trade Secrets Act (DTSA), and international trade secret protections, the following items are designated as **Confidential Trade Secrets of PerformacIA**:
16
+
17
+ 1. **Compilation Regime Mechanics:** The exact multi-stage reflection, differential parsing, and heuristic synthesis algorithms implemented in the Three-Regime Compiler (`packages/cbc-compiler`).
18
+ 2. **Cycle Detection Heuristics:** The mathematical sliding-window thresholds, state matching criteria, and detection weights of the `SilentSelfCorrectionCycle` detector (`ingestStreamEvents`).
19
+ 3. **Scoring & JIT Token Budgeting Algorithms:** The priority ranking, graph traversals, and dynamic token compression formulas used to keep context push strictly $\le 600$ tokens per agent role.
20
+ 4. **Internal Verification AST Transforms:** The automated transformation pipelines that graduate natural language agent heuristics into deterministic contract gates (`verifyGateRules`).
21
+
22
+ ---
23
+
24
+ ## 3. Contributor & Operator Guidelines
25
+
26
+ All contributors, engineers, and operational business units (including Synap-se and MktSquad operators) must adhere to the following controls:
27
+ - **Tenant Isolation Principle:** Never commit raw customer brand assets, API keys, or tenant-identifying facts into global stack bytecodes (`*.cbc.yaml`) or public repositories.
28
+ - **Cross-Tenant Sanitization Verification:** Always pass compiled experiences through the sanitizer (`sanitizeForGlobalScope`) before promoting any bytecode from local tenant scope to global squad/stack scope.
29
+ - **Access Control:** Production signing keys, compiler cloud credentials, and API service tokens must be stored in secure secret vaults and rotated periodically.
@@ -0,0 +1,55 @@
1
+ # CognitiveBC — Terms of Service & Software License Agreement (ToS / EULA)
2
+
3
+ **Last Updated:** November 2026
4
+ **Provider:** PerformacIA Tecnologia Ltda. ("PerformacIA", "we", "our", or "Licensor")
5
+ **Product:** CognitiveBC Platform, SDK, and APIs (`cognitivebc.io`, `api.cognitivebc.io`)
6
+
7
+ ---
8
+
9
+ ## 1. Acceptance of Terms
10
+
11
+ By accessing, downloading, installing, or using the CognitiveBC SDK (`cognitivebc` on npm), the CognitiveBC API (`api.cognitivebc.io`), or associated CLI/MCP servers, you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the software or services.
12
+
13
+ ---
14
+
15
+ ## 2. Intellectual Property & Ownership Boundaries
16
+
17
+ ### 2.1. The "Three-Worlds" Boundary Rule
18
+ CognitiveBC operates under a strict orthogonal property demarcation:
19
+ 1. **Tenant Data & Identity Assets (`MAP_<tenant>.md`):** You or your clients retain 100% exclusive ownership, title, and intellectual property rights in and to your proprietary business data, customer records, visual identities, private assets, and brand-specific rules. CognitiveBC claims no ownership over your Tenant Data.
20
+ 2. **Global Cognitive Bytecode (`*.cbc.yaml`) & Playbooks (`SKILL.md`):** All generic, domain-level, architectural, and stack-specific heuristics, decision invariants, execution graphs, and procedural skills compiled or provided by CognitiveBC are the proprietary intellectual property of PerformacIA and protected under international copyright and compilation laws.
21
+ 3. **Core Compilation & Runtime Software:** The CognitiveBC compiler engine, JIT context resolution algorithms, gate verification systems, and cycle detection mechanisms are protected trade secrets and proprietary software of PerformacIA.
22
+
23
+ ---
24
+
25
+ ## 3. Strict Restrictions: Anti-Distillation & Reverse Engineering
26
+
27
+ ### 3.1. Anti-Distillation & AI Model Training Prohibition
28
+ **You shall NOT, under any circumstances:**
29
+ 1. Use any output, compiled bytecode, decision heuristic, constraint rule, or JIT resolution packet obtained from CognitiveBC to train, pre-train, fine-tune, evaluate, align, distill, or benchmark any competing artificial intelligence model, LLM, autonomous agent compiler, or cognitive memory platform.
30
+ 2. Build, market, or distribute any dataset composed of CognitiveBC outputs for machine learning training purposes without explicit written authorization from PerformacIA.
31
+
32
+ ### 3.2. Prohibition of Reverse Engineering
33
+ You shall not decompile, disassemble, reverse engineer, decrypt, extract, or attempt to derive the underlying mathematical models, heuristics extraction logic, or scoring weights of the CognitiveBC Three-Regime Compiler or real-time cycle detectors, except to the extent permitted by mandatory applicable law.
34
+
35
+ ---
36
+
37
+ ## 4. API Usage, Rate Limits & Anti-Exfiltration
38
+
39
+ 1. **JIT Context Token Bounding:** All requests to `/api/v1/resolve` are subject to strict per-role token budgets. Attempting to bypass role filters or systematically scrape the entire bytecode catalog across multiple roles to reconstitute the global database is strictly prohibited.
40
+ 2. **Automated Scraping & Rate Limits:** We reserve the right to throttle, rate-limit, or terminate API keys exhibiting patterns of automated mass-scraping or credential sharing.
41
+ 3. **Integrity & Canary Tracking:** Distributed bytecode packages may contain cryptographic digests (SHA-256) and benign watermark signatures ("canary rules") to identify unauthorized leakage or distribution.
42
+
43
+ ---
44
+
45
+ ## 5. Warranties & Disclaimers
46
+
47
+ CognitiveBC provides operational rules, decision bytecode, and contract verification on an "AS IS" and "AS AVAILABLE" basis. While CognitiveBC enforces deterministic contract gates, you remain solely responsible for the final outputs, safety, and regulatory compliance of autonomous agents deployed within your operational pipelines.
48
+
49
+ ---
50
+
51
+ ## 6. Governing Law & Dispute Resolution
52
+
53
+ These Terms shall be governed by and construed in accordance with the laws of the Federative Republic of Brazil, notably Law 9.609/1998 (Software Law), Law 9.610/1998 (Copyright Law), and Law 9.279/1996 (Industrial Property Law). For international enterprise clients, disputes may be resolved under the Rules of Arbitration of the International Chamber of Commerce (ICC).
54
+
55
+ For licensing inquiries or commercial exemptions, contact: `legal@cognitivebc.io` or `contato@performacia.com.br`.
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * One-shot bootstrap of a CognitiveBC Postgres database:
6
+ * - migrates schema (store + project registry)
7
+ * - imports a file store (public + private roots, promoted candidates) idempotently
8
+ * - imports local telemetry JSONL
9
+ * - seeds Profarma projects
10
+ * - optionally issues the first admin token (printed once)
11
+ *
12
+ * Usage:
13
+ * COGNITIVEBC_DATABASE_URL=postgres://... node bin/cbc-cloud-bootstrap.js \
14
+ * --store /abs/store [--telemetry ~/.cognitivebc/telemetry] [--seed] [--admin-token "label"]
15
+ */
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+ const { poolFrom } = require('../services/cbc-api/cloud');
19
+ const { PgCognitiveStore } = require('../services/cbc-api/pg-store');
20
+ const { CognitiveStore, resolvePrivateDirs } = require('../services/cbc-api/store-loader');
21
+ const { createTokenService } = require('../services/cbc-api/token-service');
22
+
23
+ function arg(name) { const i = process.argv.indexOf(name); return i >= 0 ? process.argv[i + 1] : undefined; }
24
+ const flag = name => process.argv.includes(name);
25
+
26
+ async function main() {
27
+ const url = process.env.COGNITIVEBC_DATABASE_URL;
28
+ if (!url) throw new Error('COGNITIVEBC_DATABASE_URL required');
29
+ const pool = poolFrom(url);
30
+ const SYSTEM = { id: 'system-bootstrap', tenants: ['*'], permissions: ['*'] };
31
+ try {
32
+ const store = await new PgCognitiveStore(pool).init();
33
+ const storeDir = arg('--store');
34
+ if (storeDir) {
35
+ const source = new CognitiveStore(path.resolve(storeDir), { privateDirs: resolvePrivateDirs() });
36
+ const report = source.loadAll();
37
+ if (!report.integrity) throw new Error(`Source store has load errors: ${JSON.stringify(report.errors)}`);
38
+ let imported = 0;
39
+ for (const [type, collection] of [['bytecode', source.bytecodes], ['skill', source.skills], ['map', source.maps]]) {
40
+ for (const [id, entry] of collection) {
41
+ if (entry.candidateId) continue; // promoted bundles are imported with their candidate below
42
+ const raw = type === 'bytecode' ? entry.raw : entry.content;
43
+ await pool.query(
44
+ `INSERT INTO cbc_artifacts (type, id, raw, sha256, private) VALUES ($1,$2,$3,$4,$5)
45
+ ON CONFLICT (type, id) DO UPDATE SET raw=EXCLUDED.raw, sha256=EXCLUDED.sha256, private=EXCLUDED.private, updated_at=now()
46
+ WHERE cbc_artifacts.candidate_id IS NULL`, [type, id, raw, entry.sha256, Boolean(entry.private)]);
47
+ imported++;
48
+ }
49
+ }
50
+ let candidates = 0;
51
+ for (const root of source.roots()) {
52
+ const dir = path.join(root.dir, '.candidates');
53
+ if (!fs.existsSync(dir)) continue;
54
+ for (const name of fs.readdirSync(dir).filter(n => /^candidate_[a-f0-9]{64}\.json$/.test(n))) {
55
+ const record = source._readCandidate(path.join(dir, name));
56
+ await pool.query('INSERT INTO cbc_candidates (id, tenant, status, record) VALUES ($1,$2,$3,$4) ON CONFLICT (id) DO NOTHING', [record.id, record.scope.tenant, record.status, JSON.stringify(record)]);
57
+ if (record.status === 'promoted') {
58
+ for (const [type, prepared] of source._bundle(record)) await store._upsertArtifact(pool, type, prepared, { isPrivate: true, candidateId: record.id, scope: record.scope });
59
+ }
60
+ candidates++;
61
+ }
62
+ }
63
+ console.log(`imported ${imported} artifacts and ${candidates} candidates from ${storeDir}`);
64
+ }
65
+ const telemetryDir = arg('--telemetry');
66
+ if (telemetryDir) {
67
+ const { rows } = await pool.query('SELECT count(*)::int AS n FROM cbc_telemetry');
68
+ if (rows[0].n > 0) console.log('telemetry already present, skipping import');
69
+ else {
70
+ let n = 0;
71
+ for (const file of ['usage.jsonl', 'activity.jsonl']) {
72
+ const p = path.join(telemetryDir, file);
73
+ if (!fs.existsSync(p)) continue;
74
+ for (const line of fs.readFileSync(p, 'utf8').split('\n')) {
75
+ let rec; try { rec = JSON.parse(line); } catch { continue; }
76
+ if (!rec?.ts || !Number.isFinite(Date.parse(rec.ts))) continue;
77
+ await pool.query('INSERT INTO cbc_telemetry (ts, kind, tenant, record) VALUES ($1,$2,$3,$4)', [rec.ts, rec.kind || 'event', rec.tenant ?? null, JSON.stringify(rec)]);
78
+ n++;
79
+ }
80
+ }
81
+ console.log(`imported ${n} telemetry records`);
82
+ }
83
+ }
84
+ if (flag('--seed')) {
85
+ const { createProjectRegistry, seedProjects } = require('../services/cbc-api/project-registry');
86
+ const registry = createProjectRegistry({ db: pool });
87
+ await registry.migrate();
88
+ for (const p of await seedProjects(registry)) console.log(`seeded project ${p.id}`);
89
+ }
90
+ const label = arg('--admin-token');
91
+ const presetDigest = arg('--admin-token-sha256');
92
+ if (label && presetDigest) {
93
+ // Remote bootstrap: the secret never leaves the operator machine, only its digest.
94
+ if (!/^[a-f0-9]{64}$/.test(presetDigest)) throw new Error('--admin-token-sha256 must be 64 hex chars');
95
+ await pool.query('INSERT INTO cbc_tokens (token_sha256, label, principal, created_by) VALUES ($1,$2,$3,$4) ON CONFLICT (token_sha256) DO NOTHING',
96
+ [presetDigest, label, JSON.stringify({ id: arg('--admin-id') || 'admin', tenants: ['*'], permissions: ['*'] }), SYSTEM.id]);
97
+ console.log(`registered admin token ${presetDigest.slice(0, 16)}`);
98
+ } else if (label) {
99
+ const issued = await createTokenService(pool).issue({ label, principal: { id: arg('--admin-id') || 'admin', tenants: ['*'], permissions: ['*'] } }, SYSTEM);
100
+ // Printed once to stdout only; never logged elsewhere.
101
+ process.stdout.write(`ADMIN_TOKEN=${issued.token}\n`);
102
+ }
103
+ await store.refresh();
104
+ console.error(`database ready: ${store.bytecodes.size} bytecodes, ${store.skills.size} skills, ${store.maps.size} maps`);
105
+ } finally { await pool.end(); }
106
+ }
107
+
108
+ main().catch(err => { console.error(err.message); process.exit(1); });
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Upserts PROFARMA_SEED into the project registry.
5
+ // Usage: COGNITIVEBC_DATABASE_URL=postgres://... cbc-seed-projects | cbc-seed-projects --dir <path>
6
+ const { createProjectRegistry, seedProjects } = require('../services/cbc-api/project-registry');
7
+
8
+ async function main(argv = process.argv.slice(2)) {
9
+ const i = argv.indexOf('--dir');
10
+ const dir = i >= 0 ? argv[i + 1] : null;
11
+ let pool = null;
12
+ let registry;
13
+ if (dir) registry = createProjectRegistry({ dir });
14
+ else if (process.env.COGNITIVEBC_DATABASE_URL) {
15
+ const { Pool } = require('pg');
16
+ pool = new Pool({ connectionString: process.env.COGNITIVEBC_DATABASE_URL });
17
+ registry = createProjectRegistry({ db: pool });
18
+ } else {
19
+ console.error('Usage: cbc-seed-projects --dir <path> (or set COGNITIVEBC_DATABASE_URL)');
20
+ process.exit(2);
21
+ }
22
+ try {
23
+ await registry.migrate();
24
+ const out = await seedProjects(registry);
25
+ for (const p of out) console.log(`seeded ${p.id}`);
26
+ } finally { if (pool) await pool.end(); }
27
+ }
28
+
29
+ main().catch(err => { console.error(err.message); process.exit(1); });
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { startServer } = require('../services/cbc-api/server');
5
+ const path = require('node:path');
6
+ const { CognitiveStore, resolvePrivateDirs } = require('../services/cbc-api/store-loader');
7
+
8
+ const portText = process.env.PORT || process.env.COGNITIVEBC_PORT || '4780';
9
+ if (!/^\d+$/.test(portText) || Number(portText) > 65535) throw new Error('PORT must be an integer between 0 and 65535');
10
+ const port = Number(portText);
11
+ const host = process.env.HOST || '127.0.0.1';
12
+
13
+ async function main() {
14
+ // Cloud mode: Postgres is the single source of truth for every replica.
15
+ if (process.env.COGNITIVEBC_DATABASE_URL) {
16
+ const { createCloudServer } = require('../services/cbc-api/cloud');
17
+ const publicUrl = process.env.COGNITIVEBC_PUBLIC_URL;
18
+ const list = name => (process.env[name] || '').split(',').map(s => s.trim()).filter(Boolean);
19
+ // COGNITIVEBC_SITE_URL / COGNITIVEBC_APP_URL enable the site/app/API host split.
20
+ const site = list('COGNITIVEBC_SITE_URL'), app = list('COGNITIVEBC_APP_URL');
21
+ const origins = site.length || app.length ? { site, app, api: publicUrl ? [publicUrl] : [] } : undefined;
22
+ const allowedHosts = publicUrl ? [new URL(publicUrl).hostname] : [];
23
+ const { server, store } = await createCloudServer({ allowedHosts, origins, onError: e => console.error('[CognitiveBC] request failed', e) });
24
+ await new Promise(resolve => server.listen(port, host, resolve));
25
+ console.log(`[CognitiveBC] cloud API listening on http://${host}:${port} (postgres: ${store.bytecodes.size} bytecodes, ${store.maps.size} maps)`);
26
+ const stop = () => server.close(() => process.exit(0));
27
+ process.on('SIGTERM', stop); process.on('SIGINT', stop);
28
+ return;
29
+ }
30
+ const storeDir = process.env.COGNITIVEBC_STORE_DIR;
31
+ if (storeDir !== undefined && (!storeDir.trim() || !path.isAbsolute(storeDir))) {
32
+ throw new Error('COGNITIVEBC_STORE_DIR must be an absolute directory');
33
+ }
34
+ // An immutable application release must not copy or replace operational knowledge.
35
+ // Explicitly preserve the configured/default private roots when selecting a public root.
36
+ const options = storeDir === undefined ? {} : {
37
+ store: new CognitiveStore(storeDir, { privateDirs: resolvePrivateDirs() }),
38
+ };
39
+ await startServer(port, host, options);
40
+ }
41
+
42
+ main().catch(err => {
43
+ console.error('[CognitiveBC] Fatal start error:', err);
44
+ process.exit(1);
45
+ });