@documentation-robotics/cli 0.1.12 → 0.2.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 +39 -1
- package/dist/analyzers/verify-engine.js +22 -19
- package/dist/analyzers/verify-engine.js.map +2 -2
- package/dist/cli.js +101 -27
- package/dist/cli.js.map +3 -3
- package/dist/coding-agents/agents/claude-code.js +3 -1
- package/dist/coding-agents/agents/claude-code.js.map +2 -2
- package/dist/coding-agents/claude-code-client.js +2 -1
- package/dist/coding-agents/claude-code-client.js.map +2 -2
- package/dist/coding-agents/copilot-client.js +17 -12
- package/dist/coding-agents/copilot-client.js.map +2 -2
- package/dist/coding-agents/default-permissions.js +122 -0
- package/dist/coding-agents/default-permissions.js.map +7 -0
- package/dist/commands/add.js +10 -6
- package/dist/commands/add.js.map +2 -2
- package/dist/commands/analyzer.js +18 -10
- package/dist/commands/analyzer.js.map +2 -2
- package/dist/commands/audit.js +6 -6
- package/dist/commands/audit.js.map +2 -2
- package/dist/commands/changeset.js +238 -145
- package/dist/commands/changeset.js.map +2 -2
- package/dist/commands/delete.js +45 -18
- package/dist/commands/delete.js.map +3 -3
- package/dist/commands/element.js +3 -2
- package/dist/commands/element.js.map +2 -2
- package/dist/commands/farm.js +657 -0
- package/dist/commands/farm.js.map +7 -0
- package/dist/commands/init.js +11 -1
- package/dist/commands/init.js.map +2 -2
- package/dist/commands/mcp.js +107 -0
- package/dist/commands/mcp.js.map +7 -0
- package/dist/commands/relationship.js +53 -30
- package/dist/commands/relationship.js.map +2 -2
- package/dist/commands/reports.js +1 -1
- package/dist/commands/reports.js.map +2 -2
- package/dist/commands/update.js +19 -6
- package/dist/commands/update.js.map +2 -2
- package/dist/commands/validate.js +41 -3
- package/dist/commands/validate.js.map +2 -2
- package/dist/commands/version.js +2 -2
- package/dist/commands/version.js.map +2 -2
- package/dist/config.js +83 -0
- package/dist/config.js.map +7 -0
- package/dist/core/annotation-store.js +138 -0
- package/dist/core/annotation-store.js.map +7 -0
- package/dist/core/farm-manifest.js +134 -0
- package/dist/core/farm-manifest.js.map +7 -0
- package/dist/core/farm-sync-engine.js +346 -0
- package/dist/core/farm-sync-engine.js.map +7 -0
- package/dist/core/farm-sync-state.js +159 -0
- package/dist/core/farm-sync-state.js.map +7 -0
- package/dist/core/manifest.js +6 -3
- package/dist/core/manifest.js.map +2 -2
- package/dist/core/migration-registry.js +55 -1
- package/dist/core/migration-registry.js.map +2 -2
- package/dist/core/model.js +177 -16
- package/dist/core/model.js.map +3 -3
- package/dist/core/virtual-projection.js +1 -0
- package/dist/core/virtual-projection.js.map +2 -2
- package/dist/generated/node-types.js +1 -1
- package/dist/generated/node-types.js.map +2 -2
- package/dist/generated/relationship-index.js +45 -9
- package/dist/generated/relationship-index.js.map +2 -2
- package/dist/integrations/claude_code/docs/MCP_SERVER.md +55 -0
- package/dist/integrations/claude_code/docs/README.md +4 -0
- package/dist/mcp/api-key-manager.js +98 -0
- package/dist/mcp/api-key-manager.js.map +7 -0
- package/dist/mcp/http-transport.js +176 -0
- package/dist/mcp/http-transport.js.map +7 -0
- package/dist/mcp/resource-registry.js +97 -0
- package/dist/mcp/resource-registry.js.map +7 -0
- package/dist/mcp/tool-registry.js +44 -0
- package/dist/mcp/tool-registry.js.map +7 -0
- package/dist/mcp/tools/annotation-create.js +39 -0
- package/dist/mcp/tools/annotation-create.js.map +7 -0
- package/dist/mcp/tools/annotation-delete.js +29 -0
- package/dist/mcp/tools/annotation-delete.js.map +7 -0
- package/dist/mcp/tools/annotation-get.js +29 -0
- package/dist/mcp/tools/annotation-get.js.map +7 -0
- package/dist/mcp/tools/annotation-list.js +24 -0
- package/dist/mcp/tools/annotation-list.js.map +7 -0
- package/dist/mcp/tools/annotation-reply.js +34 -0
- package/dist/mcp/tools/annotation-reply.js.map +7 -0
- package/dist/mcp/tools/annotation-shared.js +10 -0
- package/dist/mcp/tools/annotation-shared.js.map +7 -0
- package/dist/mcp/tools/annotation-update.js +39 -0
- package/dist/mcp/tools/annotation-update.js.map +7 -0
- package/dist/mcp/tools/changeset-list.js +33 -0
- package/dist/mcp/tools/changeset-list.js.map +7 -0
- package/dist/mcp/tools/changeset-show.js +39 -0
- package/dist/mcp/tools/changeset-show.js.map +7 -0
- package/dist/mcp/tools/chat-launch.js +50 -0
- package/dist/mcp/tools/chat-launch.js.map +7 -0
- package/dist/mcp/tools/chat-status.js +26 -0
- package/dist/mcp/tools/chat-status.js.map +7 -0
- package/dist/mcp/tools/index.js +47 -0
- package/dist/mcp/tools/index.js.map +7 -0
- package/dist/mcp/tools/model-add.js +106 -0
- package/dist/mcp/tools/model-add.js.map +7 -0
- package/dist/mcp/tools/model-delete.js +99 -0
- package/dist/mcp/tools/model-delete.js.map +7 -0
- package/dist/mcp/tools/model-export.js +72 -0
- package/dist/mcp/tools/model-export.js.map +7 -0
- package/dist/mcp/tools/model-info.js +51 -0
- package/dist/mcp/tools/model-info.js.map +7 -0
- package/dist/mcp/tools/model-list.js +53 -0
- package/dist/mcp/tools/model-list.js.map +7 -0
- package/dist/mcp/tools/model-reload.js +34 -0
- package/dist/mcp/tools/model-reload.js.map +7 -0
- package/dist/mcp/tools/model-search.js +88 -0
- package/dist/mcp/tools/model-search.js.map +7 -0
- package/dist/mcp/tools/model-show.js +41 -0
- package/dist/mcp/tools/model-show.js.map +7 -0
- package/dist/mcp/tools/model-stats.js +22 -0
- package/dist/mcp/tools/model-stats.js.map +7 -0
- package/dist/mcp/tools/model-trace.js +55 -0
- package/dist/mcp/tools/model-trace.js.map +7 -0
- package/dist/mcp/tools/model-update.js +105 -0
- package/dist/mcp/tools/model-update.js.map +7 -0
- package/dist/mcp/tools/model-validate.js +78 -0
- package/dist/mcp/tools/model-validate.js.map +7 -0
- package/dist/mcp/tools/shared.js +103 -0
- package/dist/mcp/tools/shared.js.map +7 -0
- package/dist/reports/model-layer-report-generator.js +5 -3
- package/dist/reports/model-layer-report-generator.js.map +2 -2
- package/dist/reports/model-readme-generator.js +116 -0
- package/dist/reports/model-readme-generator.js.map +7 -0
- package/dist/reports/model-report-data.js +37 -1
- package/dist/reports/model-report-data.js.map +2 -2
- package/dist/reports/model-report-orchestrator.js +29 -6
- package/dist/reports/model-report-orchestrator.js.map +2 -2
- package/dist/reports/model-report-utils.js +9 -0
- package/dist/reports/model-report-utils.js.map +7 -0
- package/dist/schemas/bundled/analyzers/cbm.json +2 -2
- package/dist/schemas/bundled/analyzers/manifest.json +2 -2
- package/dist/schemas/bundled/api.json +1 -1
- package/dist/schemas/bundled/apm.json +1 -1
- package/dist/schemas/bundled/application.json +12 -1
- package/dist/schemas/bundled/base.json +1 -1
- package/dist/schemas/bundled/business.json +1 -1
- package/dist/schemas/bundled/data-model.json +38 -2
- package/dist/schemas/bundled/data-store.json +1 -1
- package/dist/schemas/bundled/manifest.json +4 -4
- package/dist/schemas/bundled/motivation.json +1 -1
- package/dist/schemas/bundled/navigation.json +1 -1
- package/dist/schemas/bundled/product.json +1 -1
- package/dist/schemas/bundled/security.json +1 -1
- package/dist/schemas/bundled/technology.json +1 -1
- package/dist/schemas/bundled/testing.json +1 -1
- package/dist/schemas/bundled/ux.json +1 -1
- package/dist/server/server.js +45 -7
- package/dist/server/server.js.map +2 -2
- package/dist/telemetry/config.js +2 -40
- package/dist/telemetry/config.js.map +2 -2
- package/dist/telemetry/index.js +1 -1
- package/dist/types/index.js.map +2 -2
- package/dist/utils/ansi-suppressor.js +25 -0
- package/dist/utils/ansi-suppressor.js.map +7 -0
- package/dist/utils/color-utils.js +34 -0
- package/dist/utils/color-utils.js.map +7 -0
- package/dist/utils/element-reference-shape.js +15 -1
- package/dist/utils/element-reference-shape.js.map +3 -3
- package/dist/utils/errors.js +69 -10
- package/dist/utils/errors.js.map +2 -2
- package/dist/utils/globals.js +17 -1
- package/dist/utils/globals.js.map +2 -2
- package/dist/utils/project-paths.js +24 -2
- package/dist/utils/project-paths.js.map +2 -2
- package/dist/utils/reference-path-parser.js +49 -0
- package/dist/utils/reference-path-parser.js.map +7 -0
- package/dist/utils/source-reference.js +5 -0
- package/dist/utils/source-reference.js.map +2 -2
- package/dist/utils/spec-version.js +10 -2
- package/dist/utils/spec-version.js.map +2 -2
- package/dist/validators/composed-reference-validator.js +262 -0
- package/dist/validators/composed-reference-validator.js.map +7 -0
- package/dist/validators/reference-validator.js +59 -8
- package/dist/validators/reference-validator.js.map +3 -3
- package/dist/validators/relationship-schema-validator.js +30 -2
- package/dist/validators/relationship-schema-validator.js.map +3 -3
- package/dist/viewer/README.md +6 -6
- package/dist/viewer/assets/main-B7AOQXXX.js +81 -0
- package/dist/viewer/assets/main-vdrFrG7q.css +1 -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 +6 -3
- package/dist/viewer/assets/main-BRPZyc36.css +0 -1
- package/dist/viewer/assets/main-BrpLargo.js +0 -81
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/commands/farm.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Farm Commands - Manage model farms and project registration\n */\n\nimport ansis from \"ansis\";\nimport { Command } from \"commander\";\nimport path from \"path\";\nimport { rm } from \"fs/promises\";\nimport { FarmManifest } from \"../core/farm-manifest.js\";\nimport { findFarmRoot } from \"../utils/project-paths.js\";\nimport { fileExists } from \"../utils/file-io.js\";\nimport { execSync, execFileSync } from \"child_process\";\nimport * as prompts from \"@clack/prompts\";\nimport { getErrorMessage, handleSuccess, handleInfo } from \"../utils/errors.js\";\nimport { isJson } from \"../utils/globals.js\";\nimport { isTelemetryEnabled, startSpan, endSpan } from \"../telemetry/index.js\";\nimport { Model } from \"../core/model.js\";\nimport { ComposedReferenceValidator } from \"../validators/composed-reference-validator.js\";\nimport { ValidationFormatter } from \"../validators/validation-formatter.js\";\nimport { FarmSyncEngine } from \"../core/farm-sync-engine.js\";\n\ninterface FarmSyncResultEntry {\n project: string;\n status: \"success\" | \"error\" | \"partial\";\n change_count?: number;\n changeset_id?: string;\n files_changed?: { added: string[]; modified: string[]; deleted: string[] };\n ambiguities?: number;\n commits_before?: string;\n commits_after?: string;\n auto_committed?: boolean;\n committed_changes?: number;\n commit_error?: string;\n message?: string;\n}\n\n/**\n * Check if a directory is a git repository.\n * Returns true if git rev-parse succeeds, false if the directory is not a git repo\n * or if unexpected errors occur (which are logged in DEBUG mode only).\n * Does not re-throw errors; unexpected git errors are logged diagnostically but do not\n * prevent the operation from proceeding.\n */\nfunction isGitRepository(cwd: string): boolean {\n try {\n execSync(\"git rev-parse --git-dir\", { cwd, stdio: \"pipe\" });\n return true;\n } catch (error) {\n const errorMsg = getErrorMessage(error);\n\n // Only return false for the \"not a git repository\" case\n // Pattern: \"fatal: not a git repository\" (case insensitive check for safety)\n if (errorMsg.toLowerCase().includes(\"not a git repository\")) {\n return false;\n }\n\n // For unexpected errors (missing git binary, permission denied, etc), log diagnostically\n // but return false to preserve existing behavior of not blocking operations\n if (process.env.DEBUG) {\n console.warn(`Warning: Unexpected error checking git repository at ${cwd}: ${errorMsg}`);\n }\n return false;\n }\n}\n\n/**\n * Initialize a new farm\n */\nexport async function farmInitCommand(options: {\n name?: string;\n description?: string;\n format?: string;\n platformView?: boolean;\n}): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.init\") : null;\n\n try {\n const farmPath = process.cwd();\n const farmYamlPath = path.join(farmPath, \"farm.yaml\");\n\n // Check if farm.yaml already exists\n const useJson = options.format === \"json\" || isJson();\n if (await fileExists(farmYamlPath)) {\n const message = \"Farm already initialized in this directory\";\n if (useJson) {\n console.log(JSON.stringify({ status: \"error\", code: 1, message }));\n } else {\n console.error(ansis.red(`Error: ${message}`));\n }\n if (span) endSpan(span);\n process.exit(1);\n }\n\n // Get farm name\n let farmName = options.name;\n if (!farmName) {\n const isInteractive = process.stdin.isTTY;\n if (isInteractive) {\n const result = await prompts.text({\n message: \"Farm name\",\n placeholder: \"My Architecture Farm\",\n });\n\n if (typeof result === \"string\") {\n farmName = result;\n }\n }\n }\n\n if (!farmName) {\n farmName = \"Architecture Farm\";\n }\n\n // Create manifest with platform_view support if requested\n const manifest = FarmManifest.create(farmName, {\n platform_view: options.platformView || false,\n });\n await manifest.save(farmYamlPath);\n\n // Initialize farm-level git repository\n try {\n execSync(\"git init\", { cwd: farmPath, stdio: useJson ? \"pipe\" : \"inherit\" });\n execSync(\"git config user.email 'dr-farm@localhost'\", {\n cwd: farmPath,\n stdio: \"pipe\",\n });\n execSync(\"git config user.name 'DR Farm'\", {\n cwd: farmPath,\n stdio: \"pipe\",\n });\n\n // Add farm.yaml and commit\n execSync(\"git add farm.yaml\", { cwd: farmPath, stdio: \"pipe\" });\n execSync(\"git commit -m 'Initialize farm manifest'\", {\n cwd: farmPath,\n stdio: useJson ? \"pipe\" : \"inherit\",\n });\n } catch (gitError) {\n throw new Error(\n `Failed to initialize farm git repository: ${getErrorMessage(gitError)}`\n );\n }\n\n if (useJson) {\n console.log(JSON.stringify({ status: \"ok\", farmPath, farmName, platform_view: options.platformView || false }));\n } else {\n const platformViewNote = options.platformView ? \" (platform-view enabled)\" : \"\";\n handleSuccess(\n `Farm initialized: ${ansis.bold(farmName)}${platformViewNote}\\n Location: ${farmPath}`\n );\n }\n\n if (span) endSpan(span);\n } catch (error) {\n const useJsonError = options.format === \"json\" || isJson();\n if (useJsonError) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 1,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(1);\n }\n}\n\n/**\n * Add a project to the farm\n */\nexport async function farmAddCommand(\n name: string,\n options: {\n remote?: string;\n codebase?: string;\n format?: string;\n }\n): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.add\", { \"project.name\": name }) : null;\n const useJson = options.format === \"json\" || isJson();\n\n try {\n // Find farm root\n const farmRoot = await findFarmRoot();\n if (!farmRoot) {\n throw new Error(\"Not in a farm directory. Run 'dr farm init' first.\");\n }\n\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n const manifest = await FarmManifest.load(farmYamlPath);\n\n // Check if project already exists\n if (manifest.getProject(name)) {\n throw new Error(`Project '${name}' already exists in this farm`);\n }\n\n // Determine codebase path\n let codebasePath = options.codebase || name;\n\n // Clone if remote URL provided\n if (options.remote) {\n const codebaseFullPath = path.join(farmRoot, codebasePath);\n if (await fileExists(codebaseFullPath)) {\n throw new Error(`Codebase directory '${codebasePath}' already exists`);\n }\n\n if (!useJson) {\n handleInfo(`Cloning ${options.remote} to ${codebasePath}...`);\n }\n\n try {\n execFileSync(\"git\", [\"clone\", options.remote, codebaseFullPath], {\n stdio: useJson ? \"pipe\" : \"inherit\",\n });\n } catch (error) {\n throw new Error(`Failed to clone repository: ${getErrorMessage(error)}`);\n }\n }\n\n // Create and scaffold model folder\n const modelFolder = `${name}-model`;\n const modelFullPath = path.join(farmRoot, modelFolder);\n\n if (!(await fileExists(modelFullPath))) {\n // Initialize model with manifest and layer structure\n await Model.init(\n modelFullPath,\n {\n name: name,\n version: \"0.1.0\",\n description: undefined,\n author: undefined,\n specVersion: (await import(\"../utils/spec-version.js\")).getCliBundledSpecVersion(),\n created: new Date().toISOString(),\n },\n { lazyLoad: false }\n );\n\n if (!useJson) {\n handleInfo(`Created and initialized model folder: ${modelFolder}`);\n }\n }\n\n // Add project to manifest\n manifest.addProject(name, {\n name,\n source: codebasePath,\n model: modelFolder,\n remote: options.remote,\n });\n\n await manifest.save(farmYamlPath);\n\n // Commit farm.yaml changes to farm-level git repository if git is available\n // Check for git repo first\n const gitRepoExists = isGitRepository(farmRoot);\n\n // If git repo exists, proceed with commit (handle commit errors independently)\n if (gitRepoExists) {\n try {\n execSync(\"git add farm.yaml\", { cwd: farmRoot, stdio: \"pipe\" });\n execFileSync(\"git\", [\"commit\", \"-m\", `Add project: ${name}`], {\n cwd: farmRoot,\n stdio: useJson ? \"pipe\" : \"inherit\",\n });\n } catch (commitError) {\n const errorMsg = getErrorMessage(commitError);\n // If nothing to commit, that's fine\n if (!errorMsg.includes(\"nothing to commit\")) {\n throw new Error(`Failed to commit farm changes: ${errorMsg}`);\n }\n }\n }\n\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"ok\",\n project: name,\n source: codebasePath,\n model: modelFolder,\n })\n );\n } else {\n handleSuccess(\n `Project added to farm: ${ansis.bold(name)}\\n Codebase: ${codebasePath}\\n Model: ${modelFolder}`\n );\n }\n\n if (span) endSpan(span);\n } catch (error) {\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 1,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(1);\n }\n}\n\n/**\n * Remove a project from the farm\n */\nexport async function farmRemoveCommand(\n name: string,\n options: {\n deleteModel?: boolean;\n format?: string;\n }\n): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.remove\", { \"project.name\": name }) : null;\n const useJson = options.format === \"json\" || isJson();\n\n try {\n // Find farm root\n const farmRoot = await findFarmRoot();\n if (!farmRoot) {\n throw new Error(\"Not in a farm directory.\");\n }\n\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n const manifest = await FarmManifest.load(farmYamlPath);\n\n // Check if project exists\n const project = manifest.getProject(name);\n if (!project) {\n throw new Error(`Project '${name}' not found in farm`);\n }\n\n // Remove model folder if requested\n if (options.deleteModel) {\n const modelFullPath = path.resolve(path.join(farmRoot, project.model));\n const farmRootResolved = path.resolve(farmRoot);\n\n // Validate that the resolved path is strictly within the farm root to prevent path traversal\n if (!modelFullPath.startsWith(farmRootResolved + path.sep)) {\n throw new Error(\n `Invalid model path: would escape farm root. Path: ${project.model}`\n );\n }\n\n if (await fileExists(modelFullPath)) {\n try {\n await rm(modelFullPath, { recursive: true, force: false });\n if (!useJson) {\n handleInfo(`Deleted model folder: ${project.model}`);\n }\n } catch (error) {\n throw new Error(`Failed to delete model folder: ${getErrorMessage(error)}`);\n }\n }\n }\n\n // Remove project from manifest\n manifest.removeProject(name);\n await manifest.save(farmYamlPath);\n\n // Commit farm.yaml changes to farm-level git repository if git is available\n // Check for git repo first\n const gitRepoExists = isGitRepository(farmRoot);\n\n // If git repo exists, proceed with commit (handle commit errors independently)\n if (gitRepoExists) {\n try {\n execSync(\"git add farm.yaml\", { cwd: farmRoot, stdio: \"pipe\" });\n execFileSync(\"git\", [\"commit\", \"-m\", `Remove project: ${name}`], {\n cwd: farmRoot,\n stdio: useJson ? \"pipe\" : \"inherit\",\n });\n } catch (commitError) {\n const errorMsg = getErrorMessage(commitError);\n // If nothing to commit, that's fine\n if (!errorMsg.includes(\"nothing to commit\")) {\n throw new Error(`Failed to commit farm changes: ${errorMsg}`);\n }\n }\n }\n\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"ok\",\n project: name,\n modelDeleted: options.deleteModel ?? false,\n })\n );\n } else {\n handleSuccess(`Project removed from farm: ${ansis.bold(name)}`);\n }\n\n if (span) endSpan(span);\n } catch (error) {\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 1,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(1);\n }\n}\n\n/**\n * Show farm status\n */\nexport async function farmStatusCommand(options: {\n format?: string;\n}): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.status\") : null;\n\n try {\n // Find farm root\n const farmRoot = await findFarmRoot();\n if (!farmRoot) {\n throw new Error(\"Not in a farm directory.\");\n }\n\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n const manifest = await FarmManifest.load(farmYamlPath);\n\n const projects = manifest.getAllProjects();\n const engine = new FarmSyncEngine(farmRoot);\n\n // Compute pending changes using lightweight commit comparison\n const projectsWithStatus = await Promise.all(\n projects.map(async (p) => {\n try {\n const syncStatePath = path.join(farmRoot, p.model, \".farm-sync.yaml\");\n const syncState = await (await import(\"../core/farm-sync-state.js\")).FarmSyncState.loadOrCreate(\n syncStatePath,\n p.name\n );\n\n // Use lightweight commit comparison instead of full diff\n const currentCommit = await engine.getCurrentCommit(p.source);\n const lastSyncCommit = syncState.lastSyncCommit;\n const hasPendingChanges = !!(lastSyncCommit && lastSyncCommit !== currentCommit);\n\n return {\n name: p.name,\n source: p.source,\n model: p.model,\n remote: p.remote,\n last_sync_commit: lastSyncCommit,\n current_commit: currentCommit,\n has_pending_changes: hasPendingChanges,\n };\n } catch (error) {\n // If sync state doesn't exist yet, that's expected - treat as no sync yet\n // For unexpected errors (YAML parse, git permission, etc), always log them\n const errorMsg = getErrorMessage(error);\n if (\n !errorMsg.includes(\"not found\") &&\n !errorMsg.includes(\"does not exist\") &&\n !errorMsg.includes(\"ENOENT\")\n ) {\n // Unexpected error - always log it to surface issues to users\n console.error(`Warning: Error reading sync state for ${p.name}: ${errorMsg}`);\n }\n return {\n name: p.name,\n source: p.source,\n model: p.model,\n remote: p.remote,\n last_sync_commit: undefined,\n current_commit: undefined,\n has_pending_changes: false,\n };\n }\n })\n );\n\n const useJson = options.format === \"json\" || isJson();\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"ok\",\n farm: {\n name: manifest.name,\n path: farmRoot,\n created: manifest.created,\n modified: manifest.modified,\n platform_view: manifest.platform_view,\n },\n projects: projectsWithStatus,\n project_count: projects.length,\n })\n );\n } else {\n console.log(ansis.bold(`Farm: ${manifest.name}`));\n console.log(`Location: ${farmRoot}`);\n if (manifest.platform_view) {\n console.log(`Platform-View: ${ansis.green(\"enabled\")}`);\n }\n console.log(`Projects: ${projects.length}\\n`);\n\n if (projects.length === 0) {\n console.log(ansis.dim(\"No projects registered yet.\"));\n } else {\n projectsWithStatus.forEach((project) => {\n console.log(` ${ansis.cyan(project.name)}`);\n console.log(` Codebase: ${project.source}`);\n console.log(` Model: ${project.model}`);\n if (project.remote) {\n console.log(` Remote: ${project.remote}`);\n }\n if (project.has_pending_changes) {\n console.log(` Status: ${ansis.yellow(\"\u26A0 Pending changes\")}`);\n } else if (project.last_sync_commit) {\n console.log(` Status: ${ansis.green(\"\u2713 Up to date\")}`);\n } else {\n console.log(` Status: ${ansis.dim(\"Not synced yet\")}`);\n }\n });\n }\n }\n\n if (span) endSpan(span);\n } catch (error) {\n const useJsonError = options.format === \"json\" || isJson();\n if (useJsonError) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 2,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(2);\n }\n}\n\n/**\n * Validate a farm project or all projects using composed scope\n */\nexport async function farmValidateCommand(options: {\n project?: string;\n verbose?: boolean;\n quiet?: boolean;\n output?: string;\n format?: string;\n}): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.validate\") : null;\n\n try {\n // Find farm root\n const farmRoot = await findFarmRoot();\n if (!farmRoot) {\n throw new Error(\"Not in a farm directory. Run 'dr farm init' first.\");\n }\n\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n const farmManifest = await FarmManifest.load(farmYamlPath);\n const useJson = options.format === \"json\" || isJson();\n\n // Determine which projects to validate\n let projectsToValidate = farmManifest.getAllProjects();\n let isPlatformViewValidation = false;\n\n if (options.project) {\n const project = farmManifest.getProject(options.project);\n if (!project) {\n throw new Error(`Project '${options.project}' not found in farm`);\n }\n projectsToValidate = [project];\n\n // Check if this is a platform-view project validation\n if (farmManifest.isPlatformViewEnabled() && options.project === \"platform-view\") {\n isPlatformViewValidation = true;\n } else if (options.project === \"platform-view\" && !farmManifest.isPlatformViewEnabled()) {\n // Warn if platform-view project is being validated but platform-view is not enabled\n if (!useJson && !options.quiet) {\n handleInfo(\n `Note: Validating platform-view project, but platform-view is not enabled on this farm`\n );\n }\n }\n }\n\n if (projectsToValidate.length === 0) {\n throw new Error(\"No projects found in farm\");\n }\n\n // Create composed validator from farm\n // This automatically resolves model-path overrides for all projects in the farm\n const composedValidator = await ComposedReferenceValidator.fromFarm(farmRoot);\n if (useJson) {\n console.log(JSON.stringify({ status: \"validating\", projects: projectsToValidate.length, platform_view: isPlatformViewValidation }));\n } else if (!options.quiet) {\n if (options.project) {\n const platformViewNote = isPlatformViewValidation ? \" (platform-view aggregation)\" : \"\";\n handleInfo(`Validating project '${options.project}'${platformViewNote} with farm-aware references...`);\n } else {\n handleInfo(`Validating ${projectsToValidate.length} farm project(s) with farm-aware references...`);\n }\n }\n\n const allResults = [];\n const reportData = [];\n\n // Validate each project\n for (const project of projectsToValidate) {\n const modelPath = path.join(farmRoot, project.model);\n\n // Check if model folder exists\n if (!(await fileExists(modelPath))) {\n const error = `Model folder not found for project '${project.name}' at ${modelPath}`;\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 2,\n project: project.name,\n message: error,\n })\n );\n } else {\n console.error(ansis.red(`Error: ${error}`));\n }\n if (span) endSpan(span);\n process.exit(2);\n }\n\n // Load the model using the safer startPath parameter\n // For detached models, check if manifest.yaml exists directly in the model folder.\n // If so, pass it directly to Model.load().\n let drModelPath = modelPath;\n const manifestPath = path.join(modelPath, \"manifest.yaml\");\n if (await fileExists(manifestPath)) {\n // Point directly to the manifest.yaml file\n drModelPath = manifestPath;\n }\n\n const model = await Model.load(drModelPath);\n\n let platformViewInfo: {\n declared_models: string[];\n missing_models: string[];\n } | undefined;\n\n // For platform-view projects, validate that all declared external models are resolvable\n if (isPlatformViewValidation) {\n const declaredModels = model.manifest.models || {};\n const declaredModelNames = Object.keys(declaredModels);\n\n platformViewInfo = {\n declared_models: declaredModelNames,\n missing_models: [],\n };\n\n if (declaredModelNames.length === 0) {\n if (!useJson && !options.quiet) {\n handleInfo(\n ` Platform-view project has no declared external models`\n );\n }\n } else {\n if (!useJson && !options.quiet) {\n handleInfo(\n ` Platform-view is declaring external models: ${declaredModelNames.join(\", \")}`\n );\n }\n\n // Verify all declared models are available in the farm\n const missingModels: string[] = [];\n for (const declaredModelName of declaredModelNames) {\n const farmProject = farmManifest.getProject(declaredModelName);\n if (!farmProject) {\n missingModels.push(declaredModelName);\n }\n }\n\n platformViewInfo.missing_models = missingModels;\n\n if (missingModels.length > 0) {\n if (!useJson) {\n console.error(\n ansis.yellow(\n ` \u26A0 Warning: The following declared external models are not registered in the farm: ${missingModels.join(\", \")}`\n )\n );\n }\n }\n }\n }\n\n // Validate using composed reference validator\n const result = await composedValidator.validateModel(model);\n\n allResults.push({ project: project.name, result });\n\n // Format and display validation output\n const formatted = ValidationFormatter.format(result, model, {\n verbose: options.verbose,\n quiet: options.quiet,\n });\n\n // Collect report data for output file\n const reportItem: any = {\n project: project.name,\n valid: result.isValid(),\n errors: result.errors.map((e) => ({\n message: e.message,\n layer: e.layer,\n elementId: e.elementId,\n location: e.location,\n })),\n warnings: result.warnings.map((w) => ({\n message: w.message,\n layer: w.layer,\n elementId: w.elementId,\n location: w.location,\n })),\n formatted,\n };\n\n if (platformViewInfo) {\n reportItem.platform_view_info = platformViewInfo;\n }\n\n reportData.push(reportItem);\n\n if (!options.quiet) {\n console.log(ansis.bold(`\\nProject: ${project.name}`));\n console.log(formatted);\n }\n\n if (!result.isValid()) {\n if (options.project) {\n // Single project validation failed\n throw new Error(`Validation failed for project '${project.name}'`);\n }\n // Multi-project validation: track but continue\n }\n }\n\n // Check if all validations passed\n const allValid = allResults.every((r) => r.result.isValid());\n\n // Write output file if requested\n if (options.output) {\n const outputExt = path.extname(options.output).toLowerCase();\n\n if (outputExt === \".json\") {\n // Write JSON report\n const jsonReport = {\n timestamp: new Date().toISOString(),\n farm_root: farmRoot,\n all_valid: allValid,\n projects: reportData.map((r) => {\n const projectData: any = {\n project: r.project,\n valid: r.valid,\n errors: r.errors,\n warnings: r.warnings,\n };\n if (r.platform_view_info) {\n projectData.platform_view_info = r.platform_view_info;\n }\n return projectData;\n }),\n };\n await (await import(\"fs/promises\")).writeFile(\n options.output,\n JSON.stringify(jsonReport, null, 2),\n \"utf-8\"\n );\n } else if (outputExt === \".md\") {\n // Write Markdown report\n let mdContent = `# Farm Validation Report\\n\\n`;\n mdContent += `**Date**: ${new Date().toISOString()}\\n`;\n mdContent += `**Farm Root**: ${farmRoot}\\n`;\n mdContent += `**Overall Status**: ${allValid ? \"\u2705 Valid\" : \"\u274C Invalid\"}\\n\\n`;\n\n mdContent += `## Projects\\n\\n`;\n for (const r of reportData) {\n mdContent += `### ${r.project}\\n\\n`;\n mdContent += `**Status**: ${r.valid ? \"\u2705 Valid\" : \"\u274C Invalid\"}\\n\\n`;\n\n if (r.errors.length > 0) {\n mdContent += `#### Errors (${r.errors.length})\\n\\n`;\n for (const err of r.errors) {\n mdContent += `- ${err.message}\\n`;\n }\n mdContent += \"\\n\";\n }\n\n if (r.warnings.length > 0) {\n mdContent += `#### Warnings (${r.warnings.length})\\n\\n`;\n for (const warn of r.warnings) {\n mdContent += `- ${warn.message}\\n`;\n }\n mdContent += \"\\n\";\n }\n }\n\n await (await import(\"fs/promises\")).writeFile(options.output, mdContent, \"utf-8\");\n } else {\n throw new Error(`Unsupported output format: ${outputExt}. Use .json or .md`);\n }\n\n if (!options.quiet) {\n handleInfo(`Report written to ${options.output}`);\n }\n }\n\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"ok\",\n projects: allResults.map((r) => ({\n name: r.project,\n valid: r.result.isValid(),\n errors: r.result.errors.length,\n warnings: r.result.warnings.length,\n })),\n all_valid: allValid,\n output: options.output ? path.resolve(options.output) : undefined,\n })\n );\n }\n\n if (!allValid) {\n if (span) endSpan(span);\n process.exit(1);\n }\n\n if (!options.quiet) {\n handleSuccess(\n options.project\n ? `Project '${options.project}' validated successfully`\n : `All farm projects validated successfully`\n );\n }\n\n if (span) endSpan(span);\n } catch (error) {\n const useJson = options.format === \"json\" || isJson();\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 2,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(2);\n }\n}\n\n/**\n * Pull latest changes from remote for farm projects\n */\nexport async function farmPullCommand(options: {\n project?: string;\n verbose?: boolean;\n format?: string;\n}): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.pull\") : null;\n\n try {\n // Find farm root\n const farmRoot = await findFarmRoot();\n if (!farmRoot) {\n throw new Error(\"Not in a farm directory. Run 'dr farm init' first.\");\n }\n\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n const manifest = await FarmManifest.load(farmYamlPath);\n\n // Determine which projects to pull\n let projectsToPull = manifest.getAllProjects();\n if (options.project) {\n const project = manifest.getProject(options.project);\n if (!project) {\n throw new Error(`Project '${options.project}' not found in farm`);\n }\n projectsToPull = [project];\n }\n\n if (projectsToPull.length === 0) {\n throw new Error(\"No projects found in farm\");\n }\n\n const useJson = options.format === \"json\" || isJson();\n if (!useJson && !options.verbose) {\n handleInfo(`Pulling ${projectsToPull.length} project(s)...`);\n }\n\n // Create sync engine (model not needed for pull-only operations)\n const engine = new FarmSyncEngine(farmRoot);\n\n const results = [];\n\n // Pull each project\n for (const project of projectsToPull) {\n try {\n const commit = await engine.pullCodebase(project.source);\n\n results.push({\n project: project.name,\n status: \"success\",\n commit,\n });\n\n if (options.verbose && !useJson) {\n handleInfo(` \u2713 ${project.name}: ${commit.substring(0, 8)}`);\n }\n } catch (error) {\n results.push({\n project: project.name,\n status: \"error\",\n message: getErrorMessage(error),\n });\n\n if (!useJson) {\n console.error(ansis.red(` \u2717 ${project.name}: ${getErrorMessage(error)}`));\n }\n }\n }\n\n const allSucceeded = results.every((r) => r.status === \"success\");\n\n if (useJson) {\n console.log(\n JSON.stringify({\n status: allSucceeded ? \"ok\" : \"partial\",\n code: allSucceeded ? 0 : 1,\n projects: results,\n pulled: results.filter((r) => r.status === \"success\").length,\n failed: results.filter((r) => r.status === \"error\").length,\n })\n );\n } else if (allSucceeded) {\n handleSuccess(`Pulled ${projectsToPull.length} project(s) successfully`);\n } else {\n console.error(ansis.red(`Pull failed for some projects`));\n }\n\n if (span) endSpan(span);\n if (!allSucceeded) {\n process.exit(1);\n }\n } catch (error) {\n const useJson = options.format === \"json\" || isJson();\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 2,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(2);\n }\n}\n\n/**\n * Sync farm projects with their models\n */\nexport async function farmSyncCommand(options: {\n project?: string;\n verbose?: boolean;\n dryRun?: boolean;\n force?: boolean;\n output?: string;\n format?: string;\n autoCommit?: boolean;\n concurrency?: string;\n}): Promise<void> {\n const span = isTelemetryEnabled ? startSpan(\"farm.sync\") : null;\n\n try {\n // Find farm root\n const farmRoot = await findFarmRoot();\n if (!farmRoot) {\n throw new Error(\"Not in a farm directory. Run 'dr farm init' first.\");\n }\n\n const farmYamlPath = path.join(farmRoot, \"farm.yaml\");\n const manifest = await FarmManifest.load(farmYamlPath);\n\n // Determine which projects to sync\n let projectsToSync = manifest.getAllProjects();\n if (options.project) {\n const project = manifest.getProject(options.project);\n if (!project) {\n throw new Error(`Project '${options.project}' not found in farm`);\n }\n projectsToSync = [project];\n }\n\n if (projectsToSync.length === 0) {\n throw new Error(\"No projects found in farm\");\n }\n\n // Parse concurrency level\n const concurrency = options.concurrency ? Math.max(1, parseInt(options.concurrency, 10)) : 1;\n if (isNaN(concurrency)) {\n throw new Error(\"Concurrency must be a positive number\");\n }\n\n // Reject incompatible option combination: --auto-commit with --concurrency > 1\n if (options.autoCommit && concurrency > 1) {\n throw new Error(\n \"Cannot use --auto-commit with --concurrency > 1: concurrent git operations would cause race conditions. \" +\n \"Use --concurrency 1 for auto-commit, or remove --auto-commit for parallel processing.\"\n );\n }\n\n const useJson = options.format === \"json\" || isJson();\n if (!useJson && !options.verbose) {\n handleInfo(`Syncing ${projectsToSync.length} project(s) (concurrency: ${concurrency})...`);\n }\n\n const allResults: FarmSyncResultEntry[] = [];\n\n // Process projects with concurrency control\n const processSyncProject = async (project: typeof projectsToSync[0]) => {\n try {\n const modelPath = path.join(farmRoot, project.model);\n\n if (!(await fileExists(modelPath))) {\n throw new Error(`Model folder not found for project '${project.name}' at ${modelPath}`);\n }\n\n // Load model using detached model layout\n let drModelPath = modelPath;\n const manifestPath = path.join(modelPath, \"manifest.yaml\");\n if (await fileExists(manifestPath)) {\n drModelPath = manifestPath;\n }\n\n try {\n const model = await Model.load(drModelPath);\n const engine = new FarmSyncEngine(farmRoot, model);\n\n const result = await engine.syncProject(project, {\n verbose: options.verbose,\n dryRun: options.dryRun,\n force: options.force,\n });\n\n const resultEntry: FarmSyncResultEntry = {\n project: project.name,\n status: result.status === \"failed\" ? \"error\" : result.status,\n change_count: result.changeCount,\n changeset_id: result.changesetId,\n files_changed: result.filesChanged,\n ambiguities: result.ambiguities.length,\n commits_before: result.commitsBefore,\n commits_after: result.commitsAfter,\n };\n\n // Auto-commit if requested and changes were staged\n if (options.autoCommit && result.changesetId && result.changeCount > 0 && !options.dryRun) {\n try {\n const projectModelPath = path.join(farmRoot, project.model);\n const stagingManager = new (await import(\"../core/staging-area.js\")).StagingAreaManager(\n projectModelPath,\n model\n );\n const commitResult = await stagingManager.commit(model, result.changesetId);\n resultEntry.auto_committed = true;\n resultEntry.committed_changes = commitResult.committed;\n\n // Commit changes to the farm-level git repository if git is available\n // Scope git add to the project's model folder to avoid staging unrelated changes\n // Check for git repo first\n const gitRepoExists = isGitRepository(farmRoot);\n\n // If git repo exists, proceed with commit (handle commit errors independently)\n if (gitRepoExists) {\n try {\n execFileSync(\"git\", [\"add\", project.model], { cwd: farmRoot, stdio: \"pipe\" });\n execFileSync(\n \"git\",\n [\"commit\", \"-m\", `Sync: ${result.changesetId} - ${commitResult.committed} change(s)`],\n { cwd: farmRoot, stdio: \"pipe\" }\n );\n } catch (gitCommitError) {\n // If there's nothing to commit (no changes), that's fine\n if (!getErrorMessage(gitCommitError).includes(\"nothing to commit\")) {\n throw gitCommitError;\n }\n }\n }\n\n if (options.verbose && !useJson) {\n handleInfo(` Auto-committed: ${commitResult.committed} change(s)`);\n }\n } catch (commitError) {\n resultEntry.auto_committed = false;\n resultEntry.commit_error = getErrorMessage(commitError);\n resultEntry.status = \"error\";\n if (!useJson) {\n handleInfo(` Auto-commit failed: ${getErrorMessage(commitError)}`);\n }\n }\n }\n\n allResults.push(resultEntry);\n\n if (options.verbose && !useJson) {\n handleInfo(`\\nProject: ${project.name}`);\n const statusEmoji = result.status === \"success\" ? \"\u2713\" : result.status === \"partial\" ? \"\u26A0\" : \"\u2717\";\n const statusText = result.status === \"success\" ? \"Success\" : result.status === \"partial\" ? \"Partial\" : \"Failed\";\n handleInfo(` Status: ${statusEmoji} ${statusText}`);\n handleInfo(` Commits: ${result.commitsBefore}...${result.commitsAfter}`);\n handleInfo(\n ` Files changed: +${result.filesChanged.added.length} ~${result.filesChanged.modified.length} -${result.filesChanged.deleted.length}`\n );\n handleInfo(` Staged changes: ${result.changeCount}`);\n if (result.changesetId) {\n handleInfo(` Changeset: ${result.changesetId}`);\n }\n if (result.ambiguities.length > 0) {\n handleInfo(` Ambiguities: ${result.ambiguities.length} (flagged for review)`);\n }\n for (const note of result.notes) {\n console.log(` ${note}`);\n }\n }\n } catch (error) {\n allResults.push({\n project: project.name,\n status: \"error\",\n message: getErrorMessage(error),\n });\n\n if (!useJson) {\n console.error(ansis.red(`\u2717 ${project.name}: ${getErrorMessage(error)}`));\n }\n }\n } catch (error) {\n allResults.push({\n project: project.name,\n status: \"error\",\n message: getErrorMessage(error),\n });\n\n if (!useJson) {\n console.error(ansis.red(`\u2717 ${project.name}: ${getErrorMessage(error)}`));\n }\n }\n };\n\n // Process with concurrency control\n if (concurrency === 1) {\n // Sequential processing\n for (const project of projectsToSync) {\n await processSyncProject(project);\n }\n } else {\n // Parallel processing with limited concurrency\n const queue = [...projectsToSync];\n const active: Promise<void>[] = [];\n\n while (queue.length > 0 || active.length > 0) {\n while (active.length < concurrency && queue.length > 0) {\n const project = queue.shift()!;\n const promise = processSyncProject(project);\n const wrapped = promise.then(() => {\n const idx = active.indexOf(wrapped);\n if (idx !== -1) {\n active.splice(idx, 1);\n }\n });\n active.push(wrapped);\n }\n\n if (active.length > 0) {\n await Promise.race(active);\n }\n }\n }\n\n const allSucceeded = allResults.every((r) => r.status === \"success\" || r.status === \"partial\");\n\n if (useJson) {\n console.log(\n JSON.stringify({\n status: allSucceeded ? \"ok\" : \"error\",\n code: allSucceeded ? 0 : 1,\n projects: allResults,\n synced: allResults.filter((r) => r.status === \"success\").length,\n failed: allResults.filter((r) => r.status === \"error\").length,\n auto_committed: options.autoCommit,\n })\n );\n } else {\n const synced = allResults.filter((r) => r.status === \"success\").length;\n if (allSucceeded) {\n handleSuccess(`Synced ${synced}/${projectsToSync.length} project(s)`);\n }\n }\n\n // Write output file if requested\n if (options.output) {\n const { writeFile } = await import(\"../utils/file-io.js\");\n const outputExt = path.extname(options.output).toLowerCase();\n\n if (outputExt === \".json\") {\n await writeFile(\n options.output,\n JSON.stringify(\n {\n timestamp: new Date().toISOString(),\n farm_root: farmRoot,\n projects: allResults,\n },\n null,\n 2\n )\n );\n }\n }\n\n if (span) endSpan(span);\n if (!allSucceeded) {\n process.exit(1);\n }\n } catch (error) {\n const useJson = options.format === \"json\" || isJson();\n if (useJson) {\n console.log(\n JSON.stringify({\n status: \"error\",\n code: 2,\n message: getErrorMessage(error),\n })\n );\n } else {\n console.error(ansis.red(`Error: ${getErrorMessage(error)}`));\n }\n if (span) endSpan(span);\n process.exit(2);\n }\n}\n\n/**\n * Register farm commands with the CLI\n */\nexport function farmCommands(program: Command): void {\n const farmGroup = program.command(\"farm\").description(\"Manage model farms\");\n\n farmGroup\n .command(\"init\")\n .description(\"Initialize a new farm\")\n .option(\"--name <name>\", \"Farm name\")\n .option(\"--platform-view\", \"Enable platform-view support for cross-model aggregation\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm init\n $ dr farm init --name \"My Architecture Farm\"\n $ dr farm init --platform-view\n $ dr farm init --format json\n\nNotes:\n When using --platform-view, create a project named exactly \"platform-view\" to serve as\n the aggregation hub. When validating this project with 'dr farm validate --project platform-view',\n the CLI will automatically resolve cross-model references from all farm projects.`\n )\n .action(async (options) => {\n await farmInitCommand(options);\n });\n\n farmGroup\n .command(\"add <name>\")\n .description(\"Add a project to the farm\")\n .option(\"--remote <url>\", \"Git remote URL to clone\")\n .option(\"--codebase <path>\", \"Path to codebase folder (defaults to project name)\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm add my-service\n $ dr farm add my-service --remote https://github.com/org/my-service.git\n $ dr farm add my-service --codebase ./services/my-service\n $ dr farm add my-service --format json`\n )\n .action(async (name, options) => {\n await farmAddCommand(name, options);\n });\n\n farmGroup\n .command(\"remove <name>\")\n .description(\"Remove a project from the farm\")\n .option(\"--delete-model\", \"Also delete the model folder\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm remove my-service\n $ dr farm remove my-service --delete-model\n $ dr farm remove my-service --format json`\n )\n .action(async (name, options) => {\n await farmRemoveCommand(name, options);\n });\n\n farmGroup\n .command(\"status\")\n .description(\"Show farm status and registered projects\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm status\n $ dr farm status --format json`\n )\n .action(async (options) => {\n await farmStatusCommand(options);\n });\n\n farmGroup\n .command(\"validate\")\n .description(\"Validate farm projects using composed scope (cross-model references)\")\n .option(\"--project <name>\", \"Validate only a specific project (default: all)\")\n .option(\"--verbose\", \"Show verbose validation output\")\n .option(\"--quiet\", \"Suppress success messages\")\n .option(\"--output <path>\", \"Export validation report to file (JSON/Markdown)\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm validate\n $ dr farm validate --project my-service\n $ dr farm validate --verbose\n $ dr farm validate --format json\n $ dr farm validate --output report.json\n\nNotes:\n For platform-view aggregation: Use 'dr farm validate --project platform-view' to validate\n a platform-view project. The project name must be exactly 'platform-view' and the farm\n must have platform-view enabled (set during 'dr farm init --platform-view').`\n )\n .action(async (options) => {\n await farmValidateCommand(options);\n });\n\n farmGroup\n .command(\"pull\")\n .description(\"Pull latest changes from remote for farm projects\")\n .option(\"--project <name>\", \"Pull only a specific project (default: all)\")\n .option(\"--verbose\", \"Show verbose output\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm pull\n $ dr farm pull --project my-service\n $ dr farm pull --verbose\n $ dr farm pull --format json`\n )\n .action(async (options) => {\n await farmPullCommand(options);\n });\n\n farmGroup\n .command(\"sync\")\n .description(\"Sync farm projects with their models (generates staged changesets)\")\n .option(\"--project <name>\", \"Sync only a specific project (default: all)\")\n .option(\"--verbose\", \"Show verbose output\")\n .option(\"--dry-run\", \"Preview without creating changesets\")\n .option(\"--force\", \"Proceed despite ambiguous file-to-element mappings\")\n .option(\"--output <path>\", \"Export sync report to file (JSON)\")\n .option(\"--format <format>\", \"Output format: text, json\", \"text\")\n .option(\"--auto-commit\", \"Automatically commit changes (bypasses staged review)\")\n .option(\"--concurrency <n>\", \"Process multiple projects in parallel (default: 1)\", \"1\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr farm sync\n $ dr farm sync --project my-service\n $ dr farm sync --verbose --output sync-report.json\n $ dr farm sync --dry-run\n $ dr farm sync --format json --auto-commit\n $ dr farm sync --concurrency 4\n\nAutomation (cron/CI):\n $ dr farm sync --format json --auto-commit --output sync-report.json\n $ dr farm sync --format json --concurrency 4 --output sync-report.json\n\nNote: --auto-commit and --concurrency > 1 cannot be used together (race condition risk).\nUse --concurrency 1 (default) with --auto-commit for automated syncs.`\n )\n .action(async (options) => {\n await farmSyncCommand(options);\n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qBAAqB,sDAAsD,GAAG,EACrF,YACC,SACA;;;;;;;;;;;;;;sEAcgE,EAEjE,OAAO,OAAO,YAAW;AACxB,UAAM,gBAAgB,OAAO;EAC/B,CAAC,GAEH,UAAU,yBAAwB;AACpC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/commands/init.js
CHANGED
|
@@ -7,6 +7,7 @@ import { installSpecReference } from "../utils/spec-installer.js";
|
|
|
7
7
|
import { getCliBundledSpecVersion } from "../utils/spec-version.js";
|
|
8
8
|
import { isTelemetryEnabled, startSpan, endSpan } from "../telemetry/index.js";
|
|
9
9
|
import { getErrorMessage } from "../utils/errors.js";
|
|
10
|
+
import { regenerateLayerReports } from "./reports.js";
|
|
10
11
|
async function initCommand(options) {
|
|
11
12
|
intro(ansis.bold(ansis.blue("\u2699\uFE0F Initialize Documentation Robotics Model")));
|
|
12
13
|
const span = isTelemetryEnabled ? startSpan("model.init", {
|
|
@@ -43,7 +44,16 @@ async function initCommand(options) {
|
|
|
43
44
|
logVerbose(`Model saved with:
|
|
44
45
|
- Version: 0.1.0
|
|
45
46
|
- Spec Version: ${getCliBundledSpecVersion()}
|
|
46
|
-
- Location: ${rootPath}/documentation-robotics/model`), logDebug("Installing spec reference (.dr/ folder)..."), await installSpecReference(rootPath, !1), logVerbose("Spec reference installed"),
|
|
47
|
+
- Location: ${rootPath}/documentation-robotics/model`), logDebug("Installing spec reference (.dr/ folder)..."), await installSpecReference(rootPath, !1), logVerbose("Spec reference installed"), logDebug("Generating reports and README...");
|
|
48
|
+
try {
|
|
49
|
+
await regenerateLayerReports(rootPath), logVerbose("Reports and README generated");
|
|
50
|
+
} catch (reportError) {
|
|
51
|
+
const reportMessage = getErrorMessage(reportError);
|
|
52
|
+
console.warn(ansis.yellow(`\u26A0 Warning: Failed to generate reports and README: ${reportMessage}
|
|
53
|
+
Model initialized successfully. To regenerate reports later, run:
|
|
54
|
+
dr reports regenerate`)), logDebug(`Report generation failed (non-fatal): ${reportMessage}`);
|
|
55
|
+
}
|
|
56
|
+
isTelemetryEnabled && span && (span.setAttribute("model.path", rootPath), span.setStatus({ code: 0 })), outro(ansis.green(`\u2713 Model initialized: ${ansis.bold(model.manifest.name)}`));
|
|
47
57
|
} catch (error) {
|
|
48
58
|
isTelemetryEnabled && span && (span.recordException(error), span.setStatus({
|
|
49
59
|
code: 2,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/init.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Initialize a new Documentation Robotics model\n */\n\nimport { intro, text, outro } from \"@clack/prompts\";\nimport ansis from \"ansis\";\nimport { Model } from \"../core/model.js\";\nimport { fileExists } from \"../utils/file-io.js\";\nimport { logVerbose, logDebug } from \"../utils/globals.js\";\nimport { installSpecReference } from \"../utils/spec-installer.js\";\nimport { getCliBundledSpecVersion } from \"../utils/spec-version.js\";\nimport { isTelemetryEnabled, startSpan, endSpan } from \"../telemetry/index.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\n\nexport interface InitOptions {\n name?: string;\n author?: string;\n description?: string;\n verbose?: boolean;\n debug?: boolean;\n}\n\nexport async function initCommand(options: InitOptions): Promise<void> {\n intro(ansis.bold(ansis.blue(\"\u2699\uFE0F Initialize Documentation Robotics Model\")));\n\n const span = isTelemetryEnabled\n ? startSpan(\"model.init\", {\n \"init.hasName\": !!options.name,\n \"init.hasDescription\": !!options.description,\n \"init.hasAuthor\": !!options.author,\n })\n : null;\n\n try {\n const rootPath = process.cwd();\n const modelPath = `${rootPath}/documentation-robotics/model`;\n const manifestPath = `${modelPath}/manifest.yaml`;\n\n // Check if model already exists\n if (await fileExists(manifestPath)) {\n console.error(ansis.red(\"Error: Model already initialized in this directory\"));\n if (isTelemetryEnabled && span) {\n (span as any).setStatus({ code: 2, message: \"Model already exists\" });\n }\n endSpan(span);\n process.exit(1);\n }\n\n // Gather model metadata\n // Check if stdin is a TTY to determine if we should prompt\n const isInteractive = process.stdin.isTTY;\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"cli.interactive\", isInteractive);\n }\n\n // If name is provided, skip all prompts\n const skipPrompts = !!options.name;\n\n const name =\n options.name ||\n (isInteractive\n ? await text({\n message: \"Model name:\",\n validate: (value) => (value.length === 0 ? \"Name is required\" : undefined),\n })\n : (() => {\n console.error(ansis.red(\"Error: Model name is required (use --name option)\"));\n if (isTelemetryEnabled && span) {\n (span as any).setStatus({ code: 2, message: \"Model name required\" });\n }\n endSpan(span);\n process.exit(1);\n })());\n\n const description =\n options.description ||\n (skipPrompts\n ? \"\"\n : isInteractive\n ? await text({\n message: \"Description (optional):\",\n defaultValue: \"\",\n })\n : \"\");\n\n const author =\n options.author ||\n (skipPrompts\n ? \"\"\n : isInteractive\n ? await text({\n message: \"Author (optional):\",\n defaultValue: \"\",\n })\n : \"\");\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"model.name\", name as string);\n (span as any).setAttribute(\"model.specVersion\", getCliBundledSpecVersion());\n }\n\n // Initialize model\n logDebug(`Creating model directory at ${rootPath}/documentation-robotics/model`);\n const model = await Model.init(\n rootPath,\n {\n name: name as string,\n version: \"0.1.0\",\n description: (description as string) || undefined,\n author: (author as string) || undefined,\n specVersion: getCliBundledSpecVersion(),\n created: new Date().toISOString(),\n },\n { lazyLoad: false }\n );\n\n logVerbose(`Model saved with:\n - Version: 0.1.0\n - Spec Version: ${getCliBundledSpecVersion()}\n - Location: ${rootPath}/documentation-robotics/model`);\n\n // Install spec reference (.dr/ folder)\n logDebug(\"Installing spec reference (.dr/ folder)...\");\n await installSpecReference(rootPath, false);\n logVerbose(\"Spec reference installed\");\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"model.path\", rootPath);\n (span as any).setStatus({ code: 0 });\n }\n\n outro(ansis.green(`\u2713 Model initialized: ${ansis.bold(model.manifest.name)}`));\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n const message = getErrorMessage(error);\n console.error(ansis.red(`Error: ${message}`));\n endSpan(span);\n process.exit(1);\n } finally {\n endSpan(span);\n }\n}\n"],
|
|
5
|
-
"mappings": "AAIA,SAAS,OAAO,MAAM,aAAa;AACnC,OAAO,WAAW;AAClB,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,YAAY,gBAAgB;AACrC,SAAS,4BAA4B;AACrC,SAAS,gCAAgC;AACzC,SAAS,oBAAoB,WAAW,eAAe;AACvD,SAAS,uBAAuB;
|
|
4
|
+
"sourcesContent": ["/**\n * Initialize a new Documentation Robotics model\n */\n\nimport { intro, text, outro } from \"@clack/prompts\";\nimport ansis from \"ansis\";\nimport { Model } from \"../core/model.js\";\nimport { fileExists } from \"../utils/file-io.js\";\nimport { logVerbose, logDebug } from \"../utils/globals.js\";\nimport { installSpecReference } from \"../utils/spec-installer.js\";\nimport { getCliBundledSpecVersion } from \"../utils/spec-version.js\";\nimport { isTelemetryEnabled, startSpan, endSpan } from \"../telemetry/index.js\";\nimport { getErrorMessage } from \"../utils/errors.js\";\nimport { regenerateLayerReports } from \"./reports.js\";\n\nexport interface InitOptions {\n name?: string;\n author?: string;\n description?: string;\n verbose?: boolean;\n debug?: boolean;\n}\n\nexport async function initCommand(options: InitOptions): Promise<void> {\n intro(ansis.bold(ansis.blue(\"\u2699\uFE0F Initialize Documentation Robotics Model\")));\n\n const span = isTelemetryEnabled\n ? startSpan(\"model.init\", {\n \"init.hasName\": !!options.name,\n \"init.hasDescription\": !!options.description,\n \"init.hasAuthor\": !!options.author,\n })\n : null;\n\n try {\n const rootPath = process.cwd();\n const modelPath = `${rootPath}/documentation-robotics/model`;\n const manifestPath = `${modelPath}/manifest.yaml`;\n\n // Check if model already exists\n if (await fileExists(manifestPath)) {\n console.error(ansis.red(\"Error: Model already initialized in this directory\"));\n if (isTelemetryEnabled && span) {\n (span as any).setStatus({ code: 2, message: \"Model already exists\" });\n }\n endSpan(span);\n process.exit(1);\n }\n\n // Gather model metadata\n // Check if stdin is a TTY to determine if we should prompt\n const isInteractive = process.stdin.isTTY;\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"cli.interactive\", isInteractive);\n }\n\n // If name is provided, skip all prompts\n const skipPrompts = !!options.name;\n\n const name =\n options.name ||\n (isInteractive\n ? await text({\n message: \"Model name:\",\n validate: (value) => (value.length === 0 ? \"Name is required\" : undefined),\n })\n : (() => {\n console.error(ansis.red(\"Error: Model name is required (use --name option)\"));\n if (isTelemetryEnabled && span) {\n (span as any).setStatus({ code: 2, message: \"Model name required\" });\n }\n endSpan(span);\n process.exit(1);\n })());\n\n const description =\n options.description ||\n (skipPrompts\n ? \"\"\n : isInteractive\n ? await text({\n message: \"Description (optional):\",\n defaultValue: \"\",\n })\n : \"\");\n\n const author =\n options.author ||\n (skipPrompts\n ? \"\"\n : isInteractive\n ? await text({\n message: \"Author (optional):\",\n defaultValue: \"\",\n })\n : \"\");\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"model.name\", name as string);\n (span as any).setAttribute(\"model.specVersion\", getCliBundledSpecVersion());\n }\n\n // Initialize model\n logDebug(`Creating model directory at ${rootPath}/documentation-robotics/model`);\n const model = await Model.init(\n rootPath,\n {\n name: name as string,\n version: \"0.1.0\",\n description: (description as string) || undefined,\n author: (author as string) || undefined,\n specVersion: getCliBundledSpecVersion(),\n created: new Date().toISOString(),\n },\n { lazyLoad: false }\n );\n\n logVerbose(`Model saved with:\n - Version: 0.1.0\n - Spec Version: ${getCliBundledSpecVersion()}\n - Location: ${rootPath}/documentation-robotics/model`);\n\n // Install spec reference (.dr/ folder)\n logDebug(\"Installing spec reference (.dr/ folder)...\");\n await installSpecReference(rootPath, false);\n logVerbose(\"Spec reference installed\");\n\n // Generate README and layer reports\n logDebug(\"Generating reports and README...\");\n try {\n await regenerateLayerReports(rootPath);\n logVerbose(\"Reports and README generated\");\n } catch (reportError) {\n const reportMessage = getErrorMessage(reportError);\n console.warn(\n ansis.yellow(\n `\u26A0 Warning: Failed to generate reports and README: ${reportMessage}\\n` +\n ` Model initialized successfully. To regenerate reports later, run:\\n` +\n ` dr reports regenerate`\n )\n );\n logDebug(`Report generation failed (non-fatal): ${reportMessage}`);\n }\n\n if (isTelemetryEnabled && span) {\n (span as any).setAttribute(\"model.path\", rootPath);\n (span as any).setStatus({ code: 0 });\n }\n\n outro(ansis.green(`\u2713 Model initialized: ${ansis.bold(model.manifest.name)}`));\n } catch (error) {\n if (isTelemetryEnabled && span) {\n (span as any).recordException(error as Error);\n (span as any).setStatus({\n code: 2,\n message: getErrorMessage(error),\n });\n }\n const message = getErrorMessage(error);\n console.error(ansis.red(`Error: ${message}`));\n endSpan(span);\n process.exit(1);\n } finally {\n endSpan(span);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAIA,SAAS,OAAO,MAAM,aAAa;AACnC,OAAO,WAAW;AAClB,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,YAAY,gBAAgB;AACrC,SAAS,4BAA4B;AACrC,SAAS,gCAAgC;AACzC,SAAS,oBAAoB,WAAW,eAAe;AACvD,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AAUvC,eAAsB,YAAY,SAAoB;AACpD,QAAM,MAAM,KAAK,MAAM,KAAK,uDAA6C,CAAC,CAAC;AAE3E,QAAM,OAAO,qBACT,UAAU,cAAc;IACtB,gBAAgB,CAAC,CAAC,QAAQ;IAC1B,uBAAuB,CAAC,CAAC,QAAQ;IACjC,kBAAkB,CAAC,CAAC,QAAQ;GAC7B,IACD;AAEJ,MAAI;AACF,UAAM,WAAW,QAAQ,IAAG,GAEtB,eAAe,GADH,GAAG,QAAQ,+BACI;AAGjC,IAAI,MAAM,WAAW,YAAY,MAC/B,QAAQ,MAAM,MAAM,IAAI,oDAAoD,CAAC,GACzE,sBAAsB,QACvB,KAAa,UAAU,EAAE,MAAM,GAAG,SAAS,uBAAsB,CAAE,GAEtE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AAM,OACJ,0DAAqD,aAAa;;wBAEzC,CAC1B,GAEH,SAAS,yCAAyC,aAAa,EAAE;IACnE;AAEA,IAAI,sBAAsB,SACvB,KAAa,aAAa,cAAc,QAAQ,GAChD,KAAa,UAAU,EAAE,MAAM,EAAC,CAAE,IAGrC,MAAM,MAAM,MAAM,6BAAwB,MAAM,KAAK,MAAM,SAAS,IAAI,CAAC,EAAE,CAAC;EAC9E,SAAS,OAAO;AACd,IAAI,sBAAsB,SACvB,KAAa,gBAAgB,KAAc,GAC3C,KAAa,UAAU;MACtB,MAAM;MACN,SAAS,gBAAgB,KAAK;KAC/B;AAEH,UAAM,UAAU,gBAAgB,KAAK;AACrC,YAAQ,MAAM,MAAM,IAAI,UAAU,OAAO,EAAE,CAAC,GAC5C,QAAQ,IAAI,GACZ,QAAQ,KAAK,CAAC;EAChB;AACE,YAAQ,IAAI;EACd;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { isCancel, text } from "@clack/prompts";
|
|
2
|
+
import { ApiKeyManager } from "../mcp/api-key-manager.js";
|
|
3
|
+
import { McpResourceRegistry } from "../mcp/resource-registry.js";
|
|
4
|
+
import { McpToolRegistry } from "../mcp/tool-registry.js";
|
|
5
|
+
import { loadModel } from "../mcp/tools/shared.js";
|
|
6
|
+
import { startActiveSpan } from "../telemetry/index.js";
|
|
7
|
+
import { CLIError, getErrorMessage } from "../utils/errors.js";
|
|
8
|
+
import { getCliVersion } from "../utils/spec-version.js";
|
|
9
|
+
const cliVersion = getCliVersion(), promptForKeyPath = async (defaultPath) => {
|
|
10
|
+
const result = await text({
|
|
11
|
+
message: "Where should the MCP API key be stored?",
|
|
12
|
+
placeholder: defaultPath,
|
|
13
|
+
defaultValue: defaultPath
|
|
14
|
+
});
|
|
15
|
+
return isCancel(result) || typeof result != "string" || result.trim().length === 0 ? defaultPath : result.trim();
|
|
16
|
+
};
|
|
17
|
+
async function createConfiguredServer() {
|
|
18
|
+
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js"), server = new McpServer({
|
|
19
|
+
name: "documentation-robotics",
|
|
20
|
+
version: cliVersion
|
|
21
|
+
});
|
|
22
|
+
new McpToolRegistry().registerAll(server), await new McpResourceRegistry().registerAll(server);
|
|
23
|
+
try {
|
|
24
|
+
await loadModel();
|
|
25
|
+
} catch (error) {
|
|
26
|
+
process.stderr.write(`[mcp] model warmup skipped: ${getErrorMessage(error)}
|
|
27
|
+
`);
|
|
28
|
+
}
|
|
29
|
+
return server;
|
|
30
|
+
}
|
|
31
|
+
async function mcpCommand(options = {}) {
|
|
32
|
+
const keyManager = new ApiKeyManager();
|
|
33
|
+
try {
|
|
34
|
+
if (options.regenerateKey) {
|
|
35
|
+
await startActiveSpan("mcp.key.rotate", async (span) => {
|
|
36
|
+
const isInteractive2 = process.stdin.isTTY === !0, { key: key2, path: path2 } = await keyManager.rotate(isInteractive2 ? promptForKeyPath : void 0);
|
|
37
|
+
span.setAttribute("mcp.key.path", path2), process.stderr.write(`Generated new MCP API key, stored at ${path2}
|
|
38
|
+
`), process.stderr.write(`MCP API key: ${key2}
|
|
39
|
+
`);
|
|
40
|
+
});
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const isInteractive = process.stdin.isTTY === !0, { key, path, isNew } = await keyManager.ensureKey(isInteractive ? promptForKeyPath : void 0);
|
|
44
|
+
if (isNew && process.stderr.write(`Generated new MCP API key, stored at ${path}
|
|
45
|
+
`), process.stderr.write(`MCP API key: ${key}
|
|
46
|
+
`), options.transport === "http") {
|
|
47
|
+
const { createMcpHttpApp, startHttpServer, closeHttpServer } = await import("../mcp/http-transport.js"), host = options.host || "127.0.0.1", port = options.port || 3100;
|
|
48
|
+
let httpApp;
|
|
49
|
+
const httpServer = await startActiveSpan("mcp.server.start", async (span) => {
|
|
50
|
+
httpApp = await createMcpHttpApp(keyManager, key, createConfiguredServer, host);
|
|
51
|
+
const server = await startHttpServer(httpApp, host, port);
|
|
52
|
+
return span.setAttribute("mcp.server.name", "documentation-robotics"), span.setAttribute("mcp.server.version", cliVersion), span.setAttribute("mcp.server.transport", "http"), span.setAttribute("mcp.server.host", host), span.setAttribute("mcp.server.port", port), server;
|
|
53
|
+
});
|
|
54
|
+
host === "0.0.0.0" && process.stderr.write(`Warning: Server bound to 0.0.0.0. DNS rebinding protection is not automatic; ensure your MCP client validates the Host header.
|
|
55
|
+
`), process.stderr.write(`Documentation Robotics MCP server ready (http://${host}:${port}/mcp)
|
|
56
|
+
`);
|
|
57
|
+
let resolveKeepAlive;
|
|
58
|
+
const keepAlive = new Promise((resolve) => {
|
|
59
|
+
resolveKeepAlive = resolve;
|
|
60
|
+
});
|
|
61
|
+
let isShuttingDown = !1;
|
|
62
|
+
const shutdown = async () => {
|
|
63
|
+
if (!isShuttingDown) {
|
|
64
|
+
isShuttingDown = !0;
|
|
65
|
+
try {
|
|
66
|
+
process.stderr.write(`
|
|
67
|
+
Shutting down HTTP server...
|
|
68
|
+
`), await closeHttpServer(httpServer, httpApp);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
const errorMsg = error instanceof Error ? error.message : "unknown error";
|
|
71
|
+
process.stderr.write(`[mcp] Error closing server: ${errorMsg}
|
|
72
|
+
`);
|
|
73
|
+
} finally {
|
|
74
|
+
resolveKeepAlive();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
process.on("SIGINT", shutdown), process.on("SIGTERM", shutdown), await keepAlive;
|
|
79
|
+
} else {
|
|
80
|
+
if (!keyManager.validate(process.env.DR_MCP_API_KEY, key))
|
|
81
|
+
throw process.stderr.write(`Error: DR_MCP_API_KEY environment variable is missing or does not match the stored API key.
|
|
82
|
+
`), process.stderr.write(`Set DR_MCP_API_KEY to the key above when configuring the MCP client, e.g.:
|
|
83
|
+
`), process.stderr.write(` { "command": "dr", "args": ["mcp"], "env": { "DR_MCP_API_KEY": "<key>" } }
|
|
84
|
+
`), new CLIError("MCP authentication failed: invalid or missing DR_MCP_API_KEY", 1);
|
|
85
|
+
const transport = await startActiveSpan("mcp.server.start", async (span) => {
|
|
86
|
+
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js"), server = await createConfiguredServer();
|
|
87
|
+
span.setAttribute("mcp.server.name", "documentation-robotics"), span.setAttribute("mcp.server.version", cliVersion), span.setAttribute("mcp.server.transport", "stdio");
|
|
88
|
+
const serverTransport = new StdioServerTransport();
|
|
89
|
+
return await server.connect(serverTransport), serverTransport;
|
|
90
|
+
});
|
|
91
|
+
process.stderr.write(`Documentation Robotics MCP server ready (stdio)
|
|
92
|
+
`), await new Promise((resolve) => {
|
|
93
|
+
transport.onclose = () => resolve();
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error instanceof CLIError)
|
|
98
|
+
throw error;
|
|
99
|
+
let message = getErrorMessage(error);
|
|
100
|
+
throw error instanceof Error && error.code === "EADDRINUSE" && (message = `Port ${options.port || 3100} is already in use. Try a different port with --port or kill the process using that port.`), process.stderr.write(`Error: ${message}
|
|
101
|
+
`), new CLIError(message, 1);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
export {
|
|
105
|
+
mcpCommand
|
|
106
|
+
};
|
|
107
|
+
//# sourceMappingURL=mcp.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/commands/mcp.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * MCP server command - Starts an MCP server for AI assistant integration\n *\n * Supports two transport modes:\n * - stdio (default): In-process over stdio; stdout carries the MCP JSON-RPC protocol\n * - http: HTTP server with Express, exposing MCP at /mcp endpoint with bearer token auth\n *\n * All non-protocol output goes to stderr.\n */\n\nimport { isCancel, text } from \"@clack/prompts\";\nimport { ApiKeyManager, type ApiKeyStoragePrompt } from \"../mcp/api-key-manager.js\";\nimport { type HttpTransportApp } from \"../mcp/http-transport.js\";\nimport { McpResourceRegistry } from \"../mcp/resource-registry.js\";\nimport { McpToolRegistry } from \"../mcp/tool-registry.js\";\nimport { loadModel } from \"../mcp/tools/shared.js\";\nimport { startActiveSpan } from \"../telemetry/index.js\";\nimport { CLIError, getErrorMessage } from \"../utils/errors.js\";\nimport { getCliVersion } from \"../utils/spec-version.js\";\n\nconst cliVersion = getCliVersion();\n\n/**\n * Prompt the user (via stdout/stdin) for where to store a newly generated API key.\n * Only invoked when stdin is a TTY \u2014 non-interactive launches (e.g. an MCP client\n * spawning `dr mcp`) fall back to the default path without prompting.\n */\nconst promptForKeyPath: ApiKeyStoragePrompt = async (defaultPath) => {\n const result = await text({\n message: \"Where should the MCP API key be stored?\",\n placeholder: defaultPath,\n defaultValue: defaultPath,\n });\n\n if (isCancel(result) || typeof result !== \"string\" || result.trim().length === 0) {\n return defaultPath;\n }\n return result.trim();\n};\n\nasync function createConfiguredServer() {\n const { McpServer } = await import(\"@modelcontextprotocol/sdk/server/mcp.js\");\n\n const server = new McpServer({\n name: \"documentation-robotics\",\n version: cliVersion,\n });\n\n // Register the model tool surface and spec/model manifest resources.\n new McpToolRegistry().registerAll(server);\n await new McpResourceRegistry().registerAll(server);\n\n // Warm the model cache at startup so it's loaded once and held in memory\n // for the session, rather than waiting for the first tool call. Best-effort:\n // a server started outside a DR project still starts up cleanly \u2014 the first\n // tool call that supplies a valid rootPath will load and cache it.\n try {\n await loadModel();\n } catch (error) {\n process.stderr.write(`[mcp] model warmup skipped: ${getErrorMessage(error)}\\n`);\n }\n\n return server;\n}\n\nexport interface McpCommandOptions {\n /** Force-generate a new API key, overwrite it at the configured storage path, and exit. */\n regenerateKey?: boolean;\n /** Transport type: \"stdio\" or \"http\" (default: \"stdio\") */\n transport?: \"stdio\" | \"http\";\n /** Port for HTTP transport (default: 3100, only meaningful with --transport http) */\n port?: number;\n /** Host address for HTTP transport (default: \"127.0.0.1\", only meaningful with --transport http) */\n host?: string;\n}\n\nexport async function mcpCommand(options: McpCommandOptions = {}): Promise<void> {\n const keyManager = new ApiKeyManager();\n\n try {\n if (options.regenerateKey) {\n await startActiveSpan(\"mcp.key.rotate\", async (span) => {\n const isInteractive = process.stdin.isTTY === true;\n const { key, path } = await keyManager.rotate(\n isInteractive ? promptForKeyPath : undefined\n );\n span.setAttribute(\"mcp.key.path\", path);\n process.stderr.write(`Generated new MCP API key, stored at ${path}\\n`);\n process.stderr.write(`MCP API key: ${key}\\n`);\n });\n return;\n }\n\n const isInteractive = process.stdin.isTTY === true;\n const { key, path, isNew } = await keyManager.ensureKey(\n isInteractive ? promptForKeyPath : undefined\n );\n\n if (isNew) {\n process.stderr.write(`Generated new MCP API key, stored at ${path}\\n`);\n }\n // Required every launch: print the API key to stderr (never stdout, which\n // carries the MCP protocol).\n process.stderr.write(`MCP API key: ${key}\\n`);\n\n if (options.transport === \"http\") {\n // HTTP transport implementation\n const { createMcpHttpApp, startHttpServer, closeHttpServer } = await import(\n \"../mcp/http-transport.js\"\n );\n\n const host = options.host || \"127.0.0.1\";\n const port = options.port || 3100;\n\n let httpApp: HttpTransportApp;\n const httpServer = await startActiveSpan(\n \"mcp.server.start\",\n async (span) => {\n httpApp = await createMcpHttpApp(keyManager, key, createConfiguredServer, host);\n const server = await startHttpServer(httpApp, host, port);\n\n span.setAttribute(\"mcp.server.name\", \"documentation-robotics\");\n span.setAttribute(\"mcp.server.version\", cliVersion);\n span.setAttribute(\"mcp.server.transport\", \"http\");\n span.setAttribute(\"mcp.server.host\", host);\n span.setAttribute(\"mcp.server.port\", port);\n\n return server;\n }\n );\n\n // Warn if bound to 0.0.0.0\n if (host === \"0.0.0.0\") {\n process.stderr.write(\n \"Warning: Server bound to 0.0.0.0. DNS rebinding protection is not automatic; ensure your MCP client validates the Host header.\\n\"\n );\n }\n\n process.stderr.write(`Documentation Robotics MCP server ready (http://${host}:${port}/mcp)\\n`);\n\n // Set up graceful shutdown on SIGINT/SIGTERM\n let resolveKeepAlive: () => void;\n const keepAlive = new Promise<void>((resolve) => {\n resolveKeepAlive = resolve;\n });\n\n let isShuttingDown = false;\n const shutdown = async () => {\n if (isShuttingDown) {\n return;\n }\n isShuttingDown = true;\n\n try {\n process.stderr.write(\"\\nShutting down HTTP server...\\n\");\n await closeHttpServer(httpServer, httpApp);\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : \"unknown error\";\n process.stderr.write(`[mcp] Error closing server: ${errorMsg}\\n`);\n } finally {\n resolveKeepAlive!();\n }\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // Keep the process alive until explicitly terminated\n await keepAlive;\n } else {\n // Stdio transport (default)\n // Validate that the environment has the correct API key configured\n if (!keyManager.validate(process.env.DR_MCP_API_KEY, key)) {\n process.stderr.write(\n \"Error: DR_MCP_API_KEY environment variable is missing or does not match the stored API key.\\n\"\n );\n process.stderr.write(\n \"Set DR_MCP_API_KEY to the key above when configuring the MCP client, e.g.:\\n\"\n );\n process.stderr.write(\n ' { \"command\": \"dr\", \"args\": [\"mcp\"], \"env\": { \"DR_MCP_API_KEY\": \"<key>\" } }\\n'\n );\n throw new CLIError(\"MCP authentication failed: invalid or missing DR_MCP_API_KEY\", 1);\n }\n\n const transport = await startActiveSpan(\n \"mcp.server.start\",\n async (span) => {\n const { StdioServerTransport } = await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n\n const server = await createConfiguredServer();\n\n span.setAttribute(\"mcp.server.name\", \"documentation-robotics\");\n span.setAttribute(\"mcp.server.version\", cliVersion);\n span.setAttribute(\"mcp.server.transport\", \"stdio\");\n\n const serverTransport = new StdioServerTransport();\n await server.connect(serverTransport);\n return serverTransport;\n }\n );\n\n process.stderr.write(\"Documentation Robotics MCP server ready (stdio)\\n\");\n\n // Keep the process alive for the lifetime of the stdio session; the\n // transport closes (and the process exits) when stdin closes. Shutdown\n // is implicit in the `mcp.server.start` span's end, so no separate\n // zero-duration \"stop\" span is recorded here.\n await new Promise<void>((resolve) => {\n transport.onclose = () => resolve();\n });\n }\n } catch (error) {\n if (error instanceof CLIError) {\n throw error;\n }\n\n let message = getErrorMessage(error);\n\n // Handle port-in-use errors with actionable message\n if (error instanceof Error && (error as NodeJS.ErrnoException).code === \"EADDRINUSE\") {\n const port = options.port || 3100;\n message = `Port ${port} is already in use. Try a different port with --port or kill the process using that port.`;\n }\n\n process.stderr.write(`Error: ${message}\\n`);\n throw new CLIError(message, 1);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAUA,SAAS,UAAU,YAAY;AAC/B,SAAS,qBAA+C;AAExD,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,UAAU,uBAAuB;AAC1C,SAAS,qBAAqB;AAE9B,MAAM,aAAa,cAAa,GAO1B,mBAAwC,OAAO,gBAAe;AAClE,QAAM,SAAS,MAAM,KAAK;IACxB,SAAS;IACT,aAAa;IACb,cAAc;GACf;AAED,SAAI,SAAS,MAAM,KAAK,OAAO,UAAW,YAAY,OAAO,KAAI,EAAG,WAAW,IACtE,cAEF,OAAO,KAAI;AACpB;AAEA,eAAe,yBAAsB;AACnC,QAAM,EAAE,UAAS,IAAK,MAAM,OAAO,yCAAyC,GAEtE,SAAS,IAAI,UAAU;IAC3B,MAAM;IACN,SAAS;GACV;AAGD,MAAI,gBAAe,EAAG,YAAY,MAAM,GACxC,MAAM,IAAI,oBAAmB,EAAG,YAAY,MAAM;AAMlD,MAAI;AACF,UAAM,UAAS;EACjB,SAAS,OAAO;AACd,YAAQ,OAAO,MAAM,+BAA+B,gBAAgB,KAAK,CAAC;CAAI;EAChF;AAEA,SAAO;AACT;AAaA,eAAsB,WAAW,UAA6B,CAAA,GAAE;AAC9D,QAAM,aAAa,IAAI,cAAa;AAEpC,MAAI;AACF,QAAI,QAAQ,eAAe;AACzB,YAAM,gBAAgB,kBAAkB,OAAO,SAAQ;AACrD,cAAMA,iBAAgB,QAAQ,MAAM,UAAU,IACxC,EAAE,KAAAC,MAAK,MAAA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Model } from "../core/model.js";
|
|
|
3
3
|
import { StagingAreaManager } from "../core/staging-area.js";
|
|
4
4
|
import { findElementLayer } from "../utils/element-utils.js";
|
|
5
5
|
import { isValidLayerName } from "../core/layers.js";
|
|
6
|
-
import { CLIError, ErrorCategory, handleError, getErrorMessage } from "../utils/errors.js";
|
|
6
|
+
import { CLIError, ErrorCategory, handleError, handleSuccess, handleInfo, getErrorMessage } from "../utils/errors.js";
|
|
7
7
|
import { getValidRelationships, getValidPredicatesForSource, getValidDestinationsForSourceAndPredicate } from "../generated/relationship-index.js";
|
|
8
8
|
import { normalizeNodeType } from "../generated/node-types.js";
|
|
9
9
|
import { ModelReportOrchestrator } from "../reports/model-report-orchestrator.js";
|
|
@@ -69,7 +69,7 @@ async function addRelationshipHandler(model, source, target, predicate, properti
|
|
|
69
69
|
throw new CLIError(`Invalid relationship: predicate "${predicate}" does not allow reflexive relationships (${source})`, ErrorCategory.USER);
|
|
70
70
|
}
|
|
71
71
|
if (model.relationships.find(source, target, predicate).length > 0)
|
|
72
|
-
return
|
|
72
|
+
return !1;
|
|
73
73
|
const stagingManager = new StagingAreaManager(model.rootPath, model), activeChangesetId = await stagingManager.getActiveId(), relData = {
|
|
74
74
|
source,
|
|
75
75
|
target,
|
|
@@ -161,15 +161,15 @@ async function deleteRelationshipHandler(model, source, target, predicate, preRe
|
|
|
161
161
|
}
|
|
162
162
|
return { deletedCount: resolvedToDelete.length };
|
|
163
163
|
}
|
|
164
|
-
function relationshipCommands(program) {
|
|
165
|
-
program.command("add <source> <target>").description("Add a relationship between elements (intra-layer or cross-layer)").requiredOption("--predicate <predicate>", "Relationship predicate (e.g., depends-on, realizes, exposes)").option("--properties <json>", "Relationship properties (JSON)").addHelpText("after", `
|
|
164
|
+
function relationshipCommands(program, rootProgram) {
|
|
165
|
+
program.command("add <source> <target>").description("Add a relationship between elements (intra-layer or cross-layer)").option("--model <path>", "Path to model root (contains model/manifest.yaml)").requiredOption("--predicate <predicate>", "Relationship predicate (e.g., depends-on, realizes, exposes)").option("--properties <json>", "Relationship properties (JSON)").addHelpText("after", `
|
|
166
166
|
Examples:
|
|
167
167
|
$ dr relationship add motivation.goal.goal-a motivation.goal.goal-b --predicate aggregates
|
|
168
168
|
$ dr relationship add api.operation.create-order application.service.order-service --predicate exposes
|
|
169
169
|
$ dr relationship add business.businessprocess.checkout application.applicationprocess.checkout --predicate aggregates
|
|
170
170
|
$ dr relationship add element-1 element-2 --predicate realizes --properties '{"strength":"high"}'`).action(async (source, target, options) => {
|
|
171
171
|
try {
|
|
172
|
-
const model = await Model.load(), sourceLayerName = await findElementLayer(model, source);
|
|
172
|
+
const model = await Model.load(options.model || process.cwd()), sourceLayerName = await findElementLayer(model, source);
|
|
173
173
|
if (!sourceLayerName)
|
|
174
174
|
throw new CLIError(`Source element ${source} not found`, ErrorCategory.USER);
|
|
175
175
|
const sourceLayer = await model.getLayer(sourceLayerName);
|
|
@@ -199,19 +199,33 @@ Examples:
|
|
|
199
199
|
if (!await addRelationshipHandler(model, source, target, options.predicate, properties, {
|
|
200
200
|
source: { element: sourceElement, layerName: sourceLayerName },
|
|
201
201
|
target: { element: targetElement, layerName: targetLayerName }
|
|
202
|
-
}))
|
|
202
|
+
})) {
|
|
203
|
+
handleSuccess(`Relationship ${source} --[${options.predicate}]--> ${target} already exists`, {
|
|
204
|
+
source,
|
|
205
|
+
target,
|
|
206
|
+
predicate: options.predicate,
|
|
207
|
+
layer: sourceLayerName,
|
|
208
|
+
duplicate: !0
|
|
209
|
+
}, { verbose: options.verbose });
|
|
203
210
|
return;
|
|
204
|
-
|
|
205
|
-
|
|
211
|
+
}
|
|
212
|
+
let message = `Added relationship: ${ansis.bold(source)} ${options.predicate} ${ansis.bold(target)}`;
|
|
213
|
+
const details = {
|
|
214
|
+
source,
|
|
215
|
+
target,
|
|
216
|
+
predicate: options.predicate,
|
|
217
|
+
layer: sourceLayerName
|
|
218
|
+
};
|
|
219
|
+
constraints && (message += ansis.dim(` (${constraints.cardinality}, ${constraints.strength} strength)`), details.cardinality = constraints.cardinality, details.strength = constraints.strength), activeChangesetId && (message += ansis.dim(" [staged]"), details.changesetStatus = "staged"), handleSuccess(message, details, { verbose: options.verbose });
|
|
206
220
|
} catch (error) {
|
|
207
221
|
handleError(error);
|
|
208
222
|
}
|
|
209
|
-
}), program.command("delete <source> <target>").description("Delete a relationship").option("--predicate <predicate>", "Specific predicate to delete (optional, delete all if not specified)").option("--force", "Skip confirmation prompt").addHelpText("after", `
|
|
223
|
+
}), program.command("delete <source> <target>").description("Delete a relationship").option("--model <path>", "Path to model root (contains model/manifest.yaml)").option("--predicate <predicate>", "Specific predicate to delete (optional, delete all if not specified)").option("--force", "Skip confirmation prompt").addHelpText("after", `
|
|
210
224
|
Examples:
|
|
211
225
|
$ dr relationship delete element-1 element-2 --predicate depends-on
|
|
212
226
|
$ dr relationship delete element-1 element-2 --force`).action(async (source, target, options) => {
|
|
213
227
|
try {
|
|
214
|
-
const model = await Model.load(), sourceLayerName = await findElementLayer(model, source);
|
|
228
|
+
const model = await Model.load(options.model || process.cwd()), sourceLayerName = await findElementLayer(model, source);
|
|
215
229
|
if (!sourceLayerName)
|
|
216
230
|
throw new CLIError(`Source element ${source} not found`, ErrorCategory.USER);
|
|
217
231
|
const toDelete = model.relationships.find(source, target, options.predicate);
|
|
@@ -224,73 +238,82 @@ Examples:
|
|
|
224
238
|
message: `Delete ${toDelete.length} relationship(s)? This cannot be undone.`,
|
|
225
239
|
initialValue: !1
|
|
226
240
|
})) {
|
|
227
|
-
|
|
241
|
+
handleSuccess("Deletion cancelled", {
|
|
242
|
+
source,
|
|
243
|
+
target,
|
|
244
|
+
status: "cancelled"
|
|
245
|
+
});
|
|
228
246
|
return;
|
|
229
247
|
}
|
|
230
248
|
}
|
|
231
249
|
const activeChangesetId = await new StagingAreaManager(model.rootPath, model).getActiveId(), result = await deleteRelationshipHandler(model, source, target, options.predicate, {
|
|
232
250
|
sourceLayerName,
|
|
233
251
|
toDelete
|
|
234
|
-
}), stagedSuffix = activeChangesetId ? " [staged]" : ""
|
|
235
|
-
|
|
252
|
+
}), stagedSuffix = activeChangesetId ? " [staged]" : "", deleteDetails = {
|
|
253
|
+
source,
|
|
254
|
+
target,
|
|
255
|
+
layer: sourceLayerName,
|
|
256
|
+
deletedCount: result.deletedCount
|
|
257
|
+
};
|
|
258
|
+
options.predicate && (deleteDetails.predicate = options.predicate), activeChangesetId && (deleteDetails.changesetStatus = "staged"), handleSuccess(`Deleted ${result.deletedCount} relationship(s) from ${ansis.bold(source)} to ${ansis.bold(target)}${stagedSuffix}`, deleteDetails, { verbose: options.verbose });
|
|
236
259
|
} catch (error) {
|
|
237
260
|
handleError(error);
|
|
238
261
|
}
|
|
239
|
-
}), program.command("list <id>").description("List relationships for an element").option("--direction <dir>", "Filter by direction (incoming/outgoing/all)", "all").option("--json", "Output as JSON").addHelpText("after", `
|
|
262
|
+
}), program.command("list <id>").description("List relationships for an element").option("--model <path>", "Path to model root (contains model/manifest.yaml)").option("--direction <dir>", "Filter by direction (incoming/outgoing/all)", "all").option("--json", "Output as JSON").addHelpText("after", `
|
|
240
263
|
Examples:
|
|
241
264
|
$ dr relationship list api-endpoint-create-customer
|
|
242
265
|
$ dr relationship list business-service-order --direction outgoing
|
|
243
266
|
$ dr relationship list element-1 --json`).action(async (id, options) => {
|
|
244
267
|
try {
|
|
245
|
-
const model = await Model.load();
|
|
268
|
+
const model = await Model.load(options.model || process.cwd());
|
|
246
269
|
if (!await findElementLayer(model, id))
|
|
247
270
|
throw new CLIError(`Element ${id} not found`, ErrorCategory.USER);
|
|
248
271
|
const { outgoing, incoming } = model.relationships.getForElement(id);
|
|
249
272
|
let relationships = [];
|
|
250
|
-
if ((options.direction === "outgoing" || options.direction === "all") && relationships.push(...outgoing), (options.direction === "incoming" || options.direction === "all") && relationships.push(...incoming), options.json) {
|
|
273
|
+
if ((options.direction === "outgoing" || options.direction === "all") && relationships.push(...outgoing), (options.direction === "incoming" || options.direction === "all") && relationships.push(...incoming), options.json ?? rootProgram?.opts().json) {
|
|
251
274
|
console.log(JSON.stringify(relationships, null, 2));
|
|
252
275
|
return;
|
|
253
276
|
}
|
|
254
277
|
if (relationships.length === 0) {
|
|
255
|
-
|
|
278
|
+
handleInfo(ansis.yellow(`No ${options.direction} relationships for ${id}`));
|
|
256
279
|
return;
|
|
257
280
|
}
|
|
258
|
-
|
|
281
|
+
handleInfo(""), handleInfo(ansis.bold(`${options.direction === "all" ? "" : options.direction + " "}relationships for ${ansis.cyan(id)}:`)), handleInfo(ansis.dim("\u2500".repeat(80)));
|
|
259
282
|
for (const rel of relationships) {
|
|
260
283
|
const isOutgoing = rel.source === id, direction = isOutgoing ? "\u2192" : "\u2190", otherElement = isOutgoing ? rel.target : rel.source, crossLayer = rel.targetLayer && rel.targetLayer !== rel.layer ? ansis.dim(` [${rel.layer} \u2192 ${rel.targetLayer}]`) : "";
|
|
261
|
-
if (
|
|
284
|
+
if (handleInfo(` ${direction} ${ansis.magenta(rel.predicate)}: ${ansis.yellow(otherElement)}${crossLayer}`), rel.properties) {
|
|
262
285
|
const propStr = Object.entries(rel.properties).map(([k, v]) => `${k}=${v}`).join(", ");
|
|
263
|
-
|
|
286
|
+
handleInfo(` ${ansis.dim(propStr)}`);
|
|
264
287
|
}
|
|
265
288
|
}
|
|
266
|
-
|
|
289
|
+
handleInfo(ansis.dim("\u2500".repeat(80))), handleInfo(ansis.dim(`Total: ${relationships.length} relationship(s)`)), handleInfo("");
|
|
267
290
|
} catch (error) {
|
|
268
291
|
handleError(error);
|
|
269
292
|
}
|
|
270
|
-
}), program.command("show <source> <target>").description("Show relationship details").addHelpText("after", `
|
|
293
|
+
}), program.command("show <source> <target>").description("Show relationship details").option("--model <path>", "Path to model root (contains model/manifest.yaml)").addHelpText("after", `
|
|
271
294
|
Examples:
|
|
272
295
|
$ dr relationship show api-endpoint-create-customer business-service-customer-mgmt
|
|
273
|
-
$ dr relationship show application-component-api motivation-goal-sales-efficiency`).action(async (source, target) => {
|
|
296
|
+
$ dr relationship show application-component-api motivation-goal-sales-efficiency`).action(async (source, target, options) => {
|
|
274
297
|
try {
|
|
275
|
-
const model = await Model.load();
|
|
298
|
+
const model = await Model.load(options.model || process.cwd());
|
|
276
299
|
if (!await findElementLayer(model, source))
|
|
277
300
|
throw new CLIError(`Source element ${source} not found`, ErrorCategory.USER);
|
|
278
301
|
const relationships = model.relationships.find(source, target);
|
|
279
302
|
if (relationships.length === 0)
|
|
280
303
|
throw new CLIError(`No relationships from ${source} to ${target}`, ErrorCategory.USER);
|
|
281
|
-
|
|
304
|
+
handleInfo(""), handleInfo(ansis.bold(`Relationship${relationships.length > 1 ? "s" : ""} from ${ansis.cyan(source)} to ${ansis.yellow(target)}:`)), handleInfo(ansis.dim("\u2500".repeat(60)));
|
|
282
305
|
for (let i = 0; i < relationships.length; i++) {
|
|
283
306
|
const rel = relationships[i];
|
|
284
|
-
if (i > 0 &&
|
|
285
|
-
|
|
307
|
+
if (i > 0 && handleInfo(""), handleInfo(`Predicate: ${ansis.magenta(rel.predicate)}`), handleInfo(`Layer: ${ansis.cyan(rel.layer)}`), rel.targetLayer && rel.targetLayer !== rel.layer && handleInfo(`Target Layer: ${ansis.cyan(rel.targetLayer)}`), rel.properties && Object.keys(rel.properties).length > 0) {
|
|
308
|
+
handleInfo("Properties:");
|
|
286
309
|
for (const [key, value] of Object.entries(rel.properties)) {
|
|
287
310
|
const displayValue = typeof value == "string" ? value : JSON.stringify(value, null, 2);
|
|
288
|
-
|
|
311
|
+
handleInfo(` ${ansis.cyan(key)}: ${displayValue}`);
|
|
289
312
|
}
|
|
290
313
|
} else
|
|
291
|
-
|
|
314
|
+
handleInfo("Properties: none");
|
|
292
315
|
}
|
|
293
|
-
|
|
316
|
+
handleInfo("");
|
|
294
317
|
} catch (error) {
|
|
295
318
|
handleError(error);
|
|
296
319
|
}
|