@documentation-robotics/cli 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +18 -17
  2. package/dist/audit/nodes/ai/prompts.js +1 -0
  3. package/dist/audit/nodes/ai/prompts.js.map +2 -2
  4. package/dist/audit/relationships/ai/prompts.js +20 -29
  5. package/dist/audit/relationships/ai/prompts.js.map +2 -2
  6. package/dist/audit/relationships/analysis/gap-analyzer.js.map +1 -1
  7. package/dist/audit/relationships/analysis/layer-templates.js +36 -0
  8. package/dist/audit/relationships/analysis/layer-templates.js.map +2 -2
  9. package/dist/cli.js +8 -8
  10. package/dist/cli.js.map +1 -1
  11. package/dist/commands/reports.js +3 -3
  12. package/dist/commands/reports.js.map +1 -1
  13. package/dist/commands/show.js.map +1 -1
  14. package/dist/commands/upgrade.js +1 -1
  15. package/dist/commands/upgrade.js.map +1 -1
  16. package/dist/commands/validate.js.map +1 -1
  17. package/dist/commands/version.js +1 -1
  18. package/dist/core/layers.js +1 -0
  19. package/dist/core/layers.js.map +2 -2
  20. package/dist/core/migration-registry.js +59 -2
  21. package/dist/core/migration-registry.js.map +2 -2
  22. package/dist/core/model.js +3 -16
  23. package/dist/core/model.js.map +2 -2
  24. package/dist/core/spec-loader.js.map +1 -1
  25. package/dist/core/stats-collector.js +2 -0
  26. package/dist/core/stats-collector.js.map +2 -2
  27. package/dist/export/archimate-exporter.js.map +2 -2
  28. package/dist/export/json-schema-exporter.js.map +1 -1
  29. package/dist/export/markdown-exporter.js.map +1 -1
  30. package/dist/export/markdown-utils.js +1 -0
  31. package/dist/export/markdown-utils.js.map +2 -2
  32. package/dist/export/mermaid-markdown-exporter.js.map +1 -1
  33. package/dist/export/openapi-exporter.js.map +1 -1
  34. package/dist/export/plantuml-exporter.js.map +1 -1
  35. package/dist/export/report-formatters.js +2 -2
  36. package/dist/export/report-formatters.js.map +1 -1
  37. package/dist/export/types.js +1 -0
  38. package/dist/export/types.js.map +2 -2
  39. package/dist/generated/layer-registry.js +44 -31
  40. package/dist/generated/layer-registry.js.map +2 -2
  41. package/dist/generated/layer-types.js +1 -1
  42. package/dist/generated/layer-types.js.map +2 -2
  43. package/dist/generated/node-types.js +45 -0
  44. package/dist/generated/node-types.js.map +2 -2
  45. package/dist/generated/relationship-index.js +201 -19
  46. package/dist/generated/relationship-index.js.map +2 -2
  47. package/dist/import/archimate-importer.js.map +1 -1
  48. package/dist/import/openapi-importer.js.map +1 -1
  49. package/dist/integrations/claude_code/agents/dr-advisor.md +14 -13
  50. package/dist/integrations/claude_code/agents/dr-extractor.md +2 -2
  51. package/dist/integrations/claude_code/commands/dr-info.md +1 -1
  52. package/dist/integrations/claude_code/commands/dr-init.md +3 -3
  53. package/dist/integrations/claude_code/commands/dr-map.md +2 -2
  54. package/dist/integrations/claude_code/commands/dr-model.md +1 -1
  55. package/dist/integrations/claude_code/commands/dr-relate.md +14 -4
  56. package/dist/integrations/claude_code/docs/END_TO_END_WALKTHROUGH.md +3 -3
  57. package/dist/integrations/claude_code/docs/QUICK_START.md +1 -1
  58. package/dist/integrations/claude_code/docs/README.md +2 -2
  59. package/dist/integrations/claude_code/skills/dr_01_motivation_layer/SKILL.md +2 -2
  60. package/dist/integrations/claude_code/skills/dr_03_product_layer/SKILL.md +679 -0
  61. package/dist/integrations/claude_code/skills/{dr_08_dataset_layer → dr_09_dataset_layer}/SKILL.md +1 -1
  62. package/dist/integrations/claude_code/skills/dr_engineering_guide/SKILL.md +2 -2
  63. package/dist/integrations/github_copilot/agents/dr-advisor.md +14 -13
  64. package/dist/integrations/github_copilot/agents/dr-architect.md +15 -14
  65. package/dist/integrations/github_copilot/skills/dr_01_motivation_layer/SKILL.md +2 -2
  66. package/dist/integrations/github_copilot/skills/dr_03_product_layer/SKILL.md +253 -0
  67. package/dist/reports/model-report-orchestrator.js +3 -3
  68. package/dist/reports/model-report-orchestrator.js.map +1 -1
  69. package/dist/schemas/bundled/analyzers/cbm.json +2 -2
  70. package/dist/schemas/bundled/analyzers/manifest.json +2 -2
  71. package/dist/schemas/bundled/api.json +3 -3
  72. package/dist/schemas/bundled/apm.json +3 -3
  73. package/dist/schemas/bundled/application.json +3 -3
  74. package/dist/schemas/bundled/base.json +29 -1
  75. package/dist/schemas/bundled/business.json +1 -1
  76. package/dist/schemas/bundled/data-model.json +3 -3
  77. package/dist/schemas/bundled/data-store.json +3 -3
  78. package/dist/schemas/bundled/manifest.json +20 -13
  79. package/dist/schemas/bundled/motivation.json +1 -1
  80. package/dist/schemas/bundled/navigation.json +3 -3
  81. package/dist/schemas/bundled/product.json +469 -0
  82. package/dist/schemas/bundled/security.json +3 -3
  83. package/dist/schemas/bundled/technology.json +3 -3
  84. package/dist/schemas/bundled/testing.json +3 -3
  85. package/dist/schemas/bundled/ux.json +3 -3
  86. package/dist/server/server.js +4 -15
  87. package/dist/server/server.js.map +2 -2
  88. package/dist/telemetry/index.js +1 -1
  89. package/dist/utils/spec-installer.js +2 -2
  90. package/dist/utils/spec-installer.js.map +1 -1
  91. package/dist/utils/spec-version.js +1 -1
  92. package/dist/utils/spec-version.js.map +1 -1
  93. package/dist/viewer/README.md +6 -6
  94. package/dist/viewer/assets/main-D114QwJo.css +1 -0
  95. package/dist/viewer/assets/main-DyuokeQj.js +81 -0
  96. package/dist/viewer/index.html +2 -2
  97. package/dist/viewer/manifest.json +10 -10
  98. package/dist/viewer/version.json +1 -1
  99. package/package.json +1 -1
  100. package/dist/viewer/assets/main-CY0Xufuj.css +0 -1
  101. package/dist/viewer/assets/main-DtgErnwF.js +0 -81
  102. /package/dist/integrations/claude_code/skills/{dr_03_security_layer → dr_04_security_layer}/SKILL.md +0 -0
  103. /package/dist/integrations/claude_code/skills/{dr_04_application_layer → dr_05_application_layer}/SKILL.md +0 -0
  104. /package/dist/integrations/claude_code/skills/{dr_05_technology_layer → dr_06_technology_layer}/SKILL.md +0 -0
  105. /package/dist/integrations/claude_code/skills/{dr_06_api_layer → dr_07_api_layer}/SKILL.md +0 -0
  106. /package/dist/integrations/claude_code/skills/{dr_07_data_model_layer → dr_08_data_model_layer}/SKILL.md +0 -0
  107. /package/dist/integrations/claude_code/skills/{dr_09_ux_layer → dr_10_ux_layer}/SKILL.md +0 -0
  108. /package/dist/integrations/claude_code/skills/{dr_10_navigation_layer → dr_11_navigation_layer}/SKILL.md +0 -0
  109. /package/dist/integrations/claude_code/skills/{dr_11_apm_layer → dr_12_apm_layer}/SKILL.md +0 -0
  110. /package/dist/integrations/claude_code/skills/{dr_12_testing_layer → dr_13_testing_layer}/SKILL.md +0 -0
  111. /package/dist/integrations/github_copilot/skills/{dr_03_security_layer → dr_04_security_layer}/SKILL.md +0 -0
  112. /package/dist/integrations/github_copilot/skills/{dr_04_application_layer → dr_05_application_layer}/SKILL.md +0 -0
  113. /package/dist/integrations/github_copilot/skills/{dr_05_technology_layer → dr_06_technology_layer}/SKILL.md +0 -0
  114. /package/dist/integrations/github_copilot/skills/{dr_06_api_layer → dr_07_api_layer}/SKILL.md +0 -0
  115. /package/dist/integrations/github_copilot/skills/{dr_07_data_model_layer → dr_08_data_model_layer}/SKILL.md +0 -0
  116. /package/dist/integrations/github_copilot/skills/{dr_08_dataset_layer → dr_09_dataset_layer}/SKILL.md +0 -0
  117. /package/dist/integrations/github_copilot/skills/{dr_09_ux_layer → dr_10_ux_layer}/SKILL.md +0 -0
  118. /package/dist/integrations/github_copilot/skills/{dr_10_navigation_layer → dr_11_navigation_layer}/SKILL.md +0 -0
  119. /package/dist/integrations/github_copilot/skills/{dr_11_apm_layer → dr_12_apm_layer}/SKILL.md +0 -0
  120. /package/dist/integrations/github_copilot/skills/{dr_12_testing_layer → dr_13_testing_layer}/SKILL.md +0 -0
@@ -2,7 +2,7 @@ import ansis from "ansis";
2
2
  import { getCliBundledSpecVersion } from "../utils/spec-version.js";
3
3
  import { isTelemetryBuiltIn, isTelemetryConfigured } from "../telemetry/detect.js";
4
4
  import { getSpecReferencePath, getModelPath } from "../utils/project-paths.js";
5
- const gitHash = "f413188", cliVersion = "0.1.8";
5
+ const gitHash = "5345bf8", cliVersion = "0.1.9";
6
6
  async function versionCommand() {
7
7
  const specVersion = getCliBundledSpecVersion(), telemetryBuiltIn = isTelemetryBuiltIn(), telemetryConfigured = await isTelemetryConfigured();
8
8
  let telemetryStatus;
@@ -1,6 +1,7 @@
1
1
  const CANONICAL_LAYER_NAMES = [
2
2
  "motivation",
3
3
  "business",
4
+ "product",
4
5
  "security",
5
6
  "application",
6
7
  "technology",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/core/layers.ts"],
4
- "sourcesContent": ["/**\n * Canonical layer names and ordering for the 12-layer architecture model.\n * This is the source of truth for layer naming and ordering.\n */\n\nexport const CANONICAL_LAYER_NAMES = [\n 'motivation',\n 'business',\n 'security',\n 'application',\n 'technology',\n 'api',\n 'data-model',\n 'data-store',\n 'ux',\n 'navigation',\n 'apm',\n 'testing'\n] as const;\n\nexport type CanonicalLayerName = (typeof CANONICAL_LAYER_NAMES)[number];\n\n/**\n * Get the numeric order of a layer (1-12)\n */\nexport function getLayerOrder(layerName: string): number {\n const index = CANONICAL_LAYER_NAMES.indexOf(layerName as CanonicalLayerName);\n return index >= 0 ? index + 1 : -1;\n}\n\n/**\n * Get layer name by numeric order (1-12)\n */\nexport function getLayerByOrder(order: number): string | undefined {\n if (order < 1 || order > CANONICAL_LAYER_NAMES.length) {\n return undefined;\n }\n return CANONICAL_LAYER_NAMES[order - 1];\n}\n\n/**\n * Check if a layer name is valid (type predicate for compile-time narrowing)\n */\nexport function isValidLayerName(name: string): name is CanonicalLayerName {\n return CANONICAL_LAYER_NAMES.includes(name as CanonicalLayerName);\n}\n"],
5
- "mappings": "AAKO,MAAM,wBAAwB;EACnC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAQI,SAAU,cAAc,WAAiB;AAC7C,QAAM,QAAQ,sBAAsB,QAAQ,SAA+B;AAC3E,SAAO,SAAS,IAAI,QAAQ,IAAI;AAClC;AAKM,SAAU,gBAAgB,OAAa;AAC3C,MAAI,UAAQ,KAAK,QAAQ,sBAAsB;AAG/C,WAAO,sBAAsB,QAAQ,CAAC;AACxC;AAKM,SAAU,iBAAiB,MAAY;AAC3C,SAAO,sBAAsB,SAAS,IAA0B;AAClE;",
4
+ "sourcesContent": ["/**\n * Canonical layer names and ordering for the 13-layer architecture model.\n * This is the source of truth for layer naming and ordering.\n */\n\nexport const CANONICAL_LAYER_NAMES = [\n 'motivation',\n 'business',\n 'product',\n 'security',\n 'application',\n 'technology',\n 'api',\n 'data-model',\n 'data-store',\n 'ux',\n 'navigation',\n 'apm',\n 'testing'\n] as const;\n\nexport type CanonicalLayerName = (typeof CANONICAL_LAYER_NAMES)[number];\n\n/**\n * Get the numeric order of a layer (1-13)\n */\nexport function getLayerOrder(layerName: string): number {\n const index = CANONICAL_LAYER_NAMES.indexOf(layerName as CanonicalLayerName);\n return index >= 0 ? index + 1 : -1;\n}\n\n/**\n * Get layer name by numeric order (1-13)\n */\nexport function getLayerByOrder(order: number): string | undefined {\n if (order < 1 || order > CANONICAL_LAYER_NAMES.length) {\n return undefined;\n }\n return CANONICAL_LAYER_NAMES[order - 1];\n}\n\n/**\n * Check if a layer name is valid (type predicate for compile-time narrowing)\n */\nexport function isValidLayerName(name: string): name is CanonicalLayerName {\n return CANONICAL_LAYER_NAMES.includes(name as CanonicalLayerName);\n}\n"],
5
+ "mappings": "AAKO,MAAM,wBAAwB;EACnC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAQI,SAAU,cAAc,WAAiB;AAC7C,QAAM,QAAQ,sBAAsB,QAAQ,SAA+B;AAC3E,SAAO,SAAS,IAAI,QAAQ,IAAI;AAClC;AAKM,SAAU,gBAAgB,OAAa;AAC3C,MAAI,UAAQ,KAAK,QAAQ,sBAAsB;AAG/C,WAAO,sBAAsB,QAAQ,CAAC;AACxC;AAKM,SAAU,iBAAiB,MAAY;AAC3C,SAAO,sBAAsB,SAAS,IAA0B;AAClE;",
6
6
  "names": []
7
7
  }
@@ -80,6 +80,60 @@ class MigrationRegistry {
80
80
  filesModified: 0,
81
81
  description: "Spec version updated to 0.8.4 (Analyzer Infrastructure)"
82
82
  })
