diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6dad46555586bae92f0e7468a3fa627d4e5ac962
--- /dev/null
+++ b/.github/workflows/validate.yml
@@ -0,0 +1,34 @@
+name: Validate ProjectOS
+
+on:
+ push:
+ pull_request:
+
+jobs:
+ validate:
+ runs-on: windows-latest
+ steps:
+ - name: Check out source
+ uses: actions/checkout@v4
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - name: Set up pnpm
+ uses: pnpm/action-setup@v4
+ with:
+ version: 10
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ - name: Generate configuration and documentation artifacts
+ run: pnpm generate
+ - name: Validate generated snapshot hashes
+ run: pnpm validate:generated
+ - name: Build workspace
+ run: pnpm build
+ - name: Run snapshot, alias, and documentation checks
+ run: pnpm test
+ - name: Produce the release bundle after all checks pass
+ run: pnpm --filter @projectos/schema-engine release
+ - name: Validate release package layout
+ run: pnpm validate:release
diff --git a/.gitignore b/.gitignore
index f83b497402a9a69bb4bd4af2b4ca15c3804fb56e..67618d3078c90adb733a93e78c8afa72f82f777f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,13 @@ node_modules/
.env.*
!.env.example
!configs/mcp.credentials.example.env
+**/build/
+.next/
+*.db
+*.zip
+*.tmp
+.DS_Store
+Thumbs.db
+configs/mcp.credentials.example.env
+data/
+archive/
diff --git a/apps/api/package.json b/apps/api/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..ba9afdf8ea6e796b5a887f10a3d89f518de6c9e2
--- /dev/null
+++ b/apps/api/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "@projectos/api",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "node server.mjs",
+ "start": "node server.mjs"
+ }
+}
diff --git a/apps/api/server.mjs b/apps/api/server.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..4de7666fc4cdef6f768bcbe8e2c0efe86e6a482e
--- /dev/null
+++ b/apps/api/server.mjs
@@ -0,0 +1,169 @@
+import { createServer } from 'node:http';
+import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
+import { DatabaseSync } from 'node:sqlite';
+import { dirname, extname, join, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createPlanDraft } from '../../packages/operations-agent/src/index.mjs';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const appRoot = resolve(here, '../..');
+const dataDir = join(appRoot, 'data');
+const dbFile = join(dataDir, 'projectos.sqlite');
+const storageConfigFile = join(appRoot, 'configs/generated/storage.generated.json');
+const host = '127.0.0.1';
+const port = Number(process.env.PROJECTOS_PORT || 4173);
+const maxBodyBytes = 1024 * 1024;
+
+mkdirSync(dataDir, { recursive: true });
+const existingDatabase = existsSync(dbFile);
+const storageConfig = JSON.parse(readFileSync(storageConfigFile, 'utf8'));
+if (!Array.isArray(storageConfig.providers) || !storageConfig.providers.includes('SQLite')) {
+ throw new Error('The generated storage configuration must enable SQLite for the local API.');
+}
+const db = new DatabaseSync(dbFile);
+db.exec(`
+ PRAGMA journal_mode = WAL;
+`);
+const sqliteSchema = readFileSync(join(appRoot, 'packages/storage-fabric/sqlite/schema.sql'), 'utf8');
+
+function currentStorageSchemaVersion() {
+ const migrationTable = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'storage_schema_migrations'").get();
+ if (!migrationTable) return 0;
+ return db.prepare('SELECT COALESCE(MAX(version), 0) AS version FROM storage_schema_migrations').get().version;
+}
+
+if (storageConfig.migration?.autoMigrate === true) {
+ if (existingDatabase && currentStorageSchemaVersion() < 2 && storageConfig.migration.backupBeforeMigration === true) {
+ const backupFile = `${dbFile}.pre-migration-${Date.now()}.bak`;
+ const escapedBackupPath = backupFile.replaceAll("'", "''");
+ db.exec(`VACUUM INTO '${escapedBackupPath}'`);
+ console.log(`Storage backup: ${backupFile}`);
+ }
+ db.exec(sqliteSchema);
+} else if (currentStorageSchemaVersion() < 2) {
+ throw new Error('SQLite storage schema v2 is not initialized and automatic migrations are disabled.');
+}
+
+if (storageConfig.migration?.validateSchema === true) {
+ const schemaVersion = currentStorageSchemaVersion();
+ const requiredTables = ['projects', 'snapshots', 'canon_entries', 'frontier_items', 'archive_records', 'knowledge_embeddings', 'dependency_findings', 'delta_runs', 'delta_gaps', 'delta_dependencies', 'governance_reviews', 'app_state'];
+ const missingTables = requiredTables.filter((tableName) =>
+ !db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(tableName)
+ );
+ if (schemaVersion < 2 || missingTables.length > 0) {
+ throw new Error(`SQLite schema validation failed${missingTables.length ? `; missing tables: ${missingTables.join(', ')}` : ''}.`);
+ }
+}
+
+const selectState = db.prepare('SELECT value_json FROM app_state WHERE state_key = ?');
+const saveState = db.prepare(`
+ INSERT INTO app_state (state_key, value_json, updated_at)
+ VALUES (?, ?, ?)
+ ON CONFLICT(state_key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at
+`);
+const allowedState = new Set(['projects', 'policies', 'plans', 'snapshots']);
+const publicFiles = new Set(['index.html', 'app.js', 'styles.css', 'interactions.css', 'features.css', 'clickable.css', 'snapshots.css', 'configs/projectos.generated.json']);
+const contentTypes = {
+ '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
+ '.xml': 'application/xml; charset=utf-8', '.json': 'application/json; charset=utf-8',
+ '.md': 'text/markdown; charset=utf-8', '.svg': 'image/svg+xml'
+};
+
+function sendJson(res, status, value) {
+ const body = JSON.stringify(value);
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body), 'cache-control': 'no-store' });
+ res.end(body);
+}
+
+function readState(key) {
+ const row = selectState.get(key);
+ return row ? JSON.parse(row.value_json) : null;
+}
+
+async function readJsonBody(req) {
+ const chunks = [];
+ let size = 0;
+ for await (const chunk of req) {
+ size += chunk.length;
+ if (size > maxBodyBytes) throw Object.assign(new Error('Request body is too large.'), { statusCode: 413 });
+ chunks.push(chunk);
+ }
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
+ catch { throw Object.assign(new Error('Request body must be valid JSON.'), { statusCode: 400 }); }
+}
+
+function validState(key, value) {
+ if (!Array.isArray(value)) return false;
+ if (key === 'projects') return value.every(x => x && typeof x.name === 'string' && typeof x.stage === 'string');
+ if (key === 'policies') return value.every(x => x && typeof x.id === 'string' && typeof x.title === 'string' && typeof x.status === 'string');
+ if (key === 'plans') return value.every(x => x && typeof x.question === 'string' && typeof x.council === 'string');
+ return value.every(x => x && typeof x.id === 'string' && typeof x.project === 'string' && x.state && typeof x.created === 'string');
+}
+
+async function routeApi(req, res, url) {
+ if (req.method === 'GET' && url.pathname === '/api/health') {
+ return sendJson(res, 200, { status: 'ok', storage: 'sqlite', version: '2.0.0' });
+ }
+ if (req.method === 'GET' && url.pathname === '/api/state') {
+ return sendJson(res, 200, { projects: readState('projects'), policies: readState('policies'), plans: readState('plans'), snapshots: readState('snapshots') });
+ }
+ if (req.method === 'POST' && url.pathname === '/api/plans/draft') {
+ const input = await readJsonBody(req);
+ if (!input || typeof input.question !== 'string' || input.question.trim().length === 0) return sendJson(res, 422, { error: 'A question is required.' });
+ if (input.question.length > 700 || (input.project && String(input.project).length > 100)) return sendJson(res, 422, { error: 'The question or project name is too long.' });
+ const plan = createPlanDraft({ question: input.question, project: input.project || '' });
+ const plans = readState('plans') || [];
+ plans.unshift(plan);
+ saveState.run('plans', JSON.stringify(plans.slice(0, 100)), new Date().toISOString());
+ return sendJson(res, 201, plan);
+ }
+ const match = url.pathname.match(/^\/api\/state\/(projects|policies|plans|snapshots)$/);
+ if (req.method === 'POST' && match) {
+ const key = match[1];
+ if (!allowedState.has(key)) return sendJson(res, 404, { error: 'Unknown state collection.' });
+ const value = await readJsonBody(req);
+ if (!validState(key, value)) return sendJson(res, 422, { error: `Invalid ${key} collection.` });
+ saveState.run(key, JSON.stringify(value), new Date().toISOString());
+ return sendJson(res, 200, { saved: true, key, count: value.length });
+ }
+ return sendJson(res, 404, { error: 'API route not found.' });
+}
+
+function serveFile(req, res, url) {
+ let pathname;
+ try { pathname = decodeURIComponent(url.pathname); }
+ catch { res.writeHead(400).end('Invalid URL.'); return; }
+ const relative = pathname.replace(/^[/\\]+/, '') || 'index.html';
+ if (!publicFiles.has(relative)) { res.writeHead(404).end('Not found.'); return; }
+ let target = resolve(appRoot, relative);
+ if (target !== appRoot && !target.startsWith(appRoot + sep)) { res.writeHead(403).end('Forbidden.'); return; }
+ if (!existsSync(target)) { res.writeHead(404).end('Not found.'); return; }
+ if (statSync(target).isDirectory()) target = join(target, 'index.html');
+ if (!existsSync(target)) { res.writeHead(404).end('Not found.'); return; }
+ res.writeHead(200, { 'content-type': contentTypes[extname(target).toLowerCase()] || 'application/octet-stream', 'cache-control': 'no-store' });
+ createReadStream(target).pipe(res);
+}
+
+const server = createServer(async (req, res) => {
+ const url = new URL(req.url || '/', `http://${host}:${port}`);
+ try {
+ if (url.pathname.startsWith('/api/')) await routeApi(req, res, url);
+ else if (req.method === 'GET' || req.method === 'HEAD') serveFile(req, res, url);
+ else sendJson(res, 405, { error: 'Method not allowed.' });
+ } catch (error) {
+ if (res.headersSent) { res.destroy(error); return; }
+ sendJson(res, error.statusCode || 500, { error: error.statusCode ? error.message : 'Local service error.' });
+ }
+});
+
+server.listen(port, host, () => {
+ console.log(`ProjectOS local app: http://${host}:${port}`);
+ console.log(`SQLite data: ${dbFile}`);
+});
+
+function shutdown() {
+ server.close(() => { db.close(); process.exit(0); });
+}
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/apps/dashboard/index.html b/apps/dashboard/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..faf25552a4f4538ac99b2f996ad02c039d2bdc0d
--- /dev/null
+++ b/apps/dashboard/index.html
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+ ProjectOS — Dashboard
+
+
+
+
+
+
diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..0af898495f9c40aafba2905f401e61171571bb7e
--- /dev/null
+++ b/apps/dashboard/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@projectos/dashboard",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite --host 127.0.0.1",
+ "build": "tsc -b && vite build",
+ "lint": "tsc -b --pretty false",
+ "typecheck": "tsc -b --pretty false"
+ },
+ "dependencies": {
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1"
+ },
+ "devDependencies": {
+ "@types/react": "^18.3.12",
+ "@types/react-dom": "^18.3.1",
+ "@types/node": "^22.10.0",
+ "@vitejs/plugin-react": "^4.3.3",
+ "typescript": "^5.6.3",
+ "vite": "^5.4.10"
+ }
+}
diff --git a/apps/dashboard/src/App.tsx b/apps/dashboard/src/App.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8d27de72a68aa6b52b71e94fc1255668fb29c8e0
--- /dev/null
+++ b/apps/dashboard/src/App.tsx
@@ -0,0 +1,195 @@
+import { useEffect, useMemo, useState } from 'react';
+import type { FormEvent, ReactNode } from 'react';
+import projectCatalog from '../../../configs/projectos.generated.json';
+
+type Project = { name: string; initial: string; tone: string; stage: string; kind: string; description?: string; updated: string; health: string };
+type CatalogItem = { name: string; description: string; icon?: string; capabilities: string[] };
+type Plan = { id?: string; question: string; project: string; intent?: string; council: string; agents: string[]; model: string; datasets: string; tools: string; logic: string; governance: string; created: string; executionReady?: boolean; governanceGate?: { missingIntegrations: string[]; approvalRequired: boolean } };
+type Policy = { id: string; title: string; description: string; status: string; reviewed?: string };
+type Snapshot = { id: string; project: string; created: string; state: Project };
+type Manifest = { steps: CatalogItem[]; stages: CatalogItem[]; fabrics: CatalogItem[]; agents: CatalogItem[]; councils: CatalogItem[]; governance: CatalogItem[]; knowledge: CatalogItem[] };
+type Collection = 'projects' | 'policies' | 'plans' | 'snapshots';
+type Modal = { kind: 'new-project' } | { kind: 'project'; project: Project } | { kind: 'stage'; stage: string } | { kind: 'detail'; title: string; description: string; capabilities: string[]; eyebrow: string } | { kind: 'snapshot'; snapshot: Snapshot };
+
+const seedProjects: Project[] = [
+ { name: 'Atlas Research', initial: 'A', tone: 'violet', stage: 'Active', kind: 'Research', updated: '12 min ago', health: 'Healthy' },
+ { name: 'Northstar Platform', initial: 'N', tone: 'blue', stage: 'Production', kind: 'Platform', updated: '1 hr ago', health: 'Healthy' },
+ { name: 'Signal Intelligence', initial: 'S', tone: 'orange', stage: 'Evolving', kind: 'Research', updated: 'Yesterday', health: 'Attention' },
+ { name: 'Common Ground', initial: 'C', tone: 'green', stage: 'Active', kind: 'Knowledge', updated: 'Oct 28', health: 'Healthy' }
+];
+const seedPolicies: Policy[] = [
+ { id: 'workspace-access', title: 'Workspace permission defaults', description: 'Proposal to restrict project write access to assigned contributors.', status: 'Pending' },
+ { id: 'dataset-trust', title: 'Dataset trust profile updates', description: 'Proposal to require a verified source for new external datasets.', status: 'Pending' }
+];
+const defaultManifest: Manifest = {
+ steps: [], stages: [], fabrics: [], agents: [], councils: [], governance: [], knowledge: []
+};
+const navItems = [
+ ['overview', '◫', 'Overview'], ['projects', '▤', 'Projects'], ['decision', '⌘', 'Decision flow'],
+ ['lifecycle', '⟳', 'Lifecycle'], ['fabrics', '◈', 'Fabrics'], ['agents', '♧', 'Agents'],
+ ['councils', '◎', 'Councils'], ['governance', '⬡', 'Governance'], ['knowledge', '▧', 'Knowledge']
+] as const;
+
+function readLocal(key: Collection, fallback: T): T {
+ try { return JSON.parse(localStorage.getItem(`projectos.${key}`) || 'null') ?? fallback; }
+ catch { return fallback; }
+}
+function writeLocal(key: Collection, value: T): void {
+ try { localStorage.setItem(`projectos.${key}`, JSON.stringify(value)); } catch { /* Browser storage may be disabled. */ }
+}
+function collectionRequest(key: Collection, value: unknown): void {
+ writeLocal(key, value);
+ fetch(`/api/state/${key}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) }).catch(() => undefined);
+}
+function stageTone(stage: string): string {
+ if (stage === 'Production') return 'blue';
+ if (stage === 'Evolving') return 'orange';
+ if (stage === 'Archive' || stage === 'Obsolete') return 'muted';
+ return 'green';
+}
+function localPlan(question: string, project: string): Plan {
+ const text = question.toLowerCase();
+ const council = /policy|permission|trust|privacy|risk|approval|audit/.test(text) ? 'Governance Council'
+ : /deploy|database|docker|runtime|infrastructure|install|server/.test(text) ? 'Infrastructure Council'
+ : /design|architecture|system|structure|interface/.test(text) ? 'Architecture Council'
+ : /build|implement|code|create|app|feature|fix/.test(text) ? 'Implementation Council'
+ : /improv|evol|compare|roadmap|gap|frontier/.test(text) ? 'Evolution Council' : 'Research Council';
+ const agents = council === 'Research Council' ? ['Research Agent', 'Knowledge Agent']
+ : council === 'Governance Council' ? ['Governance Agent', 'Logic Agent']
+ : council === 'Infrastructure Council' ? ['Infrastructure Agent', 'Dependency Agent']
+ : council === 'Evolution Council' ? ['Delta Agent', 'Evolution Agent']
+ : council === 'Architecture Council' ? ['Logic Agent', 'Infrastructure Agent'] : ['Implementation Agent', 'Logic Agent'];
+ return { question, project: project || 'Workspace level', intent: 'local-preview', council, agents, model: 'Not configured', datasets: project ? `${project} project context` : 'No dataset connected', tools: 'No tool adapters configured', logic: 'Draft created; feasibility has not been verified against a runtime.', governance: 'Blocked: execution requires configured providers, policies, and approval.', created: new Date().toISOString(), executionReady: false };
+}
+
+export default function App() {
+ const [view, setView] = useState('overview');
+ const [projects, setProjects] = useState(() => readLocal('projects', seedProjects));
+ const [policies, setPolicies] = useState(() => readLocal('policies', seedPolicies));
+ const [plans, setPlans] = useState(() => readLocal('plans', []));
+ const [snapshots, setSnapshots] = useState(() => readLocal('snapshots', []));
+ const [manifest, setManifest] = useState(defaultManifest);
+ const [modal, setModal] = useState(null);
+ const [plan, setPlan] = useState(null);
+ const [query, setQuery] = useState('');
+ const [projectFilter, setProjectFilter] = useState('All');
+ const [toast, setToast] = useState('');
+ const pendingCount = policies.filter(policy => policy.status === 'Pending').length;
+
+ useEffect(() => {
+ let active = true;
+ setManifest(projectCatalog as Manifest);
+ fetch('/api/state').then(response => response.ok ? response.json() : Promise.reject())
+ .then(state => {
+ if (!active) return;
+ const nextProjects = Array.isArray(state.projects) ? state.projects : readLocal('projects', seedProjects);
+ const nextPolicies = Array.isArray(state.policies) ? state.policies : readLocal('policies', seedPolicies);
+ const nextPlans = Array.isArray(state.plans) ? state.plans : readLocal('plans', []);
+ const nextSnapshots = Array.isArray(state.snapshots) ? state.snapshots : readLocal('snapshots', []);
+ setProjects(nextProjects); setPolicies(nextPolicies); setPlans(nextPlans); setSnapshots(nextSnapshots);
+ for (const [key, value, remote] of [['projects', nextProjects, state.projects], ['policies', nextPolicies, state.policies], ['plans', nextPlans, state.plans], ['snapshots', nextSnapshots, state.snapshots]] as const) {
+ if (Array.isArray(remote)) writeLocal(key, value);
+ else collectionRequest(key, value);
+ }
+ }).catch(() => undefined);
+ return () => { active = false; };
+ }, []);
+
+ useEffect(() => {
+ if (!toast) return;
+ const timer = window.setTimeout(() => setToast(''), 2600);
+ return () => window.clearTimeout(timer);
+ }, [toast]);
+
+ const visibleProjects = useMemo(() => projects.filter(project => project.name.toLowerCase().includes(query.toLowerCase()) && (projectFilter === 'All' || (projectFilter === 'Research' ? project.kind === 'Research' : project.stage === projectFilter))), [projects, projectFilter, query]);
+ const saveProjects = (next: Project[]) => { setProjects(next); collectionRequest('projects', next); };
+ const savePolicies = (next: Policy[]) => { setPolicies(next); collectionRequest('policies', next); };
+ const addProject = (event: FormEvent) => {
+ event.preventDefault();
+ const form = new FormData(event.currentTarget);
+ const name = String(form.get('name') || '').trim();
+ if (projects.some(project => project.name.toLowerCase() === name.toLowerCase())) { setToast('A project with that name already exists.'); return; }
+ const tones = ['violet', 'blue', 'orange', 'green'];
+ const project: Project = { name, initial: name[0].toUpperCase(), tone: tones[projects.length % tones.length], stage: 'Research', kind: String(form.get('kind') || '').trim() || 'General', description: String(form.get('description') || '').trim(), updated: 'Just now', health: 'Healthy' };
+ saveProjects([project, ...projects]); setModal(null); setView('projects'); setToast(`Project “${name}” created.`);
+ };
+ const updateProject = (event: FormEvent, original: Project) => {
+ event.preventDefault();
+ const form = new FormData(event.currentTarget);
+ const next = projects.map(project => project.name === original.name ? { ...project, stage: String(form.get('stage')), kind: String(form.get('kind')).trim() || 'General', updated: 'Just now' } : project);
+ saveProjects(next); setModal(null); setToast(`${original.name} updated.`);
+ };
+ const updateStage = (event: FormEvent) => {
+ event.preventDefault();
+ const form = new FormData(event.currentTarget);
+ const name = String(form.get('project'));
+ const stage = String(form.get('stage'));
+ saveProjects(projects.map(project => project.name === name ? { ...project, stage, updated: 'Just now' } : project));
+ setModal(null); setToast(`${name} moved to ${stage}.`);
+ };
+ const createSnapshot = (project: Project) => {
+ const snapshot: Snapshot = { id: globalThis.crypto?.randomUUID?.() || String(Date.now()), project: project.name, created: new Date().toISOString(), state: { ...project } };
+ const next = [snapshot, ...snapshots]; setSnapshots(next); collectionRequest('snapshots', next); setModal(null); setToast(`Snapshot saved for ${project.name}.`);
+ };
+ const reviewPolicy = (policy: Policy, status: string) => {
+ savePolicies(policies.map(item => item.id === policy.id ? { ...item, status, reviewed: new Date().toISOString() } : item));
+ setToast(`${policy.title}: ${status.toLowerCase()}.`);
+ };
+ const createPlan = async (event: FormEvent) => {
+ event.preventDefault();
+ const form = new FormData(event.currentTarget);
+ const question = String(form.get('question') || '').trim();
+ const project = String(form.get('project') || '');
+ try {
+ const response = await fetch('/api/plans/draft', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ question, project }) });
+ if (!response.ok) throw new Error('Planner unavailable');
+ const result = await response.json() as Plan;
+ const next = [result, ...plans.filter(item => item.id !== result.id)].slice(0, 100);
+ setPlans(next); writeLocal('plans', next); setPlan(result); setToast('Planning draft created. It has not been executed.');
+ } catch {
+ const result = localPlan(question, project);
+ const next = [result, ...plans].slice(0, 100); setPlans(next); collectionRequest('plans', next); setPlan(result); setToast('Created a browser-only planning draft.');
+ }
+ };
+
+ const stages = manifest.stages.length ? manifest.stages : ['Research', 'Active', 'Production', 'Evolving', 'Frontier Comparison', 'Delta Analysis', 'Missing Dependencies', 'Evolution Suggestions', 'Obsolete', 'Snapshot', 'Archive', 'Template'].map(name => ({ name, description: '', capabilities: [] }));
+ const navTo = (target: string) => { setView(target); setPlan(null); window.scrollTo({ top: 0, behavior: 'smooth' }); };
+ const projectRows = (items: Project[]) => items.map(project => );
+ const catalogCards = (items: CatalogItem[], eyebrow: string) => {items.map(item =>
)}
;
+
+ let page: ReactNode;
+ if (view === 'projects') page = <> setModal({ kind: 'new-project' })}>+ New project} />PROJECTSTAGEUPDATED
{visibleProjects.length ? projectRows(visibleProjects) : No projects match your search.
}>;
+ else if (view === 'decision') page = <>Plan a question
Generate a routing proposal for review.
LOCAL DRAFT{manifest.steps.map((step, index) =>
)}
{plan && }{plans.length > 0 && Recent planning drafts
{plans.slice(0, 5).map((item, index) => )}}>;
+ else if (view === 'lifecycle') page = <> setModal({ kind: 'stage', stage: 'Active' })}>Update a project stage} />{stages.map((stage, index) =>
)}
>;
+ else if (view === 'fabrics') page = <>{catalogCards(manifest.fabrics, 'FABRIC SUBSYSTEM')}>;
+ else if (view === 'agents') page = <>{catalogCards(manifest.agents, 'SPECIALIST AGENT')}>;
+ else if (view === 'councils') page = <>{catalogCards(manifest.councils, 'COUNCIL TEMPLATE')}>;
+ else if (view === 'governance') page = <>Review queue
{pendingCount} sample proposals pending
LOCAL DEMO {policies.map(policy => {policy.title}{policy.description}
{policy.status}{policy.status === 'Pending' &&
}
)}{catalogCards(manifest.governance, 'GOVERNANCE CONTROL')}>;
+ else if (view === 'knowledge') page = <>Project snapshots
State records stored locally
{snapshots.length} SAVED {snapshots.length ? snapshots.map(snapshot => ) : No snapshots yet. Open a project and create one to preserve its state.
}{catalogCards(manifest.knowledge, 'KNOWLEDGE AREA')}
>;
+ else page = <> setModal({ kind: 'new-project' })}>+ New project} />Workspace preview
Illustrative project records for exploring the workflow.
Recent projects
Project records saved in this browser or local database.
{projectRows(projects.slice(0, 4))}Decision flow
Question to canonical knowledge
READY TO PLAN {manifest.steps.slice(0, 6).map((step, index) => {String(index + 1).padStart(2, '0')}{step.name}
)}Architecture coverage
Subsystems represented in this monorepo.
{[['Fabrics', manifest.fabrics.length, 'fabrics'], ['Agent pool', manifest.agents.length, 'agents'], ['Council engine', manifest.councils.length, 'councils'], ['Governance', pendingCount, 'governance']].map(([name, count, target]) => )}
>;
+
+ return
+
+
{page}
+ {modal &&
{ if (event.target === event.currentTarget) setModal(null); }}>
+ {modal.kind === 'new-project' && <>PROJECTS / CREATEStart a project
Create a local project record and add context for the next planning run.
>}
+ {modal.kind === 'project' && <>PROJECT WORKSPACE{modal.project.name}
{modal.project.description || `${modal.project.kind} workspace. Project records are stored locally.`}
>}
+ {modal.kind === 'stage' && <>PROJECT LIFECYCLE / UPDATEMove a project to a new stage
Lifecycle changes are saved to the project record.
>}
+ {modal.kind === 'detail' && <>{modal.eyebrow}{modal.title}
{modal.description}
{modal.capabilities.length > 0 && {modal.eyebrow.includes('COUNCIL') ? 'Council members' : 'Responsibilities and capabilities'}
{modal.capabilities.map(capability => {capability})}
}Architecture descriptions come from generated ProjectOS configuration. Live provider integrations depend on configured services and credentials.
>}
+ {modal.kind === 'snapshot' && <>PROJECT SNAPSHOT / {new Date(modal.snapshot.created).toLocaleString()}{modal.snapshot.project}
Saved state: {modal.snapshot.state.stage} · {modal.snapshot.state.kind}
This snapshot preserves the project record. It does not yet capture project files or external service state.
>}
+ }
+ {toast &&
{toast}
}
+
;
+}
+
+function PageHeading({ eyebrow, title, description, action }: { eyebrow: string; title: string; description: string; action?: ReactNode }) {
+ return {eyebrow}{title}
{description}
{action}
;
+}
+
+function PlanCard({ plan }: { plan: Plan }) {
+ return PLANNING PREVIEW / NOT EXECUTED{plan.question}
{plan.project} · {plan.intent || 'suggested'} · {plan.council}
{[['SPECIALISTS', plan.agents.join(', ')], ['MODEL', plan.model], ['DATASETS', plan.datasets], ['TOOLS', plan.tools], ['LOGIC GATE', plan.logic], ['GOVERNANCE GATE', plan.governance]].map(([label, value]) =>
{label}{value}
)}
{plan.governanceGate?.missingIntegrations.length ? Missing integrations: {plan.governanceGate.missingIntegrations.join(', ')}. Approval required: {String(plan.governanceGate.approvalRequired)}.
: null};
+}
diff --git a/apps/dashboard/src/controls.css b/apps/dashboard/src/controls.css
new file mode 100644
index 0000000000000000000000000000000000000000..ec19ab9c76def138a06b12709cb33b3a8ac57249
--- /dev/null
+++ b/apps/dashboard/src/controls.css
@@ -0,0 +1 @@
+.filters button{border:0;background:transparent;color:#92909a;font-size:9px;padding:7px 9px;border-radius:5px}.filters button:hover{color:#665bb0;background:#f6f4fb}.filters button.active-filter{color:#655ab0;font-weight:600;background:#f0eef9}.filters button b{margin-left:4px;font-size:8px}
diff --git a/apps/dashboard/src/dashboard.css b/apps/dashboard/src/dashboard.css
new file mode 100644
index 0000000000000000000000000000000000000000..d8273839603910a8ab0f1567ab30a926a9123f6f
--- /dev/null
+++ b/apps/dashboard/src/dashboard.css
@@ -0,0 +1 @@
+:root{font-family:'DM Sans',system-ui,sans-serif;color:#292830;background:#f7f6f2;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;font-optical-sizing:auto;font-weight:400;--ink:#292830;--muted:#898792;--line:#eae8ed;--purple:#7063c7;--sidebar:246px}*{box-sizing:border-box}body{margin:0;min-width:340px;min-height:100vh}button,input,select,textarea{font:inherit}button{cursor:pointer}.app-shell{min-height:100vh}.sidebar{position:fixed;inset:0 auto 0 0;width:var(--sidebar);background:#fff;border-right:1px solid var(--line);padding:25px 16px 17px;display:flex;flex-direction:column;z-index:3}.brand{display:flex;align-items:center;gap:11px;margin:0 0 39px 7px;color:var(--ink);text-decoration:none;font:800 18px Manrope,sans-serif;letter-spacing:-.7px;cursor:pointer}.brand>span:last-child>span{color:#8b85b4}.brand small{display:block;color:#a09da8;font:700 8px 'DM Sans',sans-serif;letter-spacing:1.1px;margin-top:3px}.brand-mark{height:35px;width:35px;display:grid;place-items:center;border-radius:11px;background:#7669ca;color:white;box-shadow:0 4px 10px #7669ca35}.nav-label{font-size:9px;color:#a19ea8;font-weight:700;letter-spacing:1.2px;padding:0 10px;margin-bottom:9px}.sidebar nav{display:grid;gap:3px}.nav-item{display:flex;align-items:center;gap:11px;height:38px;padding:0 10px;border:0;border-radius:7px;background:transparent;color:#777580;text-align:left;font-size:11px}.nav-item>span{width:16px;text-align:center;color:#95929e;font-size:15px}.nav-item:hover{background:#f8f7fa}.nav-item.active{background:#f1effb;color:#594eaa;font-weight:600}.nav-item.active>span{color:#665ab9}.nav-item b{margin-left:auto;color:#918e9a;font-size:9px;font-weight:500}.sidebar-footer{margin-top:auto;border:1px solid var(--line);background:#fbfafc;border-radius:8px;padding:12px 10px;display:flex;align-items:center;gap:9px}.sidebar-footer>div{display:grid;gap:3px}.sidebar-footer strong{font-size:10px}.sidebar-footer small{font-size:9px;color:#9e9ba5}.status-dot,.local-label i{height:7px;width:7px;border-radius:50%;background:#d5a24c}.main{margin-left:var(--sidebar);min-height:100vh}.topbar{height:62px;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 40px;color:#96939d;font-size:10px}.topbar span{margin:0 8px;color:#cfccd5}.topbar strong{color:#4b4953;font-weight:600}.local-label{display:flex;align-items:center;gap:6px!important;padding:0!important;color:#77747f!important}.local-label i{margin:0!important}.page{max-width:1450px;padding:34px 41px 64px;margin:0 auto}.page-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;margin-bottom:26px}.eyebrow{font-size:9px;font-weight:700;letter-spacing:1.15px;color:#9d99a4}.page-heading h1{font:700 29px Manrope,sans-serif;letter-spacing:-1px;margin:9px 0 6px}.page-heading p{font-size:11px;color:#898691;margin:0;line-height:1.6}.primary,.secondary{border-radius:6px;padding:9px 13px;font-size:10px;font-weight:600;white-space:nowrap}.primary{border:1px solid var(--purple);background:var(--purple);color:white}.primary:hover{background:#6256b3}.secondary{border:1px solid #e5e2eb;background:#fff;color:#67636f}.secondary:hover{border-color:#cec8e8;color:#5b50a8}.stat-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.stat-grid>button{min-height:116px;text-align:left;background:#fff;border:1px solid var(--line);border-radius:9px;padding:15px 16px;color:var(--ink);transition:.15s}.stat-grid>button:hover,.health-grid>button:hover,.catalog-card:hover{transform:translateY(-1px);border-color:#d5d0ee;box-shadow:0 6px 18px #2622340d}.stat-grid small{display:block;font-size:8px;color:#9a97a1;font-weight:700;letter-spacing:.7px}.stat-grid strong{display:block;font:700 24px Manrope,sans-serif;margin:7px 0 2px}.stat-grid span{color:#96939d;font-size:9px}.section-title{display:flex;justify-content:space-between;align-items:flex-end;margin:29px 0 12px}.section-title h2,.panel-head h2,.history h2,.snapshot-panel h2{font:700 14px Manrope,sans-serif;margin:0;letter-spacing:-.2px}.section-title p,.panel-head p{font-size:9px;color:#98959f;margin:5px 0 0}.link-button{border:0;background:transparent;color:#7165bb;font-size:9px;font-weight:700;padding:6px 0}.home-grid{display:grid;grid-template-columns:1.18fr .82fr;gap:13px}.panel{background:white;border:1px solid var(--line);border-radius:9px}.recent-projects,.flow-preview{padding:16px 17px 0}.panel-head{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px}.project-row{width:100%;min-height:53px;display:flex;align-items:center;gap:10px;text-align:left;background:#fff;border:0;border-top:1px solid #f0eff3;padding:8px 0;color:var(--ink)}.project-row:hover .project-copy strong{color:#6358b4}.project-mark{width:29px;height:29px;border-radius:8px;display:grid;place-items:center;font:700 11px Manrope,sans-serif;flex:0 0 auto}.project-mark.violet{background:#f0edff;color:#766bc8}.project-mark.blue{background:#eaf2fc;color:#5989bd}.project-mark.orange{background:#fff0e5;color:#c98245}.project-mark.green{background:#eaf6ef;color:#4a9a6f}.project-copy{flex:1;min-width:0}.project-copy strong{display:block;font-size:10px;font-weight:600}.project-copy small{display:block;color:#9d9aa4;font-size:8px;margin-top:4px}.stage-pill{padding:5px 7px;border-radius:5px;font-size:8px;color:#5e9a74;background:#eff8f2;white-space:nowrap}.stage-pill.blue{color:#6389ba;background:#edf4fd}.stage-pill.orange{color:#bd8a4b;background:#fff6e9}.stage-pill.muted{color:#88838f;background:#f1f0f3}.arrow{color:#afacb5;font-size:12px;opacity:0}.project-row:hover .arrow{opacity:1}.mini-step{height:28px;display:flex;align-items:center;gap:8px;color:#706d78;font-size:9px}.mini-step span{height:18px;width:18px;border:1px solid #e6e3f3;color:#7368bd;border-radius:50%;display:grid;place-items:center;font-size:7px}.flow-preview>.link-button{width:100%;text-align:left;border-top:1px solid #f0eff3;margin-top:5px}.health-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.health-grid>button{display:flex;align-items:center;gap:9px;padding:11px;background:white;border:1px solid var(--line);border-radius:8px;text-align:left;color:var(--ink);transition:.15s}.health-grid>button strong{font-size:9px;display:block}.health-grid>button small{display:block;color:#9c99a4;font-size:8px;margin-top:4px}.health-grid>button span:last-child{font-size:8px;color:#786dbb;margin-left:auto;white-space:nowrap}.toolbar{display:flex;justify-content:space-between;align-items:center;margin:23px 0 13px}.filters{display:flex;gap:15px;align-items:center;color:#92909a;font-size:9px}.active-filter{color:#655ab0;font-weight:600;background:#f0eef9;border-radius:5px;padding:7px 9px}.filters b{margin-left:4px;font-size:8px}.toolbar input{border:1px solid var(--line);background:white;border-radius:5px;padding:8px 10px;font-size:9px;outline-color:#bdb5e6}.directory{padding:0 16px}.directory-head{display:grid;grid-template-columns:2fr .8fr 1fr 20px;gap:10px;height:37px;align-items:center;color:#aaa7b0;font-size:8px;letter-spacing:.7px;font-weight:700}.directory .project-row{min-height:58px}.decision-layout{display:grid;grid-template-columns:1fr 260px;gap:14px;margin:24px 0}.decision-panel{padding:16px 18px}.draft-label{font-size:8px;font-weight:700;letter-spacing:.6px;color:#7165b5;background:#f2f0fb;border-radius:5px;padding:6px 8px}.plan-form,.modal-form{display:grid;gap:12px;margin-top:14px}.plan-form label,.modal-form label{display:grid;gap:6px;font-size:9px;font-weight:600;color:#77747f}.plan-form textarea,.plan-form select,.modal-form input,.modal-form textarea,.modal-form select{border:1px solid #e7e5eb;border-radius:6px;background:white;padding:10px;color:#33313a;font-size:10px;outline-color:#b9b0e4}.plan-form textarea,.modal-form textarea{min-height:76px;resize:vertical}.plan-form .primary{justify-self:start}.formula-aside{background:#302f3b;color:white;border-radius:9px;padding:19px}.formula-aside>b{font-size:8px;letter-spacing:1px;color:#beb8e2}.formula-aside h2{font:700 16px Manrope,sans-serif;line-height:1.35;margin:14px 0 7px}.formula-aside p{font-size:9px;line-height:1.6;color:#c4c1ce}.aside-count{border-top:1px solid #4c4a57;display:flex;align-items:center;gap:9px;margin-top:12px;padding-top:10px}.aside-count strong{font:700 17px Manrope,sans-serif;color:#d8d3ff}.aside-count span{font-size:9px;color:#c4c1ce}.formula-list{display:grid;grid-template-columns:repeat(2,1fr);gap:8px}.formula-step{min-height:52px;display:flex;align-items:center;gap:10px;padding:9px 11px;text-align:left;border:1px solid var(--line);border-radius:7px;background:#fff;color:var(--ink)}.formula-step>span{height:25px;width:25px;border-radius:7px;background:#f0eef9;color:#7368bd;display:grid;place-items:center;font-size:9px}.formula-step div{flex:1}.formula-step strong{font-size:9px;display:block}.formula-step small{font-size:8px;color:#a09da7;display:block;margin-top:4px;line-height:1.4}.formula-step i{font-size:10px;color:#aaa6b2;font-style:normal;opacity:0}.formula-step:hover i{opacity:1}.formula-step.gate{background:#fffcf6;border-color:#f1e6d4}.lifecycle-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.lifecycle-card{min-height:98px;text-align:left;padding:13px;background:white;border:1px solid var(--line);border-radius:8px;color:var(--ink)}.lifecycle-card:hover{border-color:#d7d2ed}.lifecycle-card small{font-size:8px;letter-spacing:.6px;color:#a3a0aa}.lifecycle-card strong{display:block;font:600 11px Manrope,sans-serif;margin:8px 0 4px}.lifecycle-card p{font-size:9px;line-height:1.5;color:#97949e;margin:0}.card-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:11px;margin-top:23px}.catalog-card{min-height:136px;background:white;border:1px solid var(--line);border-radius:8px;padding:14px;text-align:left;color:var(--ink);transition:.15s}.catalog-icon{height:28px;width:28px;display:grid;place-items:center;border-radius:8px;background:#f0edfb;color:#7165b8;font-size:13px;margin-bottom:10px}.catalog-card strong{font:600 10px Manrope,sans-serif}.catalog-card p{font-size:9px;line-height:1.5;color:#95929d;margin:5px 0 8px}.catalog-card small{font-size:8px;font-weight:600;color:#7367bb}.policy-panel,.snapshot-panel{padding:16px 18px;margin:22px 0}.policy-row{display:flex;align-items:center;gap:12px;border-top:1px solid #f0eff3;padding:12px 0}.policy-row>div:first-child{flex:1}.policy-row strong{font-size:10px}.policy-row p{font-size:9px;color:#96939d;margin:4px 0 0}.policy-state{font-size:8px;padding:5px 7px;border-radius:5px}.policy-state.pending{background:#fff4e4;color:#b98443}.policy-state.done{background:#eff7f1;color:#4f926a}.policy-actions{display:flex;gap:6px}.policy-actions button{border:1px solid #e8e5ed;background:#fff;border-radius:5px;padding:7px 9px;font-size:8px;color:#6c6874}.policy-actions button:first-child{background:#eff7f1;color:#4d8c65;border-color:#dcecdf}.knowledge-flow .card-grid{margin-top:22px}.snapshot-row{display:flex;align-items:center;gap:10px;width:100%;text-align:left;background:#fff;color:var(--ink);border:0;border-top:1px solid #f0eff3;padding:11px 0}.snapshot-row>span:first-child{height:27px;width:27px;display:grid;place-items:center;border-radius:7px;background:#f0eef9;color:#7165b8}.snapshot-row>div{flex:1}.snapshot-row strong,.snapshot-row small{display:block}.snapshot-row strong{font-size:10px}.snapshot-row small{font-size:8px;color:#9895a0;margin-top:4px}.snapshot-row i{font-style:normal;color:#aaa7b1}.history{margin-top:16px;padding:16px}.history h2{margin-bottom:10px}.history>button{display:grid;grid-template-columns:1fr auto;gap:4px 10px;width:100%;text-align:left;background:#fff;border:0;border-top:1px solid #f0eff3;padding:10px 0}.history>button strong{font-size:9px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.history>button small{font-size:8px;color:#9895a0}.history>button span{grid-column:2;grid-row:1/3;align-self:center;color:#7165bb;font-size:8px}.plan-card{padding:16px;margin-top:14px}.plan-card h2{font:700 14px Manrope,sans-serif;margin:8px 0}.plan-card>p{font-size:9px;color:#898691}.plan-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;margin:12px 0}.plan-grid>div{padding:9px;background:#f8f7fa;border-radius:6px}.plan-grid small{display:block;font-size:7px;letter-spacing:.7px;color:#9c99a3}.plan-grid strong{display:block;font-size:9px;margin-top:5px;line-height:1.45}.overlay{position:fixed;inset:0;background:#24212e77;z-index:10;display:grid;place-items:center;padding:18px}.modal{position:relative;width:min(560px,100%);max-height:88vh;overflow:auto;border-radius:11px;background:white;padding:25px;box-shadow:0 20px 70px #19172545}.modal-close{position:absolute;right:13px;top:12px;width:28px;height:28px;border:0;border-radius:50%;background:#f5f4f7;font-size:20px;color:#77737e}.modal h2{font:700 20px Manrope,sans-serif;margin:9px 32px 8px 0;letter-spacing:-.4px}.modal-lead{font-size:10px;line-height:1.65;color:#82808a;margin:0}.modal-section{border-top:1px solid var(--line);margin-top:15px;padding-top:13px}.modal-section h3{font-size:9px;letter-spacing:.6px;color:#9b98a2}.capability-grid{display:grid;grid-template-columns:1fr 1fr;gap:7px}.capability-grid span{padding:8px;background:#f7f6fa;border-radius:5px;color:#5f5b67;font-size:9px}.notice{margin-top:14px;padding:10px;background:#f4f2fb;border-radius:6px;color:#6a62a7;font-size:9px;line-height:1.6}.modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:15px}.modal-actions.spread{justify-content:initial}.modal-actions.spread>span{flex:1}.empty{font-size:10px;color:#97949f;padding:13px 0}.toast{position:fixed;right:22px;bottom:20px;z-index:20;padding:11px 14px;background:#302f3b;color:#fff;border-radius:7px;box-shadow:0 7px 20px #26233630;font-size:10px}@media(max-width:1050px){:root{--sidebar:210px}.page{padding:28px 25px}.topbar{padding:0 25px}.home-grid{grid-template-columns:1fr}.health-grid{grid-template-columns:repeat(2,1fr)}}@media(max-width:720px){:root{--sidebar:58px}.sidebar{padding:16px 7px}.brand{margin:0 auto 32px}.brand>span:last-child,.nav-label,.sidebar-footer{display:none}.nav-item{justify-content:center;padding:0;font-size:0}.nav-item>span{font-size:16px}.nav-item b{display:none}.page{padding:23px 14px}.topbar{padding:0 15px}.page-heading{align-items:flex-start}.page-heading h1{font-size:23px}.stat-grid{grid-template-columns:repeat(2,1fr);gap:8px}.stat-grid>button{padding:12px;min-height:103px}.home-grid,.decision-layout{grid-template-columns:1fr}.formula-aside{display:none}.formula-list{grid-template-columns:1fr}.lifecycle-grid{grid-template-columns:repeat(2,1fr)}.card-grid{grid-template-columns:1fr 1fr}.health-grid{grid-template-columns:1fr 1fr}.toolbar{gap:8px;align-items:flex-start;flex-direction:column}.directory-head{grid-template-columns:1fr auto}.directory-head span:nth-child(3){display:none}.project-row .stage-pill{font-size:0;padding:4px}.project-row .stage-pill::first-letter{font-size:8px}.policy-row{flex-wrap:wrap}.policy-row>div:first-child{flex-basis:100%}.plan-grid{grid-template-columns:1fr 1fr}.capability-grid{grid-template-columns:1fr}.page-heading .primary,.page-heading .secondary{white-space:normal}.modal{padding:22px 17px}}
diff --git a/apps/dashboard/src/main.tsx b/apps/dashboard/src/main.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b24fe0b9b193ab428d0111c67f7f47ba6b9f4d53
--- /dev/null
+++ b/apps/dashboard/src/main.tsx
@@ -0,0 +1,11 @@
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import App from './App';
+import './dashboard.css';
+import './controls.css';
+
+createRoot(document.getElementById('root')!).render(
+
+
+
+);
diff --git a/apps/dashboard/tsconfig.json b/apps/dashboard/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..c55479db3203e2b6b05070891e38967c39233ce4
--- /dev/null
+++ b/apps/dashboard/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "../..",
+ "jsx": "react-jsx",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "outDir": "dist/types",
+ "tsBuildInfoFile": "dist/.tsbuildinfo",
+ "types": ["vite/client", "node"]
+ },
+ "include": ["src", "vite.config.ts", "../../configs/projectos.generated.json"]
+}
diff --git a/apps/dashboard/vite.config.ts b/apps/dashboard/vite.config.ts
new file mode 100644
index 0000000000000000000000000000000000000000..022d859364b62d4599aaf4500871591a9069178c
--- /dev/null
+++ b/apps/dashboard/vite.config.ts
@@ -0,0 +1,20 @@
+import { defineConfig } from 'vite';
+import react from '@vitejs/plugin-react';
+import { fileURLToPath } from 'node:url';
+
+export default defineConfig({
+ plugins: [react()],
+ resolve: {
+ alias: {
+ '@': fileURLToPath(new URL('./src', import.meta.url))
+ }
+ },
+ server: {
+ host: '127.0.0.1',
+ port: 5173,
+ strictPort: true,
+ proxy: {
+ '/api': 'http://127.0.0.1:4173'
+ }
+ }
+});
diff --git a/apps/runtime/package.json b/apps/runtime/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..2a8c074a9de2e4111b022038db96d00c9bd46d6d
--- /dev/null
+++ b/apps/runtime/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@projectos/runtime",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "tsx src/index.ts",
+ "build": "tsc -b",
+ "lint": "tsc -b --pretty false",
+ "typecheck": "tsc -b --pretty false"
+ },
+ "dependencies": {
+ "@projectos/common": "workspace:*",
+ "@projectos/mcp-fabric": "workspace:*",
+ "@projectos/operations-agent": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "tsx": "^4.19.1",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/apps/runtime/src/index.ts b/apps/runtime/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..636c183fe5da7ff776be7c27562aa8e04ce5b3a0
--- /dev/null
+++ b/apps/runtime/src/index.ts
@@ -0,0 +1,75 @@
+import { loadGenerated, loadRuntime, validateEnvironment } from '@projectos/common';
+import { loadMcpLibrary } from '@projectos/mcp-fabric';
+import { OperationsAgent } from '@projectos/operations-agent';
+
+const environment = validateEnvironment();
+const config = loadRuntime();
+type ProjectCatalog = {
+ fabrics: Array<{ name: string }>;
+ councils: Array<{ name: string }>;
+};
+type AgentDefinition = { name: string };
+type PermissionRegistry = { rules: Array<{ id: string }> };
+
+let project: ProjectCatalog | undefined;
+let agents: AgentDefinition[] | undefined;
+let models: Record | undefined;
+let workspaces: Record | undefined;
+let permissions: PermissionRegistry | undefined;
+
+console.log('ProjectOS Runtime Starting...');
+console.log(`Profile: ${environment.PROJECTOS_PROFILE ?? config.profile}`);
+console.log(`Snapshots: ${config.snapshots ? 'enabled' : 'disabled'}`);
+console.log(`Automatic routing: ${config.automaticRouting ? 'enabled' : 'disabled'}`);
+
+let operationsAgent: OperationsAgent | undefined;
+let councilAgents: string[] = [];
+const initializers: Record void | Promise> = {
+ schema: () => console.log('Schema validation completed before runtime startup.'),
+ bootstrap: () => console.log('Generated runtime configuration loaded.'),
+ fabrics: () => {
+ project = loadGenerated('projectos.generated.json');
+ console.log(`Initializing ${project.fabrics.length} Fabrics...`);
+ },
+ identity: () => console.log('Initializing Identity Fabric...'),
+ trust: () => console.log('Initializing Trust Fabric...'),
+ storage: () => console.log('Initializing Storage Fabric...'),
+ knowledge: () => console.log('Initializing Knowledge Fabric...'),
+ logic: () => console.log('Initializing Logic Fabric...'),
+ governance: () => {
+ permissions = loadGenerated('permissions.generated.json');
+ console.log(`Initializing Governance Fabric with ${permissions.rules.length} permission rules...`);
+ },
+ operations: () => {
+ operationsAgent = new OperationsAgent();
+ console.log('Initializing Operations Agent...');
+ },
+ agents: () => {
+ agents = loadGenerated('agents.generated.json');
+ console.log(`Loading ${agents.length} specialist Agents...`);
+ },
+ registries: () => {
+ models = loadGenerated>('models.generated.json');
+ workspaces = loadGenerated>('workspaces.generated.json');
+ console.log(`Loading ${Object.keys(models).length} model routes and ${Object.keys(workspaces).length} workspace routes...`);
+ },
+ council: () => {
+ if (!operationsAgent || !project) throw new Error('Operations Agent and project configuration must initialize before the Council Engine.');
+ console.log(`Initializing ${project.councils.length} Council Templates...`);
+ councilAgents = operationsAgent.createCouncil('runtime initialization');
+ },
+ mcp: async () => {
+ const library = await loadMcpLibrary();
+ const enabledProfiles = library.profiles.filter((profile) => profile.enabled);
+ console.log(`Loaded MCP adapter library: ${library.servers.length} server entries, ${enabledProfiles.length} enabled profiles.`);
+ },
+ desktop: () => console.log('Dashboard launch scheduled after runtime initialization.')
+};
+
+for (const stage of config.startupOrder) {
+ const initialize = initializers[stage];
+ if (!initialize) throw new Error(`No runtime initializer is registered for startup stage "${stage}".`);
+ await initialize();
+}
+
+console.log(`Runtime Ready · ${councilAgents.length} specialist agents available to planning`);
diff --git a/apps/runtime/tsconfig.json b/apps/runtime/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..62fdff65a8dc8fc7c497192766d2f53fac04def1
--- /dev/null
+++ b/apps/runtime/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": ["node"]
+ },
+ "references": [
+ { "path": "../../packages/common" },
+ { "path": "../../packages/mcp-fabric" },
+ { "path": "../../packages/operations-agent" }
+ ],
+ "include": ["src/**/*.ts"]
+}
diff --git a/bootstrap/bootstrap-projectos.ps1 b/bootstrap/bootstrap-projectos.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..903bf3fddb76d93450f271e943e9c99b20561e45
--- /dev/null
+++ b/bootstrap/bootstrap-projectos.ps1
@@ -0,0 +1,48 @@
+$ErrorActionPreference = 'Stop'
+
+Write-Host ''
+Write-Host 'ProjectOS Bootstrap' -ForegroundColor Cyan
+Write-Host ''
+
+$projectRoot = Split-Path -Parent $PSScriptRoot
+Set-Location $projectRoot
+
+function Require-Command {
+ param([Parameter(Mandatory = $true)][string]$Name)
+ if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
+ throw "$Name is missing. Install it and run bootstrap again."
+ }
+}
+
+Require-Command git
+Require-Command node
+
+$nodeVersion = [version](node -p "process.versions.node")
+if ($nodeVersion -lt [version]'22.5.0') {
+ throw "Node.js 22.5 or later is required. Found $nodeVersion."
+}
+
+if (-not (Get-Command pnpm -ErrorAction SilentlyContinue)) {
+ Require-Command npm
+ npm install --global pnpm@10
+}
+
+New-Item -ItemType Directory -Path (Join-Path $projectRoot 'configs') -Force | Out-Null
+if (-not (Test-Path (Join-Path $projectRoot 'bootstrap.xml'))) {
+ Copy-Item -LiteralPath (Join-Path $projectRoot 'defaults\bootstrap.xml') -Destination (Join-Path $projectRoot 'bootstrap.xml')
+ Write-Host 'Created default bootstrap.xml'
+}
+
+pnpm install
+if ($LASTEXITCODE -ne 0) {
+ throw 'pnpm install failed.'
+}
+
+pnpm generate
+if ($LASTEXITCODE -ne 0) {
+ throw 'ProjectOS manifest validation or configuration generation failed.'
+}
+
+Write-Host ''
+Write-Host 'Bootstrap Complete' -ForegroundColor Green
+Write-Host 'Generated configuration is ready. Start ProjectOS with: pnpm dev'
diff --git a/configs/agents.generated.json b/configs/agents.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..8dfae341c52028c51cb9835faba60bd3157931a6
--- /dev/null
+++ b/configs/agents.generated.json
@@ -0,0 +1,62 @@
+[
+ {
+ "name": "Research Agent",
+ "description": "Finds evidence and records sources relevant to a question.",
+ "capabilities": []
+ },
+ {
+ "name": "ML Agent",
+ "description": "Reviews model choices, evaluation needs, and model-specific constraints.",
+ "capabilities": []
+ },
+ {
+ "name": "Logic Agent",
+ "description": "Checks plans for feasibility, consistency, and contradictions.",
+ "capabilities": []
+ },
+ {
+ "name": "Knowledge Agent",
+ "description": "Retrieves and organizes project memory and research.",
+ "capabilities": []
+ },
+ {
+ "name": "Dependency Agent",
+ "description": "Identifies missing tools, permissions, libraries, data, or infrastructure.",
+ "capabilities": []
+ },
+ {
+ "name": "Delta Agent",
+ "description": "Compares current project state with a target or frontier.",
+ "capabilities": []
+ },
+ {
+ "name": "Evolution Agent",
+ "description": "Turns comparison results into sequenced improvement suggestions.",
+ "capabilities": []
+ },
+ {
+ "name": "Infrastructure Agent",
+ "description": "Plans runtime, storage, and environment requirements.",
+ "capabilities": []
+ },
+ {
+ "name": "Tool Execution Agent",
+ "description": "Coordinates approved tool calls through configured adapters.",
+ "capabilities": []
+ },
+ {
+ "name": "Governance Agent",
+ "description": "Applies policy checks and identifies human approval needs.",
+ "capabilities": []
+ },
+ {
+ "name": "Canonicalization Agent",
+ "description": "Turns verified outcomes into structured, reusable canon.",
+ "capabilities": []
+ },
+ {
+ "name": "Implementation Agent",
+ "description": "Plans approved implementation work.",
+ "capabilities": []
+ }
+]
diff --git a/configs/generated/language-profiles.generated.json b/configs/generated/language-profiles.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..f1e85a55e0a1ba833245a1ba6dd8b6626103a2d8
--- /dev/null
+++ b/configs/generated/language-profiles.generated.json
@@ -0,0 +1,14 @@
+{
+ "CSharp": {
+ "interfacePrefix": "I"
+ },
+ "TypeScript": {
+ "interfacePrefix": ""
+ },
+ "Java": {
+ "interfacePrefix": ""
+ },
+ "OpenAPITypeScript": {
+ "interfacePrefix": "I"
+ }
+}
diff --git a/configs/generated/storage.generated.json b/configs/generated/storage.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..2230d9ca9c231d4812f62e8626eaef528925654c
--- /dev/null
+++ b/configs/generated/storage.generated.json
@@ -0,0 +1,26 @@
+{
+ "providers": [
+ "SQLite",
+ "PostgreSQL"
+ ],
+ "vectorStores": [
+ {
+ "provider": "sqlite-vec",
+ "dimensions": 1536
+ },
+ {
+ "provider": "pgvector",
+ "dimensions": 1536
+ }
+ ],
+ "retention": {
+ "snapshotDays": 90,
+ "archiveYears": 7,
+ "keepCanonForever": true
+ },
+ "migration": {
+ "autoMigrate": true,
+ "backupBeforeMigration": true,
+ "validateSchema": true
+ }
+}
diff --git a/configs/generated/symbol-aliases.generated.json b/configs/generated/symbol-aliases.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..bd12b88db8a8d34120f54c5b5eb0f4cea2f1a6c7
--- /dev/null
+++ b/configs/generated/symbol-aliases.generated.json
@@ -0,0 +1,32 @@
+{
+ "ProjectRepository": [
+ "IProjectRepository",
+ "ProjectRepo",
+ "ProjectStore"
+ ],
+ "CanonRepository": [
+ "ICanonRepository",
+ "CanonRepo",
+ "CanonStore"
+ ],
+ "SnapshotRepository": [
+ "ISnapshotRepository",
+ "SnapshotRepo",
+ "SnapshotStore"
+ ],
+ "FrontierRepository": [
+ "IFrontierRepository",
+ "FrontierRepo",
+ "FrontierStore"
+ ],
+ "ArchiveRepository": [
+ "IArchiveRepository",
+ "ArchiveRepo",
+ "ArchiveStore"
+ ],
+ "EmbeddingRepository": [
+ "IEmbeddingRepository",
+ "EmbeddingRepo",
+ "EmbeddingStore"
+ ]
+}
diff --git a/configs/mcp-profiles.generated.json b/configs/mcp-profiles.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..bf39fe5e1887952c41320476245bc88de9b3164c
--- /dev/null
+++ b/configs/mcp-profiles.generated.json
@@ -0,0 +1,45 @@
+[
+ {
+ "name": "workspace",
+ "description": "Workspace files and persistent MCP memory.",
+ "enabled": true,
+ "servers": [
+ "filesystem",
+ "memory"
+ ]
+ },
+ {
+ "name": "research",
+ "description": "Public web research and read-only GitHub context.",
+ "enabled": true,
+ "servers": [
+ "fetch",
+ "github-readonly"
+ ]
+ },
+ {
+ "name": "implementation",
+ "description": "Workspace files and read-only GitHub context.",
+ "enabled": true,
+ "servers": [
+ "filesystem",
+ "github-readonly"
+ ]
+ },
+ {
+ "name": "database-readonly",
+ "description": "Read-only PostgreSQL access using an OS keyring profile.",
+ "enabled": true,
+ "servers": [
+ "postgres-readonly"
+ ]
+ },
+ {
+ "name": "database-write",
+ "description": "Explicitly disabled write access; requires a separate least-privilege database role and approval policy.",
+ "enabled": false,
+ "servers": [
+ "postgres-write"
+ ]
+ }
+]
diff --git a/configs/mcp.generated.json b/configs/mcp.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..f7eef37d4d79b7f840ba127f1fb22ff819689df9
--- /dev/null
+++ b/configs/mcp.generated.json
@@ -0,0 +1,68 @@
+[
+ {
+ "name": "filesystem",
+ "adapter": "filesystem",
+ "trust": "High",
+ "enabled": true,
+ "authMode": "none",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "git",
+ "adapter": "git",
+ "trust": "High",
+ "enabled": false,
+ "authMode": "none",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "github-readonly",
+ "adapter": "github",
+ "trust": "Verified",
+ "enabled": true,
+ "authMode": "oauth",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "github-write",
+ "adapter": "github",
+ "trust": "High",
+ "enabled": false,
+ "authMode": "oauth",
+ "accessMode": "read-write"
+ },
+ {
+ "name": "postgres-readonly",
+ "adapter": "postgres",
+ "trust": "Verified",
+ "enabled": true,
+ "authMode": "keyring",
+ "credentialRef": "PROJECTOS_POSTGRES_READ_PROFILE",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "postgres-write",
+ "adapter": "postgres",
+ "trust": "High",
+ "enabled": false,
+ "authMode": "keyring",
+ "credentialRef": "PROJECTOS_POSTGRES_WRITE_PROFILE",
+ "accessMode": "read-write"
+ },
+ {
+ "name": "fetch",
+ "adapter": "fetch",
+ "trust": "Medium",
+ "enabled": true,
+ "authMode": "none",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "memory",
+ "adapter": "memory",
+ "trust": "High",
+ "enabled": true,
+ "authMode": "none",
+ "accessMode": "read-only"
+ }
+]
diff --git a/configs/models.generated.json b/configs/models.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..a999fabd658409eb2da16ec2701ffa24fbc90ab8
--- /dev/null
+++ b/configs/models.generated.json
@@ -0,0 +1,7 @@
+{
+ "operations": "omni",
+ "research": "sonar",
+ "implementation": "copilot",
+ "ml": "qwen",
+ "logic": "claude"
+}
diff --git a/configs/permissions.generated.json b/configs/permissions.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..b52525bb907da73cba61f9e32e0811109dcb0f6e
--- /dev/null
+++ b/configs/permissions.generated.json
@@ -0,0 +1,32 @@
+{
+ "rules": [
+ {
+ "id": "workspace-read",
+ "resource": "workspace",
+ "action": "read",
+ "effect": "allow",
+ "requiresApproval": false
+ },
+ {
+ "id": "workspace-write",
+ "resource": "workspace",
+ "action": "write",
+ "effect": "require-approval",
+ "requiresApproval": true
+ },
+ {
+ "id": "tool-execution",
+ "resource": "tools",
+ "action": "execute",
+ "effect": "require-approval",
+ "requiresApproval": true
+ },
+ {
+ "id": "external-network",
+ "resource": "external-network",
+ "action": "access",
+ "effect": "deny",
+ "requiresApproval": true
+ }
+ ]
+}
diff --git a/configs/projectos.generated.json b/configs/projectos.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..f896d1fd0f9cd8de2cdba7645b7fdf1da431621d
--- /dev/null
+++ b/configs/projectos.generated.json
@@ -0,0 +1,649 @@
+{
+ "version": "2.0",
+ "name": "ProjectOS",
+ "mode": "local",
+ "steps": [
+ {
+ "name": "Question",
+ "description": "A person or connected system submits a question or requested outcome.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Operations Agent",
+ "description": "Coordinates intent analysis, routing, validation, and execution planning.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Determine Intent",
+ "description": "Classifies the request as research, implementation, infrastructure, evolution, or governance work.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Choose Council Template",
+ "description": "Selects a council template with the relevant specialists.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Assign Models",
+ "description": "Selects model providers and capabilities that match the task and trust requirements.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Assign Datasets",
+ "description": "Attaches project knowledge and datasets with source and permission context.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Assign Tools",
+ "description": "Selects tools required by the plan, subject to policy and permission checks.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Assign Workspace",
+ "description": "Binds the plan to a project workspace and runtime boundary.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Validate Through Logic",
+ "description": "Checks feasibility, consistency, assumptions, and contradictions before action.",
+ "capabilities": [],
+ "gate": true
+ },
+ {
+ "name": "Validate Through Governance",
+ "description": "Checks trust, policies, permissions, and approval requirements before action.",
+ "capabilities": [],
+ "gate": true
+ },
+ {
+ "name": "Execute",
+ "description": "Runs only actions that are available, authorized, and within the configured runtime.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Store Knowledge",
+ "description": "Records useful evidence, decisions, and outcomes with provenance.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Snapshot",
+ "description": "Captures the project state needed to reproduce or review the work.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Consolidate",
+ "description": "Merges compatible learning into organized project knowledge.",
+ "capabilities": [],
+ "gate": false
+ },
+ {
+ "name": "Update Canon",
+ "description": "Updates the canonical project record with reviewed, durable findings.",
+ "capabilities": [],
+ "gate": false
+ }
+ ],
+ "stages": [
+ {
+ "name": "Research",
+ "description": "Discover the problem and evidence.",
+ "capabilities": []
+ },
+ {
+ "name": "Active",
+ "description": "Coordinate work and decisions.",
+ "capabilities": []
+ },
+ {
+ "name": "Production",
+ "description": "Deliver stable project outcomes.",
+ "capabilities": []
+ },
+ {
+ "name": "Evolving",
+ "description": "Improve capabilities continuously.",
+ "capabilities": []
+ },
+ {
+ "name": "Frontier Comparison",
+ "description": "Compare current project state with emerging approaches.",
+ "capabilities": []
+ },
+ {
+ "name": "Delta Analysis",
+ "description": "Identify the gaps between current and target state.",
+ "capabilities": []
+ },
+ {
+ "name": "Missing Dependencies",
+ "description": "Surface unavailable requirements.",
+ "capabilities": []
+ },
+ {
+ "name": "Evolution Suggestions",
+ "description": "Propose the next improvements.",
+ "capabilities": []
+ },
+ {
+ "name": "Obsolete",
+ "description": "Mark work that is ready for retirement.",
+ "capabilities": []
+ },
+ {
+ "name": "Snapshot",
+ "description": "Preserve a durable project state.",
+ "capabilities": []
+ },
+ {
+ "name": "Archive",
+ "description": "Store completed work and its history.",
+ "capabilities": []
+ },
+ {
+ "name": "Template",
+ "description": "Make proven project patterns reusable.",
+ "capabilities": []
+ }
+ ],
+ "fabrics": [
+ {
+ "name": "Identity",
+ "description": "Resolves who is acting, what they own, and which roles apply.",
+ "icon": "◉",
+ "capabilities": [
+ "Ownership graph",
+ "Role registry",
+ "LDAP, Entra, OAuth, and SAML connectors"
+ ]
+ },
+ {
+ "name": "Trust",
+ "description": "Evaluates sources, datasets, and models against workspace trust requirements.",
+ "icon": "⬡",
+ "capabilities": [
+ "Source verification",
+ "Dataset and model verification",
+ "Trust scores"
+ ]
+ },
+ {
+ "name": "Research",
+ "description": "Connects research sources and organizes evidence for project decisions.",
+ "icon": "⌕",
+ "capabilities": [
+ "Web and paper discovery",
+ "Documentation connectors",
+ "Research source attribution"
+ ]
+ },
+ {
+ "name": "Knowledge",
+ "description": "Organizes project memory into research, lessons, canon, frontier, and archive.",
+ "icon": "▧",
+ "capabilities": [
+ "Project memory",
+ "Canonical knowledge",
+ "Snapshots and archive"
+ ]
+ },
+ {
+ "name": "Logic",
+ "description": "Builds plans and checks feasibility, consistency, and competing claims.",
+ "icon": "⌘",
+ "capabilities": [
+ "Intent analysis",
+ "Planning and validation",
+ "Consensus and contradictions"
+ ]
+ },
+ {
+ "name": "Delta",
+ "description": "Compares current and target states to identify gaps and useful evolution.",
+ "icon": "Δ",
+ "capabilities": [
+ "Current and frontier state",
+ "Gap analysis",
+ "Evolution and obsolescence"
+ ]
+ },
+ {
+ "name": "Dependency",
+ "description": "Finds unmet runtime, access, model, tool, library, and dataset requirements.",
+ "icon": "⛓",
+ "capabilities": [
+ "Missing permissions",
+ "Missing tools and models",
+ "Missing libraries, datasets, and infrastructure"
+ ]
+ },
+ {
+ "name": "Governance",
+ "description": "Applies policy gates, approval decisions, overrides, and audit recording.",
+ "icon": "⬡",
+ "capabilities": [
+ "Policy registry",
+ "Approval queue",
+ "Audit history"
+ ]
+ },
+ {
+ "name": "Execution",
+ "description": "Dispatches approved work to the appropriate execution adapter.",
+ "icon": "▶",
+ "capabilities": [
+ "PowerShell, Python, and Node",
+ "Docker and Git",
+ "MCP tools"
+ ]
+ },
+ {
+ "name": "Storage",
+ "description": "Defines local and enterprise storage for project artifacts and vectors.",
+ "icon": "▤",
+ "capabilities": [
+ "SQLite and sqlite-vec",
+ "PostgreSQL and pgvector",
+ "Snapshots, consolidation, and archives"
+ ]
+ },
+ {
+ "name": "Canvas",
+ "description": "Provides visual workspaces for diagrams, whiteboards, and knowledge views.",
+ "icon": "▱",
+ "capabilities": [
+ "Whiteboard canvas",
+ "Diagram engine",
+ "Knowledge views"
+ ]
+ }
+ ],
+ "agents": [
+ {
+ "name": "Research Agent",
+ "description": "Finds evidence and records sources relevant to a question.",
+ "capabilities": []
+ },
+ {
+ "name": "ML Agent",
+ "description": "Reviews model choices, evaluation needs, and model-specific constraints.",
+ "capabilities": []
+ },
+ {
+ "name": "Logic Agent",
+ "description": "Checks plans for feasibility, consistency, and contradictions.",
+ "capabilities": []
+ },
+ {
+ "name": "Knowledge Agent",
+ "description": "Retrieves and organizes project memory and research.",
+ "capabilities": []
+ },
+ {
+ "name": "Dependency Agent",
+ "description": "Identifies missing tools, permissions, libraries, data, or infrastructure.",
+ "capabilities": []
+ },
+ {
+ "name": "Delta Agent",
+ "description": "Compares current project state with a target or frontier.",
+ "capabilities": []
+ },
+ {
+ "name": "Evolution Agent",
+ "description": "Turns comparison results into sequenced improvement suggestions.",
+ "capabilities": []
+ },
+ {
+ "name": "Infrastructure Agent",
+ "description": "Plans runtime, storage, and environment requirements.",
+ "capabilities": []
+ },
+ {
+ "name": "Tool Execution Agent",
+ "description": "Coordinates approved tool calls through configured adapters.",
+ "capabilities": []
+ },
+ {
+ "name": "Governance Agent",
+ "description": "Applies policy checks and identifies human approval needs.",
+ "capabilities": []
+ },
+ {
+ "name": "Canonicalization Agent",
+ "description": "Turns verified outcomes into structured, reusable canon.",
+ "capabilities": []
+ },
+ {
+ "name": "Implementation Agent",
+ "description": "Plans approved implementation work.",
+ "capabilities": []
+ }
+ ],
+ "councils": [
+ {
+ "name": "Research Council",
+ "description": "Combines research and knowledge specialists to answer evidence questions.",
+ "icon": "◎",
+ "capabilities": [
+ "Research Agent",
+ "Knowledge Agent",
+ "Trust review"
+ ]
+ },
+ {
+ "name": "Architecture Council",
+ "description": "Reviews boundaries, dependencies, and system-level trade-offs.",
+ "icon": "◇",
+ "capabilities": [
+ "Logic Agent",
+ "Dependency Agent",
+ "Infrastructure Agent"
+ ]
+ },
+ {
+ "name": "Implementation Council",
+ "description": "Coordinates implementation from an approved plan through a reviewable change.",
+ "icon": "⚒",
+ "capabilities": [
+ "Implementation Agent",
+ "Logic Agent",
+ "Tool Execution Agent"
+ ]
+ },
+ {
+ "name": "Infrastructure Council",
+ "description": "Checks environments, storage, runtime, and deployment dependencies.",
+ "icon": "⌂",
+ "capabilities": [
+ "Infrastructure Agent",
+ "Dependency Agent",
+ "Governance Agent"
+ ]
+ },
+ {
+ "name": "Evolution Council",
+ "description": "Compares project state with the frontier and ranks improvement opportunities.",
+ "icon": "↻",
+ "capabilities": [
+ "Delta Agent",
+ "Evolution Agent",
+ "Knowledge Agent"
+ ]
+ },
+ {
+ "name": "Governance Council",
+ "description": "Reviews policies, trust, approvals, and recorded exceptions.",
+ "icon": "⬡",
+ "capabilities": [
+ "Governance Agent",
+ "Trust validation",
+ "Approval engine"
+ ]
+ }
+ ],
+ "governance": [
+ {
+ "name": "Policy Engine",
+ "description": "Evaluates plans against the active policy registry.",
+ "capabilities": []
+ },
+ {
+ "name": "Approval Engine",
+ "description": "Routes gated actions to the right reviewer.",
+ "capabilities": []
+ },
+ {
+ "name": "Trust Validation",
+ "description": "Checks identity, sources, datasets, and models.",
+ "capabilities": []
+ },
+ {
+ "name": "Override Engine",
+ "description": "Records scoped exceptions with justification.",
+ "capabilities": []
+ },
+ {
+ "name": "Audit Log",
+ "description": "Keeps an attributable record of decisions and actions.",
+ "capabilities": []
+ },
+ {
+ "name": "Policy Registry",
+ "description": "Maintains versioned workspace rules.",
+ "capabilities": []
+ }
+ ],
+ "knowledge": [
+ {
+ "name": "Project memory",
+ "description": "Working context and decisions.",
+ "capabilities": []
+ },
+ {
+ "name": "Research",
+ "description": "Sources, findings, and evidence.",
+ "capabilities": []
+ },
+ {
+ "name": "Lessons",
+ "description": "Reusable outcomes and reflections.",
+ "capabilities": []
+ },
+ {
+ "name": "Canon",
+ "description": "The current trusted project record.",
+ "capabilities": []
+ },
+ {
+ "name": "Frontier",
+ "description": "Emerging ideas and state of the art.",
+ "capabilities": []
+ },
+ {
+ "name": "Snapshots",
+ "description": "Point-in-time project state.",
+ "capabilities": []
+ },
+ {
+ "name": "Archive",
+ "description": "Preserved retired work.",
+ "capabilities": []
+ }
+ ],
+ "runtime": {
+ "profile": "Privileged",
+ "snapshots": true,
+ "automaticRouting": true,
+ "consolidation": true,
+ "startupOrder": [
+ "schema",
+ "bootstrap",
+ "fabrics",
+ "identity",
+ "trust",
+ "storage",
+ "knowledge",
+ "logic",
+ "governance",
+ "operations",
+ "agents",
+ "registries",
+ "council",
+ "mcp",
+ "desktop"
+ ]
+ },
+ "storage": {
+ "local": "SQLite,sqlite-vec",
+ "enterprise": "PostgreSQL,pgvector"
+ },
+ "models": {
+ "operations": "omni",
+ "research": "sonar",
+ "implementation": "copilot",
+ "ml": "qwen",
+ "logic": "claude"
+ },
+ "workspaces": {
+ "research": "VSCode",
+ "implementation": "Zed",
+ "ml": "PyCharm",
+ "logic": "IntelliJ",
+ "database": "DataGrip",
+ "canvas": "HFSpace"
+ },
+ "permissions": [
+ {
+ "id": "workspace-read",
+ "resource": "workspace",
+ "action": "read",
+ "effect": "allow",
+ "requiresApproval": false
+ },
+ {
+ "id": "workspace-write",
+ "resource": "workspace",
+ "action": "write",
+ "effect": "require-approval",
+ "requiresApproval": true
+ },
+ {
+ "id": "tool-execution",
+ "resource": "tools",
+ "action": "execute",
+ "effect": "require-approval",
+ "requiresApproval": true
+ },
+ {
+ "id": "external-network",
+ "resource": "external-network",
+ "action": "access",
+ "effect": "deny",
+ "requiresApproval": true
+ }
+ ],
+ "mcpServers": [
+ {
+ "name": "filesystem",
+ "adapter": "filesystem",
+ "trust": "High",
+ "enabled": true,
+ "authMode": "none",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "git",
+ "adapter": "git",
+ "trust": "High",
+ "enabled": false,
+ "authMode": "none",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "github-readonly",
+ "adapter": "github",
+ "trust": "Verified",
+ "enabled": true,
+ "authMode": "oauth",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "github-write",
+ "adapter": "github",
+ "trust": "High",
+ "enabled": false,
+ "authMode": "oauth",
+ "accessMode": "read-write"
+ },
+ {
+ "name": "postgres-readonly",
+ "adapter": "postgres",
+ "trust": "Verified",
+ "enabled": true,
+ "authMode": "keyring",
+ "credentialRef": "PROJECTOS_POSTGRES_READ_PROFILE",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "postgres-write",
+ "adapter": "postgres",
+ "trust": "High",
+ "enabled": false,
+ "authMode": "keyring",
+ "credentialRef": "PROJECTOS_POSTGRES_WRITE_PROFILE",
+ "accessMode": "read-write"
+ },
+ {
+ "name": "fetch",
+ "adapter": "fetch",
+ "trust": "Medium",
+ "enabled": true,
+ "authMode": "none",
+ "accessMode": "read-only"
+ },
+ {
+ "name": "memory",
+ "adapter": "memory",
+ "trust": "High",
+ "enabled": true,
+ "authMode": "none",
+ "accessMode": "read-only"
+ }
+ ],
+ "mcpProfiles": [
+ {
+ "name": "workspace",
+ "description": "Workspace files and persistent MCP memory.",
+ "enabled": true,
+ "servers": [
+ "filesystem",
+ "memory"
+ ]
+ },
+ {
+ "name": "research",
+ "description": "Public web research and read-only GitHub context.",
+ "enabled": true,
+ "servers": [
+ "fetch",
+ "github-readonly"
+ ]
+ },
+ {
+ "name": "implementation",
+ "description": "Workspace files and read-only GitHub context.",
+ "enabled": true,
+ "servers": [
+ "filesystem",
+ "github-readonly"
+ ]
+ },
+ {
+ "name": "database-readonly",
+ "description": "Read-only PostgreSQL access using an OS keyring profile.",
+ "enabled": true,
+ "servers": [
+ "postgres-readonly"
+ ]
+ },
+ {
+ "name": "database-write",
+ "description": "Explicitly disabled write access; requires a separate least-privilege database role and approval policy.",
+ "enabled": false,
+ "servers": [
+ "postgres-write"
+ ]
+ }
+ ]
+}
diff --git a/configs/runtime.generated.json b/configs/runtime.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..95b4565709d55d3f5202033bd59be5c16340cd2d
--- /dev/null
+++ b/configs/runtime.generated.json
@@ -0,0 +1,23 @@
+{
+ "profile": "Privileged",
+ "snapshots": true,
+ "automaticRouting": true,
+ "consolidation": true,
+ "startupOrder": [
+ "schema",
+ "bootstrap",
+ "fabrics",
+ "identity",
+ "trust",
+ "storage",
+ "knowledge",
+ "logic",
+ "governance",
+ "operations",
+ "agents",
+ "registries",
+ "council",
+ "mcp",
+ "desktop"
+ ]
+}
diff --git a/configs/workspaces.generated.json b/configs/workspaces.generated.json
new file mode 100644
index 0000000000000000000000000000000000000000..10fa47b5a654daa8ce9ba96982c42e9fc3fdfb6d
--- /dev/null
+++ b/configs/workspaces.generated.json
@@ -0,0 +1,8 @@
+{
+ "research": "VSCode",
+ "implementation": "Zed",
+ "ml": "PyCharm",
+ "logic": "IntelliJ",
+ "database": "DataGrip",
+ "canvas": "HFSpace"
+}
diff --git a/defaults/bootstrap.xml b/defaults/bootstrap.xml
new file mode 100644
index 0000000000000000000000000000000000000000..ac7563ca4ee0534da4980df0083982b74ffe33e5
--- /dev/null
+++ b/defaults/bootstrap.xml
@@ -0,0 +1,215 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Research AgentKnowledge AgentTrust review
+ Logic AgentDependency AgentInfrastructure Agent
+ Implementation AgentLogic AgentTool Execution Agent
+ Infrastructure AgentDependency AgentGovernance Agent
+ Delta AgentEvolution AgentKnowledge Agent
+ Governance AgentTrust validationApproval engine
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ IProjectRepository
+ ProjectRepo
+ ProjectStore
+
+
+ ICanonRepository
+ CanonRepo
+ CanonStore
+
+
+ ISnapshotRepository
+ SnapshotRepo
+ SnapshotStore
+
+
+ IFrontierRepository
+ FrontierRepo
+ FrontierStore
+
+
+ IArchiveRepository
+ ArchiveRepo
+ ArchiveStore
+
+
+ IEmbeddingRepository
+ EmbeddingRepo
+ EmbeddingStore
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/docs/storage-migration-plan.md b/docs/storage-migration-plan.md
new file mode 100644
index 0000000000000000000000000000000000000000..34e3e36a4f4252e2f27b0818c4b3636dd4903eb1
--- /dev/null
+++ b/docs/storage-migration-plan.md
@@ -0,0 +1,35 @@
+# Storage migration plan
+
+`bootstrap.xml` is the source of storage configuration. The schema engine validates the provider, vector-store, retention, and migration settings, then writes `configs/generated/storage.generated.json`. The local SQLite schema is already applied when the API opens `data/projectos.sqlite`; existing state routes still use `app_state`.
+
+## Phase 1: Dual-write
+
+Add normalized writes for project and snapshot changes while continuing to update `app_state`. Perform both writes in one SQLite transaction, and return success only after both have committed. Give events and snapshots stable IDs so retries do not create duplicates.
+
+## Phase 2: Repositories
+
+Introduce `ProjectRepository`, `SnapshotRepository`, `CanonRepository`, `FrontierRepository`, `ArchiveRepository`, and `EmbeddingRepository`. Keep HTTP handlers responsible for request validation and call the repositories for persistence.
+
+| Route | Primary table |
+| --- | --- |
+| `POST /api/projects` | `projects` |
+| `POST /api/snapshots` | `snapshots`, `snapshot_items` |
+| `POST /api/canon` | `canon_entries`, `canon_revisions` |
+| `POST /api/frontier` | `frontier_items`, `frontier_observations` |
+| `POST /api/archive` | `archive_records` |
+
+## Phase 3: Backfill and read cutover
+
+Read legacy arrays from `app_state`, map each record into its normalized table, and preserve the original JSON payload for fields without a normalized column. Make the backfill idempotent. Compare record counts and content checksums before switching reads to repositories. Keep the old state values until the cutover is confirmed.
+
+- `app_state.projects` → `projects`
+- `app_state.snapshots` → `snapshots` and `snapshot_items`
+- governance history → `project_events`
+
+## Phase 4: Vector backfill
+
+Generate embeddings for canon entries, frontier items, and project descriptions through the configured embedding provider. Record model key, dimensions, and source content hash. Verify the configured dimensions before writing. SQLite stores JSON vectors; PostgreSQL uses `vector(1536)` and its HNSW cosine index. Change both schemas and the manifest together when adopting a model with a different dimension.
+
+## Phase 5: Remove compatibility storage
+
+After all reads and writes use repositories and the backfill is verified, remove `app_state`, its route compatibility code, and legacy migration logic. Keep migration history and archive records according to the configured retention policy. Before enabling automatic schema changes, honor `backupBeforeMigration` and `validateSchema` from the generated storage config.
diff --git a/docs/symbol-resolution.md b/docs/symbol-resolution.md
new file mode 100644
index 0000000000000000000000000000000000000000..bce51e65eac7157255165538e2753e5e78ee8c1b
--- /dev/null
+++ b/docs/symbol-resolution.md
@@ -0,0 +1,21 @@
+# Canonical symbols and language profiles
+
+`bootstrap.xml` stores architecture names in canonical form and lists aliases that may appear in generated artifacts or external clients. The schema engine validates the registry, then generates:
+
+- `configs/generated/symbol-aliases.generated.json`
+- `configs/generated/language-profiles.generated.json`
+
+For example, `IProjectRepository`, `ProjectRepo`, and `ProjectStore` all resolve to `ProjectRepository`. Unknown symbols pass through unchanged; ambiguous aliases fail generation.
+
+Logic Fabric exposes `resolveSymbols` for type lookup and `emitSymbols` for target-language naming. A generator can resolve an alias first, then emit the canonical symbol with its selected profile:
+
+```ts
+import { SymbolResolver } from '@projectos/schema-engine';
+
+const resolver = new SymbolResolver(aliases, languageProfiles);
+resolver.resolve('IProjectRepository'); // ProjectRepository
+resolver.emit('IProjectRepository', 'CSharp'); // IProjectRepository
+resolver.emit('ProjectRepository', 'TypeScript'); // ProjectRepository
+```
+
+Language profiles only affect emitted names. They do not change the canonical registry used for planning, dependency analysis, council requests, or type lookup.
diff --git a/packages/common/package.json b/packages/common/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..ed409d58f55739a097cdb6bb2867c2ac532211f4
--- /dev/null
+++ b/packages/common/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@projectos/common",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc -b",
+ "typecheck": "tsc -b --pretty false"
+ },
+ "dependencies": {
+ "zod": "^3.23.8"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/packages/common/src/config.ts b/packages/common/src/config.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a3c52c34fe9697d7debd4792961eb38b05a08189
--- /dev/null
+++ b/packages/common/src/config.ts
@@ -0,0 +1,50 @@
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { z } from 'zod';
+
+const moduleDirectory = dirname(fileURLToPath(import.meta.url));
+export const projectRoot = resolve(moduleDirectory, '../../..');
+
+export const RuntimeSchema = z.object({
+ profile: z.string().min(1),
+ snapshots: z.boolean(),
+ automaticRouting: z.boolean(),
+ consolidation: z.boolean(),
+ startupOrder: z.array(z.string().min(1))
+});
+
+export type RuntimeConfig = z.infer;
+
+export const GeneratedArtifactSchema = z.enum([
+ 'runtime.generated.json',
+ 'models.generated.json',
+ 'workspaces.generated.json',
+ 'agents.generated.json',
+ 'permissions.generated.json',
+ 'projectos.generated.json'
+]);
+export type GeneratedArtifact = z.infer;
+
+export const EnvironmentSchema = z.object({
+ PROJECTOS_PROFILE: z.string().min(1).optional(),
+ PROJECTOS_PORT: z.coerce.number().int().min(1).max(65535).optional()
+}).passthrough();
+
+export function validateRuntime(value: unknown): RuntimeConfig {
+ return RuntimeSchema.parse(value);
+}
+
+export function loadGenerated(artifact: GeneratedArtifact): T {
+ const safeName = GeneratedArtifactSchema.parse(artifact);
+ const filePath = resolve(projectRoot, 'configs', safeName);
+ return JSON.parse(readFileSync(filePath, 'utf8')) as T;
+}
+
+export function loadRuntime(): RuntimeConfig {
+ return validateRuntime(loadGenerated('runtime.generated.json'));
+}
+
+export function validateEnvironment(environment: NodeJS.ProcessEnv = process.env) {
+ return EnvironmentSchema.parse(environment);
+}
diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e6fce234d1de7b877a9b7a1f9847b9a7662f1e2b
--- /dev/null
+++ b/packages/common/src/index.ts
@@ -0,0 +1,12 @@
+export {
+ EnvironmentSchema,
+ GeneratedArtifactSchema,
+ RuntimeSchema,
+ loadGenerated,
+ loadRuntime,
+ projectRoot,
+ validateRuntime,
+ validateEnvironment
+} from './config.js';
+export type { GeneratedArtifact, RuntimeConfig } from './config.js';
+export { loadProjectCatalog } from './schema.js';
diff --git a/packages/common/src/schema.ts b/packages/common/src/schema.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1f268eb2d8f7da510be4c090876f5f85c9d9f93e
--- /dev/null
+++ b/packages/common/src/schema.ts
@@ -0,0 +1,5 @@
+import { loadGenerated } from './config.js';
+
+export function loadProjectCatalog(): T {
+ return loadGenerated('projectos.generated.json');
+}
diff --git a/packages/common/tsconfig.json b/packages/common/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..b0f4e56ed66059d864d5dce40b505d5676001e2b
--- /dev/null
+++ b/packages/common/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/council-engine/package.json b/packages/council-engine/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..380616aa14444eb86de00773eb07df97c4506621
--- /dev/null
+++ b/packages/council-engine/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@projectos/council-engine",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "exports": "./src/index.mjs"
+}
diff --git a/packages/council-engine/src/index.mjs b/packages/council-engine/src/index.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..cb8b872927412e3a20dffbcba0a4059a87f7fe39
--- /dev/null
+++ b/packages/council-engine/src/index.mjs
@@ -0,0 +1,43 @@
+export const councilTemplates = [
+ {
+ name: 'Research Council',
+ intents: ['research'],
+ agents: ['Research Agent', 'Knowledge Agent'],
+ description: 'Evidence gathering, source review, and discovery.'
+ },
+ {
+ name: 'Architecture Council',
+ intents: ['architecture'],
+ agents: ['Logic Agent', 'Dependency Agent', 'Infrastructure Agent'],
+ description: 'System boundaries, interfaces, and technical direction.'
+ },
+ {
+ name: 'Implementation Council',
+ intents: ['implementation'],
+ agents: ['Implementation Agent', 'Logic Agent', 'Tool Execution Agent'],
+ description: 'Code changes, integration, and delivery planning.'
+ },
+ {
+ name: 'Infrastructure Council',
+ intents: ['infrastructure'],
+ agents: ['Infrastructure Agent', 'Dependency Agent', 'Governance Agent'],
+ description: 'Environments, runtime, storage, and deployment.'
+ },
+ {
+ name: 'Evolution Council',
+ intents: ['evolution'],
+ agents: ['Delta Agent', 'Evolution Agent', 'Knowledge Agent'],
+ description: 'Frontier comparison and continuous improvement.'
+ },
+ {
+ name: 'Governance Council',
+ intents: ['governance'],
+ agents: ['Governance Agent', 'Logic Agent'],
+ description: 'Policy, trust, risk, and approval decisions.'
+ }
+];
+
+export function getCouncilTemplate(intent) {
+ return councilTemplates.find(template => template.intents.includes(intent))
+ ?? councilTemplates[0];
+}
diff --git a/packages/delta-fabric/README.md b/packages/delta-fabric/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..624a912d18dacdfa2a1283b627185b50e37ec40d
--- /dev/null
+++ b/packages/delta-fabric/README.md
@@ -0,0 +1,3 @@
+# Delta Fabric
+
+`DeltaService` compares declared current and target requirement sets, writes each run and gap to storage, and links open dependency findings as blockers. A run is complete only when the target has no missing values and no open blockers.
diff --git a/packages/delta-fabric/package.json b/packages/delta-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..f84395b8e3c2bffb536fe45729de71e30ba3cd78
--- /dev/null
+++ b/packages/delta-fabric/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@projectos/delta-fabric",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc -b",
+ "typecheck": "tsc -b --pretty false",
+ "test": "node --test tests/delta-comparison.test.mjs"
+ },
+ "dependencies": {
+ "@projectos/dependency-fabric": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/packages/delta-fabric/src/index.ts b/packages/delta-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..568c0366af0bcbde81651a0af941a4795f35051d
--- /dev/null
+++ b/packages/delta-fabric/src/index.ts
@@ -0,0 +1,114 @@
+import { randomUUID } from 'node:crypto';
+import type { DatabaseSync } from 'node:sqlite';
+import type { DependencyFinding, DependencyInput, DependencyService } from '@projectos/dependency-fabric';
+
+export type RequirementMap = Record;
+export type DeltaGap = {
+ id: string;
+ dimension: string;
+ current: string[];
+ target: string[];
+ missing: string[];
+ severity: 'gap' | 'blocker';
+};
+export type DeltaResult = {
+ id: string;
+ current: string;
+ target: string;
+ status: 'complete' | 'blocked';
+ gaps: DeltaGap[];
+ blockers: DependencyFinding[];
+};
+export type DeltaInput = {
+ projectId: string;
+ current: { label: string; requirements: RequirementMap };
+ target: { label: string; requirements: RequirementMap };
+ dependencies?: Array & { projectId?: string }>;
+ createdBy?: string;
+};
+
+function normalize(values: string[] | undefined): string[] {
+ return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))].sort();
+}
+
+function compareRequirements(current: RequirementMap, target: RequirementMap): Omit[] {
+ const dimensions = [...new Set([...Object.keys(current), ...Object.keys(target)])].sort();
+ return dimensions.flatMap((dimension) => {
+ const currentValues = normalize(current[dimension]);
+ const targetValues = normalize(target[dimension]);
+ const currentSet = new Set(currentValues);
+ const missing = targetValues.filter((value) => !currentSet.has(value));
+ return missing.length ? [{ dimension, current: currentValues, target: targetValues, missing, severity: 'gap' as const }] : [];
+ });
+}
+
+export class DeltaService {
+ constructor(private readonly db: DatabaseSync, private readonly dependencyService: DependencyService) {}
+
+ compare(input: DeltaInput): DeltaResult {
+ if (!input.projectId) throw new Error('A project is required for a delta run.');
+ if (!input.current.label.trim() || !input.target.label.trim()) throw new Error('Current and target labels are required.');
+ const proposedGaps = compareRequirements(input.current.requirements, input.target.requirements);
+ const runId = randomUUID();
+ this.db.exec('BEGIN IMMEDIATE');
+ try {
+ const blockers = (input.dependencies ?? []).map((dependency) => this.dependencyService.record({
+ ...dependency,
+ projectId: input.projectId
+ })).filter((finding) => finding.status === 'open');
+ const status = proposedGaps.length || blockers.length ? 'blocked' : 'complete';
+ this.db.prepare(`INSERT INTO delta_runs(delta_run_id, project_id, current_label, target_label, current_state_json,
+ target_state_json, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
+ .run(runId, input.projectId, input.current.label, input.target.label, JSON.stringify(input.current.requirements),
+ JSON.stringify(input.target.requirements), status, input.createdBy ?? null);
+ const insertGap = this.db.prepare(`INSERT INTO delta_gaps(gap_id, delta_run_id, dimension, current_values_json,
+ target_values_json, missing_values_json, severity) VALUES (?, ?, ?, ?, ?, ?, ?)`);
+ const gaps = proposedGaps.map((gap) => ({ ...gap, id: randomUUID() }));
+ for (const gap of gaps) {
+ insertGap.run(gap.id, runId, gap.dimension, JSON.stringify(gap.current), JSON.stringify(gap.target), JSON.stringify(gap.missing), gap.severity);
+ }
+ const linkDependency = this.db.prepare('INSERT INTO delta_dependencies(delta_dependency_id, delta_run_id, finding_id) VALUES (?, ?, ?)');
+ for (const blocker of blockers) linkDependency.run(randomUUID(), runId, blocker.id);
+ this.db.exec('COMMIT');
+ return { id: runId, current: input.current.label, target: input.target.label, status, gaps, blockers };
+ } catch (error) {
+ this.db.exec('ROLLBACK');
+ throw error;
+ }
+ }
+
+ get(runId: string): DeltaResult | null {
+ const row = this.db.prepare('SELECT * FROM delta_runs WHERE delta_run_id = ?').get(runId) as Record | undefined;
+ if (!row) return null;
+ const gaps = this.db.prepare('SELECT * FROM delta_gaps WHERE delta_run_id = ? ORDER BY dimension').all(runId).map((gap) => {
+ const item = gap as Record;
+ return {
+ id: String(item.gap_id), dimension: String(item.dimension),
+ current: JSON.parse(String(item.current_values_json)) as string[],
+ target: JSON.parse(String(item.target_values_json)) as string[],
+ missing: JSON.parse(String(item.missing_values_json)) as string[],
+ severity: item.severity as DeltaGap['severity']
+ };
+ });
+ const blockers = this.db.prepare(`SELECT f.finding_id FROM dependency_findings f
+ INNER JOIN delta_dependencies d ON d.finding_id = f.finding_id WHERE d.delta_run_id = ? ORDER BY f.finding_id`)
+ .all(runId).map((link) => this.dependencyService.get(String((link as { finding_id: string }).finding_id)))
+ .filter((finding): finding is DependencyFinding => finding !== null);
+ return {
+ id: String(row.delta_run_id), current: String(row.current_label), target: String(row.target_label),
+ status: row.status as DeltaResult['status'], gaps, blockers
+ };
+ }
+}
+
+export interface StateDelta { added: string[]; removed: string[]; changed: string[] }
+
+export function compareState(current: Record, target: Record): StateDelta {
+ const currentKeys = new Set(Object.keys(current));
+ const targetKeys = new Set(Object.keys(target));
+ return {
+ added: [...targetKeys].filter((key) => !currentKeys.has(key)),
+ removed: [...currentKeys].filter((key) => !targetKeys.has(key)),
+ changed: [...targetKeys].filter((key) => currentKeys.has(key) && JSON.stringify(current[key]) !== JSON.stringify(target[key]))
+ };
+}
diff --git a/packages/delta-fabric/tests/delta-comparison.test.mjs b/packages/delta-fabric/tests/delta-comparison.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..999af30fd011c2c40f686b84d3b733fc44309662
--- /dev/null
+++ b/packages/delta-fabric/tests/delta-comparison.test.mjs
@@ -0,0 +1,50 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { DatabaseSync } from 'node:sqlite';
+import { test } from 'node:test';
+import { DependencyService } from '../../dependency-fabric/dist/index.js';
+import { DeltaService } from '../dist/index.js';
+
+function setup() {
+ const db = new DatabaseSync(':memory:');
+ db.exec(readFileSync(new URL('../../storage-fabric/sqlite/schema.sql', import.meta.url), 'utf8'));
+ db.prepare("INSERT INTO projects(project_id, name) VALUES ('p1', 'Project One')").run();
+ return { db, dependencies: new DependencyService(db) };
+}
+
+test('persists target gaps and open dependency blockers', () => {
+ const { db, dependencies } = setup();
+ try {
+ const delta = new DeltaService(db, dependencies);
+ const result = delta.compare({
+ projectId: 'p1',
+ current: { label: 'current', requirements: { runtimes: ['node'] } },
+ target: { label: 'target', requirements: { runtimes: ['node', 'python'], storage: ['pgvector'] } },
+ dependencies: [{ kind: 'tool', name: 'postgres connector', description: 'Connector is not configured.' }]
+ });
+ assert.equal(result.status, 'blocked');
+ assert.equal(result.gaps.length, 2);
+ assert.equal(result.blockers.length, 1);
+ assert.equal(delta.get(result.id)?.gaps.find((gap) => gap.dimension === 'storage')?.missing[0], 'pgvector');
+ assert.equal(db.prepare('SELECT count(*) AS n FROM delta_dependencies WHERE delta_run_id = ?').get(result.id).n, 1);
+ } finally {
+ db.close();
+ }
+});
+
+test('marks a matching target complete', () => {
+ const { db, dependencies } = setup();
+ try {
+ const delta = new DeltaService(db, dependencies);
+ const result = delta.compare({
+ projectId: 'p1',
+ current: { label: 'current', requirements: { runtimes: ['node'] } },
+ target: { label: 'target', requirements: { runtimes: ['node'] } }
+ });
+ assert.equal(result.status, 'complete');
+ assert.deepEqual(result.gaps, []);
+ assert.deepEqual(result.blockers, []);
+ } finally {
+ db.close();
+ }
+});
diff --git a/packages/delta-fabric/tsconfig.json b/packages/delta-fabric/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..8d35f91dbbad8055508a340b2b151b1a0e4597d7
--- /dev/null
+++ b/packages/delta-fabric/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": ["node"]
+ },
+ "references": [
+ { "path": "../dependency-fabric" }
+ ],
+ "include": ["src"]
+}
diff --git a/packages/dependency-fabric/README.md b/packages/dependency-fabric/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cc3e4d32dae91ead2ddbd9a22ce44fdf99ad3768
--- /dev/null
+++ b/packages/dependency-fabric/README.md
@@ -0,0 +1,3 @@
+# Dependency Fabric
+
+`DependencyService` records missing models, datasets, permissions, tools, and infrastructure in the normalized `dependency_findings` table. Open findings are deduplicated by project, category, and name; resolved or waived findings retain their history.
diff --git a/packages/dependency-fabric/package.json b/packages/dependency-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..0effb1be9a1ad40166ed12161a4115429c8502a0
--- /dev/null
+++ b/packages/dependency-fabric/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@projectos/dependency-fabric",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc -b",
+ "typecheck": "tsc -b --pretty false",
+ "test": "node --test tests/dependency-findings.test.mjs"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/packages/dependency-fabric/src/index.ts b/packages/dependency-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a655ca52c42d088b17d90bf726e3f34813805e5e
--- /dev/null
+++ b/packages/dependency-fabric/src/index.ts
@@ -0,0 +1,85 @@
+import { randomUUID } from 'node:crypto';
+import type { DatabaseSync } from 'node:sqlite';
+
+export const dependencyKinds = ['model', 'dataset', 'permission', 'tool', 'infrastructure'] as const;
+export type DependencyKind = typeof dependencyKinds[number];
+export type DependencyStatus = 'open' | 'resolved' | 'waived';
+export type DependencyFinding = {
+ id: string;
+ projectId: string;
+ kind: DependencyKind;
+ name: string;
+ description: string;
+ status: DependencyStatus;
+ source: string;
+ metadata: Record;
+ detectedAt: string;
+ resolvedAt: string | null;
+};
+export type DependencyInput = {
+ projectId: string;
+ kind: DependencyKind;
+ name: string;
+ description?: string;
+ source?: string;
+ metadata?: Record;
+};
+
+function fromRow(row: Record | undefined): DependencyFinding | null {
+ if (!row) return null;
+ return {
+ id: String(row.finding_id),
+ projectId: String(row.project_id),
+ kind: row.kind as DependencyKind,
+ name: String(row.name),
+ description: String(row.description),
+ status: row.status as DependencyStatus,
+ source: String(row.source),
+ metadata: JSON.parse(String(row.metadata_json)) as Record,
+ detectedAt: String(row.detected_at),
+ resolvedAt: row.resolved_at === null ? null : String(row.resolved_at)
+ };
+}
+
+export class DependencyService {
+ constructor(private readonly db: DatabaseSync) {}
+
+ record(input: DependencyInput): DependencyFinding {
+ if (!dependencyKinds.includes(input.kind)) throw new Error(`Unsupported dependency kind: ${String(input.kind)}`);
+ const name = input.name.trim();
+ if (!name) throw new Error('Dependency name is required.');
+ const existing = this.db.prepare(`SELECT * FROM dependency_findings
+ WHERE project_id = ? AND kind = ? AND name = ? AND status = 'open'
+ ORDER BY detected_at DESC LIMIT 1`).get(input.projectId, input.kind, name);
+ if (existing) return fromRow(existing as Record)!;
+ const id = randomUUID();
+ this.db.prepare(`INSERT INTO dependency_findings(finding_id, project_id, kind, name, description, status, source, metadata_json)
+ VALUES (?, ?, ?, ?, ?, 'open', ?, ?)`)
+ .run(id, input.projectId, input.kind, name, input.description ?? '', input.source ?? 'manual', JSON.stringify(input.metadata ?? {}));
+ return this.get(id)!;
+ }
+
+ get(findingId: string): DependencyFinding | null {
+ return fromRow(this.db.prepare('SELECT * FROM dependency_findings WHERE finding_id = ?').get(findingId) as Record | undefined);
+ }
+
+ list(projectId: string, filters: { status?: DependencyStatus; kind?: DependencyKind } = {}): DependencyFinding[] {
+ const clauses = ['project_id = ?'];
+ const values: string[] = [projectId];
+ if (filters.status) { clauses.push('status = ?'); values.push(filters.status); }
+ if (filters.kind) { clauses.push('kind = ?'); values.push(filters.kind); }
+ return this.db.prepare(`SELECT * FROM dependency_findings WHERE ${clauses.join(' AND ')} ORDER BY detected_at DESC, finding_id`)
+ .all(...values)
+ .map((row) => fromRow(row as Record)!);
+ }
+
+ resolve(findingId: string, resolution: 'resolved' | 'waived' = 'resolved'): DependencyFinding {
+ if (resolution !== 'resolved' && resolution !== 'waived') throw new Error('Resolution must be resolved or waived.');
+ const result = this.db.prepare(`UPDATE dependency_findings SET status = ?, resolved_at = ?
+ WHERE finding_id = ? AND status = 'open'`).run(resolution, new Date().toISOString(), findingId);
+ const finding = this.get(findingId);
+ if (!finding) throw new Error(`Dependency finding "${findingId}" does not exist.`);
+ if (result.changes === 0 && finding.status === 'open') throw new Error(`Dependency finding "${findingId}" could not be updated.`);
+ return finding;
+ }
+}
diff --git a/packages/dependency-fabric/tests/dependency-findings.test.mjs b/packages/dependency-fabric/tests/dependency-findings.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..79efd75f0c91604fe9b1ed0c518f3cf67618bf51
--- /dev/null
+++ b/packages/dependency-fabric/tests/dependency-findings.test.mjs
@@ -0,0 +1,37 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { DatabaseSync } from 'node:sqlite';
+import { test } from 'node:test';
+import { DependencyService } from '../dist/index.js';
+
+function setup() {
+ const db = new DatabaseSync(':memory:');
+ db.exec(readFileSync(new URL('../../storage-fabric/sqlite/schema.sql', import.meta.url), 'utf8'));
+ db.prepare("INSERT INTO projects(project_id, name) VALUES ('p1', 'Project One')").run();
+ return { db, dependencies: new DependencyService(db) };
+}
+
+test('records, deduplicates, lists, and resolves missing dependencies', () => {
+ const { db, dependencies } = setup();
+ try {
+ const first = dependencies.record({ projectId: 'p1', kind: 'model', name: 'logic-model', description: 'No configured logic model.' });
+ const duplicate = dependencies.record({ projectId: 'p1', kind: 'model', name: 'logic-model' });
+ assert.equal(first.id, duplicate.id);
+ assert.equal(dependencies.list('p1', { status: 'open' }).length, 1);
+ assert.equal(dependencies.resolve(first.id).status, 'resolved');
+ const replacement = dependencies.record({ projectId: 'p1', kind: 'model', name: 'logic-model' });
+ assert.notEqual(replacement.id, first.id);
+ } finally {
+ db.close();
+ }
+});
+
+test('rejects unsupported dependency categories and empty names', () => {
+ const { db, dependencies } = setup();
+ try {
+ assert.throws(() => dependencies.record({ projectId: 'p1', kind: 'model', name: ' ' }), /name is required/);
+ assert.throws(() => dependencies.record({ projectId: 'p1', kind: 'network', name: 'egress' }), /Unsupported dependency kind/);
+ } finally {
+ db.close();
+ }
+});
diff --git a/packages/dependency-fabric/tsconfig.json b/packages/dependency-fabric/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..45939b4c2d4e76eb44080d8e3f0fe85d19fd0ddf
--- /dev/null
+++ b/packages/dependency-fabric/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": ["node"]
+ },
+ "include": ["src"]
+}
diff --git a/packages/execution-fabric/package.json b/packages/execution-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..a9ebb7947662b9fba9f09615fdb721c486dff158
--- /dev/null
+++ b/packages/execution-fabric/package.json
@@ -0,0 +1 @@
+{"name":"@projectos/execution-fabric","version":"0.1.0","private":true,"type":"module"}
diff --git a/packages/execution-fabric/src/index.ts b/packages/execution-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..15a22a60d798146e731e6619003afe99c09f9e0c
--- /dev/null
+++ b/packages/execution-fabric/src/index.ts
@@ -0,0 +1,8 @@
+export interface ExecutionGate { allowed: boolean; missing: string[] }
+
+export function checkExecutionConfiguration(configured: string[] = []): ExecutionGate {
+ const required = ['identity', 'model-provider', 'dataset-provider', 'tool-adapter', 'approval'];
+ const configuredSet = new Set(configured);
+ const missing = required.filter(item => !configuredSet.has(item));
+ return { allowed: missing.length === 0, missing };
+}
diff --git a/packages/governance-fabric/package.json b/packages/governance-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..5334c09fee2dcf5ffb12d92c5b28ca0e87bd9003
--- /dev/null
+++ b/packages/governance-fabric/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "@projectos/governance-fabric",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "exports": "./src/index.mjs",
+ "scripts": {
+ "test": "node --test tests/governance-reviews.test.mjs"
+ }
+}
diff --git a/packages/governance-fabric/src/index.mjs b/packages/governance-fabric/src/index.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..76bd69adaf5799dde5cd0872e33e810dee48cda7
--- /dev/null
+++ b/packages/governance-fabric/src/index.mjs
@@ -0,0 +1,103 @@
+import { randomUUID } from 'node:crypto';
+
+export function evaluateExecutionGate({ integrations = {}, hasApproval = false } = {}) {
+ const requiredIntegrations = ['modelProvider', 'datasetProvider', 'toolAdapter', 'identityProvider'];
+ const missing = requiredIntegrations.filter(name => integrations[name] !== true);
+ const needsApproval = !hasApproval;
+ return {
+ allowed: missing.length === 0 && !needsApproval,
+ status: missing.length || needsApproval ? 'Blocked' : 'Ready',
+ missingIntegrations: missing,
+ approvalRequired: needsApproval,
+ reason: missing.length
+ ? 'Execution is unavailable until required provider integrations are configured.'
+ : needsApproval
+ ? 'A governance approval is required before execution.'
+ : 'Governance requirements are satisfied.'
+ };
+}
+
+function mapReview(row) {
+ if (!row) return null;
+ return {
+ id: row.review_id,
+ projectId: row.project_id,
+ action: row.action,
+ resourceType: row.resource_type,
+ resourceId: row.resource_id,
+ decision: row.decision,
+ requestedBy: row.requested_by,
+ requestedAt: row.requested_at,
+ reviewedBy: row.reviewed_by,
+ reviewedAt: row.reviewed_at,
+ reason: row.reason,
+ metadata: JSON.parse(row.metadata_json)
+ };
+}
+
+export class GovernanceService {
+ constructor(db) { this.db = db; }
+
+ request(input) {
+ for (const field of ['projectId', 'action', 'resourceType', 'resourceId']) {
+ if (!String(input[field] ?? '').trim()) throw new Error(`Governance review ${field} is required.`);
+ }
+ const pending = this.db.prepare(`SELECT * FROM governance_reviews WHERE project_id = ? AND action = ?
+ AND resource_type = ? AND resource_id = ? AND decision = 'pending' ORDER BY requested_at DESC LIMIT 1`)
+ .get(input.projectId, input.action, input.resourceType, input.resourceId);
+ if (pending) return mapReview(pending);
+ const id = randomUUID();
+ this.db.prepare(`INSERT INTO governance_reviews(review_id, project_id, action, resource_type, resource_id,
+ decision, requested_by, reason, metadata_json) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`)
+ .run(id, input.projectId, input.action, input.resourceType, input.resourceId, input.requestedBy ?? null,
+ input.reason ?? '', JSON.stringify(input.metadata ?? {}));
+ return this.get(id);
+ }
+
+ review({ action, projectId, frontierItem, requestedBy } = {}) {
+ const resourceId = String(frontierItem?.id ?? '');
+ if (!String(action ?? '').trim() || !String(projectId ?? '').trim() || !resourceId.trim()) {
+ throw new Error('Governance review requires an action, project, and resource identifier.');
+ }
+ const latest = this.db.prepare(`SELECT * FROM governance_reviews WHERE project_id = ? AND action = ?
+ AND resource_type = 'frontier' AND resource_id = ? ORDER BY requested_at DESC LIMIT 1`)
+ .get(projectId, action, resourceId);
+ if (latest?.decision === 'approved') {
+ return { approved: true, decision: 'approved', approvalId: latest.review_id, reviewId: latest.review_id };
+ }
+ if (latest?.decision === 'pending') {
+ const reason = latest.reason || (latest.decision === 'pending' ? 'Governance approval is pending.' : 'The latest governance review rejected this action.');
+ return { approved: false, decision: latest.decision, reviewId: latest.review_id, reason };
+ }
+ const pending = this.request({
+ projectId, action, resourceType: 'frontier', resourceId, requestedBy,
+ reason: 'Frontier promotion requires an explicit governance decision.'
+ });
+ return { approved: false, decision: 'pending', reviewId: pending.id, reason: 'Governance approval is required.' };
+ }
+
+ decide(reviewId, input) {
+ if (!['approved', 'rejected'].includes(input.decision)) throw new Error('Governance decision must be approved or rejected.');
+ if (!input.reviewedBy?.trim()) throw new Error('A reviewer identity is required.');
+ const result = this.db.prepare(`UPDATE governance_reviews SET decision = ?, reviewed_by = ?, reviewed_at = ?, reason = ?
+ WHERE review_id = ? AND decision = 'pending'`)
+ .run(input.decision, input.reviewedBy, new Date().toISOString(), input.reason ?? '', reviewId);
+ if (!result.changes) {
+ const current = this.get(reviewId);
+ if (!current) throw new Error(`Governance review "${reviewId}" does not exist.`);
+ throw new Error(`Governance review "${reviewId}" is already ${current.decision}.`);
+ }
+ return this.get(reviewId);
+ }
+
+ get(reviewId) {
+ return mapReview(this.db.prepare('SELECT * FROM governance_reviews WHERE review_id = ?').get(reviewId));
+ }
+
+ list(projectId, decision) {
+ const rows = decision
+ ? this.db.prepare('SELECT * FROM governance_reviews WHERE project_id = ? AND decision = ? ORDER BY requested_at DESC').all(projectId, decision)
+ : this.db.prepare('SELECT * FROM governance_reviews WHERE project_id = ? ORDER BY requested_at DESC').all(projectId);
+ return rows.map(mapReview);
+ }
+}
diff --git a/packages/governance-fabric/tests/governance-reviews.test.mjs b/packages/governance-fabric/tests/governance-reviews.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..ea84fc2226c403b8fcad28c3880fd34338af9888
--- /dev/null
+++ b/packages/governance-fabric/tests/governance-reviews.test.mjs
@@ -0,0 +1,56 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { DatabaseSync } from 'node:sqlite';
+import { test } from 'node:test';
+import { GovernanceService } from '../src/index.mjs';
+
+function setup() {
+ const db = new DatabaseSync(':memory:');
+ db.exec(readFileSync(new URL('../../storage-fabric/sqlite/schema.sql', import.meta.url), 'utf8'));
+ db.prepare("INSERT INTO projects(project_id, name) VALUES ('p1', 'Project One')").run();
+ return { db, governance: new GovernanceService(db) };
+}
+
+test('creates pending review and returns approval only after an explicit decision', () => {
+ const { db, governance } = setup();
+ try {
+ const frontierItem = { id: 'frontier-1' };
+ const first = governance.review({ action: 'frontier.promote', projectId: 'p1', frontierItem, requestedBy: 'agent-1' });
+ assert.equal(first.approved, false);
+ assert.ok(first.reviewId);
+ governance.decide(first.reviewId, { decision: 'approved', reviewedBy: 'owner-1', reason: 'Evidence reviewed.' });
+ const approved = governance.review({ action: 'frontier.promote', projectId: 'p1', frontierItem });
+ assert.equal(approved.approved, true);
+ assert.equal(approved.approvalId, first.reviewId);
+ } finally {
+ db.close();
+ }
+});
+
+test('rejects unknown, duplicate, and unattributed governance decisions', () => {
+ const { db, governance } = setup();
+ try {
+ assert.throws(() => governance.decide('missing', { decision: 'approved', reviewedBy: 'owner' }), /does not exist/);
+ const review = governance.request({ projectId: 'p1', action: 'frontier.promote', resourceType: 'frontier', resourceId: 'f2' });
+ assert.throws(() => governance.decide(review.id, { decision: 'approved', reviewedBy: '' }), /reviewer identity/);
+ governance.decide(review.id, { decision: 'rejected', reviewedBy: 'owner', reason: 'Insufficient evidence.' });
+ assert.throws(() => governance.decide(review.id, { decision: 'approved', reviewedBy: 'owner' }), /already rejected/);
+ } finally {
+ db.close();
+ }
+});
+
+test('a rejected action can be resubmitted as a new auditable review', () => {
+ const { db, governance } = setup();
+ try {
+ const request = { action: 'frontier.promote', projectId: 'p1', frontierItem: { id: 'frontier-resubmit' } };
+ const first = governance.review(request);
+ governance.decide(first.reviewId, { decision: 'rejected', reviewedBy: 'owner-1', reason: 'Add more evidence.' });
+ const second = governance.review(request);
+ assert.equal(second.approved, false);
+ assert.notEqual(second.reviewId, first.reviewId);
+ assert.equal(governance.list('p1').length, 2);
+ } finally {
+ db.close();
+ }
+});
diff --git a/packages/identity-fabric/package.json b/packages/identity-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..bf34ea68cef934ba00d95348ee0fea26a3740235
--- /dev/null
+++ b/packages/identity-fabric/package.json
@@ -0,0 +1 @@
+{"name":"@projectos/identity-fabric","version":"0.1.0","private":true,"type":"module"}
diff --git a/packages/identity-fabric/src/index.ts b/packages/identity-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ca171075a9cbb8cd68aec48da7ef8541fdb94637
--- /dev/null
+++ b/packages/identity-fabric/src/index.ts
@@ -0,0 +1,5 @@
+export interface IdentityContext { principal: string; roles: string[]; source: 'local-placeholder' }
+
+export function resolveIdentity(principal: string, roles: string[] = []): IdentityContext {
+ return { principal, roles: [...new Set(roles)], source: 'local-placeholder' };
+}
diff --git a/packages/knowledge-fabric/README.md b/packages/knowledge-fabric/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..6a8782eb99928076a2ce341e87062be2823fa990
--- /dev/null
+++ b/packages/knowledge-fabric/README.md
@@ -0,0 +1,3 @@
+# Knowledge Fabric
+
+The lifecycle services create frontier records, validate promotions through Logic and Governance, write a versioned canon entry, and capture a post-promotion snapshot in one database transaction. Consolidation prepares a frontier candidate from active canon sources; it does not silently promote generated text. Snapshot and archive services use checksummed storage-fabric records.
diff --git a/packages/knowledge-fabric/package.json b/packages/knowledge-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..1c71e14b40792c6a293f77cbbe80adb1d11b16da
--- /dev/null
+++ b/packages/knowledge-fabric/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@projectos/knowledge-fabric",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc -b",
+ "typecheck": "tsc -b --pretty false",
+ "test": "node --test tests/knowledge-lifecycle.test.mjs"
+ },
+ "dependencies": {
+ "@projectos/storage-fabric": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/packages/knowledge-fabric/src/ArchiveService.ts b/packages/knowledge-fabric/src/ArchiveService.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1ab5e315d16b51ab987d622b312cd44af3c2f5a4
--- /dev/null
+++ b/packages/knowledge-fabric/src/ArchiveService.ts
@@ -0,0 +1,51 @@
+import { createHash, randomUUID } from 'node:crypto';
+import type { DatabaseSync } from 'node:sqlite';
+
+export type ArchiveInput = {
+ projectId?: string | null;
+ resourceType: string;
+ resourceId: string;
+ snapshotId?: string | null;
+ payload: Record;
+ reason?: string;
+ archivedBy?: string;
+ retentionUntil?: string | null;
+};
+
+export class ArchiveService {
+ constructor(private readonly db: DatabaseSync) {}
+
+ archive(input: ArchiveInput) {
+ const payloadJson = JSON.stringify(input.payload);
+ const checksum = createHash('sha256').update(payloadJson).digest('hex');
+ const archiveId = randomUUID();
+ this.db.prepare(`INSERT INTO archive_records(archive_id, project_id, resource_type, resource_id, snapshot_id,
+ payload_json, checksum, archive_reason, archived_by, retention_until, metadata_json)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '{}')`)
+ .run(archiveId, input.projectId ?? null, input.resourceType, input.resourceId, input.snapshotId ?? null,
+ payloadJson, checksum, input.reason ?? '', input.archivedBy ?? null, input.retentionUntil ?? null);
+ return this.get(archiveId);
+ }
+
+ get(archiveId: string) {
+ const row = this.db.prepare('SELECT * FROM archive_records WHERE archive_id = ?').get(archiveId) as Record | undefined;
+ if (!row) return null;
+ const payloadJson = String(row.payload_json);
+ const checksum = createHash('sha256').update(payloadJson).digest('hex');
+ if (checksum !== row.checksum) throw new Error(`Archived resource "${archiveId}" failed checksum validation.`);
+ return {
+ id: String(row.archive_id), projectId: row.project_id === null ? null : String(row.project_id),
+ resourceType: String(row.resource_type), resourceId: String(row.resource_id),
+ snapshotId: row.snapshot_id === null ? null : String(row.snapshot_id), payload: JSON.parse(payloadJson) as Record,
+ checksum, reason: String(row.archive_reason), archivedAt: String(row.archived_at),
+ retentionUntil: row.retention_until === null ? null : String(row.retention_until)
+ };
+ }
+
+ restore(archiveId: string) {
+ const record = this.get(archiveId);
+ if (!record) throw new Error(`Archive record "${archiveId}" does not exist.`);
+ this.db.prepare('UPDATE archive_records SET restored_at = ? WHERE archive_id = ?').run(new Date().toISOString(), archiveId);
+ return record.payload;
+ }
+}
diff --git a/packages/knowledge-fabric/src/CanonService.ts b/packages/knowledge-fabric/src/CanonService.ts
new file mode 100644
index 0000000000000000000000000000000000000000..108cbe2d93b0f4f3d51f1d98b1ca87457f7c372b
--- /dev/null
+++ b/packages/knowledge-fabric/src/CanonService.ts
@@ -0,0 +1,9 @@
+import { CanonRepository, type CanonEntryInput } from '@projectos/storage-fabric/sqlite/repositories';
+import type { DatabaseSync } from 'node:sqlite';
+
+export class CanonService {
+ readonly repository: CanonRepository;
+ constructor(db: DatabaseSync, repository = new CanonRepository(db)) { this.repository = repository; }
+ create(entry: CanonEntryInput) { return this.repository.create(entry); }
+ get(entryId: string) { return this.repository.get(entryId); }
+}
diff --git a/packages/knowledge-fabric/src/ConsolidationService.ts b/packages/knowledge-fabric/src/ConsolidationService.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3c3ce047b92b06279faf9e64b6382880e0c0c816
--- /dev/null
+++ b/packages/knowledge-fabric/src/ConsolidationService.ts
@@ -0,0 +1,42 @@
+import type { DatabaseSync } from 'node:sqlite';
+import { CanonService } from './CanonService.js';
+import { FrontierService } from './FrontierService.js';
+
+export type ConsolidationInput = {
+ projectId: string;
+ title: string;
+ body: string;
+ sourceEntryIds: string[];
+ createdBy?: string;
+};
+
+export class ConsolidationService {
+ private readonly canon: CanonService;
+ private readonly frontier: FrontierService;
+
+ constructor(db: DatabaseSync) {
+ this.canon = new CanonService(db);
+ this.frontier = new FrontierService(db);
+ }
+
+ prepare(input: ConsolidationInput) {
+ const title = input.title.trim();
+ const body = input.body.trim();
+ const sourceEntryIds = [...new Set(input.sourceEntryIds)];
+ if (!title || !body) throw new Error('A consolidation needs a title and reviewed content.');
+ if (!sourceEntryIds.length) throw new Error('A consolidation needs at least one source canon entry.');
+ const sources = sourceEntryIds.map((id) => this.canon.get(id));
+ if (sources.some((entry) => !entry || entry.status !== 'active' || entry.projectId !== input.projectId)) {
+ throw new Error('Every consolidation source must be an active canon entry in the same project.');
+ }
+ return this.frontier.create({
+ projectId: input.projectId,
+ domain: 'knowledge-consolidation',
+ itemType: 'research',
+ title,
+ description: body,
+ rationale: 'Prepared from reviewed canon sources; pending logic and governance review.',
+ metadata: { sourceEntryIds, createdBy: input.createdBy ?? null }
+ });
+ }
+}
diff --git a/packages/knowledge-fabric/src/FrontierService.ts b/packages/knowledge-fabric/src/FrontierService.ts
new file mode 100644
index 0000000000000000000000000000000000000000..2ee3689b12afffd838c3d3e8e03440880ffd3697
--- /dev/null
+++ b/packages/knowledge-fabric/src/FrontierService.ts
@@ -0,0 +1,9 @@
+import { FrontierRepository, type FrontierItemInput } from '@projectos/storage-fabric/sqlite/repositories';
+import type { DatabaseSync } from 'node:sqlite';
+
+export class FrontierService {
+ readonly repository: FrontierRepository;
+ constructor(db: DatabaseSync, repository = new FrontierRepository(db)) { this.repository = repository; }
+ create(item: FrontierItemInput) { return this.repository.create(item); }
+ get(frontierId: string) { return this.repository.get(frontierId); }
+}
diff --git a/packages/knowledge-fabric/src/PromotionService.ts b/packages/knowledge-fabric/src/PromotionService.ts
new file mode 100644
index 0000000000000000000000000000000000000000..73cedaaf15402abca6076c0b4aa633d9773f0ab3
--- /dev/null
+++ b/packages/knowledge-fabric/src/PromotionService.ts
@@ -0,0 +1,63 @@
+import { FrontierRepository, SnapshotRepository } from '@projectos/storage-fabric/sqlite/repositories';
+import type { DatabaseSync } from 'node:sqlite';
+
+export type LogicPromotionResult = boolean | { valid: boolean; issues?: string[] };
+export type GovernancePromotionResult = boolean | { approved: boolean; decision?: string; reason?: string; approvalId?: string; reviewId?: string };
+export type PromotionDependencies = {
+ logic: { validatePromotion(input: { frontierItem: Record; projectId: string }): Promise | LogicPromotionResult };
+ governance: { review(input: { action: 'frontier.promote'; frontierItem: Record; projectId: string; requestedBy?: string }): Promise | GovernancePromotionResult };
+};
+
+export class PromotionService {
+ private readonly frontier: FrontierRepository;
+ private readonly snapshots: SnapshotRepository;
+
+ constructor(private readonly db: DatabaseSync, private readonly dependencies: PromotionDependencies) {
+ this.frontier = new FrontierRepository(db);
+ this.snapshots = new SnapshotRepository(db);
+ }
+
+ async promote(frontierId: string, options: { requestedBy?: string; changeSummary?: string } = {}) {
+ const frontierItem = this.frontier.get(frontierId) as unknown as Record | null;
+ if (!frontierItem) throw new Error(`Frontier item "${frontierId}" does not exist.`);
+ const projectId = String(frontierItem.projectId ?? '');
+ if (!projectId) throw new Error('Frontier promotion requires a project-owned item.');
+ const logic = await this.dependencies.logic.validatePromotion({ frontierItem, projectId });
+ const logicValid = typeof logic === 'boolean' ? logic : logic.valid;
+ if (!logicValid) {
+ const issues = typeof logic === 'boolean' ? [] : logic.issues ?? [];
+ throw new Error(`Logic validation rejected promotion${issues.length ? `: ${issues.join('; ')}` : '.'}`);
+ }
+ const governance = await this.dependencies.governance.review({
+ action: 'frontier.promote', frontierItem, projectId, requestedBy: options.requestedBy
+ });
+ const approved = typeof governance === 'boolean' ? governance : governance.approved;
+ if (!approved) {
+ const reason = typeof governance === 'boolean' ? '' : governance.reason ?? governance.decision ?? '';
+ const reviewId = typeof governance === 'boolean' ? '' : governance.reviewId ?? '';
+ throw new Error(`Governance did not approve promotion${reason ? `: ${reason}` : '.'}${reviewId ? ` Review ID: ${reviewId}.` : ''}`);
+ }
+
+ this.db.exec('BEGIN IMMEDIATE');
+ try {
+ const changeSummary = options.changeSummary ?? 'Validated and approved frontier promotion';
+ const canonEntry = this.frontier.promote(frontierId, { changeSummary, createdBy: options.requestedBy, withinTransaction: true });
+ const snapshot = this.snapshots.create(projectId, {
+ type: 'canon',
+ label: `After canon promotion: ${String(frontierItem.title)}`,
+ createdBy: options.requestedBy,
+ metadata: {
+ sourceFrontierId: frontierId,
+ governanceApprovalId: typeof governance === 'boolean' ? null : governance.approvalId ?? null,
+ changeSummary
+ },
+ withinTransaction: true
+ });
+ this.db.exec('COMMIT');
+ return { frontierId, canonEntry, snapshot };
+ } catch (error) {
+ this.db.exec('ROLLBACK');
+ throw error;
+ }
+ }
+}
diff --git a/packages/knowledge-fabric/src/SnapshotService.ts b/packages/knowledge-fabric/src/SnapshotService.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6887d89e754440b1fd3f92cc2a62d352d412ffd2
--- /dev/null
+++ b/packages/knowledge-fabric/src/SnapshotService.ts
@@ -0,0 +1,10 @@
+import { SnapshotRepository } from '@projectos/storage-fabric/sqlite/repositories';
+import type { DatabaseSync } from 'node:sqlite';
+
+export class SnapshotService {
+ readonly repository: SnapshotRepository;
+ constructor(db: DatabaseSync, repository = new SnapshotRepository(db)) { this.repository = repository; }
+ capture(projectId: string, options: Parameters[1] = {}) { return this.repository.create(projectId, options); }
+ get(snapshotId: string) { return this.repository.get(snapshotId); }
+ restore(snapshotId: string) { return this.repository.restore(snapshotId); }
+}
diff --git a/packages/knowledge-fabric/src/index.ts b/packages/knowledge-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5f2931f6d11a9e7a54fa8cd346a6ebd2c44228c2
--- /dev/null
+++ b/packages/knowledge-fabric/src/index.ts
@@ -0,0 +1,17 @@
+import { randomUUID } from 'node:crypto';
+export { CanonService } from './CanonService.js';
+export { FrontierService } from './FrontierService.js';
+export { SnapshotService } from './SnapshotService.js';
+export { ArchiveService, type ArchiveInput } from './ArchiveService.js';
+export { PromotionService, type GovernancePromotionResult, type LogicPromotionResult, type PromotionDependencies } from './PromotionService.js';
+export { ConsolidationService, type ConsolidationInput } from './ConsolidationService.js';
+
+export interface KnowledgeRecord { id: string; project: string; kind: string; title: string; created: string; payload: unknown }
+
+export function createKnowledgeRecord(input: Omit): KnowledgeRecord {
+ return { ...input, created: new Date().toISOString() };
+}
+
+export function createProjectSnapshot(project: string, payload: unknown): KnowledgeRecord {
+ return createKnowledgeRecord({ id: randomUUID(), project, kind: 'snapshot', title: `${project} snapshot`, payload });
+}
diff --git a/packages/knowledge-fabric/tests/knowledge-lifecycle.test.mjs b/packages/knowledge-fabric/tests/knowledge-lifecycle.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..a9220624743c7ebea2d9cb18aa21ee286faec73c
--- /dev/null
+++ b/packages/knowledge-fabric/tests/knowledge-lifecycle.test.mjs
@@ -0,0 +1,128 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { DatabaseSync } from 'node:sqlite';
+import { test } from 'node:test';
+import { GovernanceService } from '../../governance-fabric/src/index.mjs';
+import { validateFrontierPromotion } from '../../logic-fabric/dist/index.js';
+import { ArchiveService, CanonService, ConsolidationService, FrontierService, PromotionService, SnapshotService } from '../dist/index.js';
+
+function setup() {
+ const db = new DatabaseSync(':memory:');
+ db.exec(readFileSync(new URL('../../storage-fabric/sqlite/schema.sql', import.meta.url), 'utf8'));
+ db.prepare("INSERT INTO projects(project_id, name) VALUES ('p1', 'Project One')").run();
+ return db;
+}
+
+test('promotion requires both logic and governance and commits canon plus snapshot atomically', async () => {
+ const db = setup();
+ try {
+ const frontier = new FrontierService(db);
+ const item = frontier.create({ id: 'f1', projectId: 'p1', title: 'Reviewed practice', description: 'Use the reviewed practice.' });
+ let governanceCalled = false;
+ const promotion = new PromotionService(db, {
+ logic: { validatePromotion: ({ frontierItem }) => ({ valid: Boolean(frontierItem.title) }) },
+ governance: { review: () => { governanceCalled = true; return { approved: true, approvalId: 'approval-1' }; } }
+ });
+ const result = await promotion.promote(item.id, { requestedBy: 'reviewer-1' });
+ assert.equal(governanceCalled, true);
+ assert.equal(result.canonEntry.entry_id, item.id);
+ assert.equal(frontier.get(item.id).status, 'adopted');
+ assert.equal(new SnapshotService(db).get(result.snapshot.id).state.canonEntries[0].entry_id, item.id);
+ } finally {
+ db.close();
+ }
+});
+
+test('rejected governance leaves frontier unchanged and creates no canon entry', async () => {
+ const db = setup();
+ try {
+ const frontier = new FrontierService(db);
+ const item = frontier.create({ id: 'f-reject', projectId: 'p1', title: 'Unapproved practice' });
+ const promotion = new PromotionService(db, {
+ logic: { validatePromotion: () => true },
+ governance: { review: () => ({ approved: false, reason: 'approval required' }) }
+ });
+ await assert.rejects(promotion.promote(item.id), /approval required/);
+ assert.equal(frontier.get(item.id).status, 'candidate');
+ assert.equal(new CanonService(db).get(item.id), null);
+ } finally {
+ db.close();
+ }
+});
+
+test('Logic validation and a persisted Governance approval gate canon promotion', async () => {
+ const db = setup();
+ try {
+ const frontier = new FrontierService(db);
+ const item = frontier.create({ id: 'f-governed', projectId: 'p1', title: 'Governed practice', description: 'Supported by reviewed evidence.' });
+ const governance = new GovernanceService(db);
+ const promotion = new PromotionService(db, {
+ logic: { validatePromotion: ({ frontierItem, projectId }) => validateFrontierPromotion(frontierItem, projectId) },
+ governance
+ });
+ let reviewId;
+ await assert.rejects(promotion.promote(item.id), /Review ID:/);
+ reviewId = governance.list('p1', 'pending')[0].id;
+ governance.decide(reviewId, { decision: 'approved', reviewedBy: 'project-owner', reason: 'Evidence and impact reviewed.' });
+ const result = await promotion.promote(item.id, { requestedBy: 'operations-agent' });
+ const snapshots = new SnapshotService(db);
+ const captured = snapshots.get(result.snapshot.id);
+ assert.equal(result.canonEntry.entry_id, item.id);
+ assert.equal(captured.state.governanceReviews[0].decision, 'approved');
+ db.prepare('DELETE FROM governance_reviews').run();
+ snapshots.restore(result.snapshot.id);
+ assert.equal(governance.get(reviewId).decision, 'approved');
+ } finally {
+ db.close();
+ }
+});
+
+test('promotion rolls back canon and Frontier changes when snapshot capture fails', async () => {
+ const db = setup();
+ try {
+ const frontier = new FrontierService(db);
+ const item = frontier.create({ id: 'f-snapshot-fail', projectId: 'p1', title: 'Atomic practice', description: 'A complete practice.' });
+ const promotion = new PromotionService(db, {
+ logic: { validatePromotion: () => true },
+ governance: { review: () => ({ approved: true, approvalId: 'approved' }) }
+ });
+ db.exec(`CREATE TRIGGER fail_snapshot_insert BEFORE INSERT ON snapshots BEGIN SELECT RAISE(ABORT, 'snapshot write failed'); END;`);
+ await assert.rejects(promotion.promote(item.id), /snapshot write failed/);
+ assert.equal(frontier.get(item.id).status, 'candidate');
+ assert.equal(new CanonService(db).get(item.id), null);
+ assert.equal(db.prepare("SELECT count(*) AS n FROM project_events WHERE event_type = 'frontier.promoted'").get().n, 0);
+ } finally {
+ db.close();
+ }
+});
+
+test('consolidation prepares a frontier candidate tied to same-project active canon', () => {
+ const db = setup();
+ try {
+ const canon = new CanonService(db);
+ const source = canon.create({ id: 'c1', projectId: 'p1', title: 'Source principle', body: 'Keep provenance.', status: 'active' });
+ const candidate = new ConsolidationService(db).prepare({
+ projectId: 'p1', title: 'Consolidated principle', body: 'Preserve evidence and provenance.', sourceEntryIds: [source.id]
+ });
+ assert.equal(candidate.status, 'candidate');
+ assert.deepEqual(candidate.metadata.sourceEntryIds, [source.id]);
+ assert.throws(() => new ConsolidationService(db).prepare({
+ projectId: 'p1', title: 'Bad consolidation', body: 'No source', sourceEntryIds: ['missing']
+ }), /active canon entry/);
+ } finally {
+ db.close();
+ }
+});
+
+test('archives and restores checksummed payloads', () => {
+ const db = setup();
+ try {
+ const archives = new ArchiveService(db);
+ const record = archives.archive({ projectId: 'p1', resourceType: 'document', resourceId: 'doc-1', payload: { text: 'retained' } });
+ assert.deepEqual(archives.restore(record.id), { text: 'retained' });
+ db.prepare('UPDATE archive_records SET payload_json = ? WHERE archive_id = ?').run('{"text":"changed"}', record.id);
+ assert.throws(() => archives.get(record.id), /checksum validation/);
+ } finally {
+ db.close();
+ }
+});
diff --git a/packages/knowledge-fabric/tsconfig.json b/packages/knowledge-fabric/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..1d569b0d4a788ec99fe7fae251176294b82fea84
--- /dev/null
+++ b/packages/knowledge-fabric/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": ["node"]
+ },
+ "references": [
+ { "path": "../storage-fabric" }
+ ],
+ "include": ["src"]
+}
diff --git a/packages/logic-fabric/package.json b/packages/logic-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..ec1fc1a48130bde4a635a7747c0ccf8122e18a8d
--- /dev/null
+++ b/packages/logic-fabric/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@projectos/logic-fabric",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc -b",
+ "typecheck": "tsc -b --pretty false",
+ "test": "node --test tests/promotion-validation.test.mjs"
+ },
+ "dependencies": {
+ "@projectos/schema-engine": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/packages/logic-fabric/src/index.ts b/packages/logic-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d61d8a5e78015f7cc020d72911ec91026edc31aa
--- /dev/null
+++ b/packages/logic-fabric/src/index.ts
@@ -0,0 +1,40 @@
+import { SymbolResolver, type LanguageProfileRegistry, type SymbolAliasRegistry } from '@projectos/schema-engine';
+
+export interface PlanCheck { valid: boolean; issues: string[] }
+export interface PromotionCheck { valid: boolean; issues: string[] }
+
+export function validateFrontierPromotion(
+ item: { id?: string; projectId?: string | null; title?: string; description?: string; rationale?: string; status?: string },
+ projectId: string
+): PromotionCheck {
+ const issues: string[] = [];
+ if (!item.id?.trim()) issues.push('A frontier record identifier is required.');
+ if (!projectId.trim() || item.projectId !== projectId) issues.push('The frontier record must belong to the target project.');
+ if (!item.title?.trim()) issues.push('A titled frontier record is required.');
+ if (!(item.description?.trim() || item.rationale?.trim())) issues.push('Promotion needs a description or rationale.');
+ if (item.status !== 'candidate' && item.status !== 'tracking') issues.push('Only candidate or tracking frontier records can be promoted.');
+ return { valid: issues.length === 0, issues };
+}
+
+export function validatePlanDraft(plan: { question?: string; council?: string; agents?: string[] }): PlanCheck {
+ const issues: string[] = [];
+ if (!plan.question?.trim()) issues.push('A question is required.');
+ if (!plan.council?.trim()) issues.push('A council template must be selected.');
+ if (!plan.agents?.length) issues.push('At least one specialist agent must be assigned.');
+ return { valid: issues.length === 0, issues };
+}
+
+export function resolveSymbols(names: string[], registry: SymbolAliasRegistry): string[] {
+ const resolver = new SymbolResolver(registry);
+ return names.map((name) => resolver.resolve(name));
+}
+
+export function emitSymbols(
+ names: string[],
+ registry: SymbolAliasRegistry,
+ profiles: LanguageProfileRegistry,
+ profileName: string
+): string[] {
+ const resolver = new SymbolResolver(registry, profiles);
+ return names.map((name) => resolver.emit(name, profileName));
+}
diff --git a/packages/logic-fabric/tests/promotion-validation.test.mjs b/packages/logic-fabric/tests/promotion-validation.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..6242b02f17075b7d2b55cd0ff70ab4012335b424
--- /dev/null
+++ b/packages/logic-fabric/tests/promotion-validation.test.mjs
@@ -0,0 +1,20 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { validateFrontierPromotion } from '../dist/index.js';
+
+test('accepts only complete, project-owned frontier candidates', () => {
+ const valid = validateFrontierPromotion({
+ id: 'frontier-1',
+ projectId: 'project-1',
+ title: 'Reviewed practice',
+ description: 'A practice supported by evidence.',
+ status: 'candidate'
+ }, 'project-1');
+ assert.deepEqual(valid, { valid: true, issues: [] });
+});
+
+test('reports missing ownership, evidence, title, and promotable status', () => {
+ const invalid = validateFrontierPromotion({ id: 'frontier-2', projectId: 'other-project', status: 'rejected' }, 'project-1');
+ assert.equal(invalid.valid, false);
+ assert.equal(invalid.issues.length, 4);
+});
diff --git a/packages/logic-fabric/tsconfig.json b/packages/logic-fabric/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..c2c555b592a8bcc48b04fbabe52d9c117405266f
--- /dev/null
+++ b/packages/logic-fabric/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": ["node"]
+ },
+ "include": ["src"],
+ "references": [
+ { "path": "../schema-engine" }
+ ]
+}
diff --git a/packages/mcp-fabric/package.json b/packages/mcp-fabric/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..b38259c0b04532fc6d4e042f37eba2d3c896011d
--- /dev/null
+++ b/packages/mcp-fabric/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@projectos/mcp-fabric",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "dev": "tsx src/cli.ts",
+ "profiles": "tsx src/cli.ts profiles",
+ "check": "tsx src/cli.ts check",
+ "connect": "tsx src/cli.ts connect",
+ "build": "tsc -b",
+ "typecheck": "tsc -b --pretty false"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "tsx": "^4.19.1",
+ "typescript": "^5.6.3"
+ }
+}
diff --git a/packages/mcp-fabric/src/adapters.ts b/packages/mcp-fabric/src/adapters.ts
new file mode 100644
index 0000000000000000000000000000000000000000..44a5d8c6159aa01cb8b0531a71b1b831e226c58a
--- /dev/null
+++ b/packages/mcp-fabric/src/adapters.ts
@@ -0,0 +1,188 @@
+import { mkdir } from 'node:fs/promises';
+import { existsSync, statSync } from 'node:fs';
+import { delimiter, dirname, join, resolve } from 'node:path';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+export type AdapterName = 'filesystem' | 'git' | 'github' | 'postgres' | 'fetch' | 'memory';
+export type ServerDefinition = {
+ name: string;
+ adapter: string;
+ trust: string;
+ enabled: boolean;
+ authMode: 'none' | 'oauth' | 'environment' | 'keyring';
+ credentialRef?: string;
+ accessMode: 'read-only' | 'read-write';
+};
+
+export type AdapterDescriptor = {
+ name: AdapterName;
+ title: string;
+ description: string;
+ source: string;
+ transport: 'stdio';
+ requires: string[];
+};
+
+export const adapterCatalog: Record = {
+ filesystem: {
+ name: 'filesystem', title: 'Model Context Protocol filesystem server',
+ description: 'Local file tools limited to the ProjectOS workspace root.',
+ source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem', transport: 'stdio', requires: ['Node.js 24.22.1+ or 26.12.1+', 'npm CLI']
+ },
+ git: {
+ name: 'git', title: 'Model Context Protocol Git server',
+ description: 'Repository-scoped Git inspection and operations; requires PROJECTOS_GIT_ROOT.',
+ source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/git', transport: 'stdio', requires: ['uvx', 'PROJECTOS_GIT_ROOT']
+ },
+ github: {
+ name: 'github', title: 'GitHub official MCP server',
+ description: 'GitHub API tools; browser OAuth is the default and read profiles enable server read-only mode.',
+ source: 'https://github.com/github/github-mcp-server', transport: 'stdio', requires: ['Docker', 'browser sign-in on first use']
+ },
+ postgres: {
+ name: 'postgres', title: 'Microsoft PostgreSQL MCP server',
+ description: 'PostgreSQL tools using a saved OS keyring connection profile.',
+ source: 'https://github.com/microsoft/postgres-mcp', transport: 'stdio', requires: ['Node.js', 'npm CLI', 'OS keyring connection profile']
+ },
+ fetch: {
+ name: 'fetch', title: 'Model Context Protocol fetch server',
+ description: 'Fetches public web pages and extracts readable content.',
+ source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/fetch', transport: 'stdio', requires: ['uvx']
+ },
+ memory: {
+ name: 'memory', title: 'Model Context Protocol memory server',
+ description: 'Local persistent knowledge graph stored in ProjectOS data/.',
+ source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/memory', transport: 'stdio', requires: ['Node.js 24.22.1+ or 26.12.1+', 'npm CLI']
+ }
+};
+
+export type LaunchSpec = { command: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv };
+
+const sourceDirectory = dirname(fileURLToPath(import.meta.url));
+export const projectRoot = resolve(sourceDirectory, '../../..');
+const npxCli = findNpxCli();
+
+function findNpxCli(): string | undefined {
+ const candidates = [
+ process.env.PROJECTOS_NPX_CLI,
+ resolve(dirname(process.execPath), '../lib/node_modules/npm/bin/npx-cli.js'),
+ resolve(dirname(process.execPath), '../node_modules/npm/bin/npx-cli.js'),
+ 'C:/Program Files/nodejs/node_modules/npm/bin/npx-cli.js',
+ ...String(process.env.PATH ?? '').split(delimiter).flatMap((part) => [
+ join(part, 'node_modules/npm/bin/npx-cli.js'),
+ join(dirname(part), 'node_modules/npm/bin/npx-cli.js')
+ ])
+ ].filter((value): value is string => Boolean(value));
+ return candidates.find((candidate) => {
+ try { return statSync(candidate).isFile(); } catch { return false; }
+ });
+}
+
+function inheritedEnvironment(): NodeJS.ProcessEnv {
+ const allowed = ['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'HOME', 'HOMEDRIVE', 'HOMEPATH', 'LANG'];
+ return Object.fromEntries(allowed.flatMap((key) => process.env[key] === undefined ? [] : [[key, process.env[key]!]]));
+}
+
+function findExecutable(name: string): string | undefined {
+ const suffixes = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];
+ for (const entry of String(process.env.PATH ?? '').split(delimiter)) {
+ for (const suffix of ['', ...suffixes]) {
+ const candidate = join(entry, `${name}${suffix}`);
+ try { if (statSync(candidate).isFile()) return candidate; } catch { /* keep searching PATH */ }
+ }
+ }
+ return undefined;
+}
+
+export function missingPrerequisites(adapter: string, credentialRef?: string): string[] {
+ const missing: string[] = [];
+ if (!adapterCatalog[adapter as AdapterName]) return [`No adapter registered for '${adapter}'.`];
+ if (credentialRef && !process.env[credentialRef]?.trim()) missing.push(`credential ${credentialRef} is not configured`);
+ if (adapter === 'filesystem' || adapter === 'memory') {
+ const [major = 0, minor = 0, patch = 0] = process.versions.node.split('.').map(Number);
+ const supportedRuntime = (major === 24 && (minor > 22 || (minor === 22 && patch >= 1))) || (major === 26 && (minor > 12 || (minor === 12 && patch >= 1))) || major > 26;
+ if (!supportedRuntime) missing.push('Node.js 24.22.1+ or 26.12.1+ is required by the upstream server security release');
+ }
+ if (adapter === 'filesystem' || adapter === 'memory' || adapter === 'postgres') {
+ if (!npxCli) missing.push('npm CLI was not found; set PROJECTOS_NPX_CLI to npx-cli.js');
+ }
+ if (adapter === 'github' && !findExecutable('docker')) missing.push('Docker is not available on PATH');
+ if ((adapter === 'git' || adapter === 'fetch') && !findExecutable('uvx')) missing.push('uvx is not available on PATH');
+ if (adapter === 'git' && !process.env.PROJECTOS_GIT_ROOT?.trim()) missing.push('PROJECTOS_GIT_ROOT is not configured');
+ if (adapter === 'git' && process.env.PROJECTOS_GIT_ROOT && !exists(process.env.PROJECTOS_GIT_ROOT)) missing.push('PROJECTOS_GIT_ROOT does not exist');
+ return missing;
+}
+
+function exists(path: string): boolean {
+ return existsSync(path);
+}
+
+export async function createLaunchSpec(server: ServerDefinition): Promise {
+ const env = inheritedEnvironment();
+ const npx = (args: string[]): LaunchSpec => {
+ if (!npxCli) throw new Error('npm CLI was not found; set PROJECTOS_NPX_CLI to npx-cli.js.');
+ return { command: process.execPath, args: [npxCli, ...args], cwd: projectRoot, env };
+ };
+ switch (server.adapter as AdapterName) {
+ case 'filesystem':
+ return npx(['-y', '@modelcontextprotocol/server-filesystem@2.1.0', resolve(process.env.PROJECTOS_MCP_FILESYSTEM_ROOT || projectRoot)]);
+ case 'memory': {
+ const memoryPath = resolve(projectRoot, 'data/mcp-memory.jsonl');
+ await mkdir(dirname(memoryPath), { recursive: true });
+ return { ...npx(['-y', '@modelcontextprotocol/server-memory@2.0.1']), env: { ...env, MEMORY_FILE_PATH: memoryPath } };
+ }
+ case 'postgres': {
+ const profileName = server.credentialRef ? process.env[server.credentialRef]?.trim() : undefined;
+ return { ...npx(['-y', '@microsoft/postgres-mcp', 'run']), env: { ...env, POSTGRES_MCP_DISABLE_CWD_ACCESS: '1', ...(profileName ? { POSTGRES_MCP_PROFILE_NAME: profileName } : {}) } };
+ }
+ case 'github': {
+ const args = ['run', '--rm', '-i', '--pull=missing', '-e', 'GITHUB_LOCKDOWN_MODE'];
+ const childEnv: NodeJS.ProcessEnv = { ...env, GITHUB_LOCKDOWN_MODE: '1' };
+ if (server.authMode === 'oauth') {
+ const callbackPort = Number(process.env.PROJECTOS_GITHUB_OAUTH_CALLBACK_PORT || '8085');
+ if (!Number.isInteger(callbackPort) || callbackPort < 1024 || callbackPort > 65535) throw new Error('PROJECTOS_GITHUB_OAUTH_CALLBACK_PORT must be a port from 1024 through 65535.');
+ args.push('-p', `127.0.0.1:${callbackPort}:${callbackPort}`, '-e', 'GITHUB_OAUTH_CALLBACK_PORT');
+ childEnv.GITHUB_OAUTH_CALLBACK_PORT = String(callbackPort);
+ } else if (server.authMode === 'environment' && server.credentialRef) {
+ const token = process.env[server.credentialRef];
+ if (!token) throw new Error(`Credential reference ${server.credentialRef} is not configured.`);
+ args.push('-e', 'GITHUB_PERSONAL_ACCESS_TOKEN');
+ childEnv.GITHUB_PERSONAL_ACCESS_TOKEN = token;
+ } else {
+ throw new Error(`GitHub authentication mode '${server.authMode}' is not supported by this adapter.`);
+ }
+ if (server.accessMode === 'read-only') {
+ args.push('-e', 'GITHUB_READ_ONLY');
+ childEnv.GITHUB_READ_ONLY = '1';
+ }
+ args.push('ghcr.io/github/github-mcp-server:v2.0.3');
+ return { command: findExecutable('docker') ?? 'docker', args, cwd: projectRoot, env: childEnv };
+ }
+ case 'fetch': {
+ const uvx = findExecutable('uvx');
+ if (!uvx) throw new Error('uvx is not available on PATH. Install uv or configure the fetch adapter.');
+ return { command: uvx, args: ['--from', 'mcp-server-fetch==2026.10.28', 'mcp-server-fetch'], cwd: projectRoot, env: { ...env, PYTHONIOENCODING: 'utf-8' } };
+ }
+ case 'git': {
+ const root = process.env.PROJECTOS_GIT_ROOT?.trim();
+ const uvx = findExecutable('uvx');
+ if (!root) throw new Error('PROJECTOS_GIT_ROOT is required for the Git adapter.');
+ if (!uvx) throw new Error('uvx is not available on PATH. Install uv or configure the Git adapter.');
+ return { command: uvx, args: ['--from', 'mcp-server-git==2026.10.28', 'mcp-server-git', '--repository', resolve(root)], cwd: projectRoot, env };
+ }
+ default:
+ throw new Error(`No launch configuration is registered for adapter '${server.adapter}'.`);
+ }
+}
+
+export function spawnAdapter(spec: LaunchSpec): ChildProcess {
+ return spawn(spec.command, spec.args, {
+ cwd: spec.cwd,
+ env: spec.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ shell: false
+ });
+}
+
diff --git a/packages/mcp-fabric/src/cli.ts b/packages/mcp-fabric/src/cli.ts
new file mode 100644
index 0000000000000000000000000000000000000000..03c8b9a172f22a68170f3f98d1980f4f79a36ff3
--- /dev/null
+++ b/packages/mcp-fabric/src/cli.ts
@@ -0,0 +1,42 @@
+import { connectProfile, listMcpLibrary, loadMcpLibrary } from './index.js';
+import { adapterCatalog } from './adapters.js';
+
+const [command = 'profiles', profileName] = process.argv.slice(2);
+
+try {
+ const library = await loadMcpLibrary();
+ if (command === 'profiles' || command === 'list') {
+ console.log('ProjectOS MCP adapter library');
+ for (const { adapter, profiles } of listMcpLibrary(library)) {
+ console.log(`\n${adapter.name} — ${adapter.title}`);
+ console.log(` ${adapter.description}`);
+ console.log(` Source: ${adapter.source}`);
+ console.log(` Requirements: ${adapter.requires.join(', ')}`);
+ for (const { profile, server } of profiles) {
+ console.log(` ${profile.enabled ? 'enabled' : 'disabled'} profile '${profile.name}' → ${server.name} (${server.accessMode}, ${server.trust} trust, auth: ${server.authMode})${server.credentialRef ? `; credential ref ${server.credentialRef}` : ''}`);
+ }
+ }
+ console.log('\nNamed profiles');
+ for (const profile of library.profiles) console.log(` ${profile.enabled ? 'enabled' : 'disabled'} ${profile.name}: ${profile.description}`);
+ } else if (command === 'check' || command === 'connect') {
+ if (!profileName) throw new Error(`Usage: pnpm mcp:${command === 'check' ? 'check' : 'connect'} `);
+ const connection = await connectProfile(profileName, library);
+ console.log(`Connected MCP profile '${connection.profile.name}'.`);
+ for (const server of connection.servers) console.log(` ${server.definition.name}: ${server.tools.length} tools available (${server.definition.accessMode}).`);
+ if (command === 'check') {
+ await connection.close();
+ console.log('Connection check passed; servers were closed cleanly.');
+ } else {
+ console.log('Profile remains connected. Press Ctrl+C to disconnect.');
+ await new Promise((resolve) => process.once('SIGINT', resolve));
+ await connection.close();
+ }
+ } else if (command === 'catalog') {
+ console.log(JSON.stringify(Object.values(adapterCatalog), null, 2));
+ } else {
+ throw new Error(`Unknown command '${command}'. Use profiles, check , or connect .`);
+ }
+} catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exitCode = 1;
+}
diff --git a/packages/mcp-fabric/src/index.ts b/packages/mcp-fabric/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..798f9a492c4a043fd96ad728915c7acb5abadfd4
--- /dev/null
+++ b/packages/mcp-fabric/src/index.ts
@@ -0,0 +1,130 @@
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { adapterCatalog, createLaunchSpec, missingPrerequisites, projectRoot, spawnAdapter, type AdapterDescriptor, type ServerDefinition } from './adapters.js';
+import { StdioMcpClient, type McpTool } from './stdio-client.js';
+
+export type McpProfile = { name: string; description: string; enabled: boolean; servers: string[] };
+export type McpLibrary = { servers: ServerDefinition[]; profiles: McpProfile[] };
+export type ConnectedServer = { definition: ServerDefinition; tools: McpTool[] };
+type ActiveServer = ConnectedServer & { client: StdioMcpClient };
+export type ConnectedProfile = {
+ profile: McpProfile;
+ servers: ConnectedServer[];
+ close(): Promise;
+ callTool(serverName: string, toolName: string, args?: Record, approved?: boolean): Promise;
+};
+
+const readOnlyToolNames: Record> = {
+ filesystem: new Set(['read_text_file', 'read_media_file', 'read_multiple_files', 'list_directory', 'list_directory_with_sizes', 'directory_tree', 'search_files', 'get_file_info', 'list_allowed_directories']),
+ memory: new Set(['read_graph', 'search_nodes', 'open_nodes', 'find_nodes']),
+ fetch: new Set(['fetch']),
+ postgres: new Set(['postgres_mcp_list_connection_profiles', 'postgres_mcp_list_databases', 'postgres_mcp_db_context', 'postgres_mcp_query', 'postgres_mcp_get_server_capabilities', 'postgres_mcp_get_metrics_group']),
+ git: new Set(['git_status', 'git_log', 'git_diff', 'git_show', 'git_branch', 'git_tag', 'git_remote', 'git_blame', 'git_list_files', 'git_search']),
+ github: new Set()
+};
+
+export async function loadMcpLibrary(root = projectRoot): Promise {
+ const [servers, profiles] = await Promise.all([
+ readFile(resolve(root, 'generated/registries/mcp.json'), 'utf8').then((text) => JSON.parse(text) as ServerDefinition[]),
+ readFile(resolve(root, 'generated/registries/mcp-profiles.json'), 'utf8').then((text) => JSON.parse(text) as McpProfile[])
+ ]);
+ return { servers, profiles };
+}
+
+export function listMcpLibrary(library: McpLibrary): Array<{ adapter: AdapterDescriptor; profiles: Array<{ profile: McpProfile; server: ServerDefinition }> }> {
+ return Object.values(adapterCatalog).map((adapter) => ({
+ adapter,
+ profiles: library.profiles.flatMap((profile) => profile.servers.flatMap((name) => {
+ const server = library.servers.find((candidate) => candidate.name === name);
+ return server?.adapter === adapter.name ? [{ profile, server }] : [];
+ }))
+ }));
+}
+
+export async function connectProfile(profileName: string, library?: McpLibrary): Promise {
+ const catalog = library ?? await loadMcpLibrary();
+ const profile = catalog.profiles.find((item) => item.name === profileName);
+ if (!profile) throw new Error(`Unknown MCP profile '${profileName}'. Run pnpm mcp:profiles to list profiles.`);
+ if (!profile.enabled) throw new Error(`MCP profile '${profileName}' is disabled in bootstrap.xml.`);
+ const definitions = profile.servers.map((name) => catalog.servers.find((server) => server.name === name));
+ const missing = definitions.flatMap((server) => {
+ if (!server) return [`A server referenced by '${profileName}' is missing from the registry.`];
+ if (!server.enabled) return [`Server '${server.name}' is disabled in bootstrap.xml.`];
+ return missingPrerequisites(server.adapter, server.credentialRef).map((issue) => `${server.name}: ${issue}`);
+ });
+ if (missing.length) throw new Error(`MCP profile '${profileName}' is not ready:\n${missing.map((item) => `- ${item}`).join('\n')}`);
+
+ const connected: ActiveServer[] = [];
+ try {
+ for (const definition of definitions as ServerDefinition[]) {
+ const spec = await createLaunchSpec(definition);
+ const client = new StdioMcpClient(spawnAdapter(spec), definition.name, [definition.credentialRef ? process.env[definition.credentialRef] ?? '' : '']);
+ const entry: ActiveServer = { definition, tools: [], client };
+ connected.push(entry);
+ const tools = await client.initialize();
+ entry.tools = tools;
+ if (definition.adapter === 'postgres') await connectSavedPostgresProfile(client, definition);
+ }
+ } catch (error) {
+ await Promise.all(connected.map(({ client }) => client.close()));
+ throw error;
+ }
+ return {
+ profile,
+ servers: connected.map(({ definition, tools }) => ({ definition, tools })),
+ async close() { await Promise.all(connected.map(({ client }) => client.close())); },
+ async callTool(serverName, toolName, args = {}, approved = false) {
+ const server = connected.find(({ definition }) => definition.name === serverName);
+ if (!server) throw new Error(`Server '${serverName}' is not connected in profile '${profileName}'.`);
+ const tool = server.tools.find((entry) => entry.name === toolName);
+ if (!tool) throw new Error(`Server '${serverName}' does not expose tool '${toolName}'.`);
+ const enforcedReadOnly = server.definition.adapter === 'github' && server.definition.accessMode === 'read-only';
+ const annotatedReadOnly = tool.annotations?.readOnlyHint === true;
+ const catalogReadOnly = readOnlyToolNames[server.definition.adapter]?.has(toolName) ?? false;
+ const readOnly = annotatedReadOnly || (tool.annotations?.readOnlyHint !== false && catalogReadOnly) || enforcedReadOnly;
+ if (server.definition.accessMode === 'read-only' && !readOnly) {
+ throw new Error(`Tool '${toolName}' is not marked read-only; this profile only permits read-only tools.`);
+ }
+ if (!readOnly && !approved) {
+ throw new Error(`Tool '${toolName}' can change data; pass approved=true after reviewing the requested action.`);
+ }
+ return server.client.callTool(toolName, args);
+ }
+ };
+}
+
+async function connectSavedPostgresProfile(client: StdioMcpClient, server: ServerDefinition): Promise {
+ const name = server.credentialRef ? process.env[server.credentialRef]?.trim() : undefined;
+ if (!name) throw new Error(`PostgreSQL profile reference ${server.credentialRef ?? '(none)'} is not configured.`);
+ const profilesTool = client.availableTools.find((tool) => tool.name === 'postgres_mcp_list_connection_profiles');
+ const connectTool = client.availableTools.find((tool) => tool.name === 'postgres_mcp_connect');
+ if (!profilesTool || !connectTool) throw new Error('PostgreSQL MCP server does not expose saved-profile connection tools.');
+ const listed = await client.callTool(profilesTool.name, {});
+ const profile = findProfile(listed, name);
+ if (!profile) throw new Error(`PostgreSQL keyring profile '${name}' was not found. Set it up with the server connection CLI.`);
+ const properties = connectTool.inputSchema?.properties ?? {};
+ const profileKey = Object.keys(properties).find((key) => /profile|connection|name|id/i.test(key));
+ if (!profileKey) throw new Error('PostgreSQL MCP connect tool schema has no profile selector.');
+ const value = profile[profileKey] ?? profile.profile_id ?? profile.profileId ?? profile.name ?? profile.id ?? name;
+ const result = await client.callTool(connectTool.name, { [profileKey]: value });
+ if ((result as { isError?: unknown } | null)?.isError === true) throw new Error(`Could not connect PostgreSQL keyring profile '${name}'.`);
+}
+
+function findProfile(value: unknown, name: string, seen = new Set