@documentation-robotics/cli 0.2.0 → 0.4.0
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.
- package/README.md +46 -16
- package/dist/analysis/relationship-classifier.js +2 -9
- package/dist/analysis/relationship-classifier.js.map +2 -2
- package/dist/analyzers/active-analyzer.js +62 -0
- package/dist/analyzers/active-analyzer.js.map +7 -0
- package/dist/analyzers/call-graph-utils.js +2 -2
- package/dist/analyzers/call-graph-utils.js.map +2 -2
- package/dist/analyzers/cards/build.js +191 -0
- package/dist/analyzers/cards/build.js.map +7 -0
- package/dist/analyzers/cards/classify.js +42 -0
- package/dist/analyzers/cards/classify.js.map +7 -0
- package/dist/analyzers/cards/edge-index.js +44 -0
- package/dist/analyzers/cards/edge-index.js.map +7 -0
- package/dist/analyzers/cards/extract.js +138 -0
- package/dist/analyzers/cards/extract.js.map +7 -0
- package/dist/analyzers/cards/facts.js +46 -0
- package/dist/analyzers/cards/facts.js.map +7 -0
- package/dist/analyzers/cards/graph.js +42 -0
- package/dist/analyzers/cards/graph.js.map +7 -0
- package/dist/analyzers/cards/index.js +8 -0
- package/dist/analyzers/cards/index.js.map +7 -0
- package/dist/analyzers/cards/routes.js +96 -0
- package/dist/analyzers/cards/routes.js.map +7 -0
- package/dist/analyzers/cards/tier0.js +18 -0
- package/dist/analyzers/cards/tier0.js.map +7 -0
- package/dist/analyzers/cards/types.js +1 -0
- package/dist/analyzers/cards/types.js.map +7 -0
- package/dist/analyzers/cbm-analyzer.js +270 -174
- package/dist/analyzers/cbm-analyzer.js.map +2 -2
- package/dist/analyzers/cbm-responses.js +342 -0
- package/dist/analyzers/cbm-responses.js.map +7 -0
- package/dist/analyzers/code-changes.js +159 -0
- package/dist/analyzers/code-changes.js.map +7 -0
- package/dist/analyzers/edge-relationships.js +49 -0
- package/dist/analyzers/edge-relationships.js.map +7 -0
- package/dist/analyzers/extraction-plan.js +541 -0
- package/dist/analyzers/extraction-plan.js.map +7 -0
- package/dist/analyzers/index-job.js +229 -0
- package/dist/analyzers/index-job.js.map +7 -0
- package/dist/analyzers/mapping-loader.js +9 -0
- package/dist/analyzers/mapping-loader.js.map +2 -2
- package/dist/analyzers/tier0-rules.js +153 -0
- package/dist/analyzers/tier0-rules.js.map +7 -0
- package/dist/analyzers/types.js.map +1 -1
- package/dist/audit/relationships/ai/prompts.js +10 -10
- package/dist/audit/relationships/ai/prompts.js.map +2 -2
- package/dist/audit/relationships/analysis/layer-templates.js +52 -52
- package/dist/audit/relationships/analysis/layer-templates.js.map +1 -1
- package/dist/cli.js +23 -11
- package/dist/cli.js.map +2 -2
- package/dist/coding-agents/default-permissions.js +31 -1
- package/dist/coding-agents/default-permissions.js.map +2 -2
- package/dist/coding-agents/drbot-mcp.js +269 -0
- package/dist/coding-agents/drbot-mcp.js.map +7 -0
- package/dist/commands/add.js +7 -4
- package/dist/commands/add.js.map +2 -2
- package/dist/commands/analyzer.js +143 -40
- package/dist/commands/analyzer.js.map +2 -2
- package/dist/commands/changeset-verify.js +63 -0
- package/dist/commands/changeset-verify.js.map +7 -0
- package/dist/commands/changeset.js +80 -29
- package/dist/commands/changeset.js.map +2 -2
- package/dist/commands/delete.js +10 -4
- package/dist/commands/delete.js.map +2 -2
- package/dist/commands/farm.js +176 -60
- package/dist/commands/farm.js.map +2 -2
- package/dist/commands/init.js +9 -26
- package/dist/commands/init.js.map +2 -2
- package/dist/commands/mcp.js +40 -21
- package/dist/commands/mcp.js.map +3 -3
- package/dist/commands/relationship.js +208 -37
- package/dist/commands/relationship.js.map +2 -2
- package/dist/commands/reports.js +3 -3
- package/dist/commands/reports.js.map +2 -2
- package/dist/commands/update.js +52 -32
- package/dist/commands/update.js.map +2 -2
- package/dist/commands/upgrade.js +99 -103
- package/dist/commands/upgrade.js.map +3 -3
- package/dist/commands/validate.js +19 -3
- package/dist/commands/validate.js.map +2 -2
- package/dist/commands/version.js +1 -1
- package/dist/commands/visualize.js +34 -15
- package/dist/commands/visualize.js.map +2 -2
- package/dist/core/annotation-store.js +15 -5
- package/dist/core/annotation-store.js.map +2 -2
- package/dist/core/catalog-migration.js +34 -0
- package/dist/core/catalog-migration.js.map +7 -0
- package/dist/core/changeset-analysis.js +421 -0
- package/dist/core/changeset-analysis.js.map +7 -0
- package/dist/core/changeset-base-index.js +160 -0
- package/dist/core/changeset-base-index.js.map +7 -0
- package/dist/core/changeset-brief-compact.js +256 -0
- package/dist/core/changeset-brief-compact.js.map +7 -0
- package/dist/core/changeset-brief-delta.js +102 -0
- package/dist/core/changeset-brief-delta.js.map +7 -0
- package/dist/core/changeset-graph.js +281 -0
- package/dist/core/changeset-graph.js.map +7 -0
- package/dist/core/changeset-only-guard.js +32 -0
- package/dist/core/changeset-only-guard.js.map +7 -0
- package/dist/core/changeset-summary.js +68 -0
- package/dist/core/changeset-summary.js.map +7 -0
- package/dist/core/changeset-validator.js +66 -20
- package/dist/core/changeset-validator.js.map +2 -2
- package/dist/core/changeset-verify.js +848 -0
- package/dist/core/changeset-verify.js.map +7 -0
- package/dist/core/changeset.js +56 -9
- package/dist/core/changeset.js.map +2 -2
- package/dist/core/element-type-migration.js +145 -0
- package/dist/core/element-type-migration.js.map +7 -0
- package/dist/core/extraction-observability.js +161 -0
- package/dist/core/extraction-observability.js.map +7 -0
- package/dist/core/farm-manifest.js +12 -6
- package/dist/core/farm-manifest.js.map +2 -2
- package/dist/core/farm-sync-engine.js +1 -1
- package/dist/core/farm-sync-engine.js.map +2 -2
- package/dist/core/farm-sync-state.js +10 -2
- package/dist/core/farm-sync-state.js.map +2 -2
- package/dist/core/migration-registry.js +88 -47
- package/dist/core/migration-registry.js.map +2 -2
- package/dist/core/model-upgrade.js +102 -0
- package/dist/core/model-upgrade.js.map +7 -0
- package/dist/core/model.js +82 -30
- package/dist/core/model.js.map +2 -2
- package/dist/core/mutation-handler.js +71 -6
- package/dist/core/mutation-handler.js.map +2 -2
- package/dist/core/project-init.js +53 -0
- package/dist/core/project-init.js.map +7 -0
- package/dist/core/relationship-migration-table.js +6639 -0
- package/dist/core/relationship-migration-table.js.map +7 -0
- package/dist/core/relationship-migration.js +272 -0
- package/dist/core/relationship-migration.js.map +7 -0
- package/dist/core/relationship-prune.js +49 -0
- package/dist/core/relationship-prune.js.map +7 -0
- package/dist/core/relationship-staging.js +161 -0
- package/dist/core/relationship-staging.js.map +7 -0
- package/dist/core/relationships.js +26 -4
- package/dist/core/relationships.js.map +2 -2
- package/dist/core/report-data-model.js +7 -13
- package/dist/core/report-data-model.js.map +2 -2
- package/dist/core/staged-changeset-storage.js +145 -18
- package/dist/core/staged-changeset-storage.js.map +2 -2
- package/dist/core/staged-source-reference.js +28 -0
- package/dist/core/staged-source-reference.js.map +7 -0
- package/dist/core/staging-area.js +166 -24
- package/dist/core/staging-area.js.map +2 -2
- package/dist/core/upgrade-plan.js +117 -0
- package/dist/core/upgrade-plan.js.map +7 -0
- package/dist/core/virtual-projection.js +13 -5
- package/dist/core/virtual-projection.js.map +2 -2
- package/dist/export/archimate-exporter.js +1 -0
- package/dist/export/archimate-exporter.js.map +2 -2
- package/dist/generated/compiled-validators.js +2 -2
- package/dist/generated/compiled-validators.js.map +2 -2
- package/dist/generated/layer-registry.js +16 -16
- package/dist/generated/layer-registry.js.map +2 -2
- package/dist/generated/node-types.js +186 -168
- package/dist/generated/node-types.js.map +2 -2
- package/dist/generated/relationship-index.js +2468 -7913
- package/dist/generated/relationship-index.js.map +2 -2
- package/dist/integrations/claude_code/.claude-plugin/plugin.json +24 -0
- package/dist/integrations/claude_code/agents/dr-architect.md +30 -3
- package/dist/integrations/claude_code/agents/dr-extractor.md +8 -2
- package/dist/integrations/claude_code/commands/dr-analyzer.md +565 -0
- package/dist/integrations/claude_code/commands/dr-changeset.md +2 -1
- package/dist/integrations/claude_code/commands/dr-map.md +20 -1
- package/dist/integrations/claude_code/commands/dr-plan.md +66 -0
- package/dist/integrations/claude_code/commands/dr-relate.md +106 -96
- package/dist/integrations/claude_code/commands/dr-verify.md +45 -2
- package/dist/integrations/claude_code/docs/END_TO_END_WALKTHROUGH.md +14 -0
- package/dist/integrations/claude_code/docs/MCP_SERVER.md +47 -26
- package/dist/integrations/claude_code/docs/QUICK_START.md +37 -8
- package/dist/integrations/claude_code/docs/README.md +68 -2
- package/dist/integrations/claude_code/plugin-agents/dr-advisor.md +255 -0
- package/dist/integrations/claude_code/plugin-agents/dr-architect.md +306 -0
- package/dist/integrations/claude_code/skills/dr_01_motivation_layer/SKILL.md +93 -72
- package/dist/integrations/claude_code/skills/dr_02_business_layer/SKILL.md +163 -126
- package/dist/integrations/claude_code/skills/dr_03_product_layer/SKILL.md +161 -126
- package/dist/integrations/claude_code/skills/dr_04_security_layer/SKILL.md +153 -133
- package/dist/integrations/claude_code/skills/dr_05_application_layer/SKILL.md +129 -100
- package/dist/integrations/claude_code/skills/dr_06_technology_layer/SKILL.md +111 -94
- package/dist/integrations/claude_code/skills/dr_07_api_layer/SKILL.md +143 -157
- package/dist/integrations/claude_code/skills/dr_08_data_model_layer/SKILL.md +117 -33
- package/dist/integrations/claude_code/skills/dr_09_dataset_layer/SKILL.md +74 -25
- package/dist/integrations/claude_code/skills/dr_10_ux_layer/SKILL.md +88 -12
- package/dist/integrations/claude_code/skills/dr_11_navigation_layer/SKILL.md +83 -24
- package/dist/integrations/claude_code/skills/dr_12_apm_layer/SKILL.md +57 -12
- package/dist/integrations/claude_code/skills/dr_13_testing_layer/SKILL.md +95 -15
- package/dist/integrations/claude_code/skills/dr_change_planning/SKILL.md +178 -0
- package/dist/integrations/claude_code/skills/dr_changeset_reviewer/SKILL.md +8 -0
- package/dist/integrations/claude_code/skills/dr_engineering_guide/SKILL.md +6 -1
- package/dist/integrations/github_copilot/agents/dr-architect.md +3 -1
- package/dist/integrations/github_copilot/skills/dr_01_motivation_layer/SKILL.md +182 -102
- package/dist/integrations/github_copilot/skills/dr_02_business_layer/SKILL.md +266 -148
- package/dist/integrations/github_copilot/skills/dr_03_product_layer/SKILL.md +547 -86
- package/dist/integrations/github_copilot/skills/dr_04_security_layer/SKILL.md +164 -169
- package/dist/integrations/github_copilot/skills/dr_05_application_layer/SKILL.md +420 -150
- package/dist/integrations/github_copilot/skills/dr_06_technology_layer/SKILL.md +331 -138
- package/dist/integrations/github_copilot/skills/dr_07_api_layer/SKILL.md +265 -201
- package/dist/integrations/github_copilot/skills/dr_08_data_model_layer/SKILL.md +181 -58
- package/dist/integrations/github_copilot/skills/dr_09_dataset_layer/SKILL.md +209 -57
- package/dist/integrations/github_copilot/skills/dr_10_ux_layer/SKILL.md +277 -112
- package/dist/integrations/github_copilot/skills/dr_11_navigation_layer/SKILL.md +219 -70
- package/dist/integrations/github_copilot/skills/dr_12_apm_layer/SKILL.md +189 -105
- package/dist/integrations/github_copilot/skills/dr_13_testing_layer/SKILL.md +225 -102
- package/dist/integrations/github_copilot/skills/dr_change_planning/SKILL.md +177 -0
- package/dist/integrations/github_copilot/skills/dr_changeset_reviewer/SKILL.md +3 -0
- package/dist/integrations/hash-utils.js.map +2 -2
- package/dist/mcp/api-key-manager.js +14 -1
- package/dist/mcp/api-key-manager.js.map +2 -2
- package/dist/mcp/changeset-only.js +45 -0
- package/dist/mcp/changeset-only.js.map +7 -0
- package/dist/mcp/project-root.js +85 -0
- package/dist/mcp/project-root.js.map +7 -0
- package/dist/mcp/server-instructions.js +27 -0
- package/dist/mcp/server-instructions.js.map +7 -0
- package/dist/mcp/strict-schema.js +52 -0
- package/dist/mcp/strict-schema.js.map +7 -0
- package/dist/mcp/tool-registry.js +55 -5
- package/dist/mcp/tool-registry.js.map +2 -2
- package/dist/mcp/tools/changeset-analysis-tools.js +98 -0
- package/dist/mcp/tools/changeset-analysis-tools.js.map +7 -0
- package/dist/mcp/tools/changeset-commit.js +224 -0
- package/dist/mcp/tools/changeset-commit.js.map +7 -0
- package/dist/mcp/tools/changeset-editing.js +260 -0
- package/dist/mcp/tools/changeset-editing.js.map +7 -0
- package/dist/mcp/tools/changeset-lifecycle.js +83 -0
- package/dist/mcp/tools/changeset-lifecycle.js.map +7 -0
- package/dist/mcp/tools/changeset-shared.js +31 -0
- package/dist/mcp/tools/changeset-shared.js.map +7 -0
- package/dist/mcp/tools/changeset-show.js +17 -1
- package/dist/mcp/tools/changeset-show.js.map +2 -2
- package/dist/mcp/tools/changeset-verify.js +49 -0
- package/dist/mcp/tools/changeset-verify.js.map +7 -0
- package/dist/mcp/tools/codebase-extract.js +836 -0
- package/dist/mcp/tools/codebase-extract.js.map +7 -0
- package/dist/mcp/tools/codebase-index.js +125 -0
- package/dist/mcp/tools/codebase-index.js.map +7 -0
- package/dist/mcp/tools/codebase-shared.js +265 -0
- package/dist/mcp/tools/codebase-shared.js.map +7 -0
- package/dist/mcp/tools/codebase-verify.js +48 -0
- package/dist/mcp/tools/codebase-verify.js.map +7 -0
- package/dist/mcp/tools/index.js +34 -1
- package/dist/mcp/tools/index.js.map +2 -2
- package/dist/mcp/tools/model-add.js +191 -74
- package/dist/mcp/tools/model-add.js.map +2 -2
- package/dist/mcp/tools/model-delete.js +2 -2
- package/dist/mcp/tools/model-delete.js.map +2 -2
- package/dist/mcp/tools/model-search.js +14 -0
- package/dist/mcp/tools/model-search.js.map +2 -2
- package/dist/mcp/tools/model-show.js +29 -2
- package/dist/mcp/tools/model-show.js.map +2 -2
- package/dist/mcp/tools/model-trace.js +93 -30
- package/dist/mcp/tools/model-trace.js.map +2 -2
- package/dist/mcp/tools/model-update.js +46 -26
- package/dist/mcp/tools/model-update.js.map +2 -2
- package/dist/mcp/tools/model-validate.js +46 -4
- package/dist/mcp/tools/model-validate.js.map +2 -2
- package/dist/mcp/tools/project-status-collectors.js +381 -0
- package/dist/mcp/tools/project-status-collectors.js.map +7 -0
- package/dist/mcp/tools/project-status.js +237 -0
- package/dist/mcp/tools/project-status.js.map +7 -0
- package/dist/mcp/tools/project-tools.js +505 -0
- package/dist/mcp/tools/project-tools.js.map +7 -0
- package/dist/mcp/tools/relationship-tools.js +167 -0
- package/dist/mcp/tools/relationship-tools.js.map +7 -0
- package/dist/mcp/tools/review-open.js +210 -0
- package/dist/mcp/tools/review-open.js.map +7 -0
- package/dist/mcp/tools/shared.js +35 -4
- package/dist/mcp/tools/shared.js.map +2 -2
- package/dist/mcp/tools/spec-type.js +90 -0
- package/dist/mcp/tools/spec-type.js.map +7 -0
- package/dist/reports/model-report-orchestrator.js +31 -2
- package/dist/reports/model-report-orchestrator.js.map +2 -2
- package/dist/schemas/bundled/analyzers/cbm.json +1200 -70
- package/dist/schemas/bundled/analyzers/manifest.json +2 -2
- package/dist/schemas/bundled/api.json +1029 -1658
- package/dist/schemas/bundled/apm.json +499 -734
- package/dist/schemas/bundled/application.json +735 -371
- package/dist/schemas/bundled/base.json +3 -220
- package/dist/schemas/bundled/business.json +452 -366
- package/dist/schemas/bundled/data-model.json +395 -411
- package/dist/schemas/bundled/data-store.json +334 -558
- package/dist/schemas/bundled/manifest.json +18 -18
- package/dist/schemas/bundled/motivation.json +349 -368
- package/dist/schemas/bundled/navigation.json +415 -731
- package/dist/schemas/bundled/product.json +325 -159
- package/dist/schemas/bundled/security.json +864 -1232
- package/dist/schemas/bundled/technology.json +574 -703
- package/dist/schemas/bundled/testing.json +865 -1646
- package/dist/schemas/bundled/ux.json +739 -1352
- package/dist/server/schemas.js +8 -0
- package/dist/server/schemas.js.map +2 -2
- package/dist/server/server.js +686 -231
- package/dist/server/server.js.map +3 -3
- package/dist/server/viewer-registry.js +264 -0
- package/dist/server/viewer-registry.js.map +7 -0
- package/dist/server-entry.js +2 -1
- package/dist/server-entry.js.map +2 -2
- package/dist/telemetry/index.js +1 -1
- package/dist/utils/ansi-suppressor.js +6 -8
- package/dist/utils/ansi-suppressor.js.map +2 -2
- package/dist/utils/attribute-patch.js +41 -0
- package/dist/utils/attribute-patch.js.map +7 -0
- package/dist/utils/error-hints.js +29 -0
- package/dist/utils/error-hints.js.map +7 -0
- package/dist/utils/errors.js +9 -3
- package/dist/utils/errors.js.map +2 -2
- package/dist/utils/id-generator.js +5 -2
- package/dist/utils/id-generator.js.map +2 -2
- package/dist/utils/project-paths.js +26 -1
- package/dist/utils/project-paths.js.map +2 -2
- package/dist/utils/source-reference.js +64 -31
- package/dist/utils/source-reference.js.map +2 -2
- package/dist/utils/spec-version.js +2 -2
- package/dist/utils/spec-version.js.map +1 -1
- package/dist/validators/composed-reference-validator.js +5 -27
- package/dist/validators/composed-reference-validator.js.map +2 -2
- package/dist/validators/model-warnings.js +28 -0
- package/dist/validators/model-warnings.js.map +7 -0
- package/dist/validators/reference-validator.js +0 -7
- package/dist/validators/reference-validator.js.map +2 -2
- package/dist/validators/relationship-schema-validator.js +3 -3
- package/dist/validators/relationship-schema-validator.js.map +2 -2
- package/dist/validators/schema-validator.js +27 -9
- package/dist/validators/schema-validator.js.map +2 -2
- package/dist/validators/types.js.map +1 -1
- package/dist/viewer/README.md +6 -6
- package/dist/viewer/assets/main-CUOQGGRA.css +1 -0
- package/dist/viewer/assets/main-DvH3gYrI.js +84 -0
- package/dist/viewer/index.html +2 -2
- package/dist/viewer/manifest.json +10 -10
- package/dist/viewer/version.json +1 -1
- package/package.json +2 -1
- package/dist/viewer/assets/main-B7AOQXXX.js +0 -81
- package/dist/viewer/assets/main-vdrFrG7q.css +0 -1
package/dist/core/model.js.map
CHANGED
|
@@ -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 { getCodebasePath } from \"../utils/globals.js\";\nimport { getErrorMessage } from \"../utils/errors.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/**\n * Graph-internal bookkeeping keys that `layer.ts`'s node<->Element conversion stuffs into the\n * same flat `attributes`/`properties` bag the underlying graph structure uses for everything\n * (it has no separate channel for them) \u2014 `__references__`/`__relationships__`/`__semanticId__`\n * mirror `element.references`/`element.relationships`/`element.semanticId`, which are real,\n * separately-typed fields on `Element` and get serialized to their own place (references\n * inline, relationships to relationships.yaml, semanticId isn't persisted at all \u2014 it only\n * exists to resolve legacy-format elements during a single load). These must never reach the\n * persisted YAML's `attributes` object.\n *\n * Double-underscore-prefixed specifically so a schema author would have to go out of their way\n * to collide with one \u2014 confirmed zero of the 191 node schemas declare an attribute with any of\n * these names. Contrast with the *type-blind* set this replaced, which also unconditionally\n * stripped plain `\"source\"`/`\"x-source-reference\"` \u2014 both of which ARE legitimate, sometimes-\n * required domain attributes on 41 node schemas across 8 layers (e.g.\n * security.accesscondition.source), and neither of which is ever actually used as internal\n * bookkeeping anywhere in this codebase. That collision silently destroyed real data on every\n * save for any element of one of those 41 types, without ever failing validation (validation\n * runs on the in-memory element, before this stripping) \u2014 see CHANGELOG for the incident this\n * fixes.\n *\n * `__semanticId__` is listed here purely as defense-in-depth, not as the primary guard: it can\n * only ever reach `attributes` via `GraphModel.fromElement()` aliasing `properties` and\n * `attributes` to the same object, which `layer.ts`'s bookkeeping-key injection would then\n * mutate through. That aliasing is fixed at the source in graph-model.ts (`properties` is now\n * always an independent copy), so `__semanticId__` should never actually arrive here \u2014 but\n * listing it means a regression of that aliasing fix fails safe instead of silently reopening\n * the same leak `__semanticId__` briefly caused.\n */\nconst ALWAYS_INTERNAL_ATTRIBUTE_KEYS = new Set([\"__references__\", \"__relationships__\", \"__semanticId__\"]);\n\n/**\n * Whether `key` should survive persistence in `specNodeId`'s `attributes`.\n *\n * Only ever strips the two confirmed-always-internal keys above, and even then only when the\n * node type's OWN schema doesn't declare that name as a real attribute \u2014 so if some future\n * schema ever legitimately needs an attribute literally called `__references__` (unlikely, but\n * the whole point of this function is to not have to trust \"unlikely\" again), it still survives.\n * Nothing else is ever stripped: the class of bug this fixes was a hardcoded, type-blind\n * reserved-word blocklist making that same \"trust the list, not the schema\" mistake for\n * `source`/`x-source-reference`. Consulting the schema instead of a fixed string list is what\n * keeps this from silently recurring for some other attribute name in the future.\n */\nfunction isPersistableAttribute(specNodeId: string | undefined, key: string): boolean {\n if (!ALWAYS_INTERNAL_ATTRIBUTE_KEYS.has(key)) return true;\n if (!specNodeId) return false;\n const nodeType = getNodeType(specNodeId as SpecNodeId);\n if (!nodeType) return false;\n return nodeType.requiredAttributes.includes(key) || nodeType.optionalAttributes.includes(key);\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 codebaseRoot: string;\n manifest: Manifest;\n graph: GraphModel;\n layers: Map<string, Layer>;\n relationships: Relationships;\n lazyLoad: boolean;\n loadedLayerFilter?: string[];\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.codebaseRoot = options.codebaseRoot ?? 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.loadedLayerFilter = options.layers;\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 // Support both standard structure (rootPath/documentation-robotics/model) and non-standard (rootPath directly)\n let 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 (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Standard structure doesn't exist, try non-standard structure (rootPath directly)\n try {\n const entries = await fs.readdir(this.rootPath, { 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 = `${this.rootPath}/${layerDir.name}`;\n }\n } catch (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Neither structure found\n }\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 (support both standard and non-standard structures)\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 (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Standard structure doesn't exist, try non-standard structure (rootPath directly)\n try {\n const entries = await fs.readdir(this.rootPath, { 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 = `${this.rootPath}/${layerDir.name}`;\n }\n } catch (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Neither structure found\n }\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 // 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 \u2014 see\n // isPersistableAttribute's own doc for why this checks the schema rather than a\n // hardcoded name list.\n const cleanAttrs = json.attributes\n ? Object.fromEntries(\n Object.entries(json.attributes).filter(([k]) =>\n isPersistableAttribute(json.spec_node_id, k)\n )\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.codebase_path) {\n yamlData.codebase_path = this.manifest.codebase_path;\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 if (this.manifest.models && Object.keys(this.manifest.models).length > 0) {\n yamlData.models = this.manifest.models;\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 // Treat null (from comment-only files) as an empty array\n if (data === null) {\n data = [];\n }\n\n if (!Array.isArray(data)) {\n const typeLabel = 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 * Auto-resolve codebaseRoot from farm manifest if inside a farm\n *\n * @param modelRoot - The model's project root (documentation_robotics parent)\n * @returns Resolved codebase root path, or null if not in farm or resolution fails\n */\n private static async resolveFarmCodebaseRoot(modelRoot: string): Promise<string | null> {\n const { findFarmRoot } = await import(\"../utils/project-paths.js\");\n const { FarmManifest } = await import(\"./farm-manifest.js\");\n\n // Find farm root (may return null if not in a farm)\n const farmRoot = await findFarmRoot(modelRoot);\n if (!farmRoot) {\n return null;\n }\n\n // Load farm manifest\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n let manifest: any;\n try {\n manifest = await FarmManifest.load(farmYamlPath);\n } catch (error) {\n // Re-throw meaningful errors (YAML parse, permission errors, etc.)\n // Only return null if the farm setup is genuinely not present\n const errorMsg = getErrorMessage(error);\n if (errorMsg.includes(\"ENOENT\") || errorMsg.includes(\"not found\")) {\n return null; // Farm not found - expected case, not an error\n }\n throw new Error(`Failed to load farm manifest at ${farmYamlPath}: ${errorMsg}`);\n }\n\n // Find the model folder name relative to farm root\n const modelName = path.basename(modelRoot);\n\n // Look for a project where model matches our model's basename\n for (const project of manifest.getAllProjects()) {\n if (path.basename(project.model) === modelName) {\n // Found matching project, resolve codebase path\n const codebaseFullPath = path.resolve(farmRoot, project.source);\n return codebaseFullPath;\n }\n }\n\n return null; // No matching project found in farm - not an error\n }\n\n /**\n * Walk upward from startPath looking for documentation-robotics/model/manifest.yaml,\n * stopping at the nearest .git directory (repo boundary) so this can never cross into\n * an unrelated parent project or a sibling farm/detached model directory.\n *\n * @param startPath - Directory to start the walk from\n * @returns Manifest path if found within the repo boundary, or null\n */\n private static async findManifestUpwardBounded(startPath: string): Promise<string | null> {\n let currentPath = startPath;\n\n while (true) {\n const candidateManifestPath = path.join(currentPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n try {\n await fs.access(candidateManifestPath);\n return candidateManifestPath;\n } catch {\n // Not found at this level, keep looking\n }\n\n // Stop once we've checked the repo root (marked by .git) - never walk past it\n try {\n await fs.access(path.join(currentPath, \".git\"));\n return null;\n } catch {\n // Not a repo boundary, continue upward\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null; // Reached filesystem root\n }\n currentPath = parentPath;\n }\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 // Highest priority: explicit startPath parameter (used in concurrent contexts to avoid env var mutations)\n if (startPath) {\n const resolvedPath = path.resolve(startPath);\n let manifestPath: string;\n\n if (resolvedPath.endsWith(\"manifest.yaml\")) {\n manifestPath = resolvedPath;\n } else if (resolvedPath.endsWith(\"model\")) {\n manifestPath = path.join(resolvedPath, \"manifest.yaml\");\n } else {\n manifestPath = path.join(resolvedPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n }\n\n try {\n await fs.access(manifestPath);\n\n // Determine projectRoot: flexible approach for both standard and non-standard structures\n let projectRoot: string;\n const manifestParentDir = path.dirname(manifestPath);\n\n // First, try assuming the standard structure (manifest 3 levels deep)\n const standardProjectRoot = path.dirname(path.dirname(path.dirname(manifestPath)));\n const standardDocRobotsPath = path.join(standardProjectRoot, \"documentation-robotics\", \"model\");\n\n try {\n await fs.access(standardDocRobotsPath);\n projectRoot = standardProjectRoot;\n } catch (err) {\n // Only ignore ENOENT (path not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Not in standard structure, use manifest's parent directory as project root\n projectRoot = manifestParentDir;\n }\n\n return { projectRoot, manifestPath: path.normalize(manifestPath) };\n } catch (err) {\n // Only wrap ENOENT errors as \"not found\" \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n\n // startPath itself doesn't directly contain the manifest (e.g. it's a\n // subdirectory of the repo, like cli/ within the repo root). Fall back to a\n // bounded upward walk stopping at the nearest .git boundary. This never crosses\n // into a sibling farm/detached model directory since those are siblings of the\n // codebase, not ancestors, so they can't be reached by walking upward.\n const fallbackManifestPath = await Model.findManifestUpwardBounded(resolvedPath);\n if (fallbackManifestPath) {\n const fallbackProjectRoot = path.dirname(path.dirname(path.dirname(fallbackManifestPath)));\n return { projectRoot: fallbackProjectRoot, manifestPath: path.normalize(fallbackManifestPath) };\n }\n\n throw new Error(`Model not found at ${startPath}`);\n }\n }\n\n // Secondary priority: optional override via env var\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\n // Determine projectRoot: flexible approach for both standard and non-standard structures\n let projectRoot: string;\n const manifestParentDir = path.dirname(manifestPath);\n\n // First, try assuming the standard structure (manifest 3 levels deep)\n const standardProjectRoot = path.dirname(path.dirname(path.dirname(manifestPath)));\n const standardDocRobotsPath = path.join(standardProjectRoot, \"documentation-robotics\", \"model\");\n\n try {\n await fs.access(standardDocRobotsPath);\n projectRoot = standardProjectRoot;\n } catch (err) {\n // Only ignore ENOENT (path not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Not in standard structure, use manifest's parent directory as project root\n projectRoot = manifestParentDir;\n }\n\n return { projectRoot, manifestPath: path.normalize(manifestPath) };\n } catch (err) {\n // Only wrap ENOENT errors as \"not found\" \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n throw new Error(`Model not found at DR_MODEL_PATH: ${process.env.DR_MODEL_PATH}`);\n }\n }\n\n // Fallback: use findProjectRoot to locate documentation_robotics/ folder\n const searchPath = process.cwd();\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 * Validate that the manifest's models field is a plain object.\n *\n * @param models - The raw value from manifest YAML\n * @returns Validation result with valid flag and error message if invalid\n */\n static validateModelsField(models: unknown): { valid: boolean; error?: string } {\n // Check if models is null or undefined (this shouldn't happen since we check before calling)\n if (models === null || models === undefined) {\n return { valid: true };\n }\n\n // Check if models is a plain object (not an array, string, or other primitive)\n if (typeof models !== \"object\" || Array.isArray(models)) {\n return {\n valid: false,\n error:\n `Invalid manifest 'models' field: expected an object with model names as keys ` +\n `(e.g., { \"auth-service\": { } }), but got ${Array.isArray(models) ? \"an array\" : `a ${typeof models}`}. ` +\n `This often happens when YAML syntax is incorrect, like writing 'models: auth-service' ` +\n `instead of 'models: { auth-service: {} }' or 'models:\\\\n auth-service: {}'.`,\n };\n }\n\n // Validate that it's a plain object (not a class instance)\n if (Object.getPrototypeOf(models) !== Object.prototype) {\n return {\n valid: false,\n error:\n `Invalid manifest 'models' field: expected a plain object, but got an instance of ${\n (models as any).constructor?.name || \"unknown\"\n }. ` +\n `Please ensure 'models' is a simple YAML object mapping model names to declarations.`,\n };\n }\n\n return { valid: true };\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 cliVersion: manifestYaml.cli_version,\n specVersion: manifestYaml.spec_version || \"0.6.0\",\n created: manifestYaml.created || new Date().toISOString(),\n modified: manifestYaml.updated || new Date().toISOString(),\n };\n\n // Load external model declarations if present\n if (manifestYaml.models) {\n const modelsValidation = Model.validateModelsField(manifestYaml.models);\n if (!modelsValidation.valid) {\n throw new Error(modelsValidation.error);\n }\n manifestData.models = manifestYaml.models;\n }\n\n // Load codebase_path if present\n if (manifestYaml.codebase_path) {\n manifestData.codebase_path = manifestYaml.codebase_path;\n }\n\n const manifest = new Manifest(manifestData);\n\n // Resolve codebaseRoot with priority: options > CLI flag > manifest > farm > default\n let codebaseRoot = projectRoot;\n if (options.codebaseRoot) {\n codebaseRoot = options.codebaseRoot;\n } else {\n const globalCodebasePath = getCodebasePath();\n if (globalCodebasePath) {\n codebaseRoot = path.resolve(globalCodebasePath);\n } else if (manifest.codebase_path) {\n codebaseRoot = path.resolve(projectRoot, manifest.codebase_path);\n } else {\n // Try to auto-resolve from farm manifest if inside a farm\n const farmCodebaseRoot = await Model.resolveFarmCodebaseRoot(projectRoot);\n if (farmCodebaseRoot) {\n codebaseRoot = farmCodebaseRoot;\n }\n }\n }\n\n const model = new Model(projectRoot, manifest, { ...options, codebaseRoot });\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 const yaml = await import(\"yaml\");\n\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\n // Resolve codebaseRoot with priority: options > CLI flag > manifest > default\n let codebaseRoot = rootPath;\n if (options.codebaseRoot) {\n codebaseRoot = options.codebaseRoot;\n } else {\n const globalCodebasePath = getCodebasePath();\n if (globalCodebasePath) {\n codebaseRoot = path.resolve(globalCodebasePath);\n } else if (manifest.codebase_path) {\n codebaseRoot = path.resolve(rootPath, manifest.codebase_path);\n }\n }\n\n const model = new Model(rootPath, manifest, { ...options, codebaseRoot });\n\n await model.saveManifest();\n\n // Initialize relationships.yaml with empty array\n const relationshipsPath = `${rootPath}/documentation-robotics/model/relationships.yaml`;\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([]);\n await writeFile(relationshipsPath, yamlContent);\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,uBAAuB;AAChC,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,SAAS,KAAK,MAAM,IAAI,EAAE,GAAG,EAAE,IAAI,KAAQ,KAAM,SAAS,EAAE,IAAI,KAAK,MAAM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,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, type Relationship } 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 { getCodebasePath } from \"../utils/globals.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\nimport { assertBaseModelWritable } from \"./changeset-only-guard.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/**\n * Graph-internal bookkeeping keys that `layer.ts`'s node<->Element conversion stuffs into the\n * same flat `attributes`/`properties` bag the underlying graph structure uses for everything\n * (it has no separate channel for them) \u2014 `__references__`/`__relationships__`/`__semanticId__`\n * mirror `element.references`/`element.relationships`/`element.semanticId`, which are real,\n * separately-typed fields on `Element` and get serialized to their own place (references\n * inline, relationships to relationships.yaml, semanticId isn't persisted at all \u2014 it only\n * exists to resolve legacy-format elements during a single load). These must never reach the\n * persisted YAML's `attributes` object.\n *\n * Double-underscore-prefixed specifically so a schema author would have to go out of their way\n * to collide with one \u2014 confirmed zero of the 191 node schemas declare an attribute with any of\n * these names. Contrast with the *type-blind* set this replaced, which also unconditionally\n * stripped plain `\"source\"`/`\"x-source-reference\"` \u2014 both of which ARE legitimate, sometimes-\n * required domain attributes on 41 node schemas across 8 layers (e.g.\n * security.accesscondition.source), and neither of which is ever actually used as internal\n * bookkeeping anywhere in this codebase. That collision silently destroyed real data on every\n * save for any element of one of those 41 types, without ever failing validation (validation\n * runs on the in-memory element, before this stripping) \u2014 see CHANGELOG for the incident this\n * fixes.\n *\n * `__semanticId__` is listed here purely as defense-in-depth, not as the primary guard: it can\n * only ever reach `attributes` via `GraphModel.fromElement()` aliasing `properties` and\n * `attributes` to the same object, which `layer.ts`'s bookkeeping-key injection would then\n * mutate through. That aliasing is fixed at the source in graph-model.ts (`properties` is now\n * always an independent copy), so `__semanticId__` should never actually arrive here \u2014 but\n * listing it means a regression of that aliasing fix fails safe instead of silently reopening\n * the same leak `__semanticId__` briefly caused.\n */\nconst ALWAYS_INTERNAL_ATTRIBUTE_KEYS = new Set([\"__references__\", \"__relationships__\", \"__semanticId__\"]);\n\n/**\n * Whether `key` should survive persistence in `specNodeId`'s `attributes`.\n *\n * Only ever strips the two confirmed-always-internal keys above, and even then only when the\n * node type's OWN schema doesn't declare that name as a real attribute \u2014 so if some future\n * schema ever legitimately needs an attribute literally called `__references__` (unlikely, but\n * the whole point of this function is to not have to trust \"unlikely\" again), it still survives.\n * Nothing else is ever stripped: the class of bug this fixes was a hardcoded, type-blind\n * reserved-word blocklist making that same \"trust the list, not the schema\" mistake for\n * `source`/`x-source-reference`. Consulting the schema instead of a fixed string list is what\n * keeps this from silently recurring for some other attribute name in the future.\n */\nfunction isPersistableAttribute(specNodeId: string | undefined, key: string): boolean {\n if (!ALWAYS_INTERNAL_ATTRIBUTE_KEYS.has(key)) return true;\n if (!specNodeId) return false;\n const nodeType = getNodeType(specNodeId as SpecNodeId);\n if (!nodeType) return false;\n return nodeType.requiredAttributes.includes(key) || nodeType.optionalAttributes.includes(key);\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 codebaseRoot: string;\n manifest: Manifest;\n graph: GraphModel;\n layers: Map<string, Layer>;\n relationships: Relationships;\n lazyLoad: boolean;\n loadedLayerFilter?: string[];\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 * relationships.yaml as committed, captured at load time before the active changeset's staged\n * relationship changes are merged into `relationships`. Null when no changeset was active.\n */\n private _baseRelationships: Relationship[] | null = null;\n\n constructor(rootPath: string, manifest: Manifest, options: ModelOptions = {}) {\n this.rootPath = rootPath;\n this.codebaseRoot = options.codebaseRoot ?? 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.loadedLayerFilter = options.layers;\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 (err) {\n // Only fall back to base layer if the changeset is missing/corrupted\n const errorMessage = err instanceof Error ? err.message : String(err);\n const isChangesetNotFound =\n errorMessage.includes(\"Changeset\") && errorMessage.includes(\"not found\");\n const isCorrupted = errorMessage.includes(\"corrupted\");\n\n if (isChangesetNotFound || isCorrupted) {\n // Expected case: changeset missing or corrupted, safe to fall back to base\n return this.layers.get(name);\n }\n\n // Unexpected error: projection engine bug (TypeError, ReferenceError, etc.)\n // Re-throw so caller sees the actual problem\n throw err;\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 * The committed relationships, without the active changeset's staged additions and removals\n * that load() merges into `relationships` for read commands. Equal to `relationships.getAll()`\n * when no changeset was active at load time.\n */\n getBaseRelationships(): Relationship[] {\n return this._baseRelationships ? [...this._baseRelationships] : this.relationships.getAll();\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 // Support both standard structure (rootPath/documentation-robotics/model) and non-standard (rootPath directly)\n let 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 (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Standard structure doesn't exist, try non-standard structure (rootPath directly)\n try {\n const entries = await fs.readdir(this.rootPath, { 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 = `${this.rootPath}/${layerDir.name}`;\n }\n } catch (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Neither structure found\n }\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 * Records that the active changeset now stages an element change in `layerName`, so\n * getLayerNames() (and findElementLayer()) discover a layer the base model does not have without\n * a reload. StagingAreaManager calls this when it stages into this model's active changeset.\n */\n noteStagedLayer(changesetId: string, layerName: string): void {\n if (this._activeChangesetId && this._activeChangesetId === changesetId && layerName) {\n this._stagedLayerNames.add(layerName);\n }\n }\n\n /**\n * Save a layer to disk (model/XX_layername/*.yaml)\n */\n async saveLayer(name: string): Promise<void> {\n assertBaseModelWritable();\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 (support both standard and non-standard structures)\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 (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Standard structure doesn't exist, try non-standard structure (rootPath directly)\n try {\n const entries = await fs.readdir(this.rootPath, { 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 = `${this.rootPath}/${layerDir.name}`;\n }\n } catch (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Neither structure found\n }\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 // 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 \u2014 see\n // isPersistableAttribute's own doc for why this checks the schema rather than a\n // hardcoded name list.\n const cleanAttrs = json.attributes\n ? Object.fromEntries(\n Object.entries(json.attributes).filter(([k]) =>\n isPersistableAttribute(json.spec_node_id, k)\n )\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 assertBaseModelWritable();\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.codebase_path) {\n yamlData.codebase_path = this.manifest.codebase_path;\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 if (this.manifest.models && Object.keys(this.manifest.models).length > 0) {\n yamlData.models = this.manifest.models;\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 // Treat null (from comment-only files) as an empty array\n if (data === null) {\n data = [];\n }\n\n if (!Array.isArray(data)) {\n const typeLabel = 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 * @param options.preserveHeader - Keep the file's existing leading comment block\n * (refreshing its `# Last updated:` line) instead of writing the standard header.\n */\n async saveRelationships(options: { preserveHeader?: boolean } = {}): Promise<void> {\n assertBaseModelWritable();\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 let header = `# Intra-layer relationships\n# Format: source_id -> predicate -> target_id\n# Last updated: ${timestamp}\n\n`;\n if (options.preserveHeader) {\n try {\n const { extractRelationshipsHeader } = await import(\"./relationship-prune.js\");\n const existing = extractRelationshipsHeader(await fs.readFile(relationshipsPath, \"utf-8\"));\n if (existing) {\n header =\n existing.replace(/^(# Last updated:).*$/m, `$1 ${timestamp}`) + \"\\n\";\n }\n } catch {\n // Missing or unreadable file: fall back to the standard header\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 * Auto-resolve codebaseRoot from farm manifest if inside a farm\n *\n * @param modelRoot - The model's project root (documentation_robotics parent)\n * @returns Resolved codebase root path, or null if not in farm or resolution fails\n */\n private static async resolveFarmCodebaseRoot(modelRoot: string): Promise<string | null> {\n const { findFarmRoot } = await import(\"../utils/project-paths.js\");\n const { FarmManifest } = await import(\"./farm-manifest.js\");\n\n // Find farm root (may return null if not in a farm)\n const farmRoot = await findFarmRoot(modelRoot);\n if (!farmRoot) {\n return null;\n }\n\n // Load farm manifest\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n let manifest: any;\n try {\n manifest = await FarmManifest.load(farmYamlPath);\n } catch (error) {\n // Re-throw meaningful errors (YAML parse, permission errors, etc.)\n // Only return null if the farm setup is genuinely not present\n const errorMsg = getErrorMessage(error);\n if (errorMsg.includes(\"ENOENT\") || errorMsg.includes(\"not found\")) {\n return null; // Farm not found - expected case, not an error\n }\n throw new Error(`Failed to load farm manifest at ${farmYamlPath}: ${errorMsg}`);\n }\n\n // Find the model folder name relative to farm root\n const modelName = path.basename(modelRoot);\n\n // Look for a project where model matches our model's basename\n for (const project of manifest.getAllProjects()) {\n if (path.basename(project.model) === modelName) {\n // Found matching project, resolve codebase path\n const codebaseFullPath = path.resolve(farmRoot, project.source);\n return codebaseFullPath;\n }\n }\n\n return null; // No matching project found in farm - not an error\n }\n\n /**\n * Walk upward from startPath looking for documentation-robotics/model/manifest.yaml,\n * stopping at the nearest .git directory (repo boundary) so this can never cross into\n * an unrelated parent project or a sibling farm/detached model directory.\n *\n * @param startPath - Directory to start the walk from\n * @returns Manifest path if found within the repo boundary, or null\n */\n private static async findManifestUpwardBounded(startPath: string): Promise<string | null> {\n let currentPath = startPath;\n\n while (true) {\n const candidateManifestPath = path.join(currentPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n try {\n await fs.access(candidateManifestPath);\n return candidateManifestPath;\n } catch (err) {\n // Only ignore ENOENT (file not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Not found at this level, keep looking\n }\n\n // Stop once we've checked the repo root (marked by .git) - never walk past it\n try {\n await fs.access(path.join(currentPath, \".git\"));\n return null;\n } catch (err) {\n // Only ignore ENOENT (directory not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Not a repo boundary, continue upward\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null; // Reached filesystem root\n }\n currentPath = parentPath;\n }\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 // Highest priority: explicit startPath parameter (used in concurrent contexts to avoid env var mutations)\n if (startPath) {\n const resolvedPath = path.resolve(startPath);\n let manifestPath: string;\n\n if (resolvedPath.endsWith(\"manifest.yaml\")) {\n manifestPath = resolvedPath;\n } else if (resolvedPath.endsWith(\"model\")) {\n manifestPath = path.join(resolvedPath, \"manifest.yaml\");\n } else {\n manifestPath = path.join(resolvedPath, \"documentation-robotics\", \"model\", \"manifest.yaml\");\n }\n\n try {\n await fs.access(manifestPath);\n\n // Determine projectRoot: flexible approach for both standard and non-standard structures\n let projectRoot: string;\n const manifestParentDir = path.dirname(manifestPath);\n\n // First, try assuming the standard structure (manifest 3 levels deep)\n const standardProjectRoot = path.dirname(path.dirname(path.dirname(manifestPath)));\n const standardDocRobotsPath = path.join(standardProjectRoot, \"documentation-robotics\", \"model\");\n\n try {\n await fs.access(standardDocRobotsPath);\n projectRoot = standardProjectRoot;\n } catch (err) {\n // Only ignore ENOENT (path not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Not in standard structure, use manifest's parent directory as project root\n projectRoot = manifestParentDir;\n }\n\n return { projectRoot, manifestPath: path.normalize(manifestPath) };\n } catch (err) {\n // Only wrap ENOENT errors as \"not found\" \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n\n // startPath itself doesn't directly contain the manifest (e.g. it's a\n // subdirectory of the repo, like cli/ within the repo root). Fall back to a\n // bounded upward walk stopping at the nearest .git boundary. This never crosses\n // into a sibling farm/detached model directory since those are siblings of the\n // codebase, not ancestors, so they can't be reached by walking upward.\n const fallbackManifestPath = await Model.findManifestUpwardBounded(resolvedPath);\n if (fallbackManifestPath) {\n const fallbackProjectRoot = path.dirname(path.dirname(path.dirname(fallbackManifestPath)));\n return { projectRoot: fallbackProjectRoot, manifestPath: path.normalize(fallbackManifestPath) };\n }\n\n throw new Error(`Model not found at ${startPath}`);\n }\n }\n\n // Secondary priority: optional override via env var\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\n // Determine projectRoot: flexible approach for both standard and non-standard structures\n let projectRoot: string;\n const manifestParentDir = path.dirname(manifestPath);\n\n // First, try assuming the standard structure (manifest 3 levels deep)\n const standardProjectRoot = path.dirname(path.dirname(path.dirname(manifestPath)));\n const standardDocRobotsPath = path.join(standardProjectRoot, \"documentation-robotics\", \"model\");\n\n try {\n await fs.access(standardDocRobotsPath);\n projectRoot = standardProjectRoot;\n } catch (err) {\n // Only ignore ENOENT (path not found) \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n // Not in standard structure, use manifest's parent directory as project root\n projectRoot = manifestParentDir;\n }\n\n return { projectRoot, manifestPath: path.normalize(manifestPath) };\n } catch (err) {\n // Only wrap ENOENT errors as \"not found\" \u2014 re-throw permission/I/O errors\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n throw err;\n }\n throw new Error(`Model not found at DR_MODEL_PATH: ${process.env.DR_MODEL_PATH}`);\n }\n }\n\n // Fallback: use findProjectRoot to locate documentation_robotics/ folder\n const searchPath = process.cwd();\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 * Validate that the manifest's models field is a plain object.\n *\n * @param models - The raw value from manifest YAML\n * @returns Validation result with valid flag and error message if invalid\n */\n static validateModelsField(models: unknown): { valid: boolean; error?: string } {\n // Check if models is null or undefined (this shouldn't happen since we check before calling)\n if (models === null || models === undefined) {\n return { valid: true };\n }\n\n // Check if models is a plain object (not an array, string, or other primitive)\n if (typeof models !== \"object\" || Array.isArray(models)) {\n return {\n valid: false,\n error:\n `Invalid manifest 'models' field: expected an object with model names as keys ` +\n `(e.g., { \"auth-service\": { } }), but got ${Array.isArray(models) ? \"an array\" : `a ${typeof models}`}. ` +\n `This often happens when YAML syntax is incorrect, like writing 'models: auth-service' ` +\n `instead of 'models: { auth-service: {} }' or 'models:\\\\n auth-service: {}'.`,\n };\n }\n\n // Validate that it's a plain object (not a class instance)\n if (Object.getPrototypeOf(models) !== Object.prototype) {\n return {\n valid: false,\n error:\n `Invalid manifest 'models' field: expected a plain object, but got an instance of ${\n (models as any).constructor?.name || \"unknown\"\n }. ` +\n `Please ensure 'models' is a simple YAML object mapping model names to declarations.`,\n };\n }\n\n return { valid: true };\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 cliVersion: manifestYaml.cli_version,\n specVersion: manifestYaml.spec_version || \"0.6.0\",\n created: manifestYaml.created || new Date().toISOString(),\n modified: manifestYaml.updated || new Date().toISOString(),\n };\n\n // Load external model declarations if present\n if (manifestYaml.models) {\n const modelsValidation = Model.validateModelsField(manifestYaml.models);\n if (!modelsValidation.valid) {\n throw new Error(modelsValidation.error);\n }\n manifestData.models = manifestYaml.models;\n }\n\n // Load codebase_path if present\n if (manifestYaml.codebase_path) {\n manifestData.codebase_path = manifestYaml.codebase_path;\n }\n\n const manifest = new Manifest(manifestData);\n\n // Resolve codebaseRoot with priority: options > CLI flag > manifest > farm > default\n let codebaseRoot = projectRoot;\n if (options.codebaseRoot) {\n codebaseRoot = options.codebaseRoot;\n } else {\n const globalCodebasePath = getCodebasePath();\n if (globalCodebasePath) {\n codebaseRoot = path.resolve(globalCodebasePath);\n } else if (manifest.codebase_path) {\n codebaseRoot = path.resolve(projectRoot, manifest.codebase_path);\n } else {\n // Try to auto-resolve from farm manifest if inside a farm\n const farmCodebaseRoot = await Model.resolveFarmCodebaseRoot(projectRoot);\n if (farmCodebaseRoot) {\n codebaseRoot = farmCodebaseRoot;\n }\n }\n }\n\n const model = new Model(projectRoot, manifest, { ...options, codebaseRoot });\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 // Keep the committed relationships before the active changeset's are merged in below,\n // for views that apply a changeset themselves (ChangesetGraph).\n model._baseRelationships = model.relationships.getAll();\n const storage = new StagedChangesetStorage(projectRoot);\n try {\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 } catch (err) {\n // Changeset loading or processing failed \u2014 re-throw with context\n const errorMessage = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Failed to load active changeset '${activeId}': ${errorMessage}`,\n { cause: err }\n );\n }\n }\n } catch (err) {\n // Only ignore ENOENT (.active file doesn't exist - expected for no active changeset)\n const isNotFoundError = (err as any)?.code === \"ENOENT\";\n if (!isNotFoundError) {\n // Re-throw permission/I/O errors and changeset loading errors\n throw err;\n }\n // No active changeset file \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 const yaml = await import(\"yaml\");\n\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\n // Resolve codebaseRoot with priority: options > CLI flag > manifest > default\n let codebaseRoot = rootPath;\n if (options.codebaseRoot) {\n codebaseRoot = options.codebaseRoot;\n } else {\n const globalCodebasePath = getCodebasePath();\n if (globalCodebasePath) {\n codebaseRoot = path.resolve(globalCodebasePath);\n } else if (manifest.codebase_path) {\n codebaseRoot = path.resolve(rootPath, manifest.codebase_path);\n }\n }\n\n const model = new Model(rootPath, manifest, { ...options, codebaseRoot });\n\n await model.saveManifest();\n\n // Initialize relationships.yaml with empty array\n const relationshipsPath = `${rootPath}/documentation-robotics/model/relationships.yaml`;\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([]);\n await writeFile(relationshipsPath, yamlContent);\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 assertBaseModelWritable();\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,qBAAwC;AACjD,SAAS,6BAA6B;AAEtC,SAAS,WAAW,iBAAiB;AACrC,SAAS,qBAAqB;AAC9B,SAAS,WAAW,SAAS,uBAAuB;AACpD,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,+BAA+B;AACxC,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,GAA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I;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;;",
|
|
6
6
|
"names": ["path", "fs", "err", "layerId", "manifestPath", "projectRoot"]
|
|
7
7
|
}
|
|
@@ -1,13 +1,24 @@
|
|
|
1
|
+
import { elementIdentifiers } from "./relationships.js";
|
|
1
2
|
import { StagingAreaManager } from "./staging-area.js";
|
|
2
3
|
import { isValidLayerName } from "./layers.js";
|
|
3
4
|
import { CLIError } from "../utils/errors.js";
|
|
5
|
+
import { ChangesetOnlyError } from "./changeset-only-guard.js";
|
|
4
6
|
import { getErrorMessage } from "../utils/errors.js";
|
|
5
7
|
import { ModelReportOrchestrator } from "../reports/model-report-orchestrator.js";
|
|
6
8
|
import { emitLog, SeverityNumber } from "../telemetry/index.js";
|
|
9
|
+
import { changedFields } from "./changeset-summary.js";
|
|
10
|
+
function foldIntoSnapshot(addAfter, before, after) {
|
|
11
|
+
const folded = { ...addAfter }, b = before ?? {}, a = after ?? {};
|
|
12
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(a)]))
|
|
13
|
+
JSON.stringify(b[key]) !== JSON.stringify(a[key]) && (a[key] === void 0 ? delete folded[key] : folded[key] = a[key]);
|
|
14
|
+
return "source_reference" in a && JSON.stringify(b.source_reference) !== JSON.stringify(a.source_reference) && delete folded.sourceReference, folded;
|
|
15
|
+
}
|
|
7
16
|
class MutationHandler {
|
|
8
17
|
context;
|
|
9
18
|
steps = [];
|
|
10
19
|
stagingManager;
|
|
20
|
+
changedFields = [];
|
|
21
|
+
foldedIntoAdd = !1;
|
|
11
22
|
constructor(model, elementId, layerName) {
|
|
12
23
|
this.context = { model, elementId, layerName }, this.stagingManager = new StagingAreaManager(model.rootPath, model);
|
|
13
24
|
}
|
|
@@ -41,6 +52,30 @@ class MutationHandler {
|
|
|
41
52
|
getStagingManager() {
|
|
42
53
|
return this.stagingManager;
|
|
43
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* The fields the last executeUpdate changed (`attributes.x` for attribute keys), sorted.
|
|
57
|
+
* Empty before an update runs or when it changed nothing.
|
|
58
|
+
*/
|
|
59
|
+
getChangedFields() {
|
|
60
|
+
return this.changedFields;
|
|
61
|
+
}
|
|
62
|
+
/** Whether the last executeUpdate rewrote the changeset's staged add of the element in place. */
|
|
63
|
+
wasFoldedIntoAdd() {
|
|
64
|
+
return this.foldedIntoAdd;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The active changeset's add of this element, when an update should be folded into it: the
|
|
68
|
+
* add is the element's only staged element change (an update staged after it by an earlier
|
|
69
|
+
* build keeps the old append behaviour, so it is not overridden), and the base model does not
|
|
70
|
+
* already hold the element (commit skips such an add; a staged update still applies).
|
|
71
|
+
*/
|
|
72
|
+
async stagedAddToFoldInto(changeset, element) {
|
|
73
|
+
const ids = new Set(elementIdentifiers(element, this.context.elementId)), own = changeset.changes.filter((c) => !c.type.startsWith("relationship-") && ids.has(c.elementId));
|
|
74
|
+
if (own.length !== 1 || own[0].type !== "add" || !own[0].after)
|
|
75
|
+
return null;
|
|
76
|
+
const baseLayer = await this.context.model.getBaseLayer(this.context.layerName);
|
|
77
|
+
return [...ids].some((id) => baseLayer?.getElement(id)) ? null : own[0];
|
|
78
|
+
}
|
|
44
79
|
/**
|
|
45
80
|
* Compute before and after states
|
|
46
81
|
*
|
|
@@ -76,7 +111,20 @@ class MutationHandler {
|
|
|
76
111
|
this.context.element = element, this.context.before = element.toJSON(), this.context.after = { ...this.context.before };
|
|
77
112
|
const activeChangeset = await this.stagingManager.getActive();
|
|
78
113
|
if (activeChangeset && activeChangeset.status === "staged") {
|
|
79
|
-
await mutator(element, this.context.after),
|
|
114
|
+
await mutator(element, this.context.after), this.changedFields = changedFields(this.context.before, this.context.after);
|
|
115
|
+
const add = await this.stagedAddToFoldInto(activeChangeset, element);
|
|
116
|
+
if (add) {
|
|
117
|
+
await this.stagingManager.restage(activeChangeset.id, add.elementId, {
|
|
118
|
+
type: "add",
|
|
119
|
+
elementId: add.elementId,
|
|
120
|
+
layerName: add.layerName,
|
|
121
|
+
...add.before !== void 0 ? { before: add.before } : {},
|
|
122
|
+
after: foldIntoSnapshot(add.after, this.context.before, this.context.after),
|
|
123
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
124
|
+
}), this.foldedIntoAdd = !0;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
await this.stagingManager.stage(activeChangeset.id, {
|
|
80
128
|
type: "update",
|
|
81
129
|
elementId: this.context.elementId,
|
|
82
130
|
layerName: this.context.layerName,
|
|
@@ -93,7 +141,7 @@ class MutationHandler {
|
|
|
93
141
|
*/
|
|
94
142
|
async executeDelete(element) {
|
|
95
143
|
this.context.element = element, this.context.before = element.toJSON(), this.context.after = void 0;
|
|
96
|
-
const activeChangeset = await this.stagingManager.getActive();
|
|
144
|
+
const identifiers = elementIdentifiers(element, this.context.elementId), activeChangeset = await this.stagingManager.getActive();
|
|
97
145
|
if (activeChangeset && activeChangeset.status === "staged") {
|
|
98
146
|
await this.stagingManager.stage(activeChangeset.id, {
|
|
99
147
|
type: "delete",
|
|
@@ -102,13 +150,29 @@ class MutationHandler {
|
|
|
102
150
|
before: this.context.before,
|
|
103
151
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
104
152
|
});
|
|
153
|
+
const ids = new Set(identifiers), alreadyStaged = new Set(activeChangeset.changes.filter((change) => change.type === "relationship-delete").map((change) => change.elementId)), dangling = this.context.model.relationships.getAll().filter((rel) => ids.has(rel.source) || ids.has(rel.target)).filter((rel) => !alreadyStaged.has(`${rel.source}::${rel.predicate}::${rel.target}`));
|
|
154
|
+
for (const rel of dangling)
|
|
155
|
+
alreadyStaged.add(`${rel.source}::${rel.predicate}::${rel.target}`), await this.stagingManager.stage(activeChangeset.id, {
|
|
156
|
+
type: "relationship-delete",
|
|
157
|
+
elementId: `${rel.source}::${rel.predicate}::${rel.target}`,
|
|
158
|
+
layerName: rel.layer,
|
|
159
|
+
before: {
|
|
160
|
+
source: rel.source,
|
|
161
|
+
target: rel.target,
|
|
162
|
+
predicate: rel.predicate,
|
|
163
|
+
layer: rel.layer,
|
|
164
|
+
...rel.targetLayer ? { targetLayer: rel.targetLayer } : {},
|
|
165
|
+
...rel.properties ? { properties: rel.properties } : {}
|
|
166
|
+
},
|
|
167
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
168
|
+
});
|
|
105
169
|
return;
|
|
106
170
|
}
|
|
107
171
|
if (!(await this.context.model.getLayer(this.context.layerName)).deleteElement(element.path || element.id))
|
|
108
172
|
throw new CLIError(`Failed to delete element ${this.context.elementId}`, 1, [
|
|
109
173
|
"Element may have already been deleted"
|
|
110
174
|
]);
|
|
111
|
-
this.context.model.relationships.deleteForElement(
|
|
175
|
+
this.context.model.relationships.deleteForElement(identifiers), await this._persistChanges("delete");
|
|
112
176
|
}
|
|
113
177
|
/**
|
|
114
178
|
* Execute all registered steps and persist
|
|
@@ -138,7 +202,7 @@ class MutationHandler {
|
|
|
138
202
|
async _executeBasePath(mutator, type) {
|
|
139
203
|
if (!this.context.element)
|
|
140
204
|
throw new CLIError("Element not set", 1);
|
|
141
|
-
this.context.before === void 0 && (this.context.before = this.context.element.toJSON()), this.context.after === void 0 && (this.context.after = { ...this.context.before }), await mutator(this.context.element, this.context.after), await this._persistChanges(type);
|
|
205
|
+
this.context.before === void 0 && (this.context.before = this.context.element.toJSON()), this.context.after === void 0 && (this.context.after = { ...this.context.before }), await mutator(this.context.element, this.context.after), this.changedFields = changedFields(this.context.before, this.context.after), await this._persistChanges(type);
|
|
142
206
|
}
|
|
143
207
|
/**
|
|
144
208
|
* Persist changes to disk
|
|
@@ -152,7 +216,7 @@ class MutationHandler {
|
|
|
152
216
|
try {
|
|
153
217
|
await this.context.model.saveLayer(this.context.layerName), type === "delete" && this.context.model.relationships.isDirty() && await this.context.model.saveRelationships(), await this.context.model.saveManifest();
|
|
154
218
|
} catch (error) {
|
|
155
|
-
throw new CLIError(`Failed to persist changes: ${getErrorMessage(error)}`, 1, ["Check that the model directory is writable", "Verify the model is not corrupted"]);
|
|
219
|
+
throw error instanceof ChangesetOnlyError ? error : new CLIError(`Failed to persist changes: ${getErrorMessage(error)}`, 1, ["Check that the model directory is writable", "Verify the model is not corrupted"]);
|
|
156
220
|
}
|
|
157
221
|
try {
|
|
158
222
|
const orchestrator = new ModelReportOrchestrator(this.context.model, this.context.model.rootPath);
|
|
@@ -174,6 +238,7 @@ class MutationHandler {
|
|
|
174
238
|
}
|
|
175
239
|
}
|
|
176
240
|
export {
|
|
177
|
-
MutationHandler
|
|
241
|
+
MutationHandler,
|
|
242
|
+
foldIntoSnapshot
|
|
178
243
|
};
|
|
179
244
|
//# sourceMappingURL=mutation-handler.js.map
|