83
+ }), this.migrations.push({
84
+ fromVersion: "0.8.4",
85
+ toVersion: "0.9.0",
86
+ description: "Product Layer Introduction (Spec v0.9.0)",
87
+ apply: async (model) => {
88
+ const fs = await import("fs/promises"), pathModule = await import("path"), modelDir = `${model.rootPath}/documentation-robotics/model`;
89
+ let filesModified = 0;
90
+ try {
91
+ await fs.access(modelDir);
92
+ } catch (error) {
93
+ if (error.code === "ENOENT")
94
+ return {
95
+ migrationsApplied: 1,
96
+ filesModified: 0,
97
+ description: "Spec version updated to 0.9.0 (Product layer introduced; no model directories to migrate)"
98
+ };
99
+ throw error;
100
+ }
101
+ const renameMap = [
102
+ ["12_testing", "13_testing"],
103
+ ["11_apm", "12_apm"],
104
+ ["10_navigation", "11_navigation"],
105
+ ["09_ux", "10_ux"],
106
+ ["08_data-store", "09_data-store"],
107
+ ["07_data-model", "08_data-model"],
108
+ ["06_api", "07_api"],
109
+ ["05_technology", "06_technology"],
110
+ ["04_application", "05_application"],
111
+ ["03_security", "04_security"]
112
+ ], renameErrors = [];
113
+ for (const [oldName, newName] of renameMap) {
114
+ const oldPath = pathModule.join(modelDir, oldName), newPath = pathModule.join(modelDir, newName);
115
+ try {
116
+ await fs.rename(oldPath, newPath), filesModified++;
117
+ } catch (error) {
118
+ if (error.code === "ENOENT")
119
+ continue;
120
+ renameErrors.push(`Failed to rename ${oldName} to ${newName}: ${getErrorMessage(error)}`);
121
+ }
122
+ }
123
+ if (renameErrors.length > 0)
124
+ return {
125
+ migrationsApplied: 1,
126
+ filesModified,
127
+ description: "Spec version updated to 0.9.0 (Product layer introduced at layer 3; Security through Testing shifted from layers 3\u201312 to 4\u201313)",
128
+ error: renameErrors.join("; ")
129
+ };
130
+ const productPath = pathModule.join(modelDir, "03_product");
131
+ return await fs.mkdir(productPath, { recursive: !0 }), {
132
+ migrationsApplied: 1,
133
+ filesModified,
134
+ description: "Spec version updated to 0.9.0 (Product layer introduced at layer 3; Security through Testing shifted from layers 3\u201312 to 4\u201313)"
135
+ };
136
+ }
83
137
  });
84
138
  }
