cognitivebc 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +70 -0
- package/README.md +98 -4
- package/SECURITY.md +29 -0
- package/TERMS_OF_SERVICE.md +55 -0
- package/bin/cbc-cloud-bootstrap.js +108 -0
- package/bin/cbc-seed-projects.js +29 -0
- package/bin/cbc-server.js +45 -0
- package/bin/cognitivebc.js +251 -0
- package/docs/ACCESS_CONTROL.md +111 -0
- package/docs/ARTIFACT_AUDIT.md +36 -0
- package/docs/CONNECT_CLIENTS.md +116 -0
- package/docs/DEPLOY_AZURE.md +136 -0
- package/docs/INGESTION.md +29 -0
- package/docs/OPERATIONS.md +85 -0
- package/docs/PROJECT_IDENTITY.md +35 -0
- package/docs/RESOLVER.md +86 -0
- package/docs/SDK.md +96 -0
- package/docs/STORAGE.md +63 -0
- package/docs/TECHNICAL_SPECIFICATION.md +365 -0
- package/docs/TELEMETRY.md +119 -0
- package/index.js +27 -2
- package/package.json +45 -5
- package/packages/cbc-compiler/index.js +357 -0
- package/packages/cbc-compiler/sanitizer.js +43 -0
- package/packages/cbc-identity/index.js +92 -0
- package/packages/cbc-mcp/http-backend.js +138 -0
- package/packages/cbc-mcp/http-route.js +64 -0
- package/packages/cbc-mcp/index.js +50 -0
- package/packages/cbc-mcp/tools.js +122 -0
- package/packages/cbc-resolver/catalog-linker.js +215 -0
- package/packages/cbc-resolver/graph-builder.js +533 -0
- package/packages/cbc-resolver/index.js +548 -0
- package/packages/cbc-resolver/obsidian-bridge.js +564 -0
- package/packages/cbc-schema/index.js +194 -0
- package/packages/cbc-sdk-js/client.js +162 -0
- package/services/cbc-api/access-policy.js +130 -0
- package/services/cbc-api/artifact-audit.js +167 -0
- package/services/cbc-api/cloud.js +56 -0
- package/services/cbc-api/context-service.js +48 -0
- package/services/cbc-api/ingestion-service.js +234 -0
- package/services/cbc-api/pg-store.js +172 -0
- package/services/cbc-api/project-registry.js +322 -0
- package/services/cbc-api/public/app.html +123 -0
- package/services/cbc-api/public/graph.html +1168 -0
- package/services/cbc-api/public/graph2.html +455 -0
- package/services/cbc-api/public/graph3.html +503 -0
- package/services/cbc-api/public/index.html +78 -0
- package/services/cbc-api/public/vendor/cbc-app.js +209 -0
- package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
- package/services/cbc-api/public/vendor/cbc-site.css +101 -0
- package/services/cbc-api/public/vendor/cose-base.js +3214 -0
- package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
- package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
- package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
- package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
- package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
- package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
- package/services/cbc-api/public/vendor/layout-base.js +5230 -0
- package/services/cbc-api/public/vendor/pf-graph.css +86 -0
- package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
- package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
- package/services/cbc-api/runtime-info.js +39 -0
- package/services/cbc-api/server.js +642 -0
- package/services/cbc-api/store-loader.js +269 -0
- package/services/cbc-api/telemetry.js +148 -0
- package/services/cbc-api/token-service.js +61 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const YAML = require('yaml');
|
|
7
|
+
const { sanitizeCrossTenant } = require('./sanitizer');
|
|
8
|
+
const { validateGateRule } = require('../cbc-schema');
|
|
9
|
+
|
|
10
|
+
/** ID determinístico derivado do conteúdo (mesma experiência => mesmo ID). */
|
|
11
|
+
function contentHash(...parts) {
|
|
12
|
+
return crypto.createHash('sha256').update(parts.map(String).join('\u0000')).digest('hex').substring(0, 24).toUpperCase();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function itemScopeOf(scope, inputPayload, stack) {
|
|
16
|
+
return scope.subscope || inputPayload.subscope || inputPayload.target_file || stack;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Ingests stream events and detects SilentSelfCorrectionCycles
|
|
21
|
+
*/
|
|
22
|
+
function ingestStreamEvents(sessionId, tenant, events = [], options = {}) {
|
|
23
|
+
const minCycleVersions = options.minCycleVersions || 2;
|
|
24
|
+
const cyclesDetected = [];
|
|
25
|
+
const triggeredCompilations = [];
|
|
26
|
+
|
|
27
|
+
for (const evt of events) {
|
|
28
|
+
const versionCount = evt.payload?.versions?.length || 0;
|
|
29
|
+
const isExplicitCycle =
|
|
30
|
+
evt.event_type === 'SilentSelfCorrectionCycle' &&
|
|
31
|
+
(versionCount === 0 || versionCount >= minCycleVersions);
|
|
32
|
+
if (isExplicitCycle || versionCount >= minCycleVersions) {
|
|
33
|
+
const identity = contentHash('event', tenant || '', sessionId || evt.session_id || '', JSON.stringify(evt));
|
|
34
|
+
const cycleId = `cycle_${identity}`;
|
|
35
|
+
cyclesDetected.push({
|
|
36
|
+
id: cycleId,
|
|
37
|
+
session_id: sessionId || evt.session_id,
|
|
38
|
+
target_file: evt.payload?.target_file || 'unknown',
|
|
39
|
+
version_count: versionCount || minCycleVersions,
|
|
40
|
+
timestamp: evt.timestamp || null,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const jobId = `job_compile_${identity}`;
|
|
44
|
+
triggeredCompilations.push({
|
|
45
|
+
job_id: jobId,
|
|
46
|
+
cycle_id: cycleId,
|
|
47
|
+
regime: 'silent_multimodal',
|
|
48
|
+
status: 'detected_not_persisted',
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
accepted: events.length,
|
|
55
|
+
cycles_detected: cyclesDetected,
|
|
56
|
+
triggered_compilations: triggeredCompilations,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Compiler of 3 Regimes (Domain-Agnostic)
|
|
62
|
+
*/
|
|
63
|
+
function compileExperience(request = {}) {
|
|
64
|
+
const invalid = message => { throw Object.assign(new Error(message), { status: 400 }); };
|
|
65
|
+
if (!request || typeof request !== 'object' || Array.isArray(request)) invalid('Invalid compilation request');
|
|
66
|
+
const { regime, scope = {}, inputPayload = {}, options = {} } = request;
|
|
67
|
+
for (const value of [scope, inputPayload, options]) if (!value || typeof value !== 'object' || Array.isArray(value)) invalid('Invalid compilation scope, input or options');
|
|
68
|
+
if (!['external_corrective', 'silent_multimodal', 'pioneer_discovery'].includes(regime)) invalid('Unknown compilation regime');
|
|
69
|
+
if (regime === 'external_corrective' && (!(typeof (inputPayload.issue || inputPayload.feedback) === 'string' && (inputPayload.issue || inputPayload.feedback).trim()) || !(typeof inputPayload.resolution === 'string' && inputPayload.resolution.trim()))) invalid('Corrective compilation requires issue and resolution evidence');
|
|
70
|
+
if (regime === 'silent_multimodal' && (!Array.isArray(inputPayload.versions) || inputPayload.versions.length < 2 || inputPayload.versions.some(v => !v || typeof v !== 'object' || Array.isArray(v)) || !Array.isArray(inputPayload.reasoning_summaries) || !inputPayload.reasoning_summaries.length || inputPayload.reasoning_summaries.some(s => typeof s !== 'string'))) invalid('Silent compilation requires versions and reasoning summaries');
|
|
71
|
+
const isCompact = options.compressionLevel === 'compact';
|
|
72
|
+
const tenant = scope.tenant || inputPayload.tenant || null;
|
|
73
|
+
const squad = scope.squad || inputPayload.squad || 'geral';
|
|
74
|
+
const stack = scope.stack || inputPayload.stack || 'general_stack';
|
|
75
|
+
const role = scope.role || inputPayload.role || 'specialist';
|
|
76
|
+
for (const value of [tenant, squad, stack, role]) if (value !== null && (typeof value !== 'string' || !value.trim() || value.length > 96)) invalid('Invalid compilation scope identifier');
|
|
77
|
+
const replacements = inputPayload.replacements || options.replacements || {};
|
|
78
|
+
|
|
79
|
+
const graduationCandidates = [];
|
|
80
|
+
let bytecodeArtifact = null;
|
|
81
|
+
let skillArtifact = null;
|
|
82
|
+
let mapArtifact = null;
|
|
83
|
+
|
|
84
|
+
if (regime === 'external_corrective') {
|
|
85
|
+
const issue = inputPayload.issue || inputPayload.feedback || 'Regra corretiva identificada após intervenção externa';
|
|
86
|
+
const resolution = inputPayload.resolution || 'Aplicar padrão validado e verificado';
|
|
87
|
+
const constraintId = `AC-${stack.toUpperCase().substring(0, 3)}-${contentHash('AC', tenant || '', role, stack, itemScopeOf(scope, inputPayload, stack), issue, resolution)}`;
|
|
88
|
+
|
|
89
|
+
const sanitizedRule = sanitizeCrossTenant(
|
|
90
|
+
isCompact ? `${issue} -> ${resolution}` : `${issue}. Solução: ${resolution}`,
|
|
91
|
+
tenant,
|
|
92
|
+
replacements
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
const itemScope = scope.subscope || inputPayload.subscope || inputPayload.target_file || stack;
|
|
96
|
+
|
|
97
|
+
const newConstraint = {
|
|
98
|
+
id: constraintId,
|
|
99
|
+
type: 'avoid',
|
|
100
|
+
rule: sanitizedRule,
|
|
101
|
+
scope: itemScope,
|
|
102
|
+
target_roles: [role, 'revisor'],
|
|
103
|
+
trigger_regime: 'external_corrective',
|
|
104
|
+
graduation_candidate: true,
|
|
105
|
+
deterministic_gate_hint: `disallow_condition: ${sanitizedRule.substring(0, 40)}`,
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
graduationCandidates.push(newConstraint);
|
|
109
|
+
|
|
110
|
+
bytecodeArtifact = {
|
|
111
|
+
schema: 'cognitivebc/v1',
|
|
112
|
+
id: `cbc:patch:${constraintId.toLowerCase()}`,
|
|
113
|
+
scope: {
|
|
114
|
+
level: tenant ? 'tenant' : 'stack',
|
|
115
|
+
squad,
|
|
116
|
+
stack,
|
|
117
|
+
tenant,
|
|
118
|
+
roles: [role, 'revisor'],
|
|
119
|
+
},
|
|
120
|
+
agent_constraints: [newConstraint],
|
|
121
|
+
};
|
|
122
|
+
} else if (regime === 'silent_multimodal') {
|
|
123
|
+
const versions = inputPayload.versions || [];
|
|
124
|
+
const summaries = inputPayload.reasoning_summaries || [];
|
|
125
|
+
const _hashBase = JSON.stringify([tenant, role, stack, scope.subscope || '', inputPayload.target_file || '', versions, summaries]);
|
|
126
|
+
const heuristicsId = `AH-${stack.toUpperCase().substring(0, 3)}-${contentHash('AH', _hashBase)}`;
|
|
127
|
+
const problemId = `EG-${stack.toUpperCase().substring(0, 3)}-${contentHash('EG', _hashBase)}`;
|
|
128
|
+
|
|
129
|
+
const summaryText = summaries.join(' ') || 'Ajuste após auto-inspeção multimodal';
|
|
130
|
+
const whenRule = isCompact
|
|
131
|
+
? `File ${inputPayload.target_file || stack}`
|
|
132
|
+
: `Ao detectar discrepância visual ou funcional em ${inputPayload.target_file || 'código da stack'}`;
|
|
133
|
+
const thenRule = sanitizeCrossTenant(summaryText, tenant, replacements);
|
|
134
|
+
|
|
135
|
+
const itemScope = scope.subscope || inputPayload.subscope || inputPayload.target_file || stack;
|
|
136
|
+
|
|
137
|
+
const newHeuristic = {
|
|
138
|
+
id: heuristicsId,
|
|
139
|
+
when: whenRule,
|
|
140
|
+
then: thenRule,
|
|
141
|
+
scope: itemScope,
|
|
142
|
+
target_roles: [role],
|
|
143
|
+
trigger_regime: 'silent_multimodal',
|
|
144
|
+
evidence_count: 1,
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const newExperienceNode = {
|
|
148
|
+
problem_id: problemId,
|
|
149
|
+
symptom: isCompact
|
|
150
|
+
? `${versions.length}x retry on ${inputPayload.target_file || stack}`
|
|
151
|
+
: `Versão inicial exigiu ${versions.length} iterações para convergência`,
|
|
152
|
+
root_cause: thenRule,
|
|
153
|
+
scope: itemScope,
|
|
154
|
+
evidence_status: 'unverified',
|
|
155
|
+
solutions_evaluated: versions.map((v, i) => ({
|
|
156
|
+
option: v.diff_summary || `Versão ${v.version || i + 1}`,
|
|
157
|
+
outcome: 'unverified',
|
|
158
|
+
reason: 'Iteração observada, sem validação independente do resultado',
|
|
159
|
+
})),
|
|
160
|
+
target_roles: [role],
|
|
161
|
+
trigger_regime: 'silent_multimodal',
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
bytecodeArtifact = {
|
|
165
|
+
schema: 'cognitivebc/v1',
|
|
166
|
+
id: `cbc:patch:${heuristicsId.toLowerCase()}`,
|
|
167
|
+
scope: {
|
|
168
|
+
level: tenant ? 'tenant' : 'stack',
|
|
169
|
+
squad,
|
|
170
|
+
stack,
|
|
171
|
+
tenant,
|
|
172
|
+
roles: [role],
|
|
173
|
+
},
|
|
174
|
+
agent_heuristics: [newHeuristic],
|
|
175
|
+
experience_graph: [newExperienceNode],
|
|
176
|
+
};
|
|
177
|
+
} else if (regime === 'pioneer_discovery') {
|
|
178
|
+
bytecodeArtifact = {
|
|
179
|
+
schema: 'cognitivebc/v1',
|
|
180
|
+
id: `cbc:pioneer:${contentHash(tenant || '', stack, role, JSON.stringify(inputPayload))}`,
|
|
181
|
+
provenance: {
|
|
182
|
+
source_sessions: inputPayload.session_id ? [{ session_id: inputPayload.session_id }] : [],
|
|
183
|
+
compiled_at: inputPayload.timestamp || null,
|
|
184
|
+
evidence_status: 'unverified',
|
|
185
|
+
compiler_version: 'cognitivebc@0.2.0',
|
|
186
|
+
},
|
|
187
|
+
scope: {
|
|
188
|
+
level: tenant ? 'tenant' : 'stack',
|
|
189
|
+
squad,
|
|
190
|
+
stack,
|
|
191
|
+
tenant,
|
|
192
|
+
roles: inputPayload.roles || [role],
|
|
193
|
+
},
|
|
194
|
+
agent_heuristics: inputPayload.heuristics || [],
|
|
195
|
+
agent_constraints: inputPayload.constraints || [],
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
skillArtifact = {
|
|
199
|
+
frontmatter: {
|
|
200
|
+
name: `${stack}-pipeline`,
|
|
201
|
+
squad,
|
|
202
|
+
category: 'Ops / Produção',
|
|
203
|
+
},
|
|
204
|
+
content: `# ${stack} Playbook\n\nGerado automaticamente via CognitiveBC Compilação Pioneira.`,
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
if (tenant) {
|
|
208
|
+
mapArtifact = {
|
|
209
|
+
tenant,
|
|
210
|
+
session_type: 'compiled_pioneer',
|
|
211
|
+
content: `# Semantic Map: ${tenant}\n\nRascunho de compilação pioneira. Ainda não contém fatos validados do tenant.`,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
} else {
|
|
215
|
+
throw new Error(`Unknown compilation regime: '${regime}'`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const serialized = typeof bytecodeArtifact === 'string' ? bytecodeArtifact : YAML.stringify(bytecodeArtifact);
|
|
219
|
+
const sha256 = crypto.createHash('sha256').update(serialized, 'utf8').digest('hex');
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
bytecode_artifact: bytecodeArtifact,
|
|
223
|
+
skill_artifact: skillArtifact,
|
|
224
|
+
map_artifact: mapArtifact,
|
|
225
|
+
sha256,
|
|
226
|
+
graduation_candidates: graduationCandidates,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Loads declarative gate_rules from store bytecodes if no rules were explicitly provided
|
|
232
|
+
*/
|
|
233
|
+
function loadDeclarativeGateRules(bytecodes = null) {
|
|
234
|
+
let sourceBytecodes = bytecodes;
|
|
235
|
+
if (!Array.isArray(sourceBytecodes)) {
|
|
236
|
+
sourceBytecodes = [];
|
|
237
|
+
const defaultDir = path.resolve(__dirname, '../../store/bytecodes');
|
|
238
|
+
if (fs.existsSync(defaultDir)) {
|
|
239
|
+
for (const file of fs.readdirSync(defaultDir)) {
|
|
240
|
+
if (file.endsWith('.yaml') || file.endsWith('.yml')) {
|
|
241
|
+
try {
|
|
242
|
+
const parsed = YAML.parse(fs.readFileSync(path.join(defaultDir, file), 'utf8'));
|
|
243
|
+
if (parsed) sourceBytecodes.push(parsed);
|
|
244
|
+
} catch (_) {
|
|
245
|
+
// ignore malformed yaml
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const collected = [];
|
|
253
|
+
for (const bc of sourceBytecodes) {
|
|
254
|
+
if (Array.isArray(bc.gate_rules)) {
|
|
255
|
+
collected.push(...bc.gate_rules);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return collected;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Generic Declarative Gate Verification Engine (ContractGate)
|
|
263
|
+
* Evaluates declarative rules defined in `rules` or inside `*.cbc.yaml` (`gate_rules` section).
|
|
264
|
+
*/
|
|
265
|
+
function verifyGateRules({ stage, draftPayload = {}, rules = [], bytecodes = null } = {}) {
|
|
266
|
+
if (!draftPayload || typeof draftPayload !== 'object' || Array.isArray(draftPayload)) throw Object.assign(new Error('Invalid gate draft payload'), { status: 400 });
|
|
267
|
+
const activeRules =
|
|
268
|
+
Array.isArray(rules) && rules.length > 0 ? rules : loadDeclarativeGateRules(bytecodes);
|
|
269
|
+
const issues = [];
|
|
270
|
+
|
|
271
|
+
const extractFieldsText = targetFields => {
|
|
272
|
+
if (Array.isArray(targetFields) && targetFields.length > 0) {
|
|
273
|
+
return targetFields
|
|
274
|
+
.map(f => (typeof draftPayload[f] === 'string' ? draftPayload[f] : ''))
|
|
275
|
+
.filter(Boolean)
|
|
276
|
+
.join(' ')
|
|
277
|
+
.trim();
|
|
278
|
+
}
|
|
279
|
+
return Object.values(draftPayload)
|
|
280
|
+
.filter(v => typeof v === 'string')
|
|
281
|
+
.join(' ')
|
|
282
|
+
.trim();
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
for (const rule of activeRules) {
|
|
286
|
+
const definitionErrors = validateGateRule(rule);
|
|
287
|
+
if (definitionErrors.length) {
|
|
288
|
+
issues.push({ id: typeof rule?.id === 'string' ? rule.id : 'GATE-INVALID', severity: 'critical', field: 'configuration', message: 'Invalid gate definition: ' + definitionErrors.join(', ') });
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
if (rule.stage && stage && rule.stage !== stage) continue;
|
|
292
|
+
|
|
293
|
+
const text = extractFieldsText(rule.target_fields);
|
|
294
|
+
|
|
295
|
+
if (rule.type === 'required_anchor') {
|
|
296
|
+
const maxWindow = rule.max_words_window || 20;
|
|
297
|
+
const words = text.toLowerCase().split(/\s+/).filter(Boolean).slice(0, maxWindow);
|
|
298
|
+
const keywords = (rule.keywords || []).map(k => k.toLowerCase());
|
|
299
|
+
const hasAnchor = keywords.some(k => words.some(w => w.includes(k)));
|
|
300
|
+
if (!hasAnchor) {
|
|
301
|
+
issues.push({
|
|
302
|
+
id: rule.id,
|
|
303
|
+
severity: rule.severity || 'critical',
|
|
304
|
+
field: rule.field || 'content',
|
|
305
|
+
message: rule.message || `Missing required anchor keyword in first ${maxWindow} words.`,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
} else if (rule.type === 'regex_disallow') {
|
|
309
|
+
const patterns = rule.patterns || (rule.pattern ? [rule.pattern] : []);
|
|
310
|
+
for (const pat of patterns) {
|
|
311
|
+
const regex = new RegExp(pat, 'i');
|
|
312
|
+
if (regex.test(text)) {
|
|
313
|
+
issues.push({
|
|
314
|
+
id: rule.id,
|
|
315
|
+
severity: rule.severity || 'critical',
|
|
316
|
+
field: rule.field || 'content',
|
|
317
|
+
message: rule.message || `Disallowed pattern matched: ${pat}`,
|
|
318
|
+
});
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
} else if (rule.type === 'code_pattern_disallow') {
|
|
323
|
+
const mainMatch = rule.pattern ? new RegExp(rule.pattern).test(text) : false;
|
|
324
|
+
const ctxMatch = rule.context_pattern ? new RegExp(rule.context_pattern, 'i').test(text) : true;
|
|
325
|
+
if (mainMatch && ctxMatch) {
|
|
326
|
+
issues.push({
|
|
327
|
+
id: rule.id,
|
|
328
|
+
severity: rule.severity || 'critical',
|
|
329
|
+
field: rule.field || 'code',
|
|
330
|
+
message: rule.message || `Disallowed code pattern matched: ${rule.pattern}`,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
} else if (rule.type === 'code_pattern_require_when') {
|
|
334
|
+
const whenMatch = rule.when_pattern ? new RegExp(rule.when_pattern, 'i').test(text) : false;
|
|
335
|
+
const reqMatch = rule.require_pattern ? new RegExp(rule.require_pattern, 'i').test(text) : true;
|
|
336
|
+
if (whenMatch && !reqMatch) {
|
|
337
|
+
issues.push({
|
|
338
|
+
id: rule.id,
|
|
339
|
+
severity: rule.severity || 'warning',
|
|
340
|
+
field: rule.field || 'code',
|
|
341
|
+
message: rule.message || `Required companion pattern missing: ${rule.require_pattern}`,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
return {
|
|
348
|
+
passed: issues.filter(i => i.severity === 'critical').length === 0,
|
|
349
|
+
issues,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
module.exports = {
|
|
354
|
+
ingestStreamEvents,
|
|
355
|
+
compileExperience,
|
|
356
|
+
verifyGateRules,
|
|
357
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Cross-Tenant Sanitizer (Domain-Agnostic)
|
|
5
|
+
* Guarantees that tenant-specific identifiers, secret keys, or custom vocabulary
|
|
6
|
+
* provided in `replacements` do not leak into global stack/squad artifacts.
|
|
7
|
+
*/
|
|
8
|
+
function sanitizeCrossTenant(text, tenantName, replacements = {}) {
|
|
9
|
+
if (!text || typeof text !== 'string') return text;
|
|
10
|
+
|
|
11
|
+
let sanitized = text;
|
|
12
|
+
|
|
13
|
+
if (tenantName) {
|
|
14
|
+
const activeReplacements = {
|
|
15
|
+
[tenantName]: '<TENANT_ID>',
|
|
16
|
+
...replacements,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
for (const [key, repl] of Object.entries(activeReplacements)) {
|
|
20
|
+
if (!key) continue;
|
|
21
|
+
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
22
|
+
const regex = new RegExp(`\\b${escapedKey}\\b`, 'gi');
|
|
23
|
+
sanitized = sanitized.replace(regex, repl);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return sanitized;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Checks if a payload contains unescaped tenant-identifiable info
|
|
32
|
+
*/
|
|
33
|
+
function containsTenantLeak(payloadStr, tenantName) {
|
|
34
|
+
if (!tenantName || !payloadStr) return false;
|
|
35
|
+
const escapedTenant = tenantName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
36
|
+
const regex = new RegExp(`\\b${escapedTenant}\\b`, 'i');
|
|
37
|
+
return regex.test(payloadStr);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = {
|
|
41
|
+
sanitizeCrossTenant,
|
|
42
|
+
containsTenantLeak,
|
|
43
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Pure client-side identity helpers. No server dependencies allowed here.
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { execFileSync } = require('node:child_process');
|
|
7
|
+
const YAML = require('yaml');
|
|
8
|
+
|
|
9
|
+
const MANIFEST_FILE = '.cognitivebc.yaml';
|
|
10
|
+
|
|
11
|
+
function normalizeGitRemote(url) {
|
|
12
|
+
if (typeof url !== 'string') return null;
|
|
13
|
+
let s = url.trim();
|
|
14
|
+
if (!s) return null;
|
|
15
|
+
let host;
|
|
16
|
+
let rest;
|
|
17
|
+
const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/.exec(s);
|
|
18
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s) && scp) {
|
|
19
|
+
host = scp[1];
|
|
20
|
+
rest = scp[2];
|
|
21
|
+
} else {
|
|
22
|
+
s = s.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '');
|
|
23
|
+
const slash = s.indexOf('/');
|
|
24
|
+
let authority = slash === -1 ? s : s.slice(0, slash);
|
|
25
|
+
rest = slash === -1 ? '' : s.slice(slash + 1);
|
|
26
|
+
authority = authority.replace(/^.*@/, ''); // strip credentials
|
|
27
|
+
host = authority.replace(/:\d*$/, '');
|
|
28
|
+
}
|
|
29
|
+
host = host.toLowerCase();
|
|
30
|
+
rest = rest.split(/[?#]/)[0].replace(/\/+$/, '').replace(/\.git$/i, '').replace(/\/+$/, '');
|
|
31
|
+
let parts = rest.split('/').filter(Boolean);
|
|
32
|
+
if (!host || !parts.length) return null;
|
|
33
|
+
// Azure DevOps variants
|
|
34
|
+
if (host === 'ssh.dev.azure.com' || host === 'vs-ssh.visualstudio.com') {
|
|
35
|
+
if (/^v\d+$/i.test(parts[0])) parts = parts.slice(1);
|
|
36
|
+
host = 'dev.azure.com';
|
|
37
|
+
} else if (host.endsWith('.visualstudio.com')) {
|
|
38
|
+
const org = host.slice(0, -'.visualstudio.com'.length);
|
|
39
|
+
parts = [org, ...parts.filter(p => p !== '_git' && p.toLowerCase() !== 'defaultcollection')];
|
|
40
|
+
host = 'dev.azure.com';
|
|
41
|
+
} else if (host === 'dev.azure.com') {
|
|
42
|
+
parts = parts.filter(p => p !== '_git');
|
|
43
|
+
}
|
|
44
|
+
// Hosted git (GitHub, Azure DevOps, GitLab) paths are case-insensitive: canonicalize fully.
|
|
45
|
+
return [host, ...parts].join('/').toLowerCase();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function git(cwd, args) {
|
|
49
|
+
try {
|
|
50
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000 }).trim();
|
|
51
|
+
} catch { return null; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readManifest(root) {
|
|
55
|
+
try {
|
|
56
|
+
const doc = YAML.parse(fs.readFileSync(path.join(root, MANIFEST_FILE), 'utf8'));
|
|
57
|
+
if (!doc || typeof doc !== 'object' || typeof doc.project_id !== 'string') return null;
|
|
58
|
+
return { project_id: doc.project_id, tenant: typeof doc.tenant === 'string' ? doc.tenant : null };
|
|
59
|
+
} catch { return null; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function collectLocalIdentity(cwd = process.cwd()) {
|
|
63
|
+
const root = git(cwd, ['rev-parse', '--show-toplevel']) || path.resolve(cwd);
|
|
64
|
+
const inGit = git(cwd, ['rev-parse', '--show-toplevel']) !== null;
|
|
65
|
+
const git_remotes = [];
|
|
66
|
+
const root_commits = [];
|
|
67
|
+
if (inGit) {
|
|
68
|
+
const names = (git(root, ['remote']) || '').split('\n').filter(Boolean);
|
|
69
|
+
for (const name of names) {
|
|
70
|
+
const urls = (git(root, ['remote', 'get-url', '--all', name]) || '').split('\n');
|
|
71
|
+
for (const u of urls) {
|
|
72
|
+
const n = normalizeGitRemote(u);
|
|
73
|
+
if (n && !git_remotes.includes(n)) git_remotes.push(n);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const c of (git(root, ['rev-list', '--max-parents=0', 'HEAD']) || '').split('\n')) {
|
|
77
|
+
if (/^[0-9a-f]{40,64}$/.test(c) && !root_commits.includes(c)) root_commits.push(c);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { manifest: readManifest(root), git_remotes, root_commits, path_hint: path.basename(root) };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function writeManifest(root, { project_id, tenant } = {}) {
|
|
84
|
+
if (typeof project_id !== 'string' || !project_id) throw new Error('project_id required');
|
|
85
|
+
const doc = { project_id };
|
|
86
|
+
if (tenant) doc.tenant = tenant;
|
|
87
|
+
const file = path.join(root, MANIFEST_FILE);
|
|
88
|
+
fs.writeFileSync(file, YAML.stringify(doc));
|
|
89
|
+
return file;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { normalizeGitRemote, collectLocalIdentity, writeManifest, readManifest, MANIFEST_FILE };
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
|
|
6
|
+
function loadIdentity(cwd) {
|
|
7
|
+
try {
|
|
8
|
+
// eslint-disable-next-line global-require
|
|
9
|
+
const mod = require('../cbc-identity');
|
|
10
|
+
if (mod && typeof mod.collectLocalIdentity === 'function') return mod.collectLocalIdentity(cwd);
|
|
11
|
+
} catch (_) { /* module not available */ }
|
|
12
|
+
return { manifest: null, git_remotes: [], root_commits: [], path_hint: require('node:path').basename(cwd) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function sha256(s) { return crypto.createHash('sha256').update(s).digest('hex'); }
|
|
16
|
+
|
|
17
|
+
function defaultSessionId() {
|
|
18
|
+
const host = sha256(os.hostname()).slice(0, 12);
|
|
19
|
+
return `mcp-${host}-${new Date().toISOString().slice(0, 10)}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
class CbcHttpError extends Error {
|
|
23
|
+
constructor(message, status, body) { super(message); this.status = status; this.body = body; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function mapError(status, body, tenant) {
|
|
27
|
+
const detail = body && (body.error || body.message) ? `: ${body.error || body.message}` : '';
|
|
28
|
+
if (status === 401) return `Unauthorized (401). Run \`cognitivebc login\` to configure a valid API key${detail}`;
|
|
29
|
+
if (status === 403) return `Forbidden (403): no access to tenant ${tenant || '(unknown)'}, ask an admin${detail}`;
|
|
30
|
+
if (status === 404) return `Not found (404)${detail}`;
|
|
31
|
+
return `CognitiveBC API error ${status}${detail}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function createHttpBackend(options = {}) {
|
|
35
|
+
const baseUrl = String(options.baseUrl || 'https://api.cognitivebc.io').replace(/\/+$/, '');
|
|
36
|
+
const apiKey = options.apiKey || '';
|
|
37
|
+
const fetchImpl = options.fetchImpl || globalThis.fetch;
|
|
38
|
+
const cwd = options.cwd || process.cwd();
|
|
39
|
+
let identity = options.identity || null;
|
|
40
|
+
let identifyCache = null;
|
|
41
|
+
|
|
42
|
+
async function request(method, path, body, tenant) {
|
|
43
|
+
const headers = { accept: 'application/json' };
|
|
44
|
+
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
45
|
+
if (body !== undefined) headers['content-type'] = 'application/json';
|
|
46
|
+
let res;
|
|
47
|
+
try {
|
|
48
|
+
res = await fetchImpl(baseUrl + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
49
|
+
} catch (err) {
|
|
50
|
+
throw new CbcHttpError(`Cannot reach CognitiveBC at ${baseUrl}: ${err.message}`, 0);
|
|
51
|
+
}
|
|
52
|
+
const text = await res.text();
|
|
53
|
+
let data;
|
|
54
|
+
try { data = text ? JSON.parse(text) : {}; } catch (_) { data = { raw: text }; }
|
|
55
|
+
if (!res.ok) throw new CbcHttpError(mapError(res.status, data, tenant), res.status, data);
|
|
56
|
+
return data;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function identify() {
|
|
60
|
+
if (identifyCache) return identifyCache;
|
|
61
|
+
if (!identity) identity = loadIdentity(cwd);
|
|
62
|
+
identifyCache = await request('POST', '/api/v1/projects/identify', { identity, register_candidate: true });
|
|
63
|
+
return identifyCache;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function safeProject() {
|
|
67
|
+
try {
|
|
68
|
+
const r = await identify();
|
|
69
|
+
return r && r.status === 'known' && r.project ? r.project : null;
|
|
70
|
+
} catch (err) {
|
|
71
|
+
if (err.status === 401) throw err;
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const handlers = {
|
|
77
|
+
async cbc_identify_project() { return identify(); },
|
|
78
|
+
|
|
79
|
+
async cbc_get_context(a) {
|
|
80
|
+
const project = await safeProject();
|
|
81
|
+
const tenant = a.tenant || (project && project.tenant) || undefined;
|
|
82
|
+
const stacks = a.stacks || (project && project.stack ? [project.stack] : undefined);
|
|
83
|
+
const body = {
|
|
84
|
+
role: a.role, task: a.task, query: a.query, stacks, max_tokens: a.max_tokens, tenant,
|
|
85
|
+
scope: { project_id: a.project_id || (project && project.id) || undefined, squad: (project && project.squad) || undefined },
|
|
86
|
+
};
|
|
87
|
+
return request('POST', '/api/v1/resolve', body, tenant);
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
async cbc_pull_experience(a) {
|
|
91
|
+
const project = await safeProject();
|
|
92
|
+
const tenant = a.tenant || (project && project.tenant) || undefined;
|
|
93
|
+
return request('POST', '/api/v1/resolve', {
|
|
94
|
+
role: a.role || 'specialist', query: a.topic, task: a.topic, tenant,
|
|
95
|
+
scope: { project_id: (project && project.id) || undefined },
|
|
96
|
+
}, tenant);
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
async cbc_read_tenant_map(a) {
|
|
100
|
+
const q = a.section ? `?section=${encodeURIComponent(a.section)}` : '';
|
|
101
|
+
return request('GET', `/api/v1/artifacts/map/${encodeURIComponent(a.tenant)}${q}`, undefined, a.tenant);
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
async cbc_check_gate_rules(a) {
|
|
105
|
+
const project = a.tenant ? null : await safeProject();
|
|
106
|
+
const tenant = a.tenant || (project && project.tenant) || undefined;
|
|
107
|
+
return request('POST', '/api/v1/gates/verify', { stage: a.stage, draft_payload: a.draft_json, tenant }, tenant);
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async cbc_report_learning(a) {
|
|
111
|
+
const project = await safeProject();
|
|
112
|
+
const tenant = a.tenant || (project && project.tenant);
|
|
113
|
+
if (!tenant) throw new Error('Cannot report learning: project is not identified and no tenant was given. Run `cognitivebc init` or pass tenant.');
|
|
114
|
+
let event_type; let payload;
|
|
115
|
+
if (a.kind === 'correction') {
|
|
116
|
+
if (!a.issue || !a.resolution) throw new Error('kind=correction requires issue and resolution');
|
|
117
|
+
event_type = 'ExternalCorrectiveFeedback'; payload = { issue: a.issue, resolution: a.resolution };
|
|
118
|
+
} else {
|
|
119
|
+
if (!Array.isArray(a.versions) || a.versions.length === 0) throw new Error('kind=self_correction requires versions');
|
|
120
|
+
event_type = 'SilentSelfCorrectionCycle'; payload = { versions: a.versions, reasoning_summaries: a.reasoning_summaries || [] };
|
|
121
|
+
}
|
|
122
|
+
const event = { event_id: sha256(JSON.stringify({ event_type, payload })), event_type, payload, timestamp: new Date().toISOString() };
|
|
123
|
+
return request('POST', '/api/v1/streams/ingest', {
|
|
124
|
+
tenant, session_id: a.session_id || defaultSessionId(), project_id: (project && project.id) || undefined, events: [event],
|
|
125
|
+
}, tenant);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
async function invoke(name, args) {
|
|
130
|
+
const h = handlers[name];
|
|
131
|
+
if (!h) throw new Error(`Unknown tool: ${name}`);
|
|
132
|
+
return h(args || {});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return { invoke, identify, request, baseUrl };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = { createHttpBackend, CbcHttpError, mapError, defaultSessionId };
|