cognitivebc 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +70 -0
- package/README.md +98 -4
- package/SECURITY.md +29 -0
- package/TERMS_OF_SERVICE.md +55 -0
- package/bin/cbc-cloud-bootstrap.js +108 -0
- package/bin/cbc-seed-projects.js +29 -0
- package/bin/cbc-server.js +45 -0
- package/bin/cognitivebc.js +251 -0
- package/docs/ACCESS_CONTROL.md +111 -0
- package/docs/ARTIFACT_AUDIT.md +36 -0
- package/docs/CONNECT_CLIENTS.md +116 -0
- package/docs/DEPLOY_AZURE.md +136 -0
- package/docs/INGESTION.md +29 -0
- package/docs/OPERATIONS.md +85 -0
- package/docs/PROJECT_IDENTITY.md +35 -0
- package/docs/RESOLVER.md +86 -0
- package/docs/SDK.md +96 -0
- package/docs/STORAGE.md +63 -0
- package/docs/TECHNICAL_SPECIFICATION.md +365 -0
- package/docs/TELEMETRY.md +119 -0
- package/index.js +27 -2
- package/package.json +45 -5
- package/packages/cbc-compiler/index.js +357 -0
- package/packages/cbc-compiler/sanitizer.js +43 -0
- package/packages/cbc-identity/index.js +92 -0
- package/packages/cbc-mcp/http-backend.js +142 -0
- package/packages/cbc-mcp/http-route.js +64 -0
- package/packages/cbc-mcp/index.js +50 -0
- package/packages/cbc-mcp/tools.js +122 -0
- package/packages/cbc-resolver/catalog-linker.js +215 -0
- package/packages/cbc-resolver/graph-builder.js +533 -0
- package/packages/cbc-resolver/index.js +548 -0
- package/packages/cbc-resolver/obsidian-bridge.js +564 -0
- package/packages/cbc-schema/index.js +194 -0
- package/packages/cbc-sdk-js/client.js +162 -0
- package/services/cbc-api/access-policy.js +130 -0
- package/services/cbc-api/artifact-audit.js +167 -0
- package/services/cbc-api/cloud.js +56 -0
- package/services/cbc-api/context-service.js +48 -0
- package/services/cbc-api/ingestion-service.js +234 -0
- package/services/cbc-api/pg-store.js +172 -0
- package/services/cbc-api/project-registry.js +343 -0
- package/services/cbc-api/public/app.html +123 -0
- package/services/cbc-api/public/graph.html +1168 -0
- package/services/cbc-api/public/graph2.html +455 -0
- package/services/cbc-api/public/graph3.html +503 -0
- package/services/cbc-api/public/index.html +78 -0
- package/services/cbc-api/public/vendor/cbc-app.js +209 -0
- package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
- package/services/cbc-api/public/vendor/cbc-site.css +101 -0
- package/services/cbc-api/public/vendor/cose-base.js +3214 -0
- package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
- package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
- package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
- package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
- package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
- package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
- package/services/cbc-api/public/vendor/layout-base.js +5230 -0
- package/services/cbc-api/public/vendor/pf-graph.css +86 -0
- package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
- package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
- package/services/cbc-api/runtime-info.js +39 -0
- package/services/cbc-api/server.js +642 -0
- package/services/cbc-api/store-loader.js +269 -0
- package/services/cbc-api/telemetry.js +148 -0
- package/services/cbc-api/token-service.js +61 -0
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const YAML = require('yaml');
|
|
6
|
+
const { buildSemanticGraph } = require('./graph-builder');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Obsidian Bridge for CognitiveBC
|
|
10
|
+
* Converts CognitiveBC bytecodes, maps, and rules into a native Obsidian Vault
|
|
11
|
+
* with full bidirectional [[wikilinks]], tags, callouts, and Mermaid diagrams.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
function sanitizeFilename(name) {
|
|
15
|
+
return name.replace(/[/\\?%*:|"<>]/g, '-').trim();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Export CognitiveBC store to a native Obsidian Vault
|
|
20
|
+
* @param {CognitiveStore} store
|
|
21
|
+
* @param {string} outputDir
|
|
22
|
+
* @returns {object} Export summary
|
|
23
|
+
*/
|
|
24
|
+
function exportToObsidianVault(store, outputDir, graphOptions = {}) {
|
|
25
|
+
if (!outputDir) {
|
|
26
|
+
throw new Error('outputDir is required for exportToObsidianVault');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Subfolders
|
|
30
|
+
const dirs = {
|
|
31
|
+
root: outputDir,
|
|
32
|
+
roles: path.join(outputDir, 'Roles'),
|
|
33
|
+
stacks: path.join(outputDir, 'Stacks'),
|
|
34
|
+
constraints: path.join(outputDir, 'Constraints'),
|
|
35
|
+
heuristics: path.join(outputDir, 'Heuristics'),
|
|
36
|
+
principles: path.join(outputDir, 'Principles'),
|
|
37
|
+
experiences: path.join(outputDir, 'Experiences'),
|
|
38
|
+
gates: path.join(outputDir, 'Gates'),
|
|
39
|
+
vaults: path.join(outputDir, 'Vaults'),
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
Object.values(dirs).forEach(d => {
|
|
43
|
+
if (!fs.existsSync(d)) {
|
|
44
|
+
fs.mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const filesWritten = [];
|
|
49
|
+
// O vault vai para store/obsidian-vault (versionado e publicado): só artefatos públicos, nunca os de tenant privado.
|
|
50
|
+
const publicView = typeof store.getPublicBytecodes === 'function'
|
|
51
|
+
? { getBytecodes: () => store.getPublicBytecodes(), getMapsDict: () => store.getPublicMapsDict() }
|
|
52
|
+
: store;
|
|
53
|
+
const bytecodes = publicView.getBytecodes();
|
|
54
|
+
const mapsDict = publicView.getMapsDict();
|
|
55
|
+
const graph = buildSemanticGraph(publicView, { ...graphOptions, catalog: false, telemetry: graphOptions.telemetry ?? false });
|
|
56
|
+
|
|
57
|
+
// 1. Export Roles (Discovered dynamically from bytecodes)
|
|
58
|
+
const discoveredRoleSet = new Set();
|
|
59
|
+
const roleBudgetMap = {};
|
|
60
|
+
for (const bc of bytecodes) {
|
|
61
|
+
(bc.scope?.roles || []).forEach(r => discoveredRoleSet.add(r));
|
|
62
|
+
if (bc.scope?.role_budgets) {
|
|
63
|
+
Object.assign(roleBudgetMap, bc.scope.role_budgets);
|
|
64
|
+
}
|
|
65
|
+
(bc.agent_constraints || []).forEach(c => (c.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
66
|
+
(bc.agent_heuristics || []).forEach(h => (h.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
67
|
+
(bc.decision_principles || []).forEach(p => (p.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
68
|
+
(bc.experience_graph || []).forEach(eg => (eg.target_roles || []).forEach(r => r !== '*' && discoveredRoleSet.add(r)));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const roles = Array.from(discoveredRoleSet).map(roleId => ({
|
|
72
|
+
id: roleId,
|
|
73
|
+
name: roleId.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
|
|
74
|
+
icon: '🤖',
|
|
75
|
+
desc: `Papel operacional de agente (${roleId}) resolvido via JIT`,
|
|
76
|
+
tokenCeiling: roleBudgetMap[roleId] || 600,
|
|
77
|
+
}));
|
|
78
|
+
|
|
79
|
+
for (const r of roles) {
|
|
80
|
+
const roleFilename = `role - ${sanitizeFilename(r.id)}.md`;
|
|
81
|
+
const rolePath = path.join(dirs.roles, roleFilename);
|
|
82
|
+
|
|
83
|
+
// Find linked constraints and heuristics
|
|
84
|
+
const connectedConstraints = [];
|
|
85
|
+
const connectedHeuristics = [];
|
|
86
|
+
const connectedPrinciples = [];
|
|
87
|
+
const connectedExperiences = [];
|
|
88
|
+
|
|
89
|
+
for (const bc of bytecodes) {
|
|
90
|
+
(bc.agent_constraints || []).forEach(c => {
|
|
91
|
+
if ((c.target_roles || []).includes(r.id)) connectedConstraints.push(c);
|
|
92
|
+
});
|
|
93
|
+
(bc.agent_heuristics || []).forEach(h => {
|
|
94
|
+
if ((h.target_roles || []).includes(r.id)) connectedHeuristics.push(h);
|
|
95
|
+
});
|
|
96
|
+
(bc.decision_principles || []).forEach(p => {
|
|
97
|
+
if ((p.target_roles || []).includes(r.id)) connectedPrinciples.push(p);
|
|
98
|
+
});
|
|
99
|
+
(bc.experience_graph || []).forEach(eg => {
|
|
100
|
+
if ((eg.target_roles || []).includes(r.id)) connectedExperiences.push(eg);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const frontmatter = {
|
|
105
|
+
type: 'role',
|
|
106
|
+
role: r.id,
|
|
107
|
+
name: r.name,
|
|
108
|
+
token_ceiling: r.tokenCeiling,
|
|
109
|
+
tags: ['cbc/role', 'cbc/agent', `cbc/role/${r.id}`],
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
let content = `---\n${YAML.stringify(frontmatter)}---\n\n`;
|
|
113
|
+
content += `# ${r.icon} ${r.name}\n\n`;
|
|
114
|
+
content += `> [!info] Perfil Cognitivo\n`;
|
|
115
|
+
content += `> **Descrição:** ${r.desc}\n`;
|
|
116
|
+
content += `> **Orçamento Máximo de Tokens:** $\\le ${r.tokenCeiling}$ tokens (JIT Pareto-Packed).\n\n`;
|
|
117
|
+
|
|
118
|
+
content += `## Stacks Associadas\n`;
|
|
119
|
+
bytecodes.forEach(bc => {
|
|
120
|
+
const stack = bc.scope?.stack || 'general_stack';
|
|
121
|
+
content += `- [[stack - ${sanitizeFilename(stack)}]]\n`;
|
|
122
|
+
});
|
|
123
|
+
content += `\n`;
|
|
124
|
+
|
|
125
|
+
content += `## Vaults de Tenant (Bases Semânticas)\n`;
|
|
126
|
+
Object.keys(mapsDict).forEach(tenantKey => {
|
|
127
|
+
content += `- [[vault - ${sanitizeFilename(tenantKey)}]]\n`;
|
|
128
|
+
});
|
|
129
|
+
content += `\n`;
|
|
130
|
+
|
|
131
|
+
if (connectedConstraints.length > 0) {
|
|
132
|
+
content += `## Restrições Ativas (Deterministic Gates)\n`;
|
|
133
|
+
connectedConstraints.forEach(c => {
|
|
134
|
+
content += `- [[constraint - ${sanitizeFilename(c.id)}]] — ${c.rule.slice(0, 80)}...\n`;
|
|
135
|
+
});
|
|
136
|
+
content += `\n`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (connectedHeuristics.length > 0) {
|
|
140
|
+
content += `## Heurísticas Operacionais (When/Then)\n`;
|
|
141
|
+
connectedHeuristics.forEach(h => {
|
|
142
|
+
content += `- [[heuristic - ${sanitizeFilename(h.id)}]] (${h.evidence_count || 1} evidências)\n`;
|
|
143
|
+
});
|
|
144
|
+
content += `\n`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (connectedPrinciples.length > 0) {
|
|
148
|
+
content += `## Princípios Decisórios\n`;
|
|
149
|
+
connectedPrinciples.forEach(p => {
|
|
150
|
+
content += `- [[principle - ${sanitizeFilename(p.id)}]] — \`${p.principle || p.id}\`\n`;
|
|
151
|
+
});
|
|
152
|
+
content += `\n`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (connectedExperiences.length > 0) {
|
|
156
|
+
content += `## Casos de Experiência Causal\n`;
|
|
157
|
+
connectedExperiences.forEach(eg => {
|
|
158
|
+
content += `- [[experience - ${sanitizeFilename(eg.problem_id)}]]\n`;
|
|
159
|
+
});
|
|
160
|
+
content += `\n`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
fs.writeFileSync(rolePath, content, 'utf8');
|
|
164
|
+
filesWritten.push(rolePath);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 2. Export Stacks & Bytecode Rules
|
|
168
|
+
for (const bc of bytecodes) {
|
|
169
|
+
const stackKey = bc.scope?.stack || 'scientific_3d_stack';
|
|
170
|
+
const stackFilename = `stack - ${sanitizeFilename(stackKey)}.md`;
|
|
171
|
+
const stackPath = path.join(dirs.stacks, stackFilename);
|
|
172
|
+
|
|
173
|
+
const frontmatter = {
|
|
174
|
+
type: 'stack',
|
|
175
|
+
stack: stackKey,
|
|
176
|
+
schema: bc.schema,
|
|
177
|
+
id: bc.id,
|
|
178
|
+
roles: bc.scope?.roles || [],
|
|
179
|
+
tags: ['cbc/stack', `cbc/stack/${stackKey}`],
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
let content = `---\n${YAML.stringify(frontmatter)}---\n\n`;
|
|
183
|
+
content += `# 🟣 Stack: ${stackKey}\n\n`;
|
|
184
|
+
content += `> [!abstract] Proveniência e Escopo\n`;
|
|
185
|
+
content += `> **ID Canônico:** \`${bc.id}\`\n`;
|
|
186
|
+
content += `> **Schema:** \`${bc.schema}\`\n`;
|
|
187
|
+
content += `> **Squad:** \`${bc.scope?.squad || 'geral'}\` | **Área:** \`${bc.scope?.area || 'geral'}\`\n\n`;
|
|
188
|
+
|
|
189
|
+
content += `## Papéis que Operam nesta Stack\n`;
|
|
190
|
+
(bc.scope?.roles || []).forEach(r => {
|
|
191
|
+
content += `- [[role - ${sanitizeFilename(r)}]]\n`;
|
|
192
|
+
});
|
|
193
|
+
content += `\n`;
|
|
194
|
+
|
|
195
|
+
content += '```mermaid\ngraph TD\n';
|
|
196
|
+
content += ` Stack["🟣 ${stackKey}"]\n`;
|
|
197
|
+
(bc.scope?.roles || []).forEach(r => {
|
|
198
|
+
content += ` Stack --> Role_${r}["[[role - ${sanitizeFilename(r)}]]"]\n`;
|
|
199
|
+
});
|
|
200
|
+
(bc.agent_constraints || []).forEach(c => {
|
|
201
|
+
content += ` Stack --> Constraint_${c.id.replace(/[^a-zA-Z0-9]/g, '_')}["[[constraint - ${sanitizeFilename(c.id)}]]"]\n`;
|
|
202
|
+
});
|
|
203
|
+
content += '```\n\n';
|
|
204
|
+
|
|
205
|
+
fs.writeFileSync(stackPath, content, 'utf8');
|
|
206
|
+
filesWritten.push(stackPath);
|
|
207
|
+
|
|
208
|
+
// 2.1. Export Constraints
|
|
209
|
+
(bc.agent_constraints || []).forEach(c => {
|
|
210
|
+
const cFilename = `constraint - ${sanitizeFilename(c.id)}.md`;
|
|
211
|
+
const cPath = path.join(dirs.constraints, cFilename);
|
|
212
|
+
|
|
213
|
+
const cFm = {
|
|
214
|
+
type: 'constraint',
|
|
215
|
+
id: c.id,
|
|
216
|
+
stack: stackKey,
|
|
217
|
+
target_roles: c.target_roles || [],
|
|
218
|
+
graduation_candidate: !!c.graduation_candidate,
|
|
219
|
+
trigger_regime: c.trigger_regime || 'external_corrective',
|
|
220
|
+
tags: ['cbc/constraint', 'cbc/gate', ...(c.target_roles || []).map(r => `cbc/role/${r}`)],
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
let cBody = `---\n${YAML.stringify(cFm)}---\n\n`;
|
|
224
|
+
cBody += `# 🛑 ${c.id}\n\n`;
|
|
225
|
+
cBody += `> [!danger] Portão Rígido (Deterministic Gate)\n`;
|
|
226
|
+
cBody += `> **Regra:** ${c.rule}\n`;
|
|
227
|
+
if (c.deterministic_gate_hint) {
|
|
228
|
+
cBody += `> **Portão Determinístico (AST/Regex):** \`${c.deterministic_gate_hint}\`\n`;
|
|
229
|
+
}
|
|
230
|
+
cBody += `\n`;
|
|
231
|
+
|
|
232
|
+
cBody += `## Metadados Operacionais\n`;
|
|
233
|
+
cBody += `- **Stack Pertencente:** [[stack - ${sanitizeFilename(stackKey)}]]\n`;
|
|
234
|
+
cBody += `- **Regime de Ativação:** \`${c.trigger_regime || 'external_corrective'}\`\n`;
|
|
235
|
+
cBody += `- **Candidato a Graduação:** \`${c.graduation_candidate ? 'Sim (Graduado para AST Gate)' : 'Não'}\`\n\n`;
|
|
236
|
+
|
|
237
|
+
cBody += `## Papéis Impactados\n`;
|
|
238
|
+
(c.target_roles || []).forEach(r => {
|
|
239
|
+
cBody += `- [[role - ${sanitizeFilename(r)}]]\n`;
|
|
240
|
+
});
|
|
241
|
+
cBody += `\n`;
|
|
242
|
+
|
|
243
|
+
fs.writeFileSync(cPath, cBody, 'utf8');
|
|
244
|
+
filesWritten.push(cPath);
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
// 2.2. Export Heuristics
|
|
248
|
+
(bc.agent_heuristics || []).forEach(h => {
|
|
249
|
+
const hFilename = `heuristic - ${sanitizeFilename(h.id)}.md`;
|
|
250
|
+
const hPath = path.join(dirs.heuristics, hFilename);
|
|
251
|
+
|
|
252
|
+
const hFm = {
|
|
253
|
+
type: 'heuristic',
|
|
254
|
+
id: h.id,
|
|
255
|
+
stack: stackKey,
|
|
256
|
+
target_roles: h.target_roles || [],
|
|
257
|
+
evidence_count: h.evidence_count || 1,
|
|
258
|
+
trigger_regime: h.trigger_regime || 'silent_multimodal',
|
|
259
|
+
tags: ['cbc/heuristic', ...(h.target_roles || []).map(r => `cbc/role/${r}`)],
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
let hBody = `---\n${YAML.stringify(hFm)}---\n\n`;
|
|
263
|
+
hBody += `# 💡 ${h.id}\n\n`;
|
|
264
|
+
hBody += `> [!tip] Heurística Operacional Validada\n`;
|
|
265
|
+
hBody += `> **Quando (When):** ${h.when}\n`;
|
|
266
|
+
hBody += `> **Então (Then):** ${h.then}\n`;
|
|
267
|
+
hBody += `> **Evidências Empíricas:** Confirmado em **${h.evidence_count || 1}** execuções em produção.\n\n`;
|
|
268
|
+
|
|
269
|
+
hBody += `## Metadados\n`;
|
|
270
|
+
hBody += `- **Stack:** [[stack - ${sanitizeFilename(stackKey)}]]\n`;
|
|
271
|
+
if (h.scope) hBody += `- **Escopo Técnico:** \`${h.scope}\`\n`;
|
|
272
|
+
hBody += `\n`;
|
|
273
|
+
|
|
274
|
+
hBody += `## Papéis que Aplicam esta Heurística\n`;
|
|
275
|
+
(h.target_roles || []).forEach(r => {
|
|
276
|
+
hBody += `- [[role - ${sanitizeFilename(r)}]]\n`;
|
|
277
|
+
});
|
|
278
|
+
hBody += `\n`;
|
|
279
|
+
|
|
280
|
+
fs.writeFileSync(hPath, hBody, 'utf8');
|
|
281
|
+
filesWritten.push(hPath);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// 2.3. Export Principles
|
|
285
|
+
(bc.decision_principles || []).forEach(p => {
|
|
286
|
+
const pFilename = `principle - ${sanitizeFilename(p.id)}.md`;
|
|
287
|
+
const pPath = path.join(dirs.principles, pFilename);
|
|
288
|
+
|
|
289
|
+
const pFm = {
|
|
290
|
+
type: 'principle',
|
|
291
|
+
id: p.id,
|
|
292
|
+
stack: stackKey,
|
|
293
|
+
target_roles: p.target_roles || [],
|
|
294
|
+
principle: p.principle || p.id,
|
|
295
|
+
tags: ['cbc/principle', ...(p.target_roles || []).map(r => `cbc/role/${r}`)],
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
let pBody = `---\n${YAML.stringify(pFm)}---\n\n`;
|
|
299
|
+
pBody += `# 🟢 ${p.principle || p.id}\n\n`;
|
|
300
|
+
pBody += `> [!check] Princípio Decisório Central\n`;
|
|
301
|
+
pBody += `> **Diretriz:** ${p.rule}\n\n`;
|
|
302
|
+
|
|
303
|
+
pBody += `## Metadados\n`;
|
|
304
|
+
pBody += `- **Stack:** [[stack - ${sanitizeFilename(stackKey)}]]\n`;
|
|
305
|
+
pBody += `\n`;
|
|
306
|
+
|
|
307
|
+
pBody += `## Papéis\n`;
|
|
308
|
+
(p.target_roles || []).forEach(r => {
|
|
309
|
+
pBody += `- [[role - ${sanitizeFilename(r)}]]\n`;
|
|
310
|
+
});
|
|
311
|
+
pBody += `\n`;
|
|
312
|
+
|
|
313
|
+
fs.writeFileSync(pPath, pBody, 'utf8');
|
|
314
|
+
filesWritten.push(pPath);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// 2.4. Export Experiences
|
|
318
|
+
(bc.experience_graph || []).forEach(eg => {
|
|
319
|
+
const egFilename = `experience - ${sanitizeFilename(eg.problem_id)}.md`;
|
|
320
|
+
const egPath = path.join(dirs.experiences, egFilename);
|
|
321
|
+
|
|
322
|
+
const egFm = {
|
|
323
|
+
type: 'experience',
|
|
324
|
+
problem_id: eg.problem_id,
|
|
325
|
+
stack: stackKey,
|
|
326
|
+
target_roles: eg.target_roles || [],
|
|
327
|
+
trigger_regime: eg.trigger_regime || 'silent_multimodal',
|
|
328
|
+
tags: ['cbc/experience', ...(eg.target_roles || []).map(r => `cbc/role/${r}`)],
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
let egBody = `---\n${YAML.stringify(egFm)}---\n\n`;
|
|
332
|
+
egBody += `# 🔵 ${eg.problem_id}\n\n`;
|
|
333
|
+
egBody += `> [!warning] Sintoma Observado\n`;
|
|
334
|
+
egBody += `> ${eg.symptom}\n\n`;
|
|
335
|
+
|
|
336
|
+
egBody += `> [!note] Causa Raiz\n`;
|
|
337
|
+
egBody += `> ${eg.root_cause}\n\n`;
|
|
338
|
+
|
|
339
|
+
if (Array.isArray(eg.solutions_evaluated)) {
|
|
340
|
+
egBody += `## Soluções Avaliadas\n\n`;
|
|
341
|
+
eg.solutions_evaluated.forEach(sol => {
|
|
342
|
+
const badge = sol.outcome === 'adopted' ? '✅ ADOTADA' : sol.outcome === 'rejected' ? '❌ REJEITADA' : '⚪ NÃO VERIFICADA';
|
|
343
|
+
egBody += `### ${badge}: ${sol.option}\n`;
|
|
344
|
+
egBody += `**Motivo:** ${sol.reason}\n\n`;
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
egBody += `## Conexões\n`;
|
|
349
|
+
egBody += `- **Stack:** [[stack - ${sanitizeFilename(stackKey)}]]\n`;
|
|
350
|
+
(eg.target_roles || []).forEach(r => {
|
|
351
|
+
egBody += `- [[role - ${sanitizeFilename(r)}]]\n`;
|
|
352
|
+
});
|
|
353
|
+
egBody += `\n`;
|
|
354
|
+
|
|
355
|
+
fs.writeFileSync(egPath, egBody, 'utf8');
|
|
356
|
+
filesWritten.push(egPath);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
// 2.5. Export Declarative Gate Rules
|
|
360
|
+
(bc.gate_rules || []).forEach(g => {
|
|
361
|
+
const gFilename = `gate - ${sanitizeFilename(g.id)}.md`;
|
|
362
|
+
const gPath = path.join(dirs.gates, gFilename);
|
|
363
|
+
|
|
364
|
+
const gFm = {
|
|
365
|
+
type: 'gate_rule',
|
|
366
|
+
id: g.id,
|
|
367
|
+
stage: g.stage,
|
|
368
|
+
gate_type: g.type,
|
|
369
|
+
severity: g.severity || 'critical',
|
|
370
|
+
field: g.field,
|
|
371
|
+
tags: ['cbc/gate', `cbc/stage/${g.stage}`],
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
let gBody = `---\n${YAML.stringify(gFm)}---\n\n`;
|
|
375
|
+
gBody += `# 🛡️ ${g.id} (${g.stage})\n\n`;
|
|
376
|
+
gBody += `> [!danger] Portão de Verificação Automática (${gFm.severity.toUpperCase()})\n`;
|
|
377
|
+
gBody += `> **Mensagem de Falha:** ${g.message}\n`;
|
|
378
|
+
gBody += `> **Tipo de Avaliação:** \`${g.type}\` no campo \`${g.field}\`\n\n`;
|
|
379
|
+
|
|
380
|
+
if (g.keywords) {
|
|
381
|
+
gBody += `**Palavras-Chave Obrigatórias:** \`${g.keywords.join(', ')}\` (Primeiras ${g.max_words_window || 20} palavras)\n\n`;
|
|
382
|
+
}
|
|
383
|
+
if (g.patterns) {
|
|
384
|
+
gBody += `**Padrões Regex Proibidos:** \`${g.patterns.join(', ')}\`\n\n`;
|
|
385
|
+
}
|
|
386
|
+
if (g.pattern) {
|
|
387
|
+
gBody += `**Padrão Proibido:** \`${g.pattern}\`\n\n`;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
gBody += `## Conexões\n`;
|
|
391
|
+
gBody += `- **Stack:** [[stack - ${sanitizeFilename(stackKey)}]]\n\n`;
|
|
392
|
+
|
|
393
|
+
fs.writeFileSync(gPath, gBody, 'utf8');
|
|
394
|
+
filesWritten.push(gPath);
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// 3. Export Vaults (Tenant Maps)
|
|
399
|
+
for (const [tenantKey, contentRaw] of Object.entries(mapsDict)) {
|
|
400
|
+
const vaultFilename = `vault - ${sanitizeFilename(tenantKey)}.md`;
|
|
401
|
+
const vaultPath = path.join(dirs.vaults, vaultFilename);
|
|
402
|
+
|
|
403
|
+
const vFm = {
|
|
404
|
+
type: 'vault',
|
|
405
|
+
tenant: tenantKey,
|
|
406
|
+
tags: ['cbc/vault', `cbc/tenant/${tenantKey}`],
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
let vBody = `---\n${YAML.stringify(vFm)}---\n\n`;
|
|
410
|
+
vBody += `# 🟠 Vault Semântico: ${tenantKey}\n\n`;
|
|
411
|
+
vBody += `> [!caution] Confidencialidade de Tenant\n`;
|
|
412
|
+
vBody += `> Este cofre contém fatos, terminologias e regras comerciais exclusivas do tenant **${tenantKey}**.\n`;
|
|
413
|
+
vBody += `> *Escopo de origem: tenant. A exportação usa a visão autorizada fornecida pelo chamador; não atesta isolamento de toda a implantação.*\n\n`;
|
|
414
|
+
|
|
415
|
+
vBody += `## Conteúdo do Vault\n\n`;
|
|
416
|
+
vBody += `${contentRaw}\n\n`;
|
|
417
|
+
|
|
418
|
+
vBody += `## Consumido por\n`;
|
|
419
|
+
roles.forEach(r => {
|
|
420
|
+
vBody += `- [[role - ${sanitizeFilename(r.id)}]]\n`;
|
|
421
|
+
});
|
|
422
|
+
vBody += `\n`;
|
|
423
|
+
|
|
424
|
+
fs.writeFileSync(vaultPath, vBody, 'utf8');
|
|
425
|
+
filesWritten.push(vaultPath);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// 4. Export Index (MOC - Map of Content)
|
|
429
|
+
const indexFilename = '00 - Index (MOC).md';
|
|
430
|
+
const indexPath = path.join(dirs.root, indexFilename);
|
|
431
|
+
|
|
432
|
+
let indexBody = `# 🧠 CognitiveBC · Neural Knowledge Vault (MOC)\n\n`;
|
|
433
|
+
indexBody += `> **Bem-vindo ao Vault Cognitivo do CognitiveBC.**\n`;
|
|
434
|
+
indexBody += `> Este vault foi gerado automaticamente pelo **CognitiveBC Graph Generator** e é 100% navegável no Obsidian.\n\n`;
|
|
435
|
+
|
|
436
|
+
indexBody += `## Estatísticas da Rede Neural\n`;
|
|
437
|
+
indexBody += `- **Total de Nós:** \`${graph.stats.total_nodes}\`\n`;
|
|
438
|
+
indexBody += `- **Sinapses Causa/Efeito:** \`${graph.stats.total_links}\`\n`;
|
|
439
|
+
indexBody += `- **Restrições Determinísticas:** \`${graph.stats.constraints_count}\`\n`;
|
|
440
|
+
indexBody += `- **Heurísticas Operacionais:** \`${graph.stats.heuristics_count}\`\n`;
|
|
441
|
+
indexBody += `- **Princípios Decisórios:** \`${graph.stats.principles_count}\`\n`;
|
|
442
|
+
indexBody += `- **Casos de Experiência Causal:** \`${graph.stats.experience_cases_count}\`\n`;
|
|
443
|
+
indexBody += `- **Vaults Isolados:** \`${graph.stats.tenants_count}\`\n\n`;
|
|
444
|
+
|
|
445
|
+
indexBody += `## Topologia do Sistema\n\n`;
|
|
446
|
+
indexBody += '```mermaid\ngraph LR\n';
|
|
447
|
+
indexBody += ` subgraph OS["Synap-se (Orquestrador Soberano)"]\n`;
|
|
448
|
+
indexBody += ` Bridge["bridge-cbc-azure"]\n`;
|
|
449
|
+
indexBody += ` end\n`;
|
|
450
|
+
indexBody += ` subgraph CBC["CognitiveBC Substrate"]\n`;
|
|
451
|
+
indexBody += ` JIT["JIT Context Resolver"]\n`;
|
|
452
|
+
indexBody += ` Gates["ContractGate Engine"]\n`;
|
|
453
|
+
indexBody += ` Graph["Neural Semantic Graph"]\n`;
|
|
454
|
+
indexBody += ` end\n`;
|
|
455
|
+
indexBody += ` subgraph Roles["Papéis Especialistas"]\n`;
|
|
456
|
+
roles.forEach(r => {
|
|
457
|
+
indexBody += ` R_${r.id}["${r.icon} [[role - ${sanitizeFilename(r.id)}|${r.name}]]"]\n`;
|
|
458
|
+
});
|
|
459
|
+
indexBody += ` end\n`;
|
|
460
|
+
indexBody += ` Bridge --> CBC\n`;
|
|
461
|
+
indexBody += ` CBC --> Roles\n`;
|
|
462
|
+
indexBody += '```\n\n';
|
|
463
|
+
|
|
464
|
+
indexBody += `## Pastas e Categorias do Grafo\n\n`;
|
|
465
|
+
indexBody += `### 🎭 Papéis de Agentes (Roles)\n`;
|
|
466
|
+
roles.forEach(r => {
|
|
467
|
+
indexBody += `- [[role - ${sanitizeFilename(r.id)}|${r.icon} ${r.name}]] — $\\le ${r.tokenCeiling}$ tokens\n`;
|
|
468
|
+
});
|
|
469
|
+
indexBody += `\n`;
|
|
470
|
+
|
|
471
|
+
indexBody += `### 🟣 Stacks Operacionais\n`;
|
|
472
|
+
bytecodes.forEach(bc => {
|
|
473
|
+
const stackKey = bc.scope?.stack || 'scientific_3d_stack';
|
|
474
|
+
indexBody += `- [[stack - ${sanitizeFilename(stackKey)}]]\n`;
|
|
475
|
+
});
|
|
476
|
+
indexBody += `\n`;
|
|
477
|
+
|
|
478
|
+
indexBody += `### 🟠 Vaults de Marca (Tenants)\n`;
|
|
479
|
+
Object.keys(mapsDict).forEach(tenantKey => {
|
|
480
|
+
indexBody += `- [[vault - ${sanitizeFilename(tenantKey)}]]\n`;
|
|
481
|
+
});
|
|
482
|
+
indexBody += `\n`;
|
|
483
|
+
|
|
484
|
+
fs.writeFileSync(indexPath, indexBody, 'utf8');
|
|
485
|
+
filesWritten.push(indexPath);
|
|
486
|
+
|
|
487
|
+
return {
|
|
488
|
+
success: true,
|
|
489
|
+
vault_path: outputDir,
|
|
490
|
+
total_files: filesWritten.length,
|
|
491
|
+
files: filesWritten,
|
|
492
|
+
stats: graph.stats,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Parses an Obsidian vault directory and extracts entities, frontmatter, and [[links]]
|
|
498
|
+
* @param {string} vaultDir
|
|
499
|
+
* @returns {object} Extracted entities and linkages
|
|
500
|
+
*/
|
|
501
|
+
function importFromObsidianVault(vaultDir) {
|
|
502
|
+
if (!fs.existsSync(vaultDir)) {
|
|
503
|
+
throw new Error(`Vault directory does not exist: ${vaultDir}`);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
const nodes = [];
|
|
507
|
+
const links = [];
|
|
508
|
+
|
|
509
|
+
function scanDir(dir) {
|
|
510
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
511
|
+
for (const ent of entries) {
|
|
512
|
+
const fullPath = path.join(dir, ent.name);
|
|
513
|
+
if (ent.isDirectory()) {
|
|
514
|
+
scanDir(fullPath);
|
|
515
|
+
} else if (ent.isFile() && ent.name.endsWith('.md')) {
|
|
516
|
+
const raw = fs.readFileSync(fullPath, 'utf8');
|
|
517
|
+
const matchFm = raw.match(/^---\n([\s\S]*?)\n---/);
|
|
518
|
+
let frontmatter = {};
|
|
519
|
+
let body = raw;
|
|
520
|
+
if (matchFm) {
|
|
521
|
+
try {
|
|
522
|
+
frontmatter = YAML.parse(matchFm[1]) || {};
|
|
523
|
+
body = raw.slice(matchFm[0].length);
|
|
524
|
+
} catch (_) {}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const id = frontmatter.id || ent.name.replace(/\.md$/, '');
|
|
528
|
+
const type = frontmatter.type || 'note';
|
|
529
|
+
|
|
530
|
+
nodes.push({
|
|
531
|
+
id,
|
|
532
|
+
type,
|
|
533
|
+
file: ent.name,
|
|
534
|
+
frontmatter,
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
// Find [[wikilinks]]
|
|
538
|
+
const linkMatches = body.matchAll(/\[\[(.*?)\]\]/g);
|
|
539
|
+
for (const lm of linkMatches) {
|
|
540
|
+
const targetStr = lm[1].split('|')[0].trim();
|
|
541
|
+
links.push({
|
|
542
|
+
source: id,
|
|
543
|
+
target: targetStr,
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
scanDir(vaultDir);
|
|
551
|
+
|
|
552
|
+
return {
|
|
553
|
+
vault_dir: vaultDir,
|
|
554
|
+
nodes_count: nodes.length,
|
|
555
|
+
links_count: links.length,
|
|
556
|
+
nodes,
|
|
557
|
+
links,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
module.exports = {
|
|
562
|
+
exportToObsidianVault,
|
|
563
|
+
importFromObsidianVault,
|
|
564
|
+
};
|