File size: 23,589 Bytes
a8f4b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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<string, unknown>;
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<string, string>;
  models: Record<string, string>;
  workspaces: Record<string, string>;
  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<string, unknown>;
  'models.generated.json': Record<string, string>;
  'workspaces.generated.json': Record<string, string>;
  '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<string, unknown>;

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 (/<!DOCTYPE\b/i.test(xml)) {
    throw new ProjectOSValidationError(['Document type declarations and custom entities are not allowed in bootstrap.xml.']);
  }
  const wellFormed = XMLValidator.validate(xml);
  if (wellFormed !== true) {
    const error = (wellFormed as { err?: { line?: number; col?: number; msg?: string } }).err;
    throw new ProjectOSValidationError([
      `bootstrap.xml is not well-formed${error?.line ? ` at line ${error.line}, column ${error.col ?? 0}` : ''}: ${error?.msg ?? 'XML parse error'}`
    ]);
  }
  const parsed = parser.parse(xml) as XmlObject;
  const document = asObject(parsed.ProjectOS, 'ProjectOS root');
  return { document, bootstrap: asObject(document.bootstrap, 'bootstrap settings') };
}

function parsePermission(element: XmlObject): PermissionRule {
  return {
    id: attribute(element, 'id'),
    resource: attribute(element, 'resource'),
    action: attribute(element, 'action'),
    effect: attribute(element, 'effect'),
    requiresApproval: asBoolean(attribute(element, 'requiresApproval'))
  };
}

export function createGeneratedArtifacts(xml: string): GeneratedArtifacts {
  const { document } = parseBootstrap(xml);
  const runtimeNode = asObject(document.runtime, 'runtime settings');
  const runtime = {
    profile: attribute(runtimeNode, 'profile'),
    snapshots: asBoolean(attribute(runtimeNode, 'snapshots')),
    automaticRouting: asBoolean(attribute(runtimeNode, 'automaticRouting')),
    consolidation: asBoolean(attribute(runtimeNode, 'consolidation')),
    startupOrder: attribute(runtimeNode, 'startupOrder').split(',').map((part) => 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<ArtifactMap> {
  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<void> {
  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<string[]> {
  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<string[]> {
  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';