85
139
  /**
@@ -137,12 +191,15 @@ class MigrationRegistry {
137
191
  else
138
192
  try {
139
193
  const result = await migration.apply(model);
140
- results.applied.push({
194
+ if (results.applied.push({
141
195
  from: migration.fromVersion,
142
196
  to: migration.toVersion,
143
197
  description: migration.description,
144
198
  changes: result
145
- }), results.totalChanges += result.migrationsApplied, model.manifest.specVersion = migration.toVersion;
199
+ }), results.totalChanges += result.migrationsApplied, !result.error)
200
+ model.manifest.specVersion = migration.toVersion;
201
+ else
202
+ throw new Error(result.error);
146
203
  } catch (error) {
147
204
  throw new Error(`Migration ${migration.fromVersion} \u2192 ${migration.toVersion} failed: ${getErrorMessage(error)}`);
148
205
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/core/migration-registry.ts"],
4
- "sourcesContent": ["/**\n * Migration Registry - Manages version-based model migrations\n *\n * Handles sequential migrations from one spec version to another,\n * supporting the evolution of the architecture model specification.\n */\n\nimport type { Model } from \"./model.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\n\n/**\n * Represents a single version migration\n */\nexport interface Migration {\n fromVersion: string;\n toVersion: string;\n description: string;\n apply: (model: Model) => Promise<MigrationResult>;\n}\n\n/**\n * Result of applying a migration\n */\nexport interface MigrationResult {\n migrationsApplied: number;\n filesModified: number;\n description: string;\n error?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Migration Registry managing all available migrations\n */\nexport class MigrationRegistry {\n private migrations: Migration[] = [];\n\n constructor() {\n this.registerMigrations();\n }\n\n /**\n * Register all available migrations\n */\n private registerMigrations(): void {\n // Migration from v0.5.0 to v0.6.0: Relationship Taxonomy\n this.migrations.push({\n fromVersion: \"0.5.0\",\n toVersion: \"0.6.0\",\n description: \"Relationship Taxonomy (Spec v0.6.0)\",\n apply: async () => {\n // This migration is opt-in - the new relationship taxonomy\n // is fully backward compatible with existing models\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.6.0 (Relationship Taxonomy now available)\",\n };\n },\n });\n\n // Migration from v0.6.0 to v0.7.0: Layer Schema Relationship Metadata\n this.migrations.push({\n fromVersion: \"0.6.0\",\n toVersion: \"0.7.0\",\n description: \"Layer Schema Relationship Metadata (Spec v0.7.0)\",\n apply: async () => {\n // This migration updates layer schemas with relationship metadata sections\n // - All 12 layer schemas now include layerMetadata, intraLayerRelationships, crossLayerRelationships\n // - Deprecated link-registry.json (removed in v0.8.0)\n // - Terminology change: \"cross-layer links\" \u2192 \"cross-layer relationships\"\n // Fully backward compatible - existing models continue to work\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description:\n \"Spec version updated to 0.7.0 (Layer schemas now include relationship metadata sections)\",\n };\n },\n });\n\n // Migration from v0.7.0 to v0.7.1: Source Code Reference Infrastructure\n this.migrations.push({\n fromVersion: \"0.7.0\",\n toVersion: \"0.7.1\",\n description: \"Source Code Reference Infrastructure (Spec v0.7.1)\",\n apply: async () => {\n // This migration adds source code reference infrastructure\n // - Common schema definitions in spec/schemas/common/\n // - Source references integrated across 10 layers\n // - Backward compatible - existing models continue to work\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.7.1 (Source Code Reference Infrastructure)\",\n };\n },\n });\n\n // Migration from v0.7.1 to v0.8.0: JSON Schema-Only Spec Architecture\n this.migrations.push({\n fromVersion: \"0.7.1\",\n toVersion: \"0.8.0\",\n description: \"JSON Schema-Only Spec Architecture (Spec v0.8.0)\",\n apply: async () => {\n // Spec architecture refactored to JSON Schema-only model:\n // - Node type definitions moved to spec/schemas/nodes/{layer}/*.node.schema.json\n // - Relationship definitions moved to spec/schemas/relationships/{layer}/*.relationship.schema.json\n // - Predicates relocated to spec/schemas/base/predicates.json\n // This is a spec architecture change only - model data files are fully backward compatible\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.0 (JSON Schema-Only Spec Architecture)\",\n };\n },\n });\n\n // Migration from v0.8.0 to v0.8.1: Expanded Relationship Coverage and Node Improvements\n this.migrations.push({\n fromVersion: \"0.8.0\",\n toVersion: \"0.8.1\",\n description: \"Expanded Relationship Coverage and Node Improvements (Spec v0.8.1)\",\n apply: async () => {\n // Spec enhancements only - no model data format changes:\n // - 733 new relationship schemas added across all 12 layers\n // - Node type descriptions improved for all 12 layers\n // - Enum-masquerader node types consolidated into parent attributes\n // - Existing models continue to work without modification\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.1 (Expanded Relationship Coverage and Node Improvements)\",\n };\n },\n });\n\n // Migration from v0.8.1 to v0.8.2: UUID/Path identifier separation\n this.migrations.push({\n fromVersion: \"0.8.1\",\n toVersion: \"0.8.2\",\n description: \"UUID/Path identifier separation (Spec v0.8.2)\",\n apply: async () => {\n // The path field is now required on all spec nodes (spec-node.schema.json).\n // Existing elements are migrated automatically on load in model.ts (loadLayer):\n // - Elements with slug-format id: slug moved to path, deterministic UUID assigned to id\n // - Elements with UUID id but no path: path derived from layer_id.type.kebab(name)\n // No manual data file changes needed; migration runs transparently on next load/save.\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.2 (UUID/Path identifier separation)\",\n };\n },\n });\n\n // Migration from v0.8.2 to v0.8.3: Inter-layer Relationship Schemas and APM Node Types\n this.migrations.push({\n fromVersion: \"0.8.2\",\n toVersion: \"0.8.3\",\n description: \"Inter-layer Relationship Schemas and APM Node Types (Spec v0.8.3)\",\n apply: async () => {\n // Major expansion of inter-layer relationship coverage and APM layer:\n // - 495 new inter-layer relationship schemas across all 12 layers\n // - Total relationship count increased from 969 to 1,447\n // - 2 new APM node types: apm.alert and apm.dashboard\n // - Backward compatible - existing models continue to work without modification\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.3 (Inter-layer Relationship Schemas and APM Node Types)\",\n };\n },\n });\n\n // Migration from v0.8.3 to v0.8.4: Analyzer Infrastructure (CBM Mapping)\n this.migrations.push({\n fromVersion: \"0.8.3\",\n toVersion: \"0.8.4\",\n description: \"Analyzer Infrastructure (Spec v0.8.4)\",\n apply: async () => {\n // Introduces spec/analyzers/ with codebase-memory (CBM) mapping:\n // - New analyzer adapter foundation and full analyzer subcommands\n // - dr analyzer verify with changeset awareness\n // - Claude Code integration commands (/dr-verify, /dr-map, dr-extractor)\n // - No model data format changes; existing models are fully compatible\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.4 (Analyzer Infrastructure)\",\n };\n },\n });\n }\n\n /**\n * Get the latest available specification version\n */\n getLatestVersion(): string {\n if (this.migrations.length === 0) {\n return \"0.7.0\";\n }\n\n // Return the highest toVersion from all migrations\n const versions = this.migrations.map((m) => m.toVersion);\n return versions.sort().reverse()[0];\n }\n\n /**\n * Get the sequence of migrations needed from one version to another\n */\n getMigrationPath(fromVersion: string, toVersion?: string): Migration[] {\n const targetVersion = toVersion || this.getLatestVersion();\n\n if (this.compareVersions(fromVersion, targetVersion) >= 0) {\n return [];\n }\n\n const path: Migration[] = [];\n let current = fromVersion;\n\n // Sort migrations by fromVersion\n const sortedMigrations = [...this.migrations].sort((a, b) =>\n this.compareVersions(a.fromVersion, b.fromVersion)\n );\n\n for (const migration of sortedMigrations) {\n // Check if this migration is in our path\n if (\n this.compareVersions(current, migration.fromVersion) >= 0 &&\n this.compareVersions(current, migration.toVersion) < 0 &&\n this.compareVersions(migration.toVersion, targetVersion) <= 0\n ) {\n path.push(migration);\n current = migration.toVersion;\n }\n }\n\n return path;\n }\n\n /**\n * Check if a model requires migration\n */\n requiresMigration(currentVersion: string): boolean {\n const path = this.getMigrationPath(currentVersion);\n return path.length > 0;\n }\n\n /**\n * Apply all migrations in sequence\n */\n async applyMigrations(\n model: Model,\n options: {\n fromVersion: string;\n toVersion?: string;\n dryRun?: boolean;\n validate?: boolean;\n }\n ): Promise<ApplyMigrationsResult> {\n const path = this.getMigrationPath(options.fromVersion, options.toVersion);\n const targetVersion = options.toVersion || this.getLatestVersion();\n\n if (path.length === 0) {\n return {\n applied: [],\n currentVersion: options.fromVersion,\n targetVersion,\n totalChanges: 0,\n };\n }\n\n const results: ApplyMigrationsResult = {\n applied: [],\n currentVersion: options.fromVersion,\n targetVersion,\n totalChanges: 0,\n };\n\n for (const migration of path) {\n if (!options.dryRun) {\n try {\n const result = await migration.apply(model);\n\n results.applied.push({\n from: migration.fromVersion,\n to: migration.toVersion,\n description: migration.description,\n changes: result,\n });\n\n results.totalChanges += result.migrationsApplied;\n\n // Update model's spec version\n model.manifest.specVersion = migration.toVersion;\n } catch (error) {\n throw new Error(\n `Migration ${migration.fromVersion} \u2192 ${migration.toVersion} failed: ${\n getErrorMessage(error)\n }`\n );\n }\n } else {\n // Dry run - just record what would happen\n results.applied.push({\n from: migration.fromVersion,\n to: migration.toVersion,\n description: migration.description,\n dryRun: true,\n });\n }\n }\n\n return results;\n }\n\n /**\n * Get a summary of migrations that would be applied\n */\n getMigrationSummary(\n fromVersion: string,\n toVersion?: string\n ): {\n currentVersion: string;\n targetVersion: string;\n migrationsNeeded: number;\n migrations: Array<{\n from: string;\n to: string;\n description: string;\n }>;\n } {\n const path = this.getMigrationPath(fromVersion, toVersion);\n const targetVersion = toVersion || this.getLatestVersion();\n\n return {\n currentVersion: fromVersion,\n targetVersion,\n migrationsNeeded: path.length,\n migrations: path.map((m) => ({\n from: m.fromVersion,\n to: m.toVersion,\n description: m.description,\n })),\n };\n }\n\n /**\n * Compare two version strings\n * Returns: -1 if a < b, 0 if a == b, 1 if a > b\n */\n private compareVersions(a: string, b: string): number {\n const aParts = a.split(\".\").map(Number);\n const bParts = b.split(\".\").map(Number);\n\n const maxLength = Math.max(aParts.length, bParts.length);\n\n for (let i = 0; i < maxLength; i++) {\n const aPart = aParts[i] || 0;\n const bPart = bParts[i] || 0;\n\n if (aPart < bPart) return -1;\n if (aPart > bPart) return 1;\n }\n\n return 0;\n }\n}\n\n/**\n * Result of applying multiple migrations\n */\nexport interface ApplyMigrationsResult {\n applied: Array<{\n from: string;\n to: string;\n description: string;\n changes?: MigrationResult;\n dryRun?: boolean;\n }>;\n currentVersion: string;\n targetVersion: string;\n totalChanges: number;\n}\n"],
5
- "mappings": "AAQA,SAAS,uBAAuB;AA0B1B,MAAO,kBAAiB;EACpB,aAA0B,CAAA;EAElC,cAAA;AACE,SAAK,mBAAkB;EACzB;;;;EAKQ,qBAAkB;AAExB,SAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAGE;QACL,mBAAmB;QACnB,eAAe;QACf,aAAa;;KAGlB,GAGD,KAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAME;QACL,mBAAmB;QACnB,eAAe;QACf,aACE;;KAGP,GAGD,KAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAKE;QACL,mBAAmB;QACnB,eAAe;QACf,aAAa;;KAGlB,GAGD,KAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAME;QACL,mBAAmB;QACnB,eAAe;QACf,aAAa;;KAGlB,GAGD,KAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAME;QACL,mBAAmB;QACnB,eAAe;QACf,aAAa;;KAGlB,GAGD,KAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAME;QACL,mBAAmB;QACnB,eAAe;QACf,aAAa;;KAGlB,GAGD,KAAK,WAAW,KAAK;MACnB,aAAa;MACb,WAAW;MACX,aAAa;MACb,OAAO,aAME;QACL,mBAAmB;QACnB,eAAe;QACf,aAAa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AAQ,KAAK;UACnB,MAAM,UAAU;UAChB,IAAI,UAAU;UACd,aAAa,UAAU;UACvB,QAAQ;SACT;;AA5BD,YAAI;AACF,gBAAM,SAAS,MAAM,UAAU,MAAM,KAAK;AAE1C,kBAAQ,QAAQ,KAAK;YACnB,MAAM,UAAU;YAChB,IAAI,UAAU;YACd,aAAa,UAAU;YACvB,SAAS;WACV,GAED,QAAQ,gBAAgB,OAAO,mBAG/B,MAAM,SAAS,cAAc,UAAU;QACzC,SAAS,OAAO;AACd,gBAAM,IAAI,MACR,aAAa,UAAU,WAAW,WAAM,UAAU,SAAS,YACzD,gBAAgB,KAAK,CACvB,EAAE;QAEN;AAYJ,WAAO;EACT;;;;EAKA,oBACE,aACA,WAAkB;AAWlB,UAAM,OAAO,KAAK,iBAAiB,aAAa,SAAS,GACnD,gBAAgB,aAAa,KAAK,iBAAgB;AAExD,WAAO;MACL,gBAAgB;MAChB;MACA,kBAAkB,KAAK;MACvB,YAAY,KAAK,IAAI,CAAC,OAAO;QAC3B,MAAM,EAAE;QACR,IAAI,EAAE;QACN,aAAa,EAAE;QACf;;EAEN;;;;;EAMQ,gBAAgB,GAAW,GAAS;AAC1C,UAAM,SAAS,EAAE,MAAM,GAAG,EAAE,IAAI,MAAM,GAChC,SAAS,EAAE,MAAM,GAAG,EAAE,IAAI,MAAM,GAEhC,YAAY,KAAK,IAAI,OAAO,QAAQ,OAAO,MAAM;AAEvD,aAAS,IAAI,GAAG,IAAI,WAAW,KAAK;AAClC,YAAM,QAAQ,OAAO,CAAC,KAAK,GACrB,QAAQ,OAAO,CAAC,KAAK;AAE3B,UAAI,QAAQ;AAAO,eAAO;AAC1B,UAAI,QAAQ;AAAO,eAAO;IAC5B;AAEA,WAAO;EACT;;",
4
+ "sourcesContent": ["/**\n * Migration Registry - Manages version-based model migrations\n *\n * Handles sequential migrations from one spec version to another,\n * supporting the evolution of the architecture model specification.\n */\n\nimport type { Model } from \"./model.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\n\n/**\n * Represents a single version migration\n */\nexport interface Migration {\n fromVersion: string;\n toVersion: string;\n description: string;\n apply: (model: Model) => Promise<MigrationResult>;\n}\n\n/**\n * Result of applying a migration\n */\nexport interface MigrationResult {\n migrationsApplied: number;\n filesModified: number;\n description: string;\n error?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Migration Registry managing all available migrations\n */\nexport class MigrationRegistry {\n private migrations: Migration[] = [];\n\n constructor() {\n this.registerMigrations();\n }\n\n /**\n * Register all available migrations\n */\n private registerMigrations(): void {\n // Migration from v0.5.0 to v0.6.0: Relationship Taxonomy\n this.migrations.push({\n fromVersion: \"0.5.0\",\n toVersion: \"0.6.0\",\n description: \"Relationship Taxonomy (Spec v0.6.0)\",\n apply: async () => {\n // This migration is opt-in - the new relationship taxonomy\n // is fully backward compatible with existing models\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.6.0 (Relationship Taxonomy now available)\",\n };\n },\n });\n\n // Migration from v0.6.0 to v0.7.0: Layer Schema Relationship Metadata\n this.migrations.push({\n fromVersion: \"0.6.0\",\n toVersion: \"0.7.0\",\n description: \"Layer Schema Relationship Metadata (Spec v0.7.0)\",\n apply: async () => {\n // This migration updates layer schemas with relationship metadata sections\n // - All 12 layer schemas now include layerMetadata, intraLayerRelationships, crossLayerRelationships\n // - Deprecated link-registry.json (removed in v0.8.0)\n // - Terminology change: \"cross-layer links\" \u2192 \"cross-layer relationships\"\n // Fully backward compatible - existing models continue to work\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description:\n \"Spec version updated to 0.7.0 (Layer schemas now include relationship metadata sections)\",\n };\n },\n });\n\n // Migration from v0.7.0 to v0.7.1: Source Code Reference Infrastructure\n this.migrations.push({\n fromVersion: \"0.7.0\",\n toVersion: \"0.7.1\",\n description: \"Source Code Reference Infrastructure (Spec v0.7.1)\",\n apply: async () => {\n // This migration adds source code reference infrastructure\n // - Common schema definitions in spec/schemas/common/\n // - Source references integrated across 10 layers\n // - Backward compatible - existing models continue to work\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.7.1 (Source Code Reference Infrastructure)\",\n };\n },\n });\n\n // Migration from v0.7.1 to v0.8.0: JSON Schema-Only Spec Architecture\n this.migrations.push({\n fromVersion: \"0.7.1\",\n toVersion: \"0.8.0\",\n description: \"JSON Schema-Only Spec Architecture (Spec v0.8.0)\",\n apply: async () => {\n // Spec architecture refactored to JSON Schema-only model:\n // - Node type definitions moved to spec/schemas/nodes/{layer}/*.node.schema.json\n // - Relationship definitions moved to spec/schemas/relationships/{layer}/*.relationship.schema.json\n // - Predicates relocated to spec/schemas/base/predicates.json\n // This is a spec architecture change only - model data files are fully backward compatible\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.0 (JSON Schema-Only Spec Architecture)\",\n };\n },\n });\n\n // Migration from v0.8.0 to v0.8.1: Expanded Relationship Coverage and Node Improvements\n this.migrations.push({\n fromVersion: \"0.8.0\",\n toVersion: \"0.8.1\",\n description: \"Expanded Relationship Coverage and Node Improvements (Spec v0.8.1)\",\n apply: async () => {\n // Spec enhancements only - no model data format changes:\n // - 733 new relationship schemas added across all 12 layers\n // - Node type descriptions improved for all 12 layers\n // - Enum-masquerader node types consolidated into parent attributes\n // - Existing models continue to work without modification\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.1 (Expanded Relationship Coverage and Node Improvements)\",\n };\n },\n });\n\n // Migration from v0.8.1 to v0.8.2: UUID/Path identifier separation\n this.migrations.push({\n fromVersion: \"0.8.1\",\n toVersion: \"0.8.2\",\n description: \"UUID/Path identifier separation (Spec v0.8.2)\",\n apply: async () => {\n // The path field is now required on all spec nodes (spec-node.schema.json).\n // Existing elements are migrated automatically on load in model.ts (loadLayer):\n // - Elements with slug-format id: slug moved to path, deterministic UUID assigned to id\n // - Elements with UUID id but no path: path derived from layer_id.type.kebab(name)\n // No manual data file changes needed; migration runs transparently on next load/save.\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.2 (UUID/Path identifier separation)\",\n };\n },\n });\n\n // Migration from v0.8.2 to v0.8.3: Inter-layer Relationship Schemas and APM Node Types\n this.migrations.push({\n fromVersion: \"0.8.2\",\n toVersion: \"0.8.3\",\n description: \"Inter-layer Relationship Schemas and APM Node Types (Spec v0.8.3)\",\n apply: async () => {\n // Major expansion of inter-layer relationship coverage and APM layer:\n // - 495 new inter-layer relationship schemas across all 12 layers\n // - Total relationship count increased from 969 to 1,447\n // - 2 new APM node types: apm.alert and apm.dashboard\n // - Backward compatible - existing models continue to work without modification\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.3 (Inter-layer Relationship Schemas and APM Node Types)\",\n };\n },\n });\n\n // Migration from v0.8.3 to v0.8.4: Analyzer Infrastructure (CBM Mapping)\n this.migrations.push({\n fromVersion: \"0.8.3\",\n toVersion: \"0.8.4\",\n description: \"Analyzer Infrastructure (Spec v0.8.4)\",\n apply: async () => {\n // Introduces spec/analyzers/ with codebase-memory (CBM) mapping:\n // - New analyzer adapter foundation and full analyzer subcommands\n // - dr analyzer verify with changeset awareness\n // - Claude Code integration commands (/dr-verify, /dr-map, dr-extractor)\n // - No model data format changes; existing models are fully compatible\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description: \"Spec version updated to 0.8.4 (Analyzer Infrastructure)\",\n };\n },\n });\n\n // Migration from v0.8.4 to v0.9.0: Product Layer Introduction\n this.migrations.push({\n fromVersion: \"0.8.4\",\n toVersion: \"0.9.0\",\n description: \"Product Layer Introduction (Spec v0.9.0)\",\n apply: async (model: Model) => {\n const fs = await import(\"fs/promises\");\n const pathModule = await import(\"path\");\n\n const modelDir = `${model.rootPath}/documentation-robotics/model`;\n let filesModified = 0;\n\n try {\n // Verify model directory exists\n await fs.access(modelDir);\n } catch (error) {\n const err = error as { code?: string };\n // ENOENT means the directory doesn't exist - nothing to migrate\n if (err.code === \"ENOENT\") {\n return {\n migrationsApplied: 1,\n filesModified: 0,\n description:\n \"Spec version updated to 0.9.0 (Product layer introduced; no model directories to migrate)\",\n };\n }\n // Re-throw other errors (e.g., EACCES for permission denied)\n throw error;\n }\n\n // Rename existing layer directories: shift from 03-12 to 04-13\n // Must do this in reverse order (12\u219213, 11\u219212, ..., 03\u219204) to avoid conflicts\n const renameMap = [\n [\"12_testing\", \"13_testing\"],\n [\"11_apm\", \"12_apm\"],\n [\"10_navigation\", \"11_navigation\"],\n [\"09_ux\", \"10_ux\"],\n [\"08_data-store\", \"09_data-store\"],\n [\"07_data-model\", \"08_data-model\"],\n [\"06_api\", \"07_api\"],\n [\"05_technology\", \"06_technology\"],\n [\"04_application\", \"05_application\"],\n [\"03_security\", \"04_security\"],\n ];\n\n const renameErrors: string[] = [];\n\n for (const [oldName, newName] of renameMap) {\n const oldPath = pathModule.join(modelDir, oldName);\n const newPath = pathModule.join(modelDir, newName);\n\n try {\n await fs.rename(oldPath, newPath);\n filesModified++;\n } catch (error) {\n const err = error as { code?: string };\n // ENOENT is expected when a directory hasn't been created yet\n if (err.code === \"ENOENT\") {\n continue;\n }\n // Track non-ENOENT errors to report them in the result\n renameErrors.push(\n `Failed to rename ${oldName} to ${newName}: ${getErrorMessage(error)}`\n );\n }\n }\n\n // If there were any rename failures, include them in the error field\n if (renameErrors.length > 0) {\n return {\n migrationsApplied: 1,\n filesModified,\n description:\n \"Spec version updated to 0.9.0 (Product layer introduced at layer 3; Security through Testing shifted from layers 3\u201312 to 4\u201313)\",\n error: renameErrors.join(\"; \"),\n };\n }\n\n // Create new product layer directory (it will be empty for now)\n // recursive: true handles EEXIST, so no catch needed\n const productPath = pathModule.join(modelDir, \"03_product\");\n await fs.mkdir(productPath, { recursive: true });\n\n return {\n migrationsApplied: 1,\n filesModified,\n description:\n \"Spec version updated to 0.9.0 (Product layer introduced at layer 3; Security through Testing shifted from layers 3\u201312 to 4\u201313)\",\n };\n },\n });\n }\n\n /**\n * Get the latest available specification version\n */\n getLatestVersion(): string {\n if (this.migrations.length === 0) {\n return \"0.7.0\";\n }\n\n // Return the highest toVersion from all migrations\n const versions = this.migrations.map((m) => m.toVersion);\n return versions.sort().reverse()[0];\n }\n\n /**\n * Get the sequence of migrations needed from one version to another\n */\n getMigrationPath(fromVersion: string, toVersion?: string): Migration[] {\n const targetVersion = toVersion || this.getLatestVersion();\n\n if (this.compareVersions(fromVersion, targetVersion) >= 0) {\n return [];\n }\n\n const path: Migration[] = [];\n let current = fromVersion;\n\n // Sort migrations by fromVersion\n const sortedMigrations = [...this.migrations].sort((a, b) =>\n this.compareVersions(a.fromVersion, b.fromVersion)\n );\n\n for (const migration of sortedMigrations) {\n // Check if this migration is in our path\n if (\n this.compareVersions(current, migration.fromVersion) >= 0 &&\n this.compareVersions(current, migration.toVersion) < 0 &&\n this.compareVersions(migration.toVersion, targetVersion) <= 0\n ) {\n path.push(migration);\n current = migration.toVersion;\n }\n }\n\n return path;\n }\n\n /**\n * Check if a model requires migration\n */\n requiresMigration(currentVersion: string): boolean {\n const path = this.getMigrationPath(currentVersion);\n return path.length > 0;\n }\n\n /**\n * Apply all migrations in sequence\n */\n async applyMigrations(\n model: Model,\n options: {\n fromVersion: string;\n toVersion?: string;\n dryRun?: boolean;\n validate?: boolean;\n }\n ): Promise<ApplyMigrationsResult> {\n const path = this.getMigrationPath(options.fromVersion, options.toVersion);\n const targetVersion = options.toVersion || this.getLatestVersion();\n\n if (path.length === 0) {\n return {\n applied: [],\n currentVersion: options.fromVersion,\n targetVersion,\n totalChanges: 0,\n };\n }\n\n const results: ApplyMigrationsResult = {\n applied: [],\n currentVersion: options.fromVersion,\n targetVersion,\n totalChanges: 0,\n };\n\n for (const migration of path) {\n if (!options.dryRun) {\n try {\n const result = await migration.apply(model);\n\n results.applied.push({\n from: migration.fromVersion,\n to: migration.toVersion,\n description: migration.description,\n changes: result,\n });\n\n results.totalChanges += result.migrationsApplied;\n\n // Only update model's spec version if migration succeeded (no error field)\n if (!result.error) {\n model.manifest.specVersion = migration.toVersion;\n } else {\n // If migration has errors, throw to prevent partial success state\n throw new Error(result.error);\n }\n } catch (error) {\n throw new Error(\n `Migration ${migration.fromVersion} \u2192 ${migration.toVersion} failed: ${\n getErrorMessage(error)\n }`\n );\n }\n } else {\n // Dry run - just record what would happen\n results.applied.push({\n from: migration.fromVersion,\n to: migration.toVersion,\n description: migration.description,\n dryRun: true,\n });\n }\n }\n\n return results;\n }\n\n /**\n * Get a summary of migrations that would be applied\n */\n getMigrationSummary(\n fromVersion: string,\n toVersion?: string\n ): {\n currentVersion: string;\n targetVersion: string;\n migrationsNeeded: number;\n migrations: Array<{\n from: string;\n to: string;\n description: string;\n }>;\n } {\n const path = this.getMigrationPath(fromVersion, toVersion);\n const targetVersion = toVersion || this.getLatestVersion();\n\n return {\n currentVersion: fromVersion,\n targetVersion,\n migrationsNeeded: path.length,\n migrations: path.map((m) => ({\n from: m.fromVersion,\n to: m.toVersion,\n description: m.description,\n })),\n };\n }\n\n /**\n * Compare two version strings\n * Returns: -1 if a < b, 0 if a == b, 1 if a > b\n */\n private compareVersions(a: string, b: string): number {\n const aParts = a.split(\".\").map(Number);\n const bParts = b.split(\".\").map(Number);\n\n const maxLength = Math.max(aParts.length, bParts.length);\n\n for (let i = 0; i < maxLength; i++) {\n const aPart = aParts[i] || 0;\n const bPart = bParts[i] || 0;\n\n if (aPart < bPart) return -1;\n if (aPart > bPart) return 1;\n }\n\n return 0;\n }\n}\n\n/**\n * Result of applying multiple migrations\n */\nexport interface ApplyMigrationsResult {\n applied: Array<{\n from: string;\n to: string;\n description: string;\n changes?: MigrationResult;\n dryRun?: boolean;\n }>;\n currentVersion: string;\n targetVersion: string;\n totalChanges: number;\n}\n"],
5
+ "mappings": "AAQA,SAAS,uBAAuB;AA0B1B,MAAO,kBAAiB;EACpB,aAA0B,CAAA;EAElC,cAAA;AACE,SAAK,mBAAkB;EACzB;;;;EAKQ,qBAAkB;AAExB,SAAK,WAAW,KAAK;MACnB,aAAa;MACb,WA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EN;AAYJ,WAAO;EACT;;;;EAKA,oBACE,aACA,WAAkB;AAWlB,UAAM,OAAO,KAAK,iBAAiB,aAAa,SAAS,GACnD,gBAAgB,aAAa,KAAK,iBAAgB;AAExD,WAAO;MACL,gBAAgB;MAChB;MACA,kBAAkB,KAAK;MACvB,YAAY,KAAK,IAAI,CAAC,OAAO;QAC3B,MAAM,EAAE;QACR,IAAI,EAAE;QACN,aAAa,EAAE;QACf;;EAEN;;;;;EAMQ,gBAAgB,GAAW,GAAS;AAC1C,UAAM,SAAS,EAAE,MAAM,GAAG,EAAE,IAAI,MAAM,GAChC,SAAS,EAAE,MAAM,GAAG,EAAE,IAAI,MAAM,GAEhC,YAAY,KAAK,IAAI,OAAO,QAAQ,OAAO,MAAM;AAEvD,aAAS,IAAI,GAAG,IAAI,WAAW,KAAK;AAClC,YAAM,QAAQ,OAAO,CAAC,KAAK,GACrB,QAAQ,OAAO,CAAC,KAAK;AAE3B,UAAI,QAAQ;AAAO,eAAO;AAC1B,UAAI,QAAQ;AAAO,eAAO;IAC5B;AAEA,WAAO;EACT;;",
6
6
  "names": []
