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,194 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const YAML = require('yaml');
5
+
6
+ const ACCEPTED_SCHEMAS = ['cognitivebc/v1', 'synapse-eeii/v1', 'synapse-eeii/v2'];
7
+ const VALID_GATE_TYPES = new Set(['required_anchor', 'regex_disallow', 'code_pattern_disallow', 'code_pattern_require_when']);
8
+ function validateGateRule(rule) {
9
+ const errors = [];
10
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) return ['Gate must be an object'];
11
+ if (typeof rule.id !== 'string' || !rule.id.trim()) errors.push('Gate requires id');
12
+ if (!VALID_GATE_TYPES.has(rule.type)) errors.push('Unsupported gate type');
13
+ if (rule.target_fields !== undefined && (!Array.isArray(rule.target_fields) || rule.target_fields.some(f => typeof f !== 'string' || !f.trim()))) errors.push('Invalid gate target_fields');
14
+ if (rule.severity !== undefined && !['critical', 'warning', 'info'].includes(rule.severity)) errors.push('Invalid gate severity');
15
+ if (rule.type === 'required_anchor' && (!Array.isArray(rule.keywords) || !rule.keywords.length || rule.keywords.some(k => typeof k !== 'string' || !k.trim()))) errors.push('Anchor gate requires keywords');
16
+ if (rule.max_words_window !== undefined && (!Number.isInteger(rule.max_words_window) || rule.max_words_window < 1 || rule.max_words_window > 10000)) errors.push('Invalid anchor window');
17
+ if (rule.patterns !== undefined && (!Array.isArray(rule.patterns) || !rule.patterns.length)) errors.push('Invalid gate patterns');
18
+ const patterns = Array.isArray(rule.patterns) ? [...rule.patterns] : [];
19
+ for (const field of ['pattern', 'context_pattern', 'when_pattern', 'require_pattern']) if (rule[field] !== undefined) patterns.push(rule[field]);
20
+ if (rule.type === 'regex_disallow' && !(typeof rule.pattern === 'string' && rule.pattern) && !(Array.isArray(rule.patterns) && rule.patterns.length)) errors.push('Gate requires a disallowed pattern');
21
+ if (rule.type === 'code_pattern_disallow' && !(typeof rule.pattern === 'string' && rule.pattern)) errors.push('Code gate requires a pattern');
22
+ if (rule.type === 'code_pattern_require_when' && (!rule.when_pattern || !rule.require_pattern)) errors.push('Conditional gate requires when and require patterns');
23
+ for (const pattern of patterns) {
24
+ if (typeof pattern !== 'string' || !pattern || pattern.length > 4096) errors.push('Invalid gate pattern');
25
+ else { try { new RegExp(pattern, 'i'); } catch { errors.push('Invalid gate regular expression'); } }
26
+ }
27
+ return errors;
28
+ }
29
+ const VALID_LEVELS = ['kernel', 'squad', 'stack', 'category', 'tenant', 'role'];
30
+
31
+ /**
32
+ * Calculates SHA-256 digest of string or object
33
+ */
34
+ function calculateSha256(input) {
35
+ const data = typeof input === 'string' ? input : JSON.stringify(input);
36
+ return crypto.createHash('sha256').update(data, 'utf8').digest('hex');
37
+ }
38
+
39
+ /**
40
+ * Validates a CognitiveBC object or YAML string against canonical cognitivebc/v1 schema
41
+ */
42
+ function validateBytecode(data) {
43
+ let doc = data;
44
+ if (typeof data === 'string') {
45
+ try {
46
+ doc = YAML.parse(data);
47
+ } catch (err) {
48
+ return { valid: false, errors: [`Invalid YAML syntax: ${err.message}`] };
49
+ }
50
+ }
51
+
52
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
53
+ return { valid: false, errors: ['Bytecode must be a valid object or YAML document'] };
54
+ }
55
+
56
+ const errors = [];
57
+
58
+ // Schema header
59
+ if (!doc.schema || !ACCEPTED_SCHEMAS.includes(doc.schema)) {
60
+ errors.push(`Invalid or missing schema: expected one of [${ACCEPTED_SCHEMAS.join(', ')}], got '${doc.schema}'`);
61
+ }
62
+
63
+ // ID
64
+ if (typeof doc.id !== 'string' || !doc.id.trim()) {
65
+ errors.push('Missing or invalid "id": must be a non-empty string');
66
+ }
67
+
68
+ // Scope
69
+ if (!doc.scope || typeof doc.scope !== 'object' || Array.isArray(doc.scope)) {
70
+ errors.push('Missing "scope" definition');
71
+ } else {
72
+ if (!doc.scope.level || !VALID_LEVELS.includes(doc.scope.level)) {
73
+ errors.push(`Invalid scope.level: expected one of [${VALID_LEVELS.join(', ')}], got '${doc.scope.level}'`);
74
+ }
75
+
76
+ // Tenant isolation rule: global levels must have tenant=null
77
+ if (['kernel', 'squad', 'stack', 'category'].includes(doc.scope.level) && doc.scope.tenant) {
78
+ errors.push(`Tenant isolation violation: scope.level '${doc.scope.level}' must not define a specific tenant`);
79
+ }
80
+
81
+ if (doc.scope.level === 'tenant' && (typeof doc.scope.tenant !== 'string' || !doc.scope.tenant.trim())) errors.push('Tenant scope requires a non-empty tenant');
82
+ if (doc.scope.roles && (!Array.isArray(doc.scope.roles) || doc.scope.roles.some(r => typeof r !== 'string' || !r.trim()))) {
83
+ errors.push('scope.roles must be an array of role identifiers');
84
+ }
85
+ }
86
+
87
+ // Section validations
88
+ if (doc.decision_principles !== undefined) {
89
+ if (!Array.isArray(doc.decision_principles)) {
90
+ errors.push('decision_principles must be an array');
91
+ } else {
92
+ doc.decision_principles.forEach((item, idx) => {
93
+ if (!item || typeof item.id !== 'string' || !item.id.trim() || typeof item.rule !== 'string' || !item.rule.trim() || !Array.isArray(item.target_roles) || item.target_roles.some(r => typeof r !== 'string' || !r.trim())) {
94
+ errors.push(`decision_principles[${idx}] must contain id, rule and target_roles array`);
95
+ }
96
+ });
97
+ }
98
+ }
99
+
100
+ if (doc.agent_constraints !== undefined) {
101
+ if (!Array.isArray(doc.agent_constraints)) {
102
+ errors.push('agent_constraints must be an array');
103
+ } else {
104
+ doc.agent_constraints.forEach((item, idx) => {
105
+ if (!item || typeof item.id !== 'string' || !item.id.trim() || typeof item.rule !== 'string' || !item.rule.trim() || !Array.isArray(item.target_roles) || item.target_roles.some(r => typeof r !== 'string' || !r.trim())) {
106
+ errors.push(`agent_constraints[${idx}] must contain id, rule and target_roles array`);
107
+ }
108
+ });
109
+ }
110
+ }
111
+
112
+ if (doc.agent_heuristics !== undefined) {
113
+ if (!Array.isArray(doc.agent_heuristics)) {
114
+ errors.push('agent_heuristics must be an array');
115
+ } else {
116
+ doc.agent_heuristics.forEach((item, idx) => {
117
+ if (!item || typeof item.id !== 'string' || !item.id.trim() || typeof item.when !== 'string' || !item.when.trim() || typeof item.then !== 'string' || !item.then.trim() || !Array.isArray(item.target_roles) || item.target_roles.some(r => typeof r !== 'string' || !r.trim())) {
118
+ errors.push(`agent_heuristics[${idx}] must contain id, when, then and target_roles array`);
119
+ }
120
+ });
121
+ }
122
+ }
123
+
124
+ if (doc.experience_graph !== undefined) {
125
+ if (!Array.isArray(doc.experience_graph)) {
126
+ errors.push('experience_graph must be an array');
127
+ } else {
128
+ doc.experience_graph.forEach((item, idx) => {
129
+ if (!item || typeof item.problem_id !== 'string' || !item.problem_id.trim() || typeof item.symptom !== 'string' || !item.symptom.trim() || typeof item.root_cause !== 'string' || !item.root_cause.trim() || !Array.isArray(item.target_roles) || item.target_roles.some(r => typeof r !== 'string' || !r.trim())) {
130
+ errors.push(`experience_graph[${idx}] must contain problem_id, symptom, root_cause and target_roles array`);
131
+ }
132
+ if (item && item.solutions_evaluated && !Array.isArray(item.solutions_evaluated)) {
133
+ errors.push(`experience_graph[${idx}].solutions_evaluated must be an array`);
134
+ }
135
+ });
136
+ }
137
+ }
138
+
139
+ if (doc.gate_rules !== undefined) {
140
+ if (!Array.isArray(doc.gate_rules)) errors.push('gate_rules must be an array');
141
+ else doc.gate_rules.forEach((rule, i) => errors.push(...validateGateRule(rule).map(e => `gate_rules[${i}]: ${e}`)));
142
+ }
143
+ return {
144
+ valid: errors.length === 0,
145
+ errors,
146
+ doc: errors.length === 0 ? doc : null,
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Normalizes legacy synapse-eeii/v1 or v2 to canonical cognitivebc/v1 format
152
+ */
153
+ function normalizeToV1(doc) {
154
+ if (!doc || typeof doc !== 'object') return doc;
155
+ const normalized = { ...doc, ...(doc.scope && typeof doc.scope === 'object' ? { scope: { ...doc.scope } } : {}) };
156
+
157
+ if (normalized.schema === 'synapse-eeii/v1' || normalized.schema === 'synapse-eeii/v2') {
158
+ normalized.schema = 'cognitivebc/v1';
159
+ }
160
+
161
+ if (!normalized.scope) {
162
+ normalized.scope = { level: 'stack', roles: [] };
163
+ }
164
+
165
+ if (!normalized.scope.roles) {
166
+ // Collect all target_roles across sections
167
+ const rolesSet = new Set();
168
+ const collect = (arr) => {
169
+ if (Array.isArray(arr)) {
170
+ arr.forEach(item => {
171
+ if (Array.isArray(item.target_roles)) {
172
+ item.target_roles.forEach(r => rolesSet.add(r));
173
+ }
174
+ });
175
+ }
176
+ };
177
+ collect(normalized.decision_principles);
178
+ collect(normalized.agent_constraints);
179
+ collect(normalized.agent_heuristics);
180
+ collect(normalized.experience_graph);
181
+ normalized.scope.roles = Array.from(rolesSet);
182
+ }
183
+
184
+ return normalized;
185
+ }
186
+
187
+ module.exports = {
188
+ ACCEPTED_SCHEMAS,
189
+ VALID_LEVELS,
190
+ calculateSha256,
191
+ validateBytecode,
192
+ validateGateRule,
193
+ normalizeToV1,
194
+ };
@@ -0,0 +1,162 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const RESOLVE = '/api/v1/resolve';
6
+ const hash = value => crypto.createHash('sha256').update(value).digest('hex');
7
+ function canonical(value) {
8
+ if (Array.isArray(value)) return value.map(canonical);
9
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]));
10
+ return value;
11
+ }
12
+ class CognitiveBCHTTPError extends Error {
13
+ constructor(message, { status = null, cause, code = 'HTTP_ERROR' } = {}) {
14
+ super(message, { cause });
15
+ this.name = 'CognitiveBCHTTPError';
16
+ this.status = status;
17
+ this.code = code;
18
+ }
19
+ }
20
+ class CognitiveBCClient {
21
+ constructor(options = {}) {
22
+ this.optionsBaseUrl = options.baseUrl || null;
23
+ this.apiKey = options.apiKey || process.env.COGNITIVEBC_API_KEY || null;
24
+ this.localFallbackDir = options.localFallbackDir || null;
25
+ this.timeoutMs = options.timeoutMs ?? 10000;
26
+ this.cacheTtlMs = options.cacheTtlMs ?? 300000;
27
+ for (const key of ['timeoutMs', 'cacheTtlMs']) {
28
+ if (!Number.isFinite(this[key]) || this[key] < 0 || (key === 'timeoutMs' && this[key] === 0)) throw new RangeError(`${key} is invalid`);
29
+ }
30
+ this._invalidNamespaces = new Set();
31
+ }
32
+ get baseUrl() {
33
+ const url = new URL(this.optionsBaseUrl || process.env.COGNITIVEBC_URL || 'http://localhost:4780');
34
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new TypeError('baseUrl requires HTTP(S), without credentials, query or fragment');
35
+ return url.href.replace(/\/+$/, '');
36
+ }
37
+ _namespace(baseUrl = this.baseUrl) {
38
+ return hash(JSON.stringify([2, baseUrl, hash(this.apiKey ? `bearer:${this.apiKey}` : 'anonymous')]));
39
+ }
40
+ async _request(method, endpoint, body = null) {
41
+ const baseUrl = this.baseUrl;
42
+ const namespace = this._namespace(baseUrl);
43
+ const payload = body === null ? null : JSON.parse(JSON.stringify(body));
44
+ const cacheable = method === 'POST' && endpoint === RESOLVE;
45
+ const controller = new AbortController();
46
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
47
+ const headers = { 'Content-Type': 'application/json', Accept: 'application/json' };
48
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
49
+ try {
50
+ const response = await fetch(`${baseUrl}${endpoint}`, { method, headers, body: payload === null ? undefined : JSON.stringify(payload), signal: controller.signal, redirect: 'error' });
51
+ if (!response.ok) {
52
+ if (response.body) { try { await response.body.cancel(); } catch (_) {} }
53
+ throw new CognitiveBCHTTPError(`CognitiveBC HTTP ${response.status}`, { status: response.status });
54
+ }
55
+ let json;
56
+ try { json = await response.json(); }
57
+ catch (cause) { if (controller.signal.aborted) throw cause; throw new CognitiveBCHTTPError('CognitiveBC invalid JSON response', { status: response.status, cause, code: 'INVALID_JSON' }); }
58
+ if (cacheable) this._writeCache(endpoint, payload, json, namespace);
59
+ return json;
60
+ } catch (cause) {
61
+ const err = cause instanceof CognitiveBCHTTPError ? cause : new CognitiveBCHTTPError(controller.signal.aborted ? 'CognitiveBC request timed out' : 'CognitiveBC network failure', { cause, code: controller.signal.aborted ? 'TIMEOUT' : 'NETWORK_ERROR' });
62
+ if (err.status === 401 || err.status === 403) this._invalidateCache(namespace);
63
+ const transient = err.code === 'TIMEOUT' || err.code === 'NETWORK_ERROR' || [408, 429, 500, 502, 503, 504].includes(err.status);
64
+ if (cacheable && transient) {
65
+ const cached = this._readCache(endpoint, payload, namespace);
66
+ if (cached && cached.data && typeof cached.data === 'object' && !Array.isArray(cached.data)) {
67
+ return { ...cached.data, _sdk: { stale: true, degraded: true, source: 'cache', status: err.status, reason: err.code, cachedAt: new Date(cached.savedAt).toISOString(), ageMs: Date.now() - cached.savedAt } };
68
+ }
69
+ }
70
+ throw err;
71
+ } finally { clearTimeout(timer); }
72
+ }
73
+ _cacheKey(endpoint, body) {
74
+ return hash(JSON.stringify([endpoint, canonical(body)])) + '.json';
75
+ }
76
+ _cacheDirectory(namespace, create = false) {
77
+ if (!this.localFallbackDir || !/^[a-f0-9]{64}$/.test(namespace)) return null;
78
+ const target = path.join(path.resolve(this.localFallbackDir), 'v2', namespace);
79
+ let current = path.parse(target).root;
80
+ for (const component of target.slice(current.length).split(path.sep)) {
81
+ current = path.join(current, component);
82
+ if (create && !fs.existsSync(current)) fs.mkdirSync(current, { mode: 0o700 });
83
+ const stat = fs.lstatSync(current);
84
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Unsafe cache directory');
85
+ }
86
+ return target;
87
+ }
88
+ _writeCache(endpoint, body, data, namespace = this._namespace()) {
89
+ if (endpoint !== RESOLVE || this.cacheTtlMs === 0 || this._invalidNamespaces.has(namespace)) return;
90
+ let temporary;
91
+ try {
92
+ const dir = this._cacheDirectory(namespace, true);
93
+ if (!dir) return;
94
+ temporary = path.join(dir, `.${crypto.randomBytes(16).toString('hex')}.tmp`);
95
+ fs.writeFileSync(temporary, JSON.stringify({ version: 2, savedAt: Date.now(), data }), { flag: 'wx', mode: 0o600 });
96
+ fs.renameSync(temporary, path.join(dir, this._cacheKey(endpoint, body)));
97
+ } catch (_) { /* Optional cache must not fail a successful request. */ }
98
+ finally { if (temporary) { try { fs.unlinkSync(temporary); } catch (_) {} } }
99
+ }
100
+ _readCache(endpoint, body, namespace = this._namespace()) {
101
+ if (endpoint !== RESOLVE || this.cacheTtlMs === 0 || this._invalidNamespaces.has(namespace)) return null;
102
+ try {
103
+ const dir = this._cacheDirectory(namespace);
104
+ if (!dir) return null;
105
+ const fd = fs.openSync(path.join(dir, this._cacheKey(endpoint, body)), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
106
+ let entry;
107
+ try { if (!fs.fstatSync(fd).isFile()) return null; entry = JSON.parse(fs.readFileSync(fd, 'utf8')); }
108
+ finally { fs.closeSync(fd); }
109
+ const age = Date.now() - entry.savedAt;
110
+ if (entry.version === 2 && Number.isFinite(entry.savedAt) && age >= 0 && age < this.cacheTtlMs) return entry;
111
+ } catch (_) {}
112
+ return null;
113
+ }
114
+ _invalidateCache(namespace) {
115
+ this._invalidNamespaces.add(namespace);
116
+ try {
117
+ const dir = this._cacheDirectory(namespace);
118
+ if (dir) fs.rmSync(dir, { recursive: true, force: true });
119
+ } catch (_) {}
120
+ }
121
+ async resolve(params) {
122
+ const { maxTokens, max_tokens, ...rest } = params;
123
+ const explicit = maxTokens ?? max_tokens;
124
+ if (maxTokens != null && max_tokens != null && maxTokens !== max_tokens) throw new RangeError('Conflicting maxTokens and max_tokens');
125
+ if (explicit != null && (typeof explicit !== 'number' || !Number.isFinite(explicit) || explicit < 100 || explicit > 2000)) throw new RangeError('maxTokens must be finite in range 100..2000');
126
+ return this._request('POST', RESOLVE, { ...rest, stacks: params.stacks || [], ...(explicit != null ? { max_tokens: explicit } : {}) });
127
+ }
128
+ async compile(params) {
129
+ return this._request('POST', '/api/v1/compile', {
130
+ regime: params.regime,
131
+ scope: params.scope,
132
+ input_payload: params.inputPayload || params.input_payload,
133
+ evidence: params.evidence,
134
+ options: params.options,
135
+ });
136
+ }
137
+ async ingestStream(params) {
138
+ return this._request('POST', '/api/v1/streams/ingest', {
139
+ session_id: params.sessionId || params.session_id,
140
+ tenant: params.tenant,
141
+ squad: params.squad,
142
+ role: params.role,
143
+ stack: params.stack,
144
+ project_id: params.projectId ?? params.project_id,
145
+ agent_id: params.agentId ?? params.agent_id,
146
+ events: params.events || [],
147
+ });
148
+ }
149
+ async getCandidate(id) {
150
+ return this._request('GET', `/api/v1/candidates/${encodeURIComponent(id)}`);
151
+ }
152
+ async promoteCandidate(id, params = {}) {
153
+ return this._request('POST', `/api/v1/candidates/${encodeURIComponent(id)}/promote`, params);
154
+ }
155
+ async verifyGate(params) {
156
+ return this._request('POST', '/api/v1/gates/verify', { stage: params.stage, draft_payload: params.draftPayload || params.draft_payload, tenant: params.tenant, squad: params.squad });
157
+ }
158
+ async getArtifact(type, id) {
159
+ return this._request('GET', `/api/v1/artifacts/${encodeURIComponent(type)}/${encodeURIComponent(id)}`);
160
+ }
161
+ }
162
+ module.exports = { CognitiveBCClient, CognitiveBCHTTPError };
@@ -0,0 +1,130 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const PERMISSIONS = new Set(['read', 'ingest', 'compile', 'write', 'export', 'approve', '*']);
5
+ const isLoopback = address => /^(127\.|::1$|::ffff:127\.)/.test(address || '');
6
+ const fail = (status, message) => { throw Object.assign(new Error(message), { status }); };
7
+
8
+ function normalizePrincipal(value) {
9
+ if (!value || typeof value !== 'object' || typeof value.id !== 'string' || !value.id.trim() ||
10
+ !Array.isArray(value.tenants) || value.tenants.some(t => typeof t !== 'string' || !t.trim()) ||
11
+ !Array.isArray(value.permissions) || value.permissions.some(p => !PERMISSIONS.has(p))) {
12
+ throw new Error('Invalid CognitiveBC principal configuration');
13
+ }
14
+ return Object.freeze({ id: value.id, tenants: Object.freeze([...new Set(value.tenants)]), permissions: Object.freeze([...new Set(value.permissions)]) });
15
+ }
16
+
17
+ function createAccessPolicy({ auth, env = process.env, tokenLookup } = {}) {
18
+ let configured = auth !== undefined || typeof tokenLookup === 'function';
19
+ if (auth === undefined && Object.hasOwn(env, 'COGNITIVEBC_AUTH_TOKENS')) {
20
+ configured = true;
21
+ try { auth = { tokens: JSON.parse(env.COGNITIVEBC_AUTH_TOKENS) }; }
22
+ catch { throw new Error('Invalid COGNITIVEBC_AUTH_TOKENS configuration'); }
23
+ }
24
+ const tokens = [];
25
+ if (configured && auth !== undefined) {
26
+ if (!auth || typeof auth !== 'object' || !auth.tokens || typeof auth.tokens !== 'object' || Array.isArray(auth.tokens)) {
27
+ throw new Error('Invalid CognitiveBC auth configuration');
28
+ }
29
+ for (const [token, principal] of Object.entries(auth.tokens)) {
30
+ if (!token.trim()) throw new Error('Invalid CognitiveBC token configuration');
31
+ tokens.push({ digest: crypto.createHash('sha256').update(token).digest(), principal: normalizePrincipal(principal) });
32
+ }
33
+ }
34
+ function authenticate(req) {
35
+ const header = req.headers?.authorization;
36
+ if (header !== undefined) {
37
+ const match = /^Bearer ([^\s]+)$/i.exec(header);
38
+ if (!match) fail(401, 'Invalid authentication');
39
+ const digest = crypto.createHash('sha256').update(match[1]).digest();
40
+ const found = tokens.find(t => crypto.timingSafeEqual(t.digest, digest));
41
+ if (found) return found.principal;
42
+ // Database tokens: only the SHA-256 is stored or queried, never the secret.
43
+ if (typeof tokenLookup === 'function') {
44
+ return Promise.resolve(tokenLookup(digest.toString('hex'))).then(principal => {
45
+ if (!principal) fail(401, 'Invalid authentication');
46
+ return normalizePrincipal(principal);
47
+ });
48
+ }
49
+ fail(401, 'Invalid authentication');
50
+ }
51
+ if (configured) fail(401, 'Authentication required');
52
+ if (isLoopback(req.socket?.remoteAddress)) return Object.freeze({ id: 'trusted-local', tenants: ['*'], permissions: ['*'], trustedLocal: true });
53
+ return Object.freeze({ id: 'anonymous-public', tenants: [], permissions: ['read'], anonymous: true });
54
+ }
55
+ function principalFromContext(value) {
56
+ return value ? normalizePrincipal(value) : Object.freeze({ id: 'anonymous-public', tenants: [], permissions: ['read'], anonymous: true });
57
+ }
58
+ return { configured, authenticate, principalFromContext };
59
+ }
60
+
61
+ function authorize(principal, operation) {
62
+ if (!principal || (!principal.permissions.includes('*') && !principal.permissions.includes(operation))) fail(403, 'Operation not permitted');
63
+ }
64
+ function allowsTenant(principal, tenant) {
65
+ return Boolean(principal && (principal.trustedLocal || principal.tenants.includes('*') || (typeof tenant === 'string' && principal.tenants.includes(tenant))));
66
+ }
67
+ function assertTenant(principal, tenant, { required = false } = {}) {
68
+ if (tenant == null || tenant === '') {
69
+ if (required) fail(400, 'Explicit origin tenant required');
70
+ return;
71
+ }
72
+ if (typeof tenant !== 'string' || !tenant.trim()) fail(400, 'Invalid tenant');
73
+ if (!principal.anonymous && !allowsTenant(principal, tenant)) fail(403, 'Tenant not permitted');
74
+ }
75
+ function contentTenant(type, id, entry) {
76
+ if (type === 'map') return id;
77
+ if (type === 'bytecode') return entry?.data?.scope?.tenant || null;
78
+ const content = entry?.content || '';
79
+ const match = /(?:^|\n)\s*tenant:\s*["']?([^\n\r"']+)/i.exec(content);
80
+ return entry?.scope?.tenant || match?.[1]?.trim() || null;
81
+ }
82
+ function canReadArtifact(principal, type, id, entry) {
83
+ if (!entry) return false;
84
+ const tenant = contentTenant(type, id, entry);
85
+ if (principal.trustedLocal) return true;
86
+ if (principal.anonymous) return !entry.private && !tenant;
87
+ if (tenant) return allowsTenant(principal, tenant);
88
+ return !entry.private || allowsTenant(principal, '*');
89
+ }
90
+ function scopeMatches(bytecode, scope = {}) {
91
+ const actual = bytecode.scope || {};
92
+ if (scope.tenant && actual.tenant && actual.tenant !== scope.tenant) return false;
93
+ for (const key of ['stack', 'squad', 'area']) if (scope[key] && actual[key] !== scope[key]) return false;
94
+ return true;
95
+ }
96
+ function createStoreView(store, principal, scope = {}) {
97
+ assertTenant(principal, scope.tenant);
98
+ const getBytecodes = () => store.getBytecodes().filter(b => {
99
+ const entry = store.getBytecode(b.id) || { data: b, private: store.isPrivate?.('bytecode', b.id) };
100
+ return canReadArtifact(principal, 'bytecode', b.id, entry) && scopeMatches(b, scope);
101
+ }).map(b => {
102
+ // Global bytecodes must not disclose names/paths of other tenants' companion maps.
103
+ if (!b.companion_artifacts?.tenant_maps || principal.trustedLocal) return b;
104
+ const copy = structuredClone(b);
105
+ copy.companion_artifacts.tenant_maps = Object.fromEntries(Object.entries(copy.companion_artifacts.tenant_maps).filter(([t]) => principal.anonymous ? false : allowsTenant(principal, t)));
106
+ return copy;
107
+ });
108
+ const getMapsDict = () => Object.fromEntries(Object.entries(store.getMapsDict()).filter(([t]) =>
109
+ (!scope.tenant || t === scope.tenant) && canReadArtifact(principal, 'map', t, { private: store.isPrivate?.('map', t) })));
110
+ return {
111
+ getBytecodes, getMapsDict,
112
+ getPublicBytecodes: getBytecodes, getPublicMapsDict: getMapsDict,
113
+ getBytecode: id => getBytecodes().find(b => b.id === id),
114
+ getMap: tenant => getMapsDict()[tenant] || null,
115
+ };
116
+ }
117
+ function selectMapSection(content, section) {
118
+ if (!section) return content;
119
+ if (typeof section !== 'string') fail(400, 'Invalid map section');
120
+ const normalize = value => value.trim().replace(/^#+\s*/, '').replace(/<!--.*?-->/g, '').replace(/^\d+[.)]?\s*/, '').trim().toLowerCase();
121
+ const lines = content.split(/\r?\n/);
122
+ const start = lines.findIndex(line => /^#{1,6}\s/.test(line) && normalize(line) === normalize(section));
123
+ if (start < 0) return null;
124
+ const level = /^#+/.exec(lines[start])[0].length;
125
+ let end = start + 1;
126
+ while (end < lines.length && !new RegExp(`^#{1,${level}}\\s`).test(lines[end])) end++;
127
+ return lines.slice(start, end).join('\n');
128
+ }
129
+
130
+ module.exports = { createAccessPolicy, normalizePrincipal, authorize, allowsTenant, assertTenant, canReadArtifact, createStoreView, scopeMatches, selectMapSection, isLoopback, fail };
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const YAML = require('yaml');
6
+ const { calculateSha256: hash } = require('../../packages/cbc-schema');
7
+ const { CognitiveStore } = require('./store-loader');
8
+
9
+ const LIMITATIONS = [
10
+ 'Structural validation uses current cbc-schema and CognitiveStore contracts, not semantic truth or provenance authenticity.',
11
+ 'Source-session digests are syntax-checked only: original source bytes are not available.',
12
+ 'Only companion_artifacts paths and explicit Markdown links to store artifacts are resolved. Prose and external links are not inferred.',
13
+ 'No role allowlist, mandatory companion per regime, migration, deletion or publication is inferred.',
14
+ 'Snapshot is best effort, not an atomic transaction. Ancestor replacement races require OS sandboxing for hostile concurrent writers.',
15
+ 'Only immediate loader directories are scanned. Other files are inventoried as unclassified, never as garbage.'
16
+ ];
17
+
18
+ function safe(file) {
19
+ const absolute = path.resolve(file);
20
+ let current = path.parse(absolute).root;
21
+ for (const part of absolute.slice(current.length).split(path.sep).filter(Boolean)) {
22
+ current = path.join(current, part);
23
+ if (fs.lstatSync(current).isSymbolicLink()) throw Object.assign(new Error(), { auditCode: 'SYMLINK' });
24
+ }
25
+ return absolute;
26
+ }
27
+ function readBounded(file, limit) {
28
+ safe(file);
29
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
30
+ try {
31
+ const before = fs.fstatSync(fd);
32
+ if (!before.isFile()) throw Object.assign(new Error(), { auditCode: 'NOT_REGULAR' });
33
+ if (before.size > limit) throw Object.assign(new Error(), { auditCode: 'SIZE_LIMIT' });
34
+ const buffer = Buffer.alloc(limit + 1);
35
+ let size = 0, n;
36
+ while (size <= limit && (n = fs.readSync(fd, buffer, size, limit + 1 - size, null))) size += n;
37
+ if (size > limit) throw Object.assign(new Error(), { auditCode: 'SIZE_LIMIT' });
38
+ const after = fs.fstatSync(fd);
39
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw Object.assign(new Error(), { auditCode: 'CHANGED_DURING_READ' });
40
+ const bytes = buffer.subarray(0, size);
41
+ if (!require('buffer').isUtf8(bytes)) throw Object.assign(new Error(), { auditCode: 'UTF8_INVALID' });
42
+ return bytes.toString('utf8');
43
+ } finally { fs.closeSync(fd); }
44
+ }
45
+ function parseYaml(raw) {
46
+ const doc = YAML.parseDocument(raw);
47
+ if (doc.errors.length || doc.warnings.length) throw Object.assign(new Error(), { auditCode: 'YAML_INVALID' });
48
+ return doc.toJS({ maxAliasCount: 100 });
49
+ }
50
+ function decode(id) { return id.startsWith('__cbc_id_') ? Buffer.from(id.slice(9), 'hex').toString() : id; }
51
+
52
+ function auditStore(roots, options = {}) {
53
+ const maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
54
+ const maxFiles = options.maxFiles ?? 10000;
55
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 16 * 1024 * 1024 || !Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > 100000) throw new Error('Invalid audit limits');
56
+ const result = { schema: 'cognitivebc/artifact-audit-v1', readonly: true, roots: roots.map(r => path.resolve(r)), limits: { maxBytes, maxFiles }, artifacts: [], findings: [], limitations: LIMITATIONS };
57
+ const entries = [], byPath = new Map(), identities = new Map(), contents = new Map();
58
+ const checker = new CognitiveStore(result.roots[0], { privateDirs: false });
59
+ const finding = (file, code, severity = 'error', extra = {}) => result.findings.push({ path: file, code, severity, ...extra });
60
+ let count = 0;
61
+ function install(type, id, raw, file, root, embedded = false) {
62
+ const prepared = checker._prepare(type, id, raw);
63
+ const item = { path: file, type, sha256: prepared.sha256, identity_sha256: hash(id), bytes: Buffer.byteLength(prepared.raw), status: 'validated', ...(embedded ? { embedded: true } : {}) };
64
+ result.artifacts.push(item);
65
+ const key = `${type}:${id}`, previous = identities.get(key);
66
+ if (previous) finding(file, previous.root === root ? 'DUPLICATE_ID' : 'ROOT_SHADOW', previous.root === root ? 'error' : 'warning', { related_path: previous.file });
67
+ identities.set(key, { file, root });
68
+ const contentKey = `${type}:${prepared.sha256}`;
69
+ if (contents.has(contentKey)) finding(file, 'DUPLICATE_CONTENT', 'warning', { related_path: contents.get(contentKey) });
70
+ contents.set(contentKey, file);
71
+ const entry = { ...prepared, type, file, root, item };
72
+ entries.push(entry);
73
+ if (!embedded) byPath.set(file, entry);
74
+ return entry;
75
+ }
76
+ for (const root of result.roots) {
77
+ try { safe(root); } catch (err) { finding(root, err.auditCode || (err.code === 'ENOENT' ? 'ROOT_MISSING' : 'ROOT_UNREADABLE')); continue; }
78
+ for (const [directory, type, extension] of [['bytecodes', 'bytecode', /\.ya?ml$/], ['skills', 'skill', /\.md$/], ['maps', 'map', /\.md$/], ['.candidates', 'candidate', /\.json$/]]) {
79
+ const dir = path.join(root, directory);
80
+ let names;
81
+ try {
82
+ safe(dir);
83
+ names = fs.readdirSync(dir).sort();
84
+ } catch (err) { if (err.code !== 'ENOENT') finding(dir, err.auditCode || 'DIRECTORY_UNREADABLE'); continue; }
85
+ for (const name of names) {
86
+ const file = path.join(dir, name);
87
+ if (++count > maxFiles) { finding(dir, 'FILE_LIMIT'); break; }
88
+ let raw;
89
+ try {
90
+ safe(file);
91
+ if (!extension.test(name)) { finding(file, 'UNCLASSIFIED', 'info'); continue; }
92
+ raw = readBounded(file, maxBytes);
93
+ if (type === 'candidate') {
94
+ const record = JSON.parse(raw);
95
+ if (typeof record?.artifacts?.bytecode_artifact === 'string') parseYaml(record.artifacts.bytecode_artifact);
96
+ const payload = checker._candidatePayload(record);
97
+ if (record.schema !== 'cognitivebc/candidate-v1' || checker._candidateId(payload) !== record.id || name !== `${record.id}.json`) throw Object.assign(new Error(), { auditCode: 'CANDIDATE_DIGEST' });
98
+ if (!['candidate', 'promoted'].includes(record.status) || !Array.isArray(record.history) || (record.status === 'candidate' ? record.version !== 1 || record.history.length !== 0 : record.version !== 2 || record.history.length !== 1)) throw Object.assign(new Error(), { auditCode: 'CANDIDATE_STATUS' });
99
+ if (record.status === 'promoted') {
100
+ const approval = record.history[0];
101
+ if (approval?.scope?.level !== 'tenant' || approval.scope.tenant !== record.scope.tenant || typeof approval.approvedBy !== 'string' || !approval.approvedBy.trim() || !approval.at) throw Object.assign(new Error(), { auditCode: 'PROMOTION_HISTORY' });
102
+ }
103
+ result.artifacts.push({ path: file, type, sha256: hash(raw), bytes: Buffer.byteLength(raw), status: record.status });
104
+ // Pending bundles are validated but never installed into the published reference index.
105
+ for (const [kind, prepared] of checker._bundle(record)) {
106
+ if (record.status === 'promoted') install(kind, prepared.id, prepared.raw, file, root, true);
107
+ }
108
+ continue;
109
+ }
110
+ let id;
111
+ if (type === 'bytecode') id = parseYaml(raw)?.id;
112
+ else if (type === 'skill') id = decode(name.replace(/(?:\.SKILL)?\.md$/, ''));
113
+ else id = raw.match(/tenant:\s*([^\n\r]+)/i)?.[1].trim() || decode(name.replace(/^MAP_/, '').replace(/\.md$/, ''));
114
+ install(type, id, raw, file, root);
115
+ } catch (err) {
116
+ if (raw !== undefined && !result.artifacts.some(a => a.path === file)) result.artifacts.push({ path: file, type, sha256: hash(raw), bytes: Buffer.byteLength(raw), status: 'error' });
117
+ finding(file, err.auditCode || (err instanceof YAML.YAMLParseError ? 'YAML_INVALID' : 'ARTIFACT_INVALID'));
118
+ }
119
+ }
120
+ }
121
+ }
122
+ for (const entry of entries) {
123
+ const { file, root, data, raw, type } = entry;
124
+ if (data?.provenance?.source_sessions !== undefined) {
125
+ if (!Array.isArray(data.provenance.source_sessions)) finding(file, 'SOURCE_DIGEST_FORMAT');
126
+ else for (const source of data.provenance.source_sessions) {
127
+ if (source && source.sha256 == null) finding(file, 'SOURCE_DIGEST_UNAVAILABLE', 'warning');
128
+ else if (!source || typeof source.sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(source.sha256)) finding(file, 'SOURCE_DIGEST_FORMAT');
129
+ }
130
+ }
131
+ let metadata = data;
132
+ if (type !== 'bytecode' && /^---\r?\n/.test(raw)) {
133
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
134
+ try { if (!match) throw new Error(); metadata = parseYaml(match[1]); } catch { finding(file, 'FRONTMATTER_INVALID'); }
135
+ }
136
+ const refs = [];
137
+ const companion = metadata?.companion_artifacts;
138
+ if (companion !== undefined) {
139
+ if (!companion || typeof companion !== 'object' || Array.isArray(companion)) finding(file, 'REFERENCE_FORMAT');
140
+ else {
141
+ if (companion.skill_playbook !== undefined) refs.push({ value: companion.skill_playbook, expected: 'skill' });
142
+ if (companion.tenant_maps !== undefined) {
143
+ if (!companion.tenant_maps || typeof companion.tenant_maps !== 'object' || Array.isArray(companion.tenant_maps)) finding(file, 'REFERENCE_FORMAT');
144
+ else for (const [tenant, value] of Object.entries(companion.tenant_maps)) refs.push({ value, expected: 'map', tenant });
145
+ }
146
+ }
147
+ }
148
+ if (type !== 'bytecode') for (const match of raw.matchAll(/\[[^\]\n]*\]\(([^\s)]+)\)/g)) {
149
+ if (/^(?:\.\.\/)?(?:bytecodes|skills|maps)\//.test(match[1])) refs.push({ value: match[1], relative: true });
150
+ }
151
+ for (const ref of refs) {
152
+ if (typeof ref.value !== 'string') { finding(file, 'REFERENCE_FORMAT'); continue; }
153
+ const target = path.resolve(ref.relative ? path.dirname(file) : root, ref.value.split('#')[0]);
154
+ if (!target.startsWith(root + path.sep)) { finding(file, 'REFERENCE_ESCAPE'); continue; }
155
+ const found = byPath.get(target);
156
+ if (!found) { finding(file, 'REFERENCE_MISSING', 'error', { reference_sha256: hash(ref.value) }); continue; }
157
+ if (ref.expected && found.type !== ref.expected) finding(file, 'REFERENCE_TYPE');
158
+ if (ref.tenant && found.id !== ref.tenant) finding(file, 'REFERENCE_TENANT');
159
+ if (data?.scope?.level === 'tenant' && ref.tenant && ref.tenant !== data.scope.tenant) finding(file, 'REFERENCE_SCOPE');
160
+ }
161
+ }
162
+ for (const artifact of result.artifacts) if (result.findings.some(f => f.path === artifact.path && f.severity === 'error')) artifact.status = 'error';
163
+ result.summary = { artifacts: result.artifacts.length, errors: result.findings.filter(f => f.severity === 'error').length, warnings: result.findings.filter(f => f.severity === 'warning').length };
164
+ result.ok = result.summary.errors === 0;
165
+ return result;
166
+ }
167
+ module.exports = { auditStore, readBounded };