ProjectOS / apps /api /server.mjs
AnthropicallyHuggingFaces's picture
Sync full ProjectOS monorepo from GitHub 7f633f5
a8f4b72 verified
Raw History Blame Contribute Delete
8.73 kB
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);