7
7
  }
@@ -314,22 +314,9 @@ class Model {
314
314
  },
315
315
  documentation: ".dr/README.md",
316
316
  layers: {}
317
- }, layerOrder = [
318
- "motivation",
319
- "business",
320
- "security",
321
- "application",
322
- "technology",
323
- "api",
324
- "data-model",
325
- "data-store",
326
- "ux",
327
- "navigation",
328
- "apm",
329
- "testing"
330
- ];
331
- for (let i = 0; i < layerOrder.length; i++) {
332
- const layerName = layerOrder[i], layer = this.layers.get(layerName), orderNum = String(i + 1).padStart(2, "0");
317
+ };
318
+ for (let i = 0; i < CANONICAL_LAYER_NAMES.length; i++) {
319
+ const layerName = CANONICAL_LAYER_NAMES[i], layer = this.layers.get(layerName), orderNum = String(i + 1).padStart(2, "0");
333
320
  yamlData.layers[layerName] = {
334
321
  order: i + 1,
335
322
  name: layerName.charAt(0).toUpperCase() + layerName.slice(1).replace("-", " "),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/core/model.ts"],
4
- "sourcesContent": ["import { Layer } from \"./layer.js\";\nimport { Manifest } from \"./manifest.js\";\nimport { Element } from \"./element.js\";\nimport { GraphModel, type GraphEdge } from \"./graph-model.js\";\nimport { VirtualProjectionEngine } from \"./virtual-projection.js\";\nimport { StagedChangesetStorage } from \"./staged-changeset-storage.js\";\nimport { Relationships } from \"./relationships.js\";\nimport { CANONICAL_LAYER_NAMES } from \"./layers.js\";\nimport type { StagedChange } from \"./changeset.js\";\nimport { ensureDir, writeFile } from \"../utils/file-io.js\";\nimport { getCliVersion } from \"../utils/spec-version.js\";\nimport { startSpan, endSpan, startActiveSpan } from \"../telemetry/index.js\";\nimport { findProjectRoot } from \"../utils/project-paths.js\";\nimport { getNodeType } from \"../generated/node-types.js\";\nimport type { SpecNodeId } from \"../generated/node-types.js\";\nimport type { ManifestData, ModelOptions } from \"../types/index.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport crypto from \"node:crypto\";\n\n/**\n * Derive a deterministic UUID from a path string using SHA-256.\n * Produces a stable UUID4-like value so migration doesn't regenerate UUIDs on every load.\n */\nfunction deterministicUUID(path: string): string {\n const hash = crypto.createHash(\"sha256\").update(path).digest(\"hex\");\n return [\n hash.slice(0, 8),\n hash.slice(8, 12),\n \"4\" + hash.slice(13, 16), // version 4 marker\n ((parseInt(hash.slice(16, 18), 16) & 0x3f) | 0x80).toString(16) + hash.slice(18, 20), // variant\n hash.slice(20, 32),\n ].join(\"-\");\n}\n\n/**\n * Convert a PascalCase title to snake_case.\n * Handles acronyms correctly: \"UXApplication\" \u2192 \"ux_application\", \"OpenAPIDocument\" \u2192 \"open_api_document\".\n */\nfunction titleToSnakeCase(title: string): string {\n return title\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\") // \"APIDoc\" \u2192 \"API_Doc\"\n .replace(/([a-z\\d])([A-Z])/g, \"$1_$2\") // \"appComponent\" \u2192 \"app_Component\"\n .toLowerCase();\n}\n\n/**\n * Derive a snake_case file stem for a given element type.\n * Uses the spec node title for accurate word boundaries (e.g., \"InputSpacePartition\" \u2192 \"input_space_partition\").\n * Falls back to the raw type string when the title is unavailable.\n */\nfunction typeToSnakeStem(specNodeId: string | undefined, type: string): string {\n if (specNodeId) {\n const nodeType = getNodeType(specNodeId as SpecNodeId);\n if (nodeType?.title) {\n return titleToSnakeCase(nodeType.title);\n }\n }\n return type;\n}\n\n// Fallback for runtime environments where TELEMETRY_ENABLED is not defined by esbuild\ndeclare const TELEMETRY_ENABLED: boolean | undefined;\nconst isTelemetryEnabled = typeof TELEMETRY_ENABLED !== \"undefined\" ? TELEMETRY_ENABLED : false;\n\n/**\n * Model class representing the complete architecture model\n * Uses GraphModel internally for graph-based storage\n */\nexport class Model {\n rootPath: string;\n manifest: Manifest;\n graph: GraphModel;\n layers: Map<string, Layer>;\n relationships: Relationships;\n lazyLoad: boolean;\n private loadedLayers: Set<string>;\n private virtualProjectionEngine?: VirtualProjectionEngine;\n /** ID of the currently active changeset, or null if none is active. Set during load(). */\n private _activeChangesetId: string | null = null;\n /** Layer names that exist only in staged changes (not yet committed to base model). */\n private _stagedLayerNames: Set<string> = new Set();\n\n constructor(rootPath: string, manifest: Manifest, options: ModelOptions = {}) {\n this.rootPath = rootPath;\n this.manifest = manifest;\n this.graph = new GraphModel();\n this.layers = new Map();\n this.relationships = new Relationships();\n this.lazyLoad = options.lazyLoad ?? false;\n this.loadedLayers = new Set();\n }\n\n /**\n * Get the committed base layer (no staging projection).\n * Used internally by VirtualProjectionEngine and commit() to access the raw base model\n * without triggering infinite recursion or double-projection.\n */\n async getBaseLayer(name: string): Promise<Layer | undefined> {\n if (this.lazyLoad && !this.loadedLayers.has(name)) {\n await this.loadLayer(name);\n }\n return this.layers.get(name);\n }\n\n /**\n * Get a layer, transparently merging staged changes when an active changeset exists.\n * Falls back to the committed base layer if no changeset is active or projection fails.\n */\n async getLayer(name: string): Promise<Layer | undefined> {\n if (this.lazyLoad && !this.loadedLayers.has(name)) {\n await this.loadLayer(name);\n }\n\n // If an active changeset is present, return a projected (base + staged) layer\n if (this._activeChangesetId) {\n try {\n return await this.getVirtualProjectionEngine().projectLayer(\n this,\n this._activeChangesetId,\n name\n );\n } catch {\n // Fall back to base layer on projection failure (e.g. corrupt changeset)\n return this.layers.get(name);\n }\n }\n\n return this.layers.get(name);\n }\n\n /**\n * Get an element by ID across all layers\n * Supports both UUID and semantic ID (layer.type.kebab-name) lookup\n */\n getElementById(id: string): Element | undefined {\n for (const layer of this.layers.values()) {\n const element = layer.getElement(id);\n if (element) {\n return element;\n }\n }\n return undefined;\n }\n\n /**\n * Get virtual projection engine (lazily initialized)\n */\n getVirtualProjectionEngine(): VirtualProjectionEngine {\n if (!this.virtualProjectionEngine) {\n this.virtualProjectionEngine = new VirtualProjectionEngine(this.rootPath);\n }\n return this.virtualProjectionEngine;\n }\n\n /**\n * Returns the active changeset ID, or null if no changeset is active.\n * Used by commands that need to project the full model (e.g. validate).\n */\n getActiveChangesetId(): string | null {\n return this._activeChangesetId;\n }\n\n /**\n * Load a layer from disk (model/XX_layername/*.yaml files)\n */\n async loadLayer(name: string): Promise<void> {\n await startActiveSpan(\"layer.load\", async (layerSpan) => {\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n\n let layerPath: string | null = null;\n\n // Auto-discover by scanning directory with naming convention\n const modelDir = `${this.rootPath}/documentation-robotics/model`;\n\n try {\n const entries = await fs.readdir(modelDir, { withFileTypes: true });\n const layerDir = entries.find(\n (e) =>\n e.isDirectory() && e.name.match(/^\\d{2}_/) && e.name.replace(/^\\d{2}_/, \"\") === name\n );\n\n if (layerDir) {\n layerPath = `${modelDir}/${layerDir.name}`;\n }\n } catch {\n // Model directory doesn't exist or can't be read\n }\n\n if (!layerPath) {\n return; // Layer directory not found\n }\n\n const layer = new Layer(name, this.graph);\n let parseErrorCount = 0;\n\n // Load all YAML files in the layer directory\n const files = await fs.readdir(layerPath);\n for (const file of files) {\n if (file.endsWith(\".yaml\") || file.endsWith(\".yml\")) {\n const filePath = `${layerPath}/${file}`;\n try {\n const yamlContent = await fs.readFile(filePath, \"utf-8\");\n const elements = yaml.parse(yamlContent);\n\n // Add each element from the YAML file\n if (elements && typeof elements === \"object\") {\n for (const [key, element] of Object.entries(elements)) {\n if (element && typeof element === \"object\") {\n const el: any = element;\n\n // Derive id, path, and type using the 3-case migration logic:\n // Case 1: element already has both id (UUID) and path \u2192 use as-is\n // Case 2: element.id looks like a slug (layer.type.name) \u2192 move to path, generate UUID\n // Case 3: element has UUID id but no path \u2192 derive path from layer_id.type.kebab(name)\n const isSlugPattern = /^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$/.test(el.id || \"\");\n const isUUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(el.id || \"\");\n\n let elementId: string;\n let elementPath: string;\n let extractedType: string | undefined = undefined;\n\n if (el.path && isUUIDPattern) {\n // Case 1: already has both path and UUID id\n elementId = el.id;\n elementPath = el.path;\n const pathParts = el.path.split(\".\");\n if (pathParts.length >= 3) extractedType = pathParts[1];\n } else if (el.path && !isUUIDPattern) {\n // Has a path but id is not a UUID \u2014 migrate id to deterministic UUID\n elementPath = el.path;\n elementId = deterministicUUID(el.path);\n const pathParts = el.path.split(\".\");\n if (pathParts.length >= 3) extractedType = pathParts[1];\n } else if (isSlugPattern) {\n // Case 2: slug-looking id \u2192 move to path, generate deterministic UUID\n elementPath = el.id;\n elementId = deterministicUUID(el.id);\n const parts = el.id.split(\".\");\n if (parts.length >= 3) extractedType = parts[1];\n } else if (isUUIDPattern) {\n // Case 3: UUID id, no path \u2192 derive path\n elementId = el.id;\n const layerId = el.layer_id || name;\n const rawType = el.type || \"\";\n const rawName = el.name || key;\n const kebabName = rawName.toLowerCase().replace(/[\\s_]+/g, \"-\").replace(/[^a-z0-9-]/g, \"\").replace(/-+/g, \"-\").replace(/^-+|-+$/g, \"\");\n elementPath = `${layerId}.${rawType}.${kebabName}`;\n extractedType = rawType || undefined;\n } else {\n // Fallback: derive a path from available data, generate deterministic UUID\n const layerId = el.layer_id || name;\n const rawType = el.type || (typeof el.id === \"string\" && el.id.includes(\".\") ? el.id.split(\".\")[1] : \"\") || \"\";\n const rawName = el.name || key;\n const kebabName = rawName.toLowerCase().replace(/[\\s_]+/g, \"-\").replace(/[^a-z0-9-]/g, \"\").replace(/-+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"unknown\";\n elementPath = `${layerId}.${rawType || \"element\"}.${kebabName}`;\n elementId = deterministicUUID(elementPath);\n if (rawType) extractedType = rawType;\n else if (typeof el.id === \"string\" && el.id.includes(\".\")) {\n const parts = el.id.split(\".\");\n if (parts.length >= 3) extractedType = parts[1];\n }\n }\n\n const elementName = el.name || key;\n const elementType = el.type || extractedType;\n const layerId = el.layer_id || name;\n\n const newElement = new Element({\n id: elementId,\n path: elementPath,\n spec_node_id: el.spec_node_id,\n layer_id: layerId,\n attributes: el.attributes,\n source_reference: el.source_reference,\n metadata: el.metadata,\n name: elementName,\n type: elementType,\n description: el.description || \"\",\n relationships: el.relationships || [],\n references: el.references || [],\n layer: layerId,\n } as any);\n layer.addElement(newElement);\n }\n }\n }\n } catch (fileError) {\n // Log YAML parsing errors but continue loading other files\n const errorMsg = fileError instanceof Error ? fileError.message : String(fileError);\n console.error(`Warning: Failed to parse ${filePath}: ${errorMsg}`);\n parseErrorCount++;\n // Continue with next file\n }\n }\n }\n\n // If we had parse errors, add a note to the layer\n if (parseErrorCount > 0) {\n console.error(\n `Warning: Layer '${name}' loaded with ${parseErrorCount} YAML parse error(s)`\n );\n }\n\n this.layers.set(name, layer);\n this.loadedLayers.add(name);\n\n layerSpan.setAttribute(\"layer.element_count\", layer.elements.size);\n }, { \"layer.name\": name });\n }\n\n /**\n * Add a layer to the model\n */\n addLayer(layer: Layer): void {\n // If the layer has elements in its isolated graph, migrate them to the model's graph\n if (layer.graph.getNodeCount() > 0) {\n for (const node of layer.graph.nodes.values()) {\n this.graph.addNode(node);\n }\n for (const edge of layer.graph.edges.values()) {\n this.graph.addEdge(edge);\n }\n }\n // Ensure layer uses the model's graph for future operations\n layer.graph = this.graph;\n this.layers.set(layer.name, layer);\n this.loadedLayers.add(layer.name);\n }\n\n /**\n * Get all layer names, including layers that exist only in staged changes.\n * When an active changeset introduces elements for a layer with no committed data,\n * that layer name is included so findElementLayer() and other callers can discover it.\n */\n getLayerNames(): string[] {\n const base = Array.from(this.layers.keys());\n if (this._stagedLayerNames.size === 0) {\n return base;\n }\n // Include staged-only layers (layers that have staged elements but no committed elements)\n const staged = Array.from(this._stagedLayerNames).filter((l) => !this.layers.has(l));\n return [...base, ...staged];\n }\n\n /**\n * Save a layer to disk (model/XX_layername/*.yaml)\n */\n async saveLayer(name: string): Promise<void> {\n const layer = this.layers.get(name);\n if (!layer) {\n throw new Error(`Layer ${name} not found`);\n }\n\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n\n let layerPath: string | null = null;\n\n // Discover by scanning directory\n const modelDir = `${this.rootPath}/documentation-robotics/model`;\n\n try {\n const entries = await fs.readdir(modelDir, { withFileTypes: true });\n const layerDir = entries.find(\n (e) =>\n e.isDirectory() && e.name.match(/^\\d{2}_/) && e.name.replace(/^\\d{2}_/, \"\") === name\n );\n\n if (layerDir) {\n layerPath = `${modelDir}/${layerDir.name}`;\n }\n } catch {\n // Model directory doesn't exist or can't be read\n }\n\n // If still not found, create using default format\n if (!layerPath) {\n // Find the order number for this layer\n // Handle layer names with or without numeric prefix (e.g., \"motivation\" or \"01-motivation\")\n const layerNameWithoutPrefix = name.replace(/^\\d{2}-/, \"\");\n const index = CANONICAL_LAYER_NAMES.indexOf(layerNameWithoutPrefix as typeof CANONICAL_LAYER_NAMES[number]);\n if (index >= 0) {\n const orderNum = String(index + 1).padStart(2, \"0\");\n layerPath = `${this.rootPath}/documentation-robotics/model/${orderNum}_${layerNameWithoutPrefix}`;\n await ensureDir(layerPath);\n } else {\n throw new Error(`Unknown layer ${name} and no path configured in manifest`);\n }\n }\n\n // Delete all existing YAML files in the layer directory to ensure\n // we don't keep stale files after element deletion\n try {\n const existingFiles = await fs.readdir(layerPath);\n for (const file of existingFiles) {\n if (file.endsWith(\".yaml\") || file.endsWith(\".yml\")) {\n await fs.unlink(`${layerPath}/${file}`);\n }\n }\n } catch (err) {\n // Only ignore \"directory not found\" errors \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw new Error(\n `Failed to clean existing YAML files: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n\n // Group elements by type, computing the snake_case file stem from the spec node title\n const elementsByType = new Map<string, { stem: string; elements: Element[] }>();\n for (const element of layer.elements.values()) {\n const typeKey = element.type;\n if (!elementsByType.has(typeKey)) {\n const stem = typeToSnakeStem(element.spec_node_id, element.type);\n elementsByType.set(typeKey, { stem, elements: [] });\n }\n elementsByType.get(typeKey)!.elements.push(element);\n }\n\n // Internal graph fields \u2014 never written to YAML\n const INTERNAL_FIELDS = new Set([\n \"__references__\", \"__relationships__\",\n \"source\", \"x-source-reference\",\n ]);\n\n // Write each type to its own YAML file\n for (const [, { stem, elements }] of elementsByType) {\n const filename = `${stem}.yaml`;\n const filePath = `${layerPath}/${filename}`;\n\n // Convert elements to spec-node format YAML\n const yamlData: any = {};\n for (const element of elements) {\n const json = element.toJSON();\n\n // Clean attributes: remove graph-internal keys that should not be persisted\n const cleanAttrs = json.attributes\n ? Object.fromEntries(\n Object.entries(json.attributes).filter(([k]) => !INTERNAL_FIELDS.has(k))\n )\n : undefined;\n\n // Use path as YAML key (human-readable); fall back to id for elements without path\n const key = element.path || element.id;\n yamlData[key] = {\n id: json.id,\n path: json.path,\n spec_node_id: json.spec_node_id,\n type: json.type,\n layer_id: json.layer_id,\n name: json.name,\n ...(json.description && { description: json.description }),\n ...(cleanAttrs && Object.keys(cleanAttrs).length > 0 && { attributes: cleanAttrs }),\n ...(json.source_reference && { source_reference: json.source_reference }),\n ...(json.metadata && { metadata: json.metadata }),\n ...(json.references && json.references.length > 0 && { references: json.references }),\n // Relationships are now stored in centralized relationships.yaml, not inline\n };\n }\n\n await writeFile(filePath, yaml.stringify(yamlData));\n }\n\n layer.markClean();\n }\n\n /**\n * Save model (saves all dirty layers and manifest)\n */\n async save(): Promise<void> {\n await this.saveDirtyLayers();\n await this.saveManifest();\n }\n\n /**\n * Save all dirty layers to disk\n */\n async saveDirtyLayers(): Promise<void> {\n // Count dirty layers before operation\n let dirtyLayerCount = 0;\n for (const layer of this.layers.values()) {\n if (layer.isDirty()) {\n dirtyLayerCount++;\n }\n }\n\n const span = isTelemetryEnabled\n ? startSpan(\"model.save\", {\n \"model.path\": this.rootPath,\n \"model.dirty_layer_count\": dirtyLayerCount,\n })\n : null;\n\n try {\n for (const layer of this.layers.values()) {\n if (layer.isDirty()) {\n await this.saveLayer(layer.name);\n }\n }\n } finally {\n if (isTelemetryEnabled) {\n endSpan(span);\n }\n }\n }\n\n /**\n * Save the manifest to disk (documentation-robotics/model/manifest.yaml)\n */\n async saveManifest(): Promise<void> {\n this.manifest.updateModified();\n const yaml = await import(\"yaml\");\n const manifestPath = `${this.rootPath}/documentation-robotics/model/manifest.yaml`;\n\n // Convert to YAML format\n const yamlData: any = {\n version: this.manifest.version,\n schema: \"documentation-robotics-v1\",\n cli_version: getCliVersion(),\n spec_version: this.manifest.specVersion,\n created: this.manifest.created,\n updated: this.manifest.modified,\n project: {\n name: this.manifest.name,\n description: this.manifest.description,\n version: this.manifest.version,\n },\n documentation: \".dr/README.md\",\n layers: {},\n };\n\n // Generate layer structure from current model state\n const layerOrder = [\n \"motivation\",\n \"business\",\n \"security\",\n \"application\",\n \"technology\",\n \"api\",\n \"data-model\",\n \"data-store\",\n \"ux\",\n \"navigation\",\n \"apm\",\n \"testing\",\n ];\n\n for (let i = 0; i < layerOrder.length; i++) {\n const layerName = layerOrder[i];\n const layer = this.layers.get(layerName);\n const orderNum = String(i + 1).padStart(2, \"0\");\n\n yamlData.layers[layerName] = {\n order: i + 1,\n name: layerName.charAt(0).toUpperCase() + layerName.slice(1).replace(\"-\", \" \"),\n path: `documentation-robotics/model/${orderNum}_${layerName}/`,\n enabled: true,\n ...(layer && { elements: this.getLayerElementCounts(layer) }),\n };\n }\n\n if (this.manifest.changeset_history && this.manifest.changeset_history.length > 0) {\n yamlData.changeset_history = this.manifest.changeset_history;\n }\n\n await ensureDir(`${this.rootPath}/documentation-robotics/model`);\n await writeFile(manifestPath, yaml.stringify(yamlData));\n }\n\n private getLayerElementCounts(layer: Layer): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const element of layer.elements.values()) {\n counts[element.type] = (counts[element.type] || 0) + 1;\n }\n return counts;\n }\n\n /**\n * Load relationships from relationships.yaml\n */\n async loadRelationships(): Promise<void> {\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n const relationshipsPath = `${this.rootPath}/documentation-robotics/model/relationships.yaml`;\n\n let data: any;\n try {\n const yamlContent = await fs.readFile(relationshipsPath, \"utf-8\");\n data = yaml.parse(yamlContent);\n } catch (err) {\n // If file doesn't exist, that's okay - start with empty relationships\n if ((err as any).code !== \"ENOENT\") {\n // But if it's a different error (YAML parse, permission denied, etc), throw it\n // so the caller knows about the issue\n throw new Error(\n `Failed to load relationships.yaml: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n // ENOENT: file doesn't exist, return with empty relationships\n return;\n }\n\n // Validate that parsed content is an array\n if (!Array.isArray(data)) {\n const typeLabel = data === null ? \"null\" : typeof data;\n console.warn(\n `Warning: relationships.yaml contains non-array content (received ${typeLabel}). Expected an array of relationships. Skipping relationship loading.`\n );\n return;\n }\n\n this.relationships = Relationships.fromArray(data);\n // Sync relationships to graph as a secondary in-memory index.\n // addEdge() may throw if nodes from other layers haven't been loaded yet;\n // failures are silently skipped \u2014 this.relationships holds the primary data.\n for (let i = 0; i < data.length; i++) {\n const rel = data[i];\n const edge: GraphEdge = {\n id: `rel-${i}-${crypto.randomBytes(4).toString(\"hex\")}`,\n source: rel.source,\n destination: rel.target,\n predicate: rel.predicate,\n properties: rel.properties,\n category: rel.category,\n };\n try {\n this.graph.addEdge(edge);\n } catch {\n // Silently skip edges whose nodes haven't been loaded yet.\n // The primary relationship data lives in this.relationships; the graph\n // is a secondary index. Cross-layer relationships referencing nodes from\n // unloaded layers are expected during partial model construction.\n }\n }\n }\n\n /**\n * Save relationships to relationships.yaml\n */\n async saveRelationships(): Promise<void> {\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n const relationshipsPath = `${this.rootPath}/documentation-robotics/model/relationships.yaml`;\n\n await ensureDir(`${this.rootPath}/documentation-robotics/model`);\n\n const data = this.relationships.toArray();\n\n // Add header comment with timestamp to ensure file always changes\n const timestamp = new Date().toISOString();\n const header = `# Intra-layer relationships\n# Format: source_id -> predicate -> target_id\n# Last updated: ${timestamp}\n\n`;\n const yamlContent = header + yaml.stringify(data);\n\n await fs.writeFile(relationshipsPath, yamlContent, \"utf-8\");\n this.relationships.markClean();\n }\n\n /**\n * Resolve model paths (private helper)\n *\n * @param startPath - Starting path for search\n * @returns Project root and manifest path\n */\n private static async resolveModelPaths(startPath?: string): Promise<{\n projectRoot: string;\n manifestPath: string;\n }> {\n const searchPath = startPath || process.cwd();\n\n // Optional override via env var (highest priority)\n if (process.env.DR_MODEL_PATH) {\n const envPath = path.resolve(process.env.DR_MODEL_PATH);\n let manifestPath: string;\n\n if (envPath.endsWith(\"manifest.yaml\")) {\n manifestPath = envPath;\n } else if (envPath.endsWith(\"model\")) {\n manifestPath = path.join(envPath, \"manifest.yaml\");\n } else {\n manifestPath = path.join(envPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n }\n\n try {\n await fs.access(manifestPath);\n const projectRoot = path.dirname(path.dirname(path.dirname(manifestPath)));\n return { projectRoot, manifestPath: path.normalize(manifestPath) };\n } catch {\n throw new Error(`Model not found at DR_MODEL_PATH: ${process.env.DR_MODEL_PATH}`);\n }\n }\n\n // Use findProjectRoot to locate documentation_robotics/ folder\n const projectRoot = await findProjectRoot(searchPath);\n\n if (!projectRoot) {\n throw new Error(\n \"No DR project found. Could not find documentation_robotics/ folder.\\n\" +\n 'Run \"dr init\" to create a new project, or navigate to a directory containing a DR project.'\n );\n }\n\n const manifestPath = path.join(projectRoot, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n\n try {\n await fs.access(manifestPath);\n return { projectRoot, manifestPath };\n } catch {\n throw new Error(\n `Found documentation_robotics/ at ${projectRoot} but no model found. ` +\n `Expected: ${manifestPath}\\n` +\n `Run \"dr init\" to create a model.`\n );\n }\n }\n\n /**\n * Load a model from disk\n *\n * Expected structure:\n * <project-root>/\n * \u2514\u2500\u2500 documentation_robotics/\n * \u2514\u2500\u2500 model/\n * \u2514\u2500\u2500 manifest.yaml\n *\n * @param startPath - Starting path for project search (defaults to process.cwd())\n * @param options - Model loading options\n * @returns Loaded Model instance\n */\n static async load(startPath?: string, options: ModelOptions = {}): Promise<Model> {\n return startActiveSpan(\"model.load\", async (span) => {\n // Resolve project root and manifest path\n const { projectRoot, manifestPath } = await Model.resolveModelPaths(startPath);\n\n const yaml = await import(\"yaml\");\n\n // Load manifest from resolved path\n const yamlContent = await fs.readFile(manifestPath, \"utf-8\");\n const manifestYaml = yaml.parse(yamlContent);\n\n // Convert manifest to internal format\n const manifestData: any = {\n name: manifestYaml.project?.name || \"Unnamed Model\",\n description: manifestYaml.project?.description || \"\",\n version: manifestYaml.project?.version || manifestYaml.version || \"0.1.0\",\n specVersion: manifestYaml.spec_version || \"0.6.0\",\n created: manifestYaml.created || new Date().toISOString(),\n modified: manifestYaml.updated || new Date().toISOString(),\n };\n const manifest = new Manifest(manifestData);\n const model = new Model(projectRoot, manifest, options);\n\n // Load all available layers if lazyLoad is false\n if (!options.lazyLoad) {\n try {\n // If manifest has layer definitions, use those\n if (manifestYaml.layers) {\n for (const layerName of Object.keys(manifestYaml.layers)) {\n const layerConfig = manifestYaml.layers[layerName];\n if (layerConfig.enabled !== false) {\n if (!options.layers || options.layers.includes(layerName)) {\n await model.loadLayer(layerName);\n }\n }\n }\n } else {\n // Otherwise scan for layer directories\n const modelDir = manifestPath.replace(\"/manifest.yaml\", \"\");\n const entries = await fs.readdir(modelDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (entry.isDirectory() && entry.name.match(/^\\d{2}_/)) {\n const layerName = entry.name.replace(/^\\d{2}_/, \"\");\n if (!options.layers || options.layers.includes(layerName)) {\n await model.loadLayer(layerName);\n }\n }\n }\n }\n } catch (e) {\n // Check if this is a \"directory not found\" error (expected case)\n const isNotFoundError = (e as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n // Re-throw non-ENOENT errors: permission errors, YAML parsing failures, I/O errors, etc.\n throw new Error(\n `Failed to load layers: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n // ENOENT is expected if layer directory doesn't exist yet, so just continue\n }\n }\n\n // Load relationships from relationships.yaml\n await model.loadRelationships();\n\n // Check for active changeset and pre-load staged metadata for transparent projection.\n // This enables getLayer() to return projected views and getLayerNames() to include\n // layers that exist only in staged changes.\n const activePath = path.join(\n projectRoot,\n \"documentation-robotics\",\n \"changesets\",\n \".active\"\n );\n try {\n const activeContent = await fs.readFile(activePath, \"utf-8\");\n const activeId = activeContent.trim();\n if (activeId) {\n model._activeChangesetId = activeId;\n const storage = new StagedChangesetStorage(projectRoot);\n const changeset = await storage.load(activeId);\n if (changeset) {\n for (const change of changeset.changes as StagedChange[]) {\n // Track layer names for getLayerNames()\n if (\n change.type === \"add\" ||\n change.type === \"update\" ||\n change.type === \"delete\"\n ) {\n model._stagedLayerNames.add(change.layerName);\n }\n\n // Inject staged relationship-adds into model.relationships so that\n // read commands (list, show, export) transparently see staged relationships.\n if (change.type === \"relationship-add\" && change.after) {\n const rel = change.after as {\n source: string;\n target: string;\n predicate: string;\n layer: string;\n targetLayer?: string;\n category?: \"structural\" | \"behavioral\";\n properties?: Record<string, unknown>;\n };\n // Only inject if not already in relationships.yaml (prevents duplicates\n // if .active file is stale after a partial commit or manual edit).\n const alreadyPresent = model.relationships.find(\n rel.source,\n rel.target,\n rel.predicate\n );\n if (alreadyPresent.length === 0) {\n model.relationships.add({\n source: rel.source,\n target: rel.target,\n predicate: rel.predicate,\n layer: rel.layer,\n ...(rel.targetLayer ? { targetLayer: rel.targetLayer } : {}),\n category: rel.category ?? \"structural\",\n ...(rel.properties ? { properties: rel.properties } : {}),\n });\n }\n }\n\n // Remove staged relationship-deletes from model.relationships so that\n // read commands see the relationship as already deleted.\n if (change.type === \"relationship-delete\" && change.before) {\n const rel = change.before as {\n source: string;\n target: string;\n predicate?: string;\n };\n model.relationships.delete(rel.source, rel.target, rel.predicate);\n }\n }\n }\n }\n } catch {\n // No active changeset or unreadable \u2014 proceed with base model only\n model._activeChangesetId = null;\n }\n\n // Count total entities across all layers\n let entityCount = 0;\n for (const layer of model.layers.values()) {\n entityCount += layer.elements.size;\n }\n\n span.setAttribute(\"model.entity_count\", entityCount);\n span.setAttribute(\"model.layer_count\", model.layers.size);\n\n return model;\n }, {\n \"model.path\": startPath || process.cwd(),\n \"model.type\": \"dr\",\n });\n }\n\n /**\n * Initialize a new model in a directory\n */\n static async init(\n rootPath: string,\n manifestData: ManifestData,\n options: ModelOptions = {}\n ): Promise<Model> {\n // Create model directory structure\n await ensureDir(`${rootPath}/documentation-robotics/model`);\n\n for (let i = 0; i < CANONICAL_LAYER_NAMES.length; i++) {\n const orderNum = String(i + 1).padStart(2, \"0\");\n const layerName = CANONICAL_LAYER_NAMES[i];\n await ensureDir(`${rootPath}/documentation-robotics/model/${orderNum}_${layerName}`);\n }\n\n const manifest = new Manifest(manifestData);\n const model = new Model(rootPath, manifest, options);\n\n await model.saveManifest();\n\n return model;\n }\n\n /**\n * Graph-based API methods for querying the model\n * These methods delegate to the underlying GraphModel for efficient queries\n */\n\n /**\n * Get a node by its UUID\n */\n getNode(id: string) {\n return this.graph.getNode(id);\n }\n\n /**\n * Get all nodes in a specific layer\n */\n getNodesByLayer(layerId: string) {\n return this.graph.getNodesByLayer(layerId);\n }\n\n /**\n * Get all nodes of a specific type\n */\n getNodesByType(type: string) {\n return this.graph.getNodesByType(type);\n }\n\n /**\n * Get all edges (relationships) in the model\n */\n getAllEdges() {\n return this.graph.getAllEdges();\n }\n\n /**\n * Get edges originating from a specific node\n */\n getEdgesFrom(nodeId: string, predicate?: string) {\n return this.graph.getEdgesFrom(nodeId, predicate);\n }\n\n /**\n * Get edges terminating at a specific node\n */\n getEdgesTo(nodeId: string, predicate?: string) {\n return this.graph.getEdgesTo(nodeId, predicate);\n }\n\n /**\n * Get edges between two specific nodes\n */\n getEdgesBetween(sourceId: string, destinationId: string, predicate?: string) {\n return this.graph.getEdgesBetween(sourceId, destinationId, predicate);\n }\n\n /**\n * Traverse the graph starting from a node, following a specific predicate\n */\n async traverse(startNodeId: string, predicate: string, maxDepth: number = 10) {\n return this.graph.traverse(startNodeId, predicate, maxDepth);\n }\n\n /**\n * Create a backup of the current model state\n * Used for rollback support in migration operations\n *\n * @param label Descriptive label for the backup (e.g., \"pre-migration\")\n * @returns Path to the backup directory\n */\n async createBackup(label: string): Promise<string> {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupDir = path.join(this.rootPath, \".dr-backups\", `${label}-${timestamp}`);\n\n // Create backup directory\n await ensureDir(backupDir);\n\n // Backup layers directory\n const layersSource = path.join(this.rootPath, \"documentation-robotics\", \"model\");\n const layersBackup = path.join(backupDir, \"layers\");\n if (await this.directoryExists(layersSource)) {\n await this.copyDirectory(layersSource, layersBackup);\n }\n\n // Backup manifest\n const manifestSource = path.join(this.rootPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n const manifestBackup = path.join(backupDir, \"manifest.yaml\");\n if (await this.fileExists(manifestSource)) {\n await fs.copyFile(manifestSource, manifestBackup);\n }\n\n return backupDir;\n }\n\n /**\n * Restore model from a backup directory\n * Used for rollback after failed migrations\n *\n * @param backupPath Path to the backup directory\n */\n async restoreFromBackup(backupPath: string): Promise<void> {\n // Restore layers\n const layersBackup = path.join(backupPath, \"layers\");\n const layersTarget = path.join(this.rootPath, \"documentation-robotics\", \"model\");\n if (await this.directoryExists(layersBackup)) {\n await this.copyDirectory(layersBackup, layersTarget);\n }\n\n // Restore manifest\n const manifestBackup = path.join(backupPath, \"manifest.yaml\");\n const manifestTarget = path.join(this.rootPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n if (await this.fileExists(manifestBackup)) {\n await fs.copyFile(manifestBackup, manifestTarget);\n }\n\n // Reload model to refresh in-memory state\n const reloadedModel = await Model.load(this.rootPath, { lazyLoad: this.lazyLoad });\n this.layers = reloadedModel.layers;\n this.manifest = reloadedModel.manifest;\n this.graph = reloadedModel.graph;\n this.relationships = reloadedModel.relationships;\n }\n\n /**\n * Save dirty layers with atomic write semantics\n * Writes to temporary file first, then renames on success to ensure data safety\n *\n * @throws Error if atomic write fails\n */\n async saveDirtyLayersAtomic(): Promise<void> {\n // First, save all layers to temporary files\n const tempLayerWrites: Array<{ layer: Layer; tempPath: string }> = [];\n\n try {\n for (const layer of this.layers.values()) {\n if (layer.isDirty()) {\n const layerPath = path.join(\n this.rootPath,\n \"documentation-robotics\",\n \"model\",\n `${layer.name}_layer`\n );\n\n const tempPath = `${layerPath}.tmp`;\n await ensureDir(tempPath);\n\n // Write layer elements to temp directory\n for (const element of layer.elements.values()) {\n const elementPath = path.join(tempPath, `${element.path || element.id}.json`);\n const content = JSON.stringify(element.toJSON(), null, 2);\n await writeFile(elementPath, content);\n }\n\n tempLayerWrites.push({ layer, tempPath });\n }\n }\n\n // All temp writes succeeded, now commit by renaming\n for (const { layer, tempPath } of tempLayerWrites) {\n const layerPath = path.join(\n this.rootPath,\n \"documentation-robotics\",\n \"model\",\n `${layer.name}_layer`\n );\n\n // Remove old directory and rename temp to actual\n if (await this.directoryExists(layerPath)) {\n await fs.rm(layerPath, { recursive: true, force: true });\n }\n await fs.rename(tempPath, layerPath);\n }\n } catch (error) {\n // Cleanup any temp directories on failure\n for (const { tempPath } of tempLayerWrites) {\n if (await this.directoryExists(tempPath)) {\n await fs.rm(tempPath, { recursive: true, force: true });\n }\n }\n throw error;\n }\n }\n\n /**\n * Helper: Check if file exists\n */\n private async fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Helper: Check if directory exists\n */\n private async directoryExists(dirPath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(dirPath);\n return stat.isDirectory();\n } catch {\n return false;\n }\n }\n\n /**\n * Helper: Recursively copy directory\n */\n private async copyDirectory(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,kBAAkC;AAC3C,SAAS,+BAA+B;AACxC,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AAEtC,SAAS,WAAW,iBAAiB;AACrC,SAAS,qBAAqB;AAC9B,SAAS,WAAW,SAAS,uBAAuB;AACpD,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAG5B,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,YAAY;AAMnB,SAAS,kBAAkBA,OAAY;AACrC,QAAM,OAAO,OAAO,WAAW,QAAQ,EAAE,OAAOA,KAAI,EAAE,OAAO,KAAK;AAClE,SAAO;IACL,KAAK,MAAM,GAAG,CAAC;IACf,KAAK,MAAM,GAAG,EAAE;IAChB,MAAM,KAAK,MAAM,IAAI,EAAE;;KACrB,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,MAAM,KAAK,gBAAgB,QAAQ,KACrC,MAAM,GAAG,GAAG,UAAU,EAAE,WAAW,IAAM,OAAO,GAAI,CAAE;AAG1D,YAAM;IACR;EACF;;;;EAKQ,MAAM,WAAW,UAAgB;AACvC,QAAI;AACF,mBAAM,GAAG,OAAO,QAAQ,GACjB;IACT,QAAQ;AACN,aAAO;IACT;EACF;;;;EAKQ,MAAM,gBAAgB,SAAe;AAC3C,QAAI;AAEF,cADa,MAAM,GAAG,KAAK,OAAO,GACtB,YAAW;IACzB,QAAQ;AACN,aAAO;IACT;EACF;;;;EAKQ,MAAM,cAAc,KAAa,MAAY;AACnD,UAAM,UAAU,IAAI;AACpB,UAAM,UAAU,MAAM,GAAG,QAAQ,KAAK,EAAE,eAAe,GAAI,CAAE;AAE7D,eAAW,SAAS,SAAS;AAC3B,YAAM,UAAU,KAAK,KAAK,KAAK,MAAM,IAAI,GACnC,WAAW,KAAK,KAAK,MAAM,MAAM,IAAI;AAE3C,MAAI,MAAM,YAAW,IACnB,MAAM,KAAK,cAAc,SAAS,QAAQ,IAE1C,MAAM,GAAG,SAAS,SAAS,QAAQ;IAEvC;EACF;;",
4
+ "sourcesContent": ["import { Layer } from \"./layer.js\";\nimport { Manifest } from \"./manifest.js\";\nimport { Element } from \"./element.js\";\nimport { GraphModel, type GraphEdge } from \"./graph-model.js\";\nimport { VirtualProjectionEngine } from \"./virtual-projection.js\";\nimport { StagedChangesetStorage } from \"./staged-changeset-storage.js\";\nimport { Relationships } from \"./relationships.js\";\nimport { CANONICAL_LAYER_NAMES } from \"./layers.js\";\nimport type { StagedChange } from \"./changeset.js\";\nimport { ensureDir, writeFile } from \"../utils/file-io.js\";\nimport { getCliVersion } from \"../utils/spec-version.js\";\nimport { startSpan, endSpan, startActiveSpan } from \"../telemetry/index.js\";\nimport { findProjectRoot } from \"../utils/project-paths.js\";\nimport { getNodeType } from \"../generated/node-types.js\";\nimport type { SpecNodeId } from \"../generated/node-types.js\";\nimport type { ManifestData, ModelOptions } from \"../types/index.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport crypto from \"node:crypto\";\n\n/**\n * Derive a deterministic UUID from a path string using SHA-256.\n * Produces a stable UUID4-like value so migration doesn't regenerate UUIDs on every load.\n */\nfunction deterministicUUID(path: string): string {\n const hash = crypto.createHash(\"sha256\").update(path).digest(\"hex\");\n return [\n hash.slice(0, 8),\n hash.slice(8, 12),\n \"4\" + hash.slice(13, 16), // version 4 marker\n ((parseInt(hash.slice(16, 18), 16) & 0x3f) | 0x80).toString(16) + hash.slice(18, 20), // variant\n hash.slice(20, 32),\n ].join(\"-\");\n}\n\n/**\n * Convert a PascalCase title to snake_case.\n * Handles acronyms correctly: \"UXApplication\" \u2192 \"ux_application\", \"OpenAPIDocument\" \u2192 \"open_api_document\".\n */\nfunction titleToSnakeCase(title: string): string {\n return title\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\") // \"APIDoc\" \u2192 \"API_Doc\"\n .replace(/([a-z\\d])([A-Z])/g, \"$1_$2\") // \"appComponent\" \u2192 \"app_Component\"\n .toLowerCase();\n}\n\n/**\n * Derive a snake_case file stem for a given element type.\n * Uses the spec node title for accurate word boundaries (e.g., \"InputSpacePartition\" \u2192 \"input_space_partition\").\n * Falls back to the raw type string when the title is unavailable.\n */\nfunction typeToSnakeStem(specNodeId: string | undefined, type: string): string {\n if (specNodeId) {\n const nodeType = getNodeType(specNodeId as SpecNodeId);\n if (nodeType?.title) {\n return titleToSnakeCase(nodeType.title);\n }\n }\n return type;\n}\n\n// Fallback for runtime environments where TELEMETRY_ENABLED is not defined by esbuild\ndeclare const TELEMETRY_ENABLED: boolean | undefined;\nconst isTelemetryEnabled = typeof TELEMETRY_ENABLED !== \"undefined\" ? TELEMETRY_ENABLED : false;\n\n/**\n * Model class representing the complete architecture model\n * Uses GraphModel internally for graph-based storage\n */\nexport class Model {\n rootPath: string;\n manifest: Manifest;\n graph: GraphModel;\n layers: Map<string, Layer>;\n relationships: Relationships;\n lazyLoad: boolean;\n private loadedLayers: Set<string>;\n private virtualProjectionEngine?: VirtualProjectionEngine;\n /** ID of the currently active changeset, or null if none is active. Set during load(). */\n private _activeChangesetId: string | null = null;\n /** Layer names that exist only in staged changes (not yet committed to base model). */\n private _stagedLayerNames: Set<string> = new Set();\n\n constructor(rootPath: string, manifest: Manifest, options: ModelOptions = {}) {\n this.rootPath = rootPath;\n this.manifest = manifest;\n this.graph = new GraphModel();\n this.layers = new Map();\n this.relationships = new Relationships();\n this.lazyLoad = options.lazyLoad ?? false;\n this.loadedLayers = new Set();\n }\n\n /**\n * Get the committed base layer (no staging projection).\n * Used internally by VirtualProjectionEngine and commit() to access the raw base model\n * without triggering infinite recursion or double-projection.\n */\n async getBaseLayer(name: string): Promise<Layer | undefined> {\n if (this.lazyLoad && !this.loadedLayers.has(name)) {\n await this.loadLayer(name);\n }\n return this.layers.get(name);\n }\n\n /**\n * Get a layer, transparently merging staged changes when an active changeset exists.\n * Falls back to the committed base layer if no changeset is active or projection fails.\n */\n async getLayer(name: string): Promise<Layer | undefined> {\n if (this.lazyLoad && !this.loadedLayers.has(name)) {\n await this.loadLayer(name);\n }\n\n // If an active changeset is present, return a projected (base + staged) layer\n if (this._activeChangesetId) {\n try {\n return await this.getVirtualProjectionEngine().projectLayer(\n this,\n this._activeChangesetId,\n name\n );\n } catch {\n // Fall back to base layer on projection failure (e.g. corrupt changeset)\n return this.layers.get(name);\n }\n }\n\n return this.layers.get(name);\n }\n\n /**\n * Get an element by ID across all layers\n * Supports both UUID and semantic ID (layer.type.kebab-name) lookup\n */\n getElementById(id: string): Element | undefined {\n for (const layer of this.layers.values()) {\n const element = layer.getElement(id);\n if (element) {\n return element;\n }\n }\n return undefined;\n }\n\n /**\n * Get virtual projection engine (lazily initialized)\n */\n getVirtualProjectionEngine(): VirtualProjectionEngine {\n if (!this.virtualProjectionEngine) {\n this.virtualProjectionEngine = new VirtualProjectionEngine(this.rootPath);\n }\n return this.virtualProjectionEngine;\n }\n\n /**\n * Returns the active changeset ID, or null if no changeset is active.\n * Used by commands that need to project the full model (e.g. validate).\n */\n getActiveChangesetId(): string | null {\n return this._activeChangesetId;\n }\n\n /**\n * Load a layer from disk (model/XX_layername/*.yaml files)\n */\n async loadLayer(name: string): Promise<void> {\n await startActiveSpan(\"layer.load\", async (layerSpan) => {\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n\n let layerPath: string | null = null;\n\n // Auto-discover by scanning directory with naming convention\n const modelDir = `${this.rootPath}/documentation-robotics/model`;\n\n try {\n const entries = await fs.readdir(modelDir, { withFileTypes: true });\n const layerDir = entries.find(\n (e) =>\n e.isDirectory() && e.name.match(/^\\d{2}_/) && e.name.replace(/^\\d{2}_/, \"\") === name\n );\n\n if (layerDir) {\n layerPath = `${modelDir}/${layerDir.name}`;\n }\n } catch {\n // Model directory doesn't exist or can't be read\n }\n\n if (!layerPath) {\n return; // Layer directory not found\n }\n\n const layer = new Layer(name, this.graph);\n let parseErrorCount = 0;\n\n // Load all YAML files in the layer directory\n const files = await fs.readdir(layerPath);\n for (const file of files) {\n if (file.endsWith(\".yaml\") || file.endsWith(\".yml\")) {\n const filePath = `${layerPath}/${file}`;\n try {\n const yamlContent = await fs.readFile(filePath, \"utf-8\");\n const elements = yaml.parse(yamlContent);\n\n // Add each element from the YAML file\n if (elements && typeof elements === \"object\") {\n for (const [key, element] of Object.entries(elements)) {\n if (element && typeof element === \"object\") {\n const el: any = element;\n\n // Derive id, path, and type using the 3-case migration logic:\n // Case 1: element already has both id (UUID) and path \u2192 use as-is\n // Case 2: element.id looks like a slug (layer.type.name) \u2192 move to path, generate UUID\n // Case 3: element has UUID id but no path \u2192 derive path from layer_id.type.kebab(name)\n const isSlugPattern = /^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$/.test(el.id || \"\");\n const isUUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(el.id || \"\");\n\n let elementId: string;\n let elementPath: string;\n let extractedType: string | undefined = undefined;\n\n if (el.path && isUUIDPattern) {\n // Case 1: already has both path and UUID id\n elementId = el.id;\n elementPath = el.path;\n const pathParts = el.path.split(\".\");\n if (pathParts.length >= 3) extractedType = pathParts[1];\n } else if (el.path && !isUUIDPattern) {\n // Has a path but id is not a UUID \u2014 migrate id to deterministic UUID\n elementPath = el.path;\n elementId = deterministicUUID(el.path);\n const pathParts = el.path.split(\".\");\n if (pathParts.length >= 3) extractedType = pathParts[1];\n } else if (isSlugPattern) {\n // Case 2: slug-looking id \u2192 move to path, generate deterministic UUID\n elementPath = el.id;\n elementId = deterministicUUID(el.id);\n const parts = el.id.split(\".\");\n if (parts.length >= 3) extractedType = parts[1];\n } else if (isUUIDPattern) {\n // Case 3: UUID id, no path \u2192 derive path\n elementId = el.id;\n const layerId = el.layer_id || name;\n const rawType = el.type || \"\";\n const rawName = el.name || key;\n const kebabName = rawName.toLowerCase().replace(/[\\s_]+/g, \"-\").replace(/[^a-z0-9-]/g, \"\").replace(/-+/g, \"-\").replace(/^-+|-+$/g, \"\");\n elementPath = `${layerId}.${rawType}.${kebabName}`;\n extractedType = rawType || undefined;\n } else {\n // Fallback: derive a path from available data, generate deterministic UUID\n const layerId = el.layer_id || name;\n const rawType = el.type || (typeof el.id === \"string\" && el.id.includes(\".\") ? el.id.split(\".\")[1] : \"\") || \"\";\n const rawName = el.name || key;\n const kebabName = rawName.toLowerCase().replace(/[\\s_]+/g, \"-\").replace(/[^a-z0-9-]/g, \"\").replace(/-+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"unknown\";\n elementPath = `${layerId}.${rawType || \"element\"}.${kebabName}`;\n elementId = deterministicUUID(elementPath);\n if (rawType) extractedType = rawType;\n else if (typeof el.id === \"string\" && el.id.includes(\".\")) {\n const parts = el.id.split(\".\");\n if (parts.length >= 3) extractedType = parts[1];\n }\n }\n\n const elementName = el.name || key;\n const elementType = el.type || extractedType;\n const layerId = el.layer_id || name;\n\n const newElement = new Element({\n id: elementId,\n path: elementPath,\n spec_node_id: el.spec_node_id,\n layer_id: layerId,\n attributes: el.attributes,\n source_reference: el.source_reference,\n metadata: el.metadata,\n name: elementName,\n type: elementType,\n description: el.description || \"\",\n relationships: el.relationships || [],\n references: el.references || [],\n layer: layerId,\n } as any);\n layer.addElement(newElement);\n }\n }\n }\n } catch (fileError) {\n // Log YAML parsing errors but continue loading other files\n const errorMsg = fileError instanceof Error ? fileError.message : String(fileError);\n console.error(`Warning: Failed to parse ${filePath}: ${errorMsg}`);\n parseErrorCount++;\n // Continue with next file\n }\n }\n }\n\n // If we had parse errors, add a note to the layer\n if (parseErrorCount > 0) {\n console.error(\n `Warning: Layer '${name}' loaded with ${parseErrorCount} YAML parse error(s)`\n );\n }\n\n this.layers.set(name, layer);\n this.loadedLayers.add(name);\n\n layerSpan.setAttribute(\"layer.element_count\", layer.elements.size);\n }, { \"layer.name\": name });\n }\n\n /**\n * Add a layer to the model\n */\n addLayer(layer: Layer): void {\n // If the layer has elements in its isolated graph, migrate them to the model's graph\n if (layer.graph.getNodeCount() > 0) {\n for (const node of layer.graph.nodes.values()) {\n this.graph.addNode(node);\n }\n for (const edge of layer.graph.edges.values()) {\n this.graph.addEdge(edge);\n }\n }\n // Ensure layer uses the model's graph for future operations\n layer.graph = this.graph;\n this.layers.set(layer.name, layer);\n this.loadedLayers.add(layer.name);\n }\n\n /**\n * Get all layer names, including layers that exist only in staged changes.\n * When an active changeset introduces elements for a layer with no committed data,\n * that layer name is included so findElementLayer() and other callers can discover it.\n */\n getLayerNames(): string[] {\n const base = Array.from(this.layers.keys());\n if (this._stagedLayerNames.size === 0) {\n return base;\n }\n // Include staged-only layers (layers that have staged elements but no committed elements)\n const staged = Array.from(this._stagedLayerNames).filter((l) => !this.layers.has(l));\n return [...base, ...staged];\n }\n\n /**\n * Save a layer to disk (model/XX_layername/*.yaml)\n */\n async saveLayer(name: string): Promise<void> {\n const layer = this.layers.get(name);\n if (!layer) {\n throw new Error(`Layer ${name} not found`);\n }\n\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n\n let layerPath: string | null = null;\n\n // Discover by scanning directory\n const modelDir = `${this.rootPath}/documentation-robotics/model`;\n\n try {\n const entries = await fs.readdir(modelDir, { withFileTypes: true });\n const layerDir = entries.find(\n (e) =>\n e.isDirectory() && e.name.match(/^\\d{2}_/) && e.name.replace(/^\\d{2}_/, \"\") === name\n );\n\n if (layerDir) {\n layerPath = `${modelDir}/${layerDir.name}`;\n }\n } catch {\n // Model directory doesn't exist or can't be read\n }\n\n // If still not found, create using default format\n if (!layerPath) {\n // Find the order number for this layer\n // Handle layer names with or without numeric prefix (e.g., \"motivation\" or \"01-motivation\")\n const layerNameWithoutPrefix = name.replace(/^\\d{2}-/, \"\");\n const index = CANONICAL_LAYER_NAMES.indexOf(layerNameWithoutPrefix as typeof CANONICAL_LAYER_NAMES[number]);\n if (index >= 0) {\n const orderNum = String(index + 1).padStart(2, \"0\");\n layerPath = `${this.rootPath}/documentation-robotics/model/${orderNum}_${layerNameWithoutPrefix}`;\n await ensureDir(layerPath);\n } else {\n throw new Error(`Unknown layer ${name} and no path configured in manifest`);\n }\n }\n\n // Delete all existing YAML files in the layer directory to ensure\n // we don't keep stale files after element deletion\n try {\n const existingFiles = await fs.readdir(layerPath);\n for (const file of existingFiles) {\n if (file.endsWith(\".yaml\") || file.endsWith(\".yml\")) {\n await fs.unlink(`${layerPath}/${file}`);\n }\n }\n } catch (err) {\n // Only ignore \"directory not found\" errors \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw new Error(\n `Failed to clean existing YAML files: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n\n // Group elements by type, computing the snake_case file stem from the spec node title\n const elementsByType = new Map<string, { stem: string; elements: Element[] }>();\n for (const element of layer.elements.values()) {\n const typeKey = element.type;\n if (!elementsByType.has(typeKey)) {\n const stem = typeToSnakeStem(element.spec_node_id, element.type);\n elementsByType.set(typeKey, { stem, elements: [] });\n }\n elementsByType.get(typeKey)!.elements.push(element);\n }\n\n // Internal graph fields \u2014 never written to YAML\n const INTERNAL_FIELDS = new Set([\n \"__references__\", \"__relationships__\",\n \"source\", \"x-source-reference\",\n ]);\n\n // Write each type to its own YAML file\n for (const [, { stem, elements }] of elementsByType) {\n const filename = `${stem}.yaml`;\n const filePath = `${layerPath}/${filename}`;\n\n // Convert elements to spec-node format YAML\n const yamlData: any = {};\n for (const element of elements) {\n const json = element.toJSON();\n\n // Clean attributes: remove graph-internal keys that should not be persisted\n const cleanAttrs = json.attributes\n ? Object.fromEntries(\n Object.entries(json.attributes).filter(([k]) => !INTERNAL_FIELDS.has(k))\n )\n : undefined;\n\n // Use path as YAML key (human-readable); fall back to id for elements without path\n const key = element.path || element.id;\n yamlData[key] = {\n id: json.id,\n path: json.path,\n spec_node_id: json.spec_node_id,\n type: json.type,\n layer_id: json.layer_id,\n name: json.name,\n ...(json.description && { description: json.description }),\n ...(cleanAttrs && Object.keys(cleanAttrs).length > 0 && { attributes: cleanAttrs }),\n ...(json.source_reference && { source_reference: json.source_reference }),\n ...(json.metadata && { metadata: json.metadata }),\n ...(json.references && json.references.length > 0 && { references: json.references }),\n // Relationships are now stored in centralized relationships.yaml, not inline\n };\n }\n\n await writeFile(filePath, yaml.stringify(yamlData));\n }\n\n layer.markClean();\n }\n\n /**\n * Save model (saves all dirty layers and manifest)\n */\n async save(): Promise<void> {\n await this.saveDirtyLayers();\n await this.saveManifest();\n }\n\n /**\n * Save all dirty layers to disk\n */\n async saveDirtyLayers(): Promise<void> {\n // Count dirty layers before operation\n let dirtyLayerCount = 0;\n for (const layer of this.layers.values()) {\n if (layer.isDirty()) {\n dirtyLayerCount++;\n }\n }\n\n const span = isTelemetryEnabled\n ? startSpan(\"model.save\", {\n \"model.path\": this.rootPath,\n \"model.dirty_layer_count\": dirtyLayerCount,\n })\n : null;\n\n try {\n for (const layer of this.layers.values()) {\n if (layer.isDirty()) {\n await this.saveLayer(layer.name);\n }\n }\n } finally {\n if (isTelemetryEnabled) {\n endSpan(span);\n }\n }\n }\n\n /**\n * Save the manifest to disk (documentation-robotics/model/manifest.yaml)\n */\n async saveManifest(): Promise<void> {\n this.manifest.updateModified();\n const yaml = await import(\"yaml\");\n const manifestPath = `${this.rootPath}/documentation-robotics/model/manifest.yaml`;\n\n // Convert to YAML format\n const yamlData: any = {\n version: this.manifest.version,\n schema: \"documentation-robotics-v1\",\n cli_version: getCliVersion(),\n spec_version: this.manifest.specVersion,\n created: this.manifest.created,\n updated: this.manifest.modified,\n project: {\n name: this.manifest.name,\n description: this.manifest.description,\n version: this.manifest.version,\n },\n documentation: \".dr/README.md\",\n layers: {},\n };\n\n // Generate layer structure from current model state\n for (let i = 0; i < CANONICAL_LAYER_NAMES.length; i++) {\n const layerName = CANONICAL_LAYER_NAMES[i];\n const layer = this.layers.get(layerName);\n const orderNum = String(i + 1).padStart(2, \"0\");\n\n yamlData.layers[layerName] = {\n order: i + 1,\n name: layerName.charAt(0).toUpperCase() + layerName.slice(1).replace(\"-\", \" \"),\n path: `documentation-robotics/model/${orderNum}_${layerName}/`,\n enabled: true,\n ...(layer && { elements: this.getLayerElementCounts(layer) }),\n };\n }\n\n if (this.manifest.changeset_history && this.manifest.changeset_history.length > 0) {\n yamlData.changeset_history = this.manifest.changeset_history;\n }\n\n await ensureDir(`${this.rootPath}/documentation-robotics/model`);\n await writeFile(manifestPath, yaml.stringify(yamlData));\n }\n\n private getLayerElementCounts(layer: Layer): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const element of layer.elements.values()) {\n counts[element.type] = (counts[element.type] || 0) + 1;\n }\n return counts;\n }\n\n /**\n * Load relationships from relationships.yaml\n */\n async loadRelationships(): Promise<void> {\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n const relationshipsPath = `${this.rootPath}/documentation-robotics/model/relationships.yaml`;\n\n let data: any;\n try {\n const yamlContent = await fs.readFile(relationshipsPath, \"utf-8\");\n data = yaml.parse(yamlContent);\n } catch (err) {\n // If file doesn't exist, that's okay - start with empty relationships\n if ((err as any).code !== \"ENOENT\") {\n // But if it's a different error (YAML parse, permission denied, etc), throw it\n // so the caller knows about the issue\n throw new Error(\n `Failed to load relationships.yaml: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n // ENOENT: file doesn't exist, return with empty relationships\n return;\n }\n\n // Validate that parsed content is an array\n if (!Array.isArray(data)) {\n const typeLabel = data === null ? \"null\" : typeof data;\n console.warn(\n `Warning: relationships.yaml contains non-array content (received ${typeLabel}). Expected an array of relationships. Skipping relationship loading.`\n );\n return;\n }\n\n this.relationships = Relationships.fromArray(data);\n // Sync relationships to graph as a secondary in-memory index.\n // addEdge() may throw if nodes from other layers haven't been loaded yet;\n // failures are silently skipped \u2014 this.relationships holds the primary data.\n for (let i = 0; i < data.length; i++) {\n const rel = data[i];\n const edge: GraphEdge = {\n id: `rel-${i}-${crypto.randomBytes(4).toString(\"hex\")}`,\n source: rel.source,\n destination: rel.target,\n predicate: rel.predicate,\n properties: rel.properties,\n category: rel.category,\n };\n try {\n this.graph.addEdge(edge);\n } catch {\n // Silently skip edges whose nodes haven't been loaded yet.\n // The primary relationship data lives in this.relationships; the graph\n // is a secondary index. Cross-layer relationships referencing nodes from\n // unloaded layers are expected during partial model construction.\n }\n }\n }\n\n /**\n * Save relationships to relationships.yaml\n */\n async saveRelationships(): Promise<void> {\n const fs = await import(\"fs/promises\");\n const yaml = await import(\"yaml\");\n const relationshipsPath = `${this.rootPath}/documentation-robotics/model/relationships.yaml`;\n\n await ensureDir(`${this.rootPath}/documentation-robotics/model`);\n\n const data = this.relationships.toArray();\n\n // Add header comment with timestamp to ensure file always changes\n const timestamp = new Date().toISOString();\n const header = `# Intra-layer relationships\n# Format: source_id -> predicate -> target_id\n# Last updated: ${timestamp}\n\n`;\n const yamlContent = header + yaml.stringify(data);\n\n await fs.writeFile(relationshipsPath, yamlContent, \"utf-8\");\n this.relationships.markClean();\n }\n\n /**\n * Resolve model paths (private helper)\n *\n * @param startPath - Starting path for search\n * @returns Project root and manifest path\n */\n private static async resolveModelPaths(startPath?: string): Promise<{\n projectRoot: string;\n manifestPath: string;\n }> {\n const searchPath = startPath || process.cwd();\n\n // Optional override via env var (highest priority)\n if (process.env.DR_MODEL_PATH) {\n const envPath = path.resolve(process.env.DR_MODEL_PATH);\n let manifestPath: string;\n\n if (envPath.endsWith(\"manifest.yaml\")) {\n manifestPath = envPath;\n } else if (envPath.endsWith(\"model\")) {\n manifestPath = path.join(envPath, \"manifest.yaml\");\n } else {\n manifestPath = path.join(envPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n }\n\n try {\n await fs.access(manifestPath);\n const projectRoot = path.dirname(path.dirname(path.dirname(manifestPath)));\n return { projectRoot, manifestPath: path.normalize(manifestPath) };\n } catch {\n throw new Error(`Model not found at DR_MODEL_PATH: ${process.env.DR_MODEL_PATH}`);\n }\n }\n\n // Use findProjectRoot to locate documentation_robotics/ folder\n const projectRoot = await findProjectRoot(searchPath);\n\n if (!projectRoot) {\n throw new Error(\n \"No DR project found. Could not find documentation_robotics/ folder.\\n\" +\n 'Run \"dr init\" to create a new project, or navigate to a directory containing a DR project.'\n );\n }\n\n const manifestPath = path.join(projectRoot, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n\n try {\n await fs.access(manifestPath);\n return { projectRoot, manifestPath };\n } catch {\n throw new Error(\n `Found documentation_robotics/ at ${projectRoot} but no model found. ` +\n `Expected: ${manifestPath}\\n` +\n `Run \"dr init\" to create a model.`\n );\n }\n }\n\n /**\n * Load a model from disk\n *\n * Expected structure:\n * <project-root>/\n * \u2514\u2500\u2500 documentation_robotics/\n * \u2514\u2500\u2500 model/\n * \u2514\u2500\u2500 manifest.yaml\n *\n * @param startPath - Starting path for project search (defaults to process.cwd())\n * @param options - Model loading options\n * @returns Loaded Model instance\n */\n static async load(startPath?: string, options: ModelOptions = {}): Promise<Model> {\n return startActiveSpan(\"model.load\", async (span) => {\n // Resolve project root and manifest path\n const { projectRoot, manifestPath } = await Model.resolveModelPaths(startPath);\n\n const yaml = await import(\"yaml\");\n\n // Load manifest from resolved path\n const yamlContent = await fs.readFile(manifestPath, \"utf-8\");\n const manifestYaml = yaml.parse(yamlContent);\n\n // Convert manifest to internal format\n const manifestData: any = {\n name: manifestYaml.project?.name || \"Unnamed Model\",\n description: manifestYaml.project?.description || \"\",\n version: manifestYaml.project?.version || manifestYaml.version || \"0.1.0\",\n specVersion: manifestYaml.spec_version || \"0.6.0\",\n created: manifestYaml.created || new Date().toISOString(),\n modified: manifestYaml.updated || new Date().toISOString(),\n };\n const manifest = new Manifest(manifestData);\n const model = new Model(projectRoot, manifest, options);\n\n // Load all available layers if lazyLoad is false\n if (!options.lazyLoad) {\n try {\n // If manifest has layer definitions, use those\n if (manifestYaml.layers) {\n for (const layerName of Object.keys(manifestYaml.layers)) {\n const layerConfig = manifestYaml.layers[layerName];\n if (layerConfig.enabled !== false) {\n if (!options.layers || options.layers.includes(layerName)) {\n await model.loadLayer(layerName);\n }\n }\n }\n } else {\n // Otherwise scan for layer directories\n const modelDir = manifestPath.replace(\"/manifest.yaml\", \"\");\n const entries = await fs.readdir(modelDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (entry.isDirectory() && entry.name.match(/^\\d{2}_/)) {\n const layerName = entry.name.replace(/^\\d{2}_/, \"\");\n if (!options.layers || options.layers.includes(layerName)) {\n await model.loadLayer(layerName);\n }\n }\n }\n }\n } catch (e) {\n // Check if this is a \"directory not found\" error (expected case)\n const isNotFoundError = (e as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n // Re-throw non-ENOENT errors: permission errors, YAML parsing failures, I/O errors, etc.\n throw new Error(\n `Failed to load layers: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n // ENOENT is expected if layer directory doesn't exist yet, so just continue\n }\n }\n\n // Load relationships from relationships.yaml\n await model.loadRelationships();\n\n // Check for active changeset and pre-load staged metadata for transparent projection.\n // This enables getLayer() to return projected views and getLayerNames() to include\n // layers that exist only in staged changes.\n const activePath = path.join(\n projectRoot,\n \"documentation-robotics\",\n \"changesets\",\n \".active\"\n );\n try {\n const activeContent = await fs.readFile(activePath, \"utf-8\");\n const activeId = activeContent.trim();\n if (activeId) {\n model._activeChangesetId = activeId;\n const storage = new StagedChangesetStorage(projectRoot);\n const changeset = await storage.load(activeId);\n if (changeset) {\n for (const change of changeset.changes as StagedChange[]) {\n // Track layer names for getLayerNames()\n if (\n change.type === \"add\" ||\n change.type === \"update\" ||\n change.type === \"delete\"\n ) {\n model._stagedLayerNames.add(change.layerName);\n }\n\n // Inject staged relationship-adds into model.relationships so that\n // read commands (list, show, export) transparently see staged relationships.\n if (change.type === \"relationship-add\" && change.after) {\n const rel = change.after as {\n source: string;\n target: string;\n predicate: string;\n layer: string;\n targetLayer?: string;\n category?: \"structural\" | \"behavioral\";\n properties?: Record<string, unknown>;\n };\n // Only inject if not already in relationships.yaml (prevents duplicates\n // if .active file is stale after a partial commit or manual edit).\n const alreadyPresent = model.relationships.find(\n rel.source,\n rel.target,\n rel.predicate\n );\n if (alreadyPresent.length === 0) {\n model.relationships.add({\n source: rel.source,\n target: rel.target,\n predicate: rel.predicate,\n layer: rel.layer,\n ...(rel.targetLayer ? { targetLayer: rel.targetLayer } : {}),\n category: rel.category ?? \"structural\",\n ...(rel.properties ? { properties: rel.properties } : {}),\n });\n }\n }\n\n // Remove staged relationship-deletes from model.relationships so that\n // read commands see the relationship as already deleted.\n if (change.type === \"relationship-delete\" && change.before) {\n const rel = change.before as {\n source: string;\n target: string;\n predicate?: string;\n };\n model.relationships.delete(rel.source, rel.target, rel.predicate);\n }\n }\n }\n }\n } catch {\n // No active changeset or unreadable \u2014 proceed with base model only\n model._activeChangesetId = null;\n }\n\n // Count total entities across all layers\n let entityCount = 0;\n for (const layer of model.layers.values()) {\n entityCount += layer.elements.size;\n }\n\n span.setAttribute(\"model.entity_count\", entityCount);\n span.setAttribute(\"model.layer_count\", model.layers.size);\n\n return model;\n }, {\n \"model.path\": startPath || process.cwd(),\n \"model.type\": \"dr\",\n });\n }\n\n /**\n * Initialize a new model in a directory\n */\n static async init(\n rootPath: string,\n manifestData: ManifestData,\n options: ModelOptions = {}\n ): Promise<Model> {\n // Create model directory structure\n await ensureDir(`${rootPath}/documentation-robotics/model`);\n\n for (let i = 0; i < CANONICAL_LAYER_NAMES.length; i++) {\n const orderNum = String(i + 1).padStart(2, \"0\");\n const layerName = CANONICAL_LAYER_NAMES[i];\n await ensureDir(`${rootPath}/documentation-robotics/model/${orderNum}_${layerName}`);\n }\n\n const manifest = new Manifest(manifestData);\n const model = new Model(rootPath, manifest, options);\n\n await model.saveManifest();\n\n return model;\n }\n\n /**\n * Graph-based API methods for querying the model\n * These methods delegate to the underlying GraphModel for efficient queries\n */\n\n /**\n * Get a node by its UUID\n */\n getNode(id: string) {\n return this.graph.getNode(id);\n }\n\n /**\n * Get all nodes in a specific layer\n */\n getNodesByLayer(layerId: string) {\n return this.graph.getNodesByLayer(layerId);\n }\n\n /**\n * Get all nodes of a specific type\n */\n getNodesByType(type: string) {\n return this.graph.getNodesByType(type);\n }\n\n /**\n * Get all edges (relationships) in the model\n */\n getAllEdges() {\n return this.graph.getAllEdges();\n }\n\n /**\n * Get edges originating from a specific node\n */\n getEdgesFrom(nodeId: string, predicate?: string) {\n return this.graph.getEdgesFrom(nodeId, predicate);\n }\n\n /**\n * Get edges terminating at a specific node\n */\n getEdgesTo(nodeId: string, predicate?: string) {\n return this.graph.getEdgesTo(nodeId, predicate);\n }\n\n /**\n * Get edges between two specific nodes\n */\n getEdgesBetween(sourceId: string, destinationId: string, predicate?: string) {\n return this.graph.getEdgesBetween(sourceId, destinationId, predicate);\n }\n\n /**\n * Traverse the graph starting from a node, following a specific predicate\n */\n async traverse(startNodeId: string, predicate: string, maxDepth: number = 10) {\n return this.graph.traverse(startNodeId, predicate, maxDepth);\n }\n\n /**\n * Create a backup of the current model state\n * Used for rollback support in migration operations\n *\n * @param label Descriptive label for the backup (e.g., \"pre-migration\")\n * @returns Path to the backup directory\n */\n async createBackup(label: string): Promise<string> {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupDir = path.join(this.rootPath, \".dr-backups\", `${label}-${timestamp}`);\n\n // Create backup directory\n await ensureDir(backupDir);\n\n // Backup layers directory\n const layersSource = path.join(this.rootPath, \"documentation-robotics\", \"model\");\n const layersBackup = path.join(backupDir, \"layers\");\n if (await this.directoryExists(layersSource)) {\n await this.copyDirectory(layersSource, layersBackup);\n }\n\n // Backup manifest\n const manifestSource = path.join(this.rootPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n const manifestBackup = path.join(backupDir, \"manifest.yaml\");\n if (await this.fileExists(manifestSource)) {\n await fs.copyFile(manifestSource, manifestBackup);\n }\n\n return backupDir;\n }\n\n /**\n * Restore model from a backup directory\n * Used for rollback after failed migrations\n *\n * @param backupPath Path to the backup directory\n */\n async restoreFromBackup(backupPath: string): Promise<void> {\n // Restore layers\n const layersBackup = path.join(backupPath, \"layers\");\n const layersTarget = path.join(this.rootPath, \"documentation-robotics\", \"model\");\n if (await this.directoryExists(layersBackup)) {\n await this.copyDirectory(layersBackup, layersTarget);\n }\n\n // Restore manifest\n const manifestBackup = path.join(backupPath, \"manifest.yaml\");\n const manifestTarget = path.join(this.rootPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n if (await this.fileExists(manifestBackup)) {\n await fs.copyFile(manifestBackup, manifestTarget);\n }\n\n // Reload model to refresh in-memory state\n const reloadedModel = await Model.load(this.rootPath, { lazyLoad: this.lazyLoad });\n this.layers = reloadedModel.layers;\n this.manifest = reloadedModel.manifest;\n this.graph = reloadedModel.graph;\n this.relationships = reloadedModel.relationships;\n }\n\n /**\n * Save dirty layers with atomic write semantics\n * Writes to temporary file first, then renames on success to ensure data safety\n *\n * @throws Error if atomic write fails\n */\n async saveDirtyLayersAtomic(): Promise<void> {\n // First, save all layers to temporary files\n const tempLayerWrites: Array<{ layer: Layer; tempPath: string }> = [];\n\n try {\n for (const layer of this.layers.values()) {\n if (layer.isDirty()) {\n const layerPath = path.join(\n this.rootPath,\n \"documentation-robotics\",\n \"model\",\n `${layer.name}_layer`\n );\n\n const tempPath = `${layerPath}.tmp`;\n await ensureDir(tempPath);\n\n // Write layer elements to temp directory\n for (const element of layer.elements.values()) {\n const elementPath = path.join(tempPath, `${element.path || element.id}.json`);\n const content = JSON.stringify(element.toJSON(), null, 2);\n await writeFile(elementPath, content);\n }\n\n tempLayerWrites.push({ layer, tempPath });\n }\n }\n\n // All temp writes succeeded, now commit by renaming\n for (const { layer, tempPath } of tempLayerWrites) {\n const layerPath = path.join(\n this.rootPath,\n \"documentation-robotics\",\n \"model\",\n `${layer.name}_layer`\n );\n\n // Remove old directory and rename temp to actual\n if (await this.directoryExists(layerPath)) {\n await fs.rm(layerPath, { recursive: true, force: true });\n }\n await fs.rename(tempPath, layerPath);\n }\n } catch (error) {\n // Cleanup any temp directories on failure\n for (const { tempPath } of tempLayerWrites) {\n if (await this.directoryExists(tempPath)) {\n await fs.rm(tempPath, { recursive: true, force: true });\n }\n }\n throw error;\n }\n }\n\n /**\n * Helper: Check if file exists\n */\n private async fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Helper: Check if directory exists\n */\n private async directoryExists(dirPath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(dirPath);\n return stat.isDirectory();\n } catch {\n return false;\n }\n }\n\n /**\n * Helper: Recursively copy directory\n */\n private async copyDirectory(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n}\n"],
5
+ "mappings": "AA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