import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; import { execFile } from 'node:child_process'; import { createHash } from 'node:crypto'; import { promisify } from 'node:util'; import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { XMLParser, XMLValidator } from 'fast-xml-parser'; import { generateDocumentation } from './generators/documentation.js'; import { SchematronEngine } from './schematron.js'; import { SymbolResolver, type LanguageProfileRegistry, type SymbolAliasRegistry } from './symbols/symbol-resolver.js'; const packageDirectory = dirname(fileURLToPath(import.meta.url)); const execFileAsync = promisify(execFile); export const projectRoot = resolve(packageDirectory, '../../..'); type XmlObject = Record; export type GeneratedCatalogItem = { name: string; description: string; icon?: string; capabilities: string[]; gate?: boolean; }; export type RuntimeConfiguration = { profile: string; snapshots: boolean; automaticRouting: boolean; consolidation: boolean; startupOrder: string[]; }; export type GeneratedProjectCatalog = { version: string; name: string; mode: string; steps: GeneratedCatalogItem[]; stages: GeneratedCatalogItem[]; fabrics: GeneratedCatalogItem[]; agents: GeneratedCatalogItem[]; councils: GeneratedCatalogItem[]; governance: GeneratedCatalogItem[]; knowledge: GeneratedCatalogItem[]; runtime: RuntimeConfiguration; storage: Record; models: Record; workspaces: Record; permissions: PermissionRule[]; mcpServers: McpServer[]; mcpProfiles: McpProfile[]; }; export type McpServer = { name: string; adapter: string; trust: 'Low' | 'Medium' | 'High' | 'Verified'; enabled: boolean; authMode: 'none' | 'oauth' | 'environment' | 'keyring'; credentialRef?: string; accessMode: 'read-only' | 'read-write'; }; export type McpProfile = { name: string; description: string; enabled: boolean; servers: string[] }; export type PermissionRule = { id: string; resource: string; action: string; effect: string; requiresApproval: boolean; }; export type StorageConfiguration = { providers: string[]; vectorStores: Array<{ provider: string; dimensions: number }>; retention: { snapshotDays: number; archiveYears: number; keepCanonForever: boolean }; migration: { autoMigrate: boolean; backupBeforeMigration: boolean; validateSchema: boolean }; }; export type { LanguageProfile, LanguageProfileRegistry, SymbolAlias, SymbolAliasInput, SymbolAliasRegistry } from './symbols/symbol-resolver.js'; export type GeneratedArtifacts = { 'runtime.generated.json': Record; 'models.generated.json': Record; 'workspaces.generated.json': Record; 'mcp.generated.json': McpServer[]; 'mcp-profiles.generated.json': McpProfile[]; 'agents.generated.json': GeneratedCatalogItem[]; 'permissions.generated.json': { rules: PermissionRule[] }; 'projectos.generated.json': GeneratedProjectCatalog; 'generated/storage.generated.json': StorageConfiguration; 'generated/symbol-aliases.generated.json': SymbolAliasRegistry; 'generated/language-profiles.generated.json': LanguageProfileRegistry; }; type ArtifactMap = Record; export class ProjectOSValidationError extends Error { constructor(readonly issues: string[]) { super(`ProjectOS validation failed:\n${issues.map((issue) => `- ${issue}`).join('\n')}`); this.name = 'ProjectOSValidationError'; } } const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', parseAttributeValue: false, parseTagValue: false, processEntities: true, trimValues: true }); function asObject(value: unknown, label: string): XmlObject { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new ProjectOSValidationError([`Expected ${label} to be an XML element.`]); } return value as XmlObject; } function values(parent: XmlObject, key: string): unknown[] { const value = parent[key]; if (value === undefined) return []; return Array.isArray(value) ? value : [value]; } function children(parent: XmlObject, key: string): XmlObject[] { return values(parent, key).map((child) => asObject(child, key)); } function attribute(element: XmlObject, key: string): string { const value = element[`@_${key}`]; return typeof value === 'string' ? value : ''; } function textValue(value: unknown): string { if (typeof value === 'string') return value; if (value && typeof value === 'object' && '#text' in value) { const text = (value as XmlObject)['#text']; return typeof text === 'string' ? text : ''; } return ''; } function asBoolean(value: string): boolean { return value.toLowerCase() === 'true' || value === '1'; } function positiveInteger(element: XmlObject, key: string): number { const value = Number(attribute(element, key)); if (!Number.isSafeInteger(value) || value <= 0) { throw new ProjectOSValidationError([`${key} must be a positive safe integer.`]); } return value; } function catalogItems(parent: XmlObject, tag: string, childTag?: string): GeneratedCatalogItem[] { return children(parent, tag).map((element) => ({ name: attribute(element, 'name'), description: attribute(element, 'description'), ...(attribute(element, 'icon') ? { icon: attribute(element, 'icon') } : {}), capabilities: childTag ? values(element, childTag).map((child) => { if (child && typeof child === 'object' && !Array.isArray(child)) { return attribute(child as XmlObject, 'name') || textValue(child); } return textValue(child); }).filter(Boolean) : [], ...(tag === 'step' ? { gate: asBoolean(attribute(element, 'gate')) } : {}) })); } function withinRoot(root: string, path: string): string { const candidate = resolve(root, path); const pathFromRoot = relative(root, candidate); if (!pathFromRoot || pathFromRoot.startsWith('..') || isAbsolute(pathFromRoot)) { throw new ProjectOSValidationError([`Configured path must stay inside the ProjectOS directory: ${path}`]); } return candidate; } function parseBootstrap(xml: string): { document: XmlObject; bootstrap: XmlObject } { if (/ part.trim()).filter(Boolean) }; const models = Object.fromEntries(children(asObject(document.models, 'models'), 'model').map((item) => [ attribute(item, 'role'), attribute(item, 'provider') ])); const workspaces = Object.fromEntries(children(asObject(document.workspaces, 'workspaces'), 'workspace').map((item) => [ attribute(item, 'role'), attribute(item, 'name') ])); const mcpNode = asObject(document.mcpServers, 'MCP servers'); const mcpServers = children(mcpNode, 'server').map((item) => ({ name: attribute(item, 'name'), adapter: attribute(item, 'adapter'), trust: attribute(item, 'trust') as McpServer['trust'], enabled: asBoolean(attribute(item, 'enabled')), authMode: attribute(item, 'authMode') as McpServer['authMode'], ...(attribute(item, 'credentialRef') ? { credentialRef: attribute(item, 'credentialRef') } : {}), accessMode: (attribute(item, 'accessMode') || 'read-only') as McpServer['accessMode'] })); const mcpProfiles = children(asObject(mcpNode.profiles, 'MCP profiles'), 'profile').map((profile) => ({ name: attribute(profile, 'name'), description: attribute(profile, 'description'), enabled: asBoolean(attribute(profile, 'enabled')), servers: children(profile, 'serverRef').map((server) => attribute(server, 'name')) })); const agents = catalogItems(asObject(document.agents, 'agents'), 'agent'); const permissions = children(asObject(document.permissions, 'permissions'), 'permission').map(parsePermission); const storageNode = asObject(document.storage, 'storage'); const storage = { local: attribute(storageNode, 'local'), enterprise: attribute(storageNode, 'enterprise') }; const storageProvidersNode = asObject(storageNode.providers, 'storage providers'); const vectorStoresNode = asObject(storageNode.vectorStores, 'vector stores'); const retentionNode = asObject(storageNode.retention, 'storage retention policy'); const migrationNode = asObject(storageNode.migration, 'storage migration policy'); const storageConfiguration: StorageConfiguration = { providers: children(storageProvidersNode, 'provider') .filter((item) => asBoolean(attribute(item, 'enabled'))) .map((item) => attribute(item, 'name')), vectorStores: children(vectorStoresNode, 'vectorStore').map((item) => ({ provider: attribute(item, 'provider'), dimensions: positiveInteger(item, 'dimensions') })), retention: { snapshotDays: positiveInteger(retentionNode, 'snapshotDays'), archiveYears: positiveInteger(retentionNode, 'archiveYears'), keepCanonForever: asBoolean(attribute(retentionNode, 'keepCanonForever')) }, migration: { autoMigrate: asBoolean(attribute(migrationNode, 'autoMigrate')), backupBeforeMigration: asBoolean(attribute(migrationNode, 'backupBeforeMigration')), validateSchema: asBoolean(attribute(migrationNode, 'validateSchema')) } }; const namingNode = asObject(document.namingConventions, 'naming conventions'); const symbolAliases = Object.fromEntries(children(namingNode, 'convention').map((convention) => [ attribute(convention, 'canonical'), values(convention, 'alias').map(textValue).filter((alias) => alias.length > 0) ])) as SymbolAliasRegistry; const languageProfileNode = asObject(namingNode.languageProfiles, 'language profiles'); const languageProfiles = Object.fromEntries(children(languageProfileNode, 'languageProfile').map((profile) => [ attribute(profile, 'name'), { interfacePrefix: attribute(profile, 'interfacePrefix') } ])) as LanguageProfileRegistry; // Reject ambiguous names before publishing any generated registry files. new SymbolResolver(symbolAliases, languageProfiles); const project: GeneratedProjectCatalog = { version: attribute(document, 'version'), name: attribute(document, 'name'), mode: attribute(document, 'mode'), steps: catalogItems(asObject(document.decisionFormula, 'decision formula'), 'step'), stages: catalogItems(asObject(document.projectLifecycle, 'project lifecycle'), 'stage'), fabrics: catalogItems(asObject(document.fabrics, 'fabrics'), 'fabric', 'capability'), agents, councils: catalogItems(asObject(document.councils, 'councils'), 'council', 'member'), governance: catalogItems(asObject(document.governanceControls, 'governance controls'), 'control'), knowledge: catalogItems(asObject(document.knowledgeAreas, 'knowledge areas'), 'area'), runtime, storage, models, workspaces, permissions, mcpServers, mcpProfiles }; return { 'runtime.generated.json': runtime, 'models.generated.json': models, 'workspaces.generated.json': workspaces, 'mcp.generated.json': mcpServers, 'mcp-profiles.generated.json': mcpProfiles, 'agents.generated.json': agents, 'permissions.generated.json': { rules: permissions }, 'projectos.generated.json': project, 'generated/storage.generated.json': storageConfiguration, 'generated/symbol-aliases.generated.json': symbolAliases, 'generated/language-profiles.generated.json': languageProfiles }; } async function createPackageArtifacts( rootDirectory: string, bootstrapXml: string, schemaPath: string, schematronPath: string, legacyArtifacts: GeneratedArtifacts, includeRelease: boolean ): Promise { const { document, bootstrap } = parseBootstrap(bootstrapXml); const project = legacyArtifacts['projectos.generated.json']; const runtime = legacyArtifacts['runtime.generated.json']; const agents = legacyArtifacts['agents.generated.json']; const models = legacyArtifacts['models.generated.json']; const permissions = legacyArtifacts['permissions.generated.json']; const workspaces = legacyArtifacts['workspaces.generated.json']; const mcpServers = legacyArtifacts['mcp.generated.json']; const mcpProfiles = legacyArtifacts['mcp-profiles.generated.json']; const storage = legacyArtifacts['generated/storage.generated.json']; const symbols = legacyArtifacts['generated/symbol-aliases.generated.json']; const outputNode = asObject(document.documentation, 'documentation outputs'); const enabledOutputs = children(outputNode, 'output') .filter((output) => asBoolean(attribute(output, 'enabled'))) .map((output) => attribute(output, 'name')); const documentation = generateDocumentation({ project, storage, symbols, bootstrap: { schema: attribute(bootstrap, 'schema'), schematron: attribute(bootstrap, 'schematron'), output: attribute(bootstrap, 'output') } }, enabledOutputs); const storagePackage = JSON.parse(await readFile(resolve(rootDirectory, 'packages/storage-fabric/package.json'), 'utf8')) as { name: string; version: string }; const repositoryNames = Object.keys(symbols).filter((name) => name.endsWith('Repository')); const packageManifest = { package: storagePackage.name, version: storagePackage.version, repositories: repositoryNames }; const migrationManifest = { schema: 1, version: 2, policy: storage.migration, tables: ['projects', 'project_events', 'snapshots', 'snapshot_items', 'canon_entries', 'canon_revisions', 'frontier_items', 'frontier_observations', 'archive_records', 'knowledge_embeddings', 'dependency_findings', 'delta_runs', 'delta_gaps', 'delta_dependencies', 'governance_reviews'], steps: [ 'Back up the local database before applying migrations when configured.', 'Apply SQLite schema version 2, including dependency findings, delta persistence, and governance review tables.', 'Apply idempotent schema updates and record the applied schema versions.', 'Validate the expected table set before the API becomes ready.', 'Backfill app_state into normalized repositories in a transaction.', 'Verify counts and checksums before switching reads or removing app_state.' ] }; const generatedAt = new Date().toISOString(); const sha256 = (value: string) => createHash('sha256').update(value).digest('hex'); const snapshotManifest = { schema: 1, timestamp: generatedAt, project: project.name, bootstrapHash: `sha256:${sha256(bootstrapXml)}`, runtimeHash: `sha256:${sha256(JSON.stringify(runtime))}`, storageHash: `sha256:${sha256(JSON.stringify(storage))}`, mcpHash: `sha256:${sha256(JSON.stringify({ servers: mcpServers, profiles: mcpProfiles }))}` }; const releaseManifest = { project: project.name, version: project.version, mode: project.mode, generatedAt, bootstrap: 'bootstrap.xml', schema: 'ProjectOS.xsd', rules: 'ProjectOS.sch', generatedDirectory: 'generated/', documentationDirectory: 'docs/', storageDirectory: 'storage/', snapshotManifest: 'generated/snapshots/snapshot-manifest.json', migrationManifest: 'migrations/manifest.json', mcpRegistry: 'generated/registries/mcp.json', mcpProfiles: 'generated/registries/mcp-profiles.json' }; const generatedConfigs: ArtifactMap = { 'runtime.json': runtime, 'registries/agents.json': agents, 'registries/models.json': models, 'registries/symbols.json': symbols, 'registries/permissions.json': permissions, 'registries/workspaces.json': workspaces, 'registries/mcp.json': mcpServers, 'registries/mcp-profiles.json': mcpProfiles, 'storage/storage.json': storage, 'storage/migrations.json': migrationManifest, 'storage/repositories.json': repositoryNames, 'storage/package-manifest.json': packageManifest }; const artifacts: ArtifactMap = { 'generated/runtime.json': runtime, 'generated/registries/agents.json': agents, 'generated/registries/models.json': models, 'generated/registries/symbols.json': symbols, 'generated/registries/permissions.json': permissions, 'generated/registries/workspaces.json': workspaces, 'generated/registries/mcp.json': mcpServers, 'generated/registries/mcp-profiles.json': mcpProfiles, 'generated/storage/storage.json': storage, 'generated/storage/migrations.json': migrationManifest, 'generated/storage/repositories.json': repositoryNames, 'generated/storage/package-manifest.json': packageManifest, 'generated/snapshots/snapshot-manifest.json': snapshotManifest, ...Object.fromEntries(Object.entries(documentation).map(([path, content]) => [`generated/${path}`, content])) }; if (!includeRelease) return artifacts; Object.assign(artifacts, { 'release/manifest.json': releaseManifest, 'release/bootstrap.xml': bootstrapXml, 'release/ProjectOS.xsd': await readFile(schemaPath, 'utf8'), 'release/ProjectOS.sch': await readFile(schematronPath, 'utf8'), 'release/migrations/manifest.json': migrationManifest, 'release/storage/package-manifest.json': packageManifest, 'release/docs/mcp-adapters.md': await readFile(resolve(rootDirectory, 'docs/mcp-adapters.md'), 'utf8'), 'release/storage/sqlite/schema.sql': await readFile(resolve(rootDirectory, 'packages/storage-fabric/sqlite/schema.sql'), 'utf8'), 'release/storage/postgres/schema.sql': await readFile(resolve(rootDirectory, 'packages/storage-fabric/pgvector/schema.sql'), 'utf8'), ...Object.fromEntries(Object.entries(artifacts).map(([path, value]) => [`release/${path}`, value])), ...Object.fromEntries(Object.entries(documentation).map(([path, content]) => [`release/${path}`, content])), 'release/projectos-manifest.json': releaseManifest, 'release/projectos-bootstrap.xml': bootstrapXml, 'release/projectos-schema.xsd': await readFile(schemaPath, 'utf8'), 'release/projectos-rules.sch': await readFile(schematronPath, 'utf8'), 'release/migration-manifest.json': migrationManifest, 'release/snapshot-manifest.json': snapshotManifest, ...Object.fromEntries(Object.entries(generatedConfigs).map(([path, value]) => [`release/generated-configs/${path}`, value])), ...Object.fromEntries(Object.entries(documentation).map(([path, content]) => [`release/generated-docs/${basename(path)}`, content])) }); return artifacts; } async function validateXsd(rootDirectory: string, manifestPath: string, schemaPath: string): Promise { const scriptPath = resolve(rootDirectory, 'scripts/validate-manifest.ps1'); const powershell = process.platform === 'win32' ? 'powershell.exe' : 'pwsh'; const args = process.platform === 'win32' ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath, '-ProjectRoot', rootDirectory, '-ManifestPath', manifestPath, '-SchemaPath', schemaPath] : ['-NoProfile', '-File', scriptPath, '-ProjectRoot', rootDirectory, '-ManifestPath', manifestPath, '-SchemaPath', schemaPath]; try { await execFileAsync(powershell, args, { cwd: rootDirectory, windowsHide: true }); } catch (error) { const diagnostic = error as Error & { stderr?: string; stdout?: string }; const detail = [diagnostic.stderr, diagnostic.stdout, diagnostic.message].filter(Boolean).join('\n').trim(); throw new ProjectOSValidationError([`XSD validation failed: ${detail || String(error)}`]); } } async function writeArtifacts(outputDirectory: string, artifacts: ArtifactMap): Promise { await mkdir(outputDirectory, { recursive: true }); const pending: Array<{ temporary: string; target: string; content: string }> = Object.entries(artifacts).map(([name, value]) => ({ target: resolve(outputDirectory, name), temporary: resolve(dirname(resolve(outputDirectory, name)), `.${basename(name)}.${process.pid}.tmp`), content: typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n` })); try { await Promise.all(pending.map(({ target }) => mkdir(dirname(target), { recursive: true }))); await Promise.all(pending.map(({ temporary, content }) => writeFile(temporary, content, 'utf8'))); for (const { temporary, target } of pending) await rename(temporary, target); } catch (error) { await Promise.all(pending.map(({ temporary }) => rm(temporary, { force: true }))); throw error; } return pending.map(({ target }) => target); } export async function validateProjectOS( rootDirectory = projectRoot, options: { includeRelease?: boolean } = {} ): Promise { const bootstrapPath = resolve(rootDirectory, 'bootstrap.xml'); const bootstrapXml = await readFile(bootstrapPath, 'utf8'); const { bootstrap } = parseBootstrap(bootstrapXml); const schemaPath = withinRoot(rootDirectory, attribute(bootstrap, 'schema')); const schematronPath = withinRoot(rootDirectory, attribute(bootstrap, 'schematron')); const outputDirectory = withinRoot(rootDirectory, attribute(bootstrap, 'output')); const schematronXml = await readFile(schematronPath, 'utf8'); await validateXsd(rootDirectory, bootstrapPath, schemaPath); const schematronIssues = new SchematronEngine(schematronXml).validate(bootstrapXml); if (schematronIssues.length) throw new ProjectOSValidationError(schematronIssues.map((issue) => `Schematron: ${issue}`)); const legacyArtifacts = createGeneratedArtifacts(bootstrapXml); const outputPrefix = relative(rootDirectory, outputDirectory); const configArtifacts = Object.fromEntries(Object.entries(legacyArtifacts).map(([name, value]) => [join(outputPrefix, name), value])); const packageArtifacts = await createPackageArtifacts( rootDirectory, bootstrapXml, schemaPath, schematronPath, legacyArtifacts, options.includeRelease ?? false ); return writeArtifacts(rootDirectory, { ...configArtifacts, ...packageArtifacts }); } export { SchematronEngine } from './schematron.js'; export { SymbolResolver } from './symbols/symbol-resolver.js';