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.
- package/LICENSE +70 -0
- package/README.md +99 -2
- 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 -0
- package/package.json +59 -4
- 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,322 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Cross-machine project identity registry (see docs/PROJECT_IDENTITY.md).
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const identity = require('../../packages/cbc-identity');
|
|
7
|
+
|
|
8
|
+
const fail = (status, message) => { throw Object.assign(new Error(message), { status }); };
|
|
9
|
+
const KINDS = ['manifest', 'git_remote', 'root_commit'];
|
|
10
|
+
const ID_RE = /^[a-z0-9_-]{1,96}\/[a-z0-9_-]{1,96}$/;
|
|
11
|
+
const SEG_RE = /^[a-z0-9_-]{1,96}$/;
|
|
12
|
+
|
|
13
|
+
const PROFARMA_SEED = Object.freeze([
|
|
14
|
+
{ id: 'profarma/balanc-linha', tenant: 'profarma', name: 'Balanceamento de Linha', stack: null, squad: null,
|
|
15
|
+
identifiers: { git_remotes: ['github.com/performacia/log-balanc-carga'], root_commits: ['6122d54c489b417c2c93c16d48c90b0dfa7ac188'] } },
|
|
16
|
+
{ id: 'profarma/pricefy', tenant: 'profarma', name: 'Pricefy', stack: 'profarma_pricefy', squad: 'pricefy',
|
|
17
|
+
identifiers: { git_remotes: ['github.com/performacia/prof-varejo-etiquetas_cartazes'],
|
|
18
|
+
root_commits: ['a8a22cfb10fec119596591e33ea9e9224d52418b', '2cd7e93df6c5fff85f09ae63bd685b4abd1cecf8'] } },
|
|
19
|
+
{ id: 'profarma/sal', tenant: 'profarma', name: 'SAL', stack: null, squad: null,
|
|
20
|
+
identifiers: { git_remotes: ['dev.azure.com/profarma/aura/sal'], root_commits: ['da4a30798ee0d26370ff6f2b437b9e51079c68b4'] } },
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
function slug(value, fallback = 'project') {
|
|
24
|
+
const s = String(value || '').toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 96);
|
|
25
|
+
return s || fallback;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function validateProjectId(id) {
|
|
29
|
+
if (typeof id !== 'string' || id.length > 96 || !ID_RE.test(id)) fail(400, 'Invalid project id (expected <tenant>/<slug>, lowercase [a-z0-9-_], max 96)');
|
|
30
|
+
return id;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function cleanIdentity(raw) {
|
|
34
|
+
const v = raw && typeof raw === 'object' ? raw : {};
|
|
35
|
+
const arr = (x, f) => [...new Set((Array.isArray(x) ? x : []).filter(s => typeof s === 'string').map(f).filter(Boolean))];
|
|
36
|
+
const manifest = v.manifest && typeof v.manifest.project_id === 'string' ? { project_id: v.manifest.project_id.trim().toLowerCase(), tenant: v.manifest.tenant || null } : null;
|
|
37
|
+
return {
|
|
38
|
+
manifest,
|
|
39
|
+
git_remotes: arr(v.git_remotes, identity.normalizeGitRemote),
|
|
40
|
+
root_commits: arr(v.root_commits, s => (/^[0-9a-f]{40,64}$/i.test(s.trim()) ? s.trim().toLowerCase() : null)),
|
|
41
|
+
path_hint: typeof v.path_hint === 'string' ? path.basename(v.path_hint).slice(0, 200) : null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function cleanIdentifiers(raw = {}) {
|
|
46
|
+
const c = cleanIdentity({ git_remotes: raw.git_remotes, root_commits: raw.root_commits });
|
|
47
|
+
const manifest_ids = [...new Set((Array.isArray(raw.manifest_ids) ? raw.manifest_ids : []).filter(s => typeof s === 'string').map(s => s.trim().toLowerCase()).filter(Boolean))];
|
|
48
|
+
return [
|
|
49
|
+
...manifest_ids.map(value => ({ kind: 'manifest', value })),
|
|
50
|
+
...c.git_remotes.map(value => ({ kind: 'git_remote', value })),
|
|
51
|
+
...c.root_commits.map(value => ({ kind: 'root_commit', value })),
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const has = (principal, perm) => !!principal && (principal.trustedLocal || (principal.permissions || []).includes('*') || (principal.permissions || []).includes(perm));
|
|
56
|
+
const canTenant = (principal, tenant) => !!principal && (principal.trustedLocal || (principal.tenants || []).includes('*') || (principal.tenants || []).includes(tenant));
|
|
57
|
+
function requirePerm(principal, perm) { if (!has(principal, perm)) fail(403, `Permission '${perm}' required`); }
|
|
58
|
+
function requireTenant(principal, tenant) { if (!canTenant(principal, tenant)) fail(403, 'Tenant access denied'); }
|
|
59
|
+
|
|
60
|
+
// ---------- backends ----------
|
|
61
|
+
function fileBackend(dir) {
|
|
62
|
+
const file = path.join(dir, 'projects.json');
|
|
63
|
+
const load = () => {
|
|
64
|
+
try { const d = JSON.parse(fs.readFileSync(file, 'utf8')); return { projects: d.projects || {}, identifiers: d.identifiers || {} }; }
|
|
65
|
+
catch (e) { if (e.code === 'ENOENT') return { projects: {}, identifiers: {} }; throw e; }
|
|
66
|
+
};
|
|
67
|
+
const save = (d) => {
|
|
68
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
69
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
70
|
+
fs.writeFileSync(tmp, JSON.stringify(d, null, 2), { mode: 0o600 });
|
|
71
|
+
fs.renameSync(tmp, file);
|
|
72
|
+
};
|
|
73
|
+
const key = (k, v) => `${k}:${v}`;
|
|
74
|
+
return {
|
|
75
|
+
async migrate() {},
|
|
76
|
+
async getProject(id) { return load().projects[id] || null; },
|
|
77
|
+
async listProjects() { return Object.values(load().projects); },
|
|
78
|
+
async putProject(p) { const d = load(); d.projects[p.id] = p; save(d); },
|
|
79
|
+
async deleteProject(id) {
|
|
80
|
+
const d = load(); delete d.projects[id];
|
|
81
|
+
for (const [k, pid] of Object.entries(d.identifiers)) if (pid === id) delete d.identifiers[k];
|
|
82
|
+
save(d);
|
|
83
|
+
},
|
|
84
|
+
async findIdentifier(kind, value) { return load().identifiers[key(kind, value)] || null; },
|
|
85
|
+
async bindIdentifier(kind, value, pid) { const d = load(); d.identifiers[key(kind, value)] = pid; save(d); },
|
|
86
|
+
async identifiersOf(pid) {
|
|
87
|
+
return Object.entries(load().identifiers).filter(([, p]) => p === pid).map(([k]) => {
|
|
88
|
+
const i = k.indexOf(':'); return { kind: k.slice(0, i), value: k.slice(i + 1) };
|
|
89
|
+
});
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function pgBackend(db) {
|
|
95
|
+
const row = r => r && ({ id: r.id, tenant: r.tenant, name: r.name, stack: r.stack, squad: r.squad, status: r.status,
|
|
96
|
+
created_by: r.created_by, created_at: new Date(r.created_at).toISOString(), updated_at: new Date(r.updated_at).toISOString() });
|
|
97
|
+
return {
|
|
98
|
+
async migrate() {
|
|
99
|
+
await db.query(`CREATE TABLE IF NOT EXISTS cbc_projects (
|
|
100
|
+
id text PRIMARY KEY, tenant text NOT NULL, name text, stack text, squad text,
|
|
101
|
+
status text NOT NULL CHECK (status IN ('active','candidate')), created_by text,
|
|
102
|
+
created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now())`);
|
|
103
|
+
await db.query(`CREATE TABLE IF NOT EXISTS cbc_project_identifiers (
|
|
104
|
+
kind text NOT NULL CHECK (kind IN ('manifest','git_remote','root_commit')), value text NOT NULL,
|
|
105
|
+
project_id text NOT NULL REFERENCES cbc_projects(id) ON DELETE CASCADE, PRIMARY KEY (kind, value))`);
|
|
106
|
+
},
|
|
107
|
+
async getProject(id) { return row((await db.query('SELECT * FROM cbc_projects WHERE id=$1', [id])).rows[0]); },
|
|
108
|
+
async listProjects() { return (await db.query('SELECT * FROM cbc_projects ORDER BY id')).rows.map(row); },
|
|
109
|
+
async putProject(p) {
|
|
110
|
+
await db.query(`INSERT INTO cbc_projects (id,tenant,name,stack,squad,status,created_by,created_at,updated_at)
|
|
111
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (id) DO UPDATE SET tenant=EXCLUDED.tenant,name=EXCLUDED.name,
|
|
112
|
+
stack=EXCLUDED.stack,squad=EXCLUDED.squad,status=EXCLUDED.status,updated_at=EXCLUDED.updated_at`,
|
|
113
|
+
[p.id, p.tenant, p.name, p.stack, p.squad, p.status, p.created_by, p.created_at, p.updated_at]);
|
|
114
|
+
},
|
|
115
|
+
async deleteProject(id) { await db.query('DELETE FROM cbc_projects WHERE id=$1', [id]); },
|
|
116
|
+
async findIdentifier(kind, value) {
|
|
117
|
+
return (await db.query('SELECT project_id FROM cbc_project_identifiers WHERE kind=$1 AND value=$2', [kind, value])).rows[0]?.project_id || null;
|
|
118
|
+
},
|
|
119
|
+
async bindIdentifier(kind, value, pid) {
|
|
120
|
+
await db.query(`INSERT INTO cbc_project_identifiers (kind,value,project_id) VALUES ($1,$2,$3)
|
|
121
|
+
ON CONFLICT (kind,value) DO UPDATE SET project_id=EXCLUDED.project_id`, [kind, value, pid]);
|
|
122
|
+
},
|
|
123
|
+
async identifiersOf(pid) {
|
|
124
|
+
return (await db.query('SELECT kind,value FROM cbc_project_identifiers WHERE project_id=$1 ORDER BY kind,value', [pid])).rows;
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---------- registry ----------
|
|
130
|
+
function createProjectRegistry({ db, dir } = {}) {
|
|
131
|
+
if (!db && !dir) throw new Error('createProjectRegistry requires db or dir');
|
|
132
|
+
const store = db ? pgBackend(db) : fileBackend(dir);
|
|
133
|
+
|
|
134
|
+
async function describe(p) {
|
|
135
|
+
const ids = await store.identifiersOf(p.id);
|
|
136
|
+
const pick = k => ids.filter(i => i.kind === k).map(i => i.value).sort();
|
|
137
|
+
return { ...p, identifiers: { manifest_ids: pick('manifest'), git_remotes: pick('git_remote'), root_commits: pick('root_commit') } };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function bindAll(projectId, idents, { move = false } = {}) {
|
|
141
|
+
const conflicts = [];
|
|
142
|
+
for (const { kind, value } of idents) {
|
|
143
|
+
const owner = await store.findIdentifier(kind, value);
|
|
144
|
+
if (owner && owner !== projectId && !move) conflicts.push({ kind, value, project_id: owner });
|
|
145
|
+
}
|
|
146
|
+
if (conflicts.length) {
|
|
147
|
+
const e = Object.assign(new Error('Identifier already bound to another project'), { status: 409, conflicts });
|
|
148
|
+
throw e;
|
|
149
|
+
}
|
|
150
|
+
for (const { kind, value } of idents) await store.bindIdentifier(kind, value, projectId);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function identify(rawIdentity, principal) {
|
|
154
|
+
const id = cleanIdentity(rawIdentity);
|
|
155
|
+
let strong = null;
|
|
156
|
+
let matched_by = null;
|
|
157
|
+
if (id.manifest) {
|
|
158
|
+
const pid = (await store.findIdentifier('manifest', id.manifest.project_id)) ||
|
|
159
|
+
((await store.getProject(id.manifest.project_id)) ? id.manifest.project_id : null);
|
|
160
|
+
if (pid) { strong = pid; matched_by = 'manifest'; }
|
|
161
|
+
}
|
|
162
|
+
if (!strong) for (const r of id.git_remotes) {
|
|
163
|
+
const pid = await store.findIdentifier('git_remote', r);
|
|
164
|
+
if (pid) { strong = pid; matched_by = 'git_remote'; break; }
|
|
165
|
+
}
|
|
166
|
+
const weak = [];
|
|
167
|
+
for (const c of id.root_commits) {
|
|
168
|
+
const pid = await store.findIdentifier('root_commit', c);
|
|
169
|
+
if (pid && !weak.includes(pid)) weak.push(pid);
|
|
170
|
+
}
|
|
171
|
+
const target = strong || weak[0];
|
|
172
|
+
if (!target) return { status: 'new' };
|
|
173
|
+
const project = await store.getProject(target);
|
|
174
|
+
if (!project) return { status: 'new' };
|
|
175
|
+
if (!canTenant(principal, project.tenant)) return { status: 'forbidden', project: { project_id: project.id } };
|
|
176
|
+
const others = weak.filter(p => p !== target);
|
|
177
|
+
const suggestions = [];
|
|
178
|
+
for (const pid of (strong ? weak.filter(p => p !== strong) : others)) {
|
|
179
|
+
const p = await store.getProject(pid);
|
|
180
|
+
if (p && canTenant(principal, p.tenant)) suggestions.push({ project_id: p.id, matched_by: 'root_commit' });
|
|
181
|
+
}
|
|
182
|
+
const out = { status: strong ? 'known' : 'probable', project: await describe(project), matched_by: strong ? matched_by : 'root_commit' };
|
|
183
|
+
if (suggestions.length) out.suggestions = suggestions;
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function registerCandidate(rawIdentity, principal) {
|
|
188
|
+
if (!principal || !principal.id) fail(403, 'Authenticated principal required');
|
|
189
|
+
const id = cleanIdentity(rawIdentity);
|
|
190
|
+
const existing = await identify(id, { trustedLocal: true });
|
|
191
|
+
if (existing.status !== 'new') {
|
|
192
|
+
const p = existing.project;
|
|
193
|
+
if (p.status === 'candidate' && canTenant({ ...principal, tenants: [...(principal.tenants || []), p.tenant] }, p.tenant) &&
|
|
194
|
+
p.tenant === `user-${slug(principal.id, 'anon')}`) {
|
|
195
|
+
return { status: 'candidate', project: p, created: false };
|
|
196
|
+
}
|
|
197
|
+
return identify(id, principal);
|
|
198
|
+
}
|
|
199
|
+
const tenant = `user-${slug(principal.id, 'anon')}`.slice(0, 96);
|
|
200
|
+
const base = slug(id.path_hint || (id.git_remotes[0] || '').split('/').pop());
|
|
201
|
+
let pid = `${tenant}/${base}`;
|
|
202
|
+
for (let n = 2; await store.getProject(pid); n++) pid = `${tenant}/${base}-${n}`;
|
|
203
|
+
validateProjectId(pid);
|
|
204
|
+
const now = new Date().toISOString();
|
|
205
|
+
await store.putProject({ id: pid, tenant, name: id.path_hint || base, stack: null, squad: null, status: 'candidate', created_by: principal.id, created_at: now, updated_at: now });
|
|
206
|
+
await bindAll(pid, [
|
|
207
|
+
...id.git_remotes.map(value => ({ kind: 'git_remote', value })),
|
|
208
|
+
...id.root_commits.map(value => ({ kind: 'root_commit', value })),
|
|
209
|
+
]);
|
|
210
|
+
return { status: 'candidate', project: await describe(await store.getProject(pid)), created: true };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function upsertProject(input = {}, principal, { move = false } = {}) {
|
|
214
|
+
requirePerm(principal, 'approve');
|
|
215
|
+
const pid = validateProjectId(input.id);
|
|
216
|
+
const tenant = input.tenant || pid.split('/')[0];
|
|
217
|
+
if (!SEG_RE.test(tenant) || pid.split('/')[0] !== tenant) fail(400, 'Project id must start with its tenant');
|
|
218
|
+
requireTenant(principal, tenant);
|
|
219
|
+
const idents = cleanIdentifiers(input.identifiers);
|
|
220
|
+
const conflicts = [];
|
|
221
|
+
for (const { kind, value } of idents) {
|
|
222
|
+
const owner = await store.findIdentifier(kind, value);
|
|
223
|
+
if (owner && owner !== pid && !(move || input.move)) conflicts.push({ kind, value, project_id: owner });
|
|
224
|
+
}
|
|
225
|
+
if (conflicts.length) throw Object.assign(new Error('Identifier already bound to another project'), { status: 409, conflicts });
|
|
226
|
+
const prev = await store.getProject(pid);
|
|
227
|
+
const now = new Date().toISOString();
|
|
228
|
+
const str = (v, d) => (v === undefined ? d : (v === null ? null : String(v)));
|
|
229
|
+
await store.putProject({
|
|
230
|
+
id: pid, tenant, name: str(input.name, prev?.name ?? null), stack: str(input.stack, prev?.stack ?? null),
|
|
231
|
+
squad: str(input.squad, prev?.squad ?? null), status: 'active', created_by: prev?.created_by || principal.id || 'system',
|
|
232
|
+
created_at: prev?.created_at || now, updated_at: now,
|
|
233
|
+
});
|
|
234
|
+
await bindAll(pid, idents, { move: true });
|
|
235
|
+
return describe(await store.getProject(pid));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function linkIdentifiers(projectId, identifiers, principal, { move = false } = {}) {
|
|
239
|
+
requirePerm(principal, 'approve');
|
|
240
|
+
const p = await store.getProject(validateProjectId(projectId));
|
|
241
|
+
if (!p) fail(404, 'Project not found');
|
|
242
|
+
requireTenant(principal, p.tenant);
|
|
243
|
+
await bindAll(p.id, cleanIdentifiers(identifiers), { move: move || identifiers?.move === true });
|
|
244
|
+
return describe(p);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function promote(candidateId, { tenant, id } = {}, principal) {
|
|
248
|
+
requirePerm(principal, 'approve');
|
|
249
|
+
const c = await store.getProject(validateProjectId(candidateId));
|
|
250
|
+
if (!c) fail(404, 'Project not found');
|
|
251
|
+
if (c.status !== 'candidate') fail(409, 'Project is not a candidate');
|
|
252
|
+
if (!tenant || !SEG_RE.test(tenant)) fail(400, 'Invalid tenant');
|
|
253
|
+
requireTenant(principal, tenant);
|
|
254
|
+
const newId = validateProjectId(id || `${tenant}/${c.id.split('/')[1]}`);
|
|
255
|
+
if (newId.split('/')[0] !== tenant) fail(400, 'Project id must start with its tenant');
|
|
256
|
+
if (newId !== c.id && await store.getProject(newId)) fail(409, 'Target project already exists');
|
|
257
|
+
const ids = await store.identifiersOf(c.id);
|
|
258
|
+
const now = new Date().toISOString();
|
|
259
|
+
await store.putProject({ ...c, id: newId, tenant, status: 'active', updated_at: now });
|
|
260
|
+
for (const { kind, value } of ids) await store.bindIdentifier(kind, value, newId);
|
|
261
|
+
if (newId !== c.id) await store.deleteProject(c.id);
|
|
262
|
+
return describe(await store.getProject(newId));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function list(principal) {
|
|
266
|
+
const all = await store.listProjects();
|
|
267
|
+
const visible = all.filter(p => canTenant(principal, p.tenant)).sort((a, b) => a.id.localeCompare(b.id));
|
|
268
|
+
return Promise.all(visible.map(describe));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return { migrate: () => store.migrate(), identify, registerCandidate, upsertProject, linkIdentifiers, promote, list, backend: db ? 'postgres' : 'file' };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------- HTTP routes ----------
|
|
275
|
+
async function handleProjectRoutes({ method, pathname, body, principal, registry }) {
|
|
276
|
+
if (!pathname || !pathname.startsWith('/api/v1/projects')) return null;
|
|
277
|
+
const b = body && typeof body === 'object' ? body : {};
|
|
278
|
+
try {
|
|
279
|
+
if (pathname === '/api/v1/projects/identify' && method === 'POST') {
|
|
280
|
+
requirePerm(principal, 'read');
|
|
281
|
+
const ident = b.identity || b;
|
|
282
|
+
const r = await registry.identify(ident, principal);
|
|
283
|
+
if (r.status === 'new' && b.register_candidate === true && has(principal, 'ingest')) {
|
|
284
|
+
return { status: 201, json: await registry.registerCandidate(ident, principal) };
|
|
285
|
+
}
|
|
286
|
+
return { status: 200, json: r };
|
|
287
|
+
}
|
|
288
|
+
if (pathname === '/api/v1/projects' && method === 'GET') {
|
|
289
|
+
requirePerm(principal, 'read');
|
|
290
|
+
return { status: 200, json: { projects: await registry.list(principal) } };
|
|
291
|
+
}
|
|
292
|
+
if (pathname === '/api/v1/projects' && method === 'POST') {
|
|
293
|
+
return { status: 200, json: { project: await registry.upsertProject(b, principal, { move: b.move === true }) } };
|
|
294
|
+
}
|
|
295
|
+
const m = /^\/api\/v1\/projects\/(.+)\/(link|promote)$/.exec(pathname);
|
|
296
|
+
if (m && method === 'POST') {
|
|
297
|
+
const pid = decodeURIComponent(m[1]);
|
|
298
|
+
if (m[2] === 'link') {
|
|
299
|
+
return { status: 200, json: { project: await registry.linkIdentifiers(pid, b.identifiers || b, principal, { move: b.move === true }) } };
|
|
300
|
+
}
|
|
301
|
+
return { status: 200, json: { project: await registry.promote(pid, { tenant: b.tenant, id: b.id }, principal) } };
|
|
302
|
+
}
|
|
303
|
+
return null;
|
|
304
|
+
} catch (err) {
|
|
305
|
+
if (!err.status) throw err;
|
|
306
|
+
const json = { error: err.message };
|
|
307
|
+
if (err.conflicts) json.conflicts = err.conflicts;
|
|
308
|
+
return { status: err.status, json };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function seedProjects(registry, seed = PROFARMA_SEED) {
|
|
313
|
+
const principal = { id: 'system', tenants: ['*'], permissions: ['*'], trustedLocal: true };
|
|
314
|
+
const out = [];
|
|
315
|
+
for (const p of seed) out.push(await registry.upsertProject(p, principal, { move: true }));
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
module.exports = {
|
|
320
|
+
createProjectRegistry, handleProjectRoutes, seedProjects, PROFARMA_SEED, validateProjectId,
|
|
321
|
+
normalizeGitRemote: identity.normalizeGitRemote, collectLocalIdentity: identity.collectLocalIdentity, writeManifest: identity.writeManifest,
|
|
322
|
+
};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="pt-BR">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<meta name="cbc-app" content="1">
|
|
7
|
+
<title>CognitiveBC · Área do usuário</title>
|
|
8
|
+
<link rel="icon" href="data:,">
|
|
9
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
10
|
+
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500;600&display=swap">
|
|
11
|
+
<link rel="stylesheet" href="/vendor/cbc-site.css">
|
|
12
|
+
<script src="/vendor/cbc-auth.js"></script>
|
|
13
|
+
<script src="/vendor/cbc-app.js" defer></script>
|
|
14
|
+
</head>
|
|
15
|
+
<body class="app">
|
|
16
|
+
<a class="skip" href="#conteudo">Pular para o conteúdo</a>
|
|
17
|
+
<header class="topbar" role="banner">
|
|
18
|
+
<a class="logo" href="/" aria-label="CognitiveBC, início">
|
|
19
|
+
<svg viewBox="0 0 20 22" aria-hidden="true"><path d="M10 1 19 6v10l-9 5-9-5V6z" fill="none" stroke="currentColor" stroke-width="1.6"/><circle cx="10" cy="11" r="3" fill="currentColor"/></svg>
|
|
20
|
+
<span>CognitiveBC</span>
|
|
21
|
+
</a>
|
|
22
|
+
<nav aria-label="Conta" class="topnav">
|
|
23
|
+
<span id="who" class="who" hidden></span>
|
|
24
|
+
<button id="logout" class="btn ghost sm" type="button" hidden>Sair</button>
|
|
25
|
+
</nav>
|
|
26
|
+
</header>
|
|
27
|
+
|
|
28
|
+
<main id="conteudo">
|
|
29
|
+
<section id="login" class="login" aria-labelledby="login-title">
|
|
30
|
+
<div class="panel">
|
|
31
|
+
<p class="eyebrow">Área do usuário</p>
|
|
32
|
+
<h1 id="login-title" style="font-size:28px;margin-bottom:16px">Entrar</h1>
|
|
33
|
+
<form id="login-form" novalidate>
|
|
34
|
+
<label for="token">Token pessoal de acesso</label>
|
|
35
|
+
<input id="token" class="mono" type="password" autocomplete="off" spellcheck="false" placeholder="cbc_…" required aria-describedby="token-hint login-err">
|
|
36
|
+
<p id="token-hint" class="hint">O token fica apenas nesta aba (sessionStorage) e é apagado ao clicar em Sair ou fechar a aba.</p>
|
|
37
|
+
<p id="login-err" class="err" role="alert"></p>
|
|
38
|
+
<button class="btn primary" type="submit" style="width:100%;margin-top:8px">Entrar</button>
|
|
39
|
+
</form>
|
|
40
|
+
<p class="hint" style="margin-top:16px">Sem token? <a href="mailto:contato@performacia.com.br?subject=Acesso%20ao%20CognitiveBC">Solicitar acesso</a></p>
|
|
41
|
+
</div>
|
|
42
|
+
</section>
|
|
43
|
+
|
|
44
|
+
<div id="shell" class="shell" hidden>
|
|
45
|
+
<nav class="side" aria-label="Seções">
|
|
46
|
+
<button type="button" data-view="projetos">Projetos</button>
|
|
47
|
+
<button type="button" data-view="grafo">Grafo</button>
|
|
48
|
+
<button type="button" data-view="candidatos">Candidatos</button>
|
|
49
|
+
<button type="button" data-view="conectar">Conectar</button>
|
|
50
|
+
<button type="button" data-view="tokens" hidden>Tokens</button>
|
|
51
|
+
</nav>
|
|
52
|
+
|
|
53
|
+
<section class="view" data-panel="projetos" aria-labelledby="h-projetos">
|
|
54
|
+
<h2 id="h-projetos">Projetos</h2>
|
|
55
|
+
<p class="sub">Projetos visíveis para o seu token. Cada projeto é reconhecido em qualquer máquina pelo git remote e pelo commit raiz.</p>
|
|
56
|
+
<div class="tablewrap"><table><thead><tr><th>ID</th><th>Tenant</th><th>Stack</th><th>Status</th><th>Identificadores</th></tr></thead><tbody id="proj-body"></tbody></table></div>
|
|
57
|
+
</section>
|
|
58
|
+
|
|
59
|
+
<section class="view" data-panel="grafo" aria-labelledby="h-grafo" hidden>
|
|
60
|
+
<h2 id="h-grafo">Grafo</h2>
|
|
61
|
+
<p class="sub">Visualização semântica dos bytecodes, mapas e gates do tenant selecionado.</p>
|
|
62
|
+
<div class="toolbar">
|
|
63
|
+
<div><label for="g-tenant">Tenant</label><select id="g-tenant"></select></div>
|
|
64
|
+
<div><label for="g-project">Projeto</label><select id="g-project"></select></div>
|
|
65
|
+
</div>
|
|
66
|
+
<iframe id="graph" class="graphframe" title="Grafo do CognitiveBC"></iframe>
|
|
67
|
+
</section>
|
|
68
|
+
|
|
69
|
+
<section class="view" data-panel="candidatos" aria-labelledby="h-cand" hidden>
|
|
70
|
+
<h2 id="h-cand">Candidatos</h2>
|
|
71
|
+
<p class="sub">Toda experiência compilada entra como <strong>candidato</strong>. Nada é publicado sem revisão: quem tem permissão de aprovação revisa o candidato e o promove para virar bytecode publicado.</p>
|
|
72
|
+
<div class="panel">
|
|
73
|
+
<div class="form" style="grid-template-columns:auto auto 1fr">
|
|
74
|
+
<div><label for="cand-status">Situação</label><select id="cand-status"><option value="candidate">Pendentes</option><option value="promoted">Publicados</option></select></div>
|
|
75
|
+
<div><button class="btn ghost" type="button" id="cand-reload">Atualizar</button></div>
|
|
76
|
+
</div>
|
|
77
|
+
<p id="cand-list-err" class="err" role="alert"></p>
|
|
78
|
+
<div class="tablewrap"><table>
|
|
79
|
+
<thead><tr><th>Candidato</th><th>Tenant</th><th>Regime</th><th>Origem</th><th>Criado</th><th></th></tr></thead>
|
|
80
|
+
<tbody id="cand-body"></tbody>
|
|
81
|
+
</table></div>
|
|
82
|
+
</div>
|
|
83
|
+
<div class="panel">
|
|
84
|
+
<form id="cand-form" class="form" novalidate>
|
|
85
|
+
<div><label for="cand-id">ID do candidato</label><input id="cand-id" class="mono" placeholder="candidate_…" required></div>
|
|
86
|
+
<div><button class="btn ghost" type="submit">Consultar</button></div>
|
|
87
|
+
</form>
|
|
88
|
+
<p id="cand-err" class="err" role="alert"></p>
|
|
89
|
+
<pre id="cand-out" hidden></pre>
|
|
90
|
+
</div>
|
|
91
|
+
</section>
|
|
92
|
+
|
|
93
|
+
<section class="view" data-panel="conectar" aria-labelledby="h-con" hidden>
|
|
94
|
+
<h2 id="h-con">Conectar</h2>
|
|
95
|
+
<p class="sub">Primeiro autentique o CLI com <code class="mono">npx -y cognitivebc login</code>. Depois registre o MCP no seu cliente (o mesmo texto de <code class="mono">cognitivebc setup <cliente></code>; use <code class="mono">--apply</code> para aplicar automaticamente).</p>
|
|
96
|
+
<div id="con-list" class="grid"></div>
|
|
97
|
+
<h3 style="margin:28px 0 10px">MCP remoto</h3>
|
|
98
|
+
<pre>URL: https://api.cognitivebc.io/mcp
|
|
99
|
+
Header: Authorization: Bearer cbc_…</pre>
|
|
100
|
+
</section>
|
|
101
|
+
|
|
102
|
+
<section class="view" data-panel="tokens" aria-labelledby="h-tok" hidden>
|
|
103
|
+
<h2 id="h-tok">Tokens</h2>
|
|
104
|
+
<p class="sub">Emita e revogue tokens. Você só pode delegar tenants e permissões que já possui.</p>
|
|
105
|
+
<form id="tok-form" class="form panel" novalidate>
|
|
106
|
+
<div><label for="t-label">Rótulo</label><input id="t-label" required maxlength="120" placeholder="notebook-joao"></div>
|
|
107
|
+
<div><label for="t-id">Principal (id)</label><input id="t-id" required placeholder="joao"></div>
|
|
108
|
+
<div><label for="t-tenants">Tenants (vírgula)</label><input id="t-tenants" required placeholder="profarma"></div>
|
|
109
|
+
<div><label for="t-perms">Permissões (vírgula)</label><input id="t-perms" required value="read"></div>
|
|
110
|
+
<div><button class="btn primary" type="submit">Criar token</button></div>
|
|
111
|
+
</form>
|
|
112
|
+
<p id="tok-err" class="err" role="alert"></p>
|
|
113
|
+
<div id="tok-secret" class="panel secret" hidden>
|
|
114
|
+
<p style="margin:0 0 8px"><strong class="ok">Token criado.</strong> Copie agora: ele não será exibido novamente.</p>
|
|
115
|
+
<pre id="tok-secret-val"></pre>
|
|
116
|
+
<button id="tok-copy" class="btn ghost sm" type="button" style="margin-top:10px">Copiar</button>
|
|
117
|
+
</div>
|
|
118
|
+
<div class="tablewrap"><table><thead><tr><th>Token ID</th><th>Rótulo</th><th>Principal</th><th>Último uso</th><th>Status</th><th></th></tr></thead><tbody id="tok-body"></tbody></table></div>
|
|
119
|
+
</section>
|
|
120
|
+
</div>
|
|
121
|
+
</main>
|
|
122
|
+
</body>
|
|
123
|
+
</html>
|