agents-united 0.13.0 → 0.14.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 +466 -411
- package/dist/cli.js +1772 -629
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
- package/registry/agents/orchestrator-business.md +21 -5
- package/registry/agents/orchestrator-design.md +21 -5
- package/registry/agents/orchestrator-digital-agency.md +9 -1
- package/registry/agents/orchestrator-engineering.md +12 -5
- package/registry/agents/orchestrator-marketing.md +14 -5
- package/registry/agents/orchestrator-research.md +14 -5
- package/registry/agents/orchestrator-security.md +15 -5
- package/registry/agents/orchestrator-system-architecture.md +14 -5
- package/registry/agents/orchestrator-universal.md +11 -2
- package/registry/agents/subagent-accessibility-lead.md +49 -3
- package/registry/agents/subagent-ai-model-architect.md +48 -2
- package/registry/agents/subagent-android-architect.md +53 -3
- package/registry/agents/subagent-appsec-penetration-tester.md +27 -1
- package/registry/agents/subagent-backend-architect.md +63 -232
- package/registry/agents/subagent-business-panel-experts.md +5 -1
- package/registry/agents/subagent-cloud-infrastructure-architect.md +23 -1
- package/registry/agents/subagent-cloud-security-architect.md +7 -1
- package/registry/agents/subagent-code-reviewer.md +31 -1
- package/registry/agents/subagent-compliance-grc-specialist.md +7 -2
- package/registry/agents/subagent-cross-platform-specialist.md +54 -3
- package/registry/agents/subagent-data-engineer.md +53 -3
- package/registry/agents/subagent-database-administrator.md +7 -1
- package/registry/agents/subagent-deep-research.md +5 -1
- package/registry/agents/subagent-design-ops-lead.md +5 -1
- package/registry/agents/subagent-design-researcher.md +5 -1
- package/registry/agents/subagent-design-systems-architect.md +5 -1
- package/registry/agents/subagent-designer-toolkit-expert.md +5 -1
- package/registry/agents/subagent-devops-engineer.md +68 -288
- package/registry/agents/subagent-distributed-systems-architect.md +54 -3
- package/registry/agents/subagent-e2e-tester.md +52 -3
- package/registry/agents/subagent-financial-analyst.md +5 -1
- package/registry/agents/subagent-finops-cost-engineer.md +5 -1
- package/registry/agents/subagent-frontend-architect.md +54 -225
- package/registry/agents/subagent-interaction-designer.md +5 -1
- package/registry/agents/subagent-ios-architect.md +53 -3
- package/registry/agents/subagent-legal-contract-analyst.md +5 -1
- package/registry/agents/subagent-lifecycle-email-specialist.md +5 -1
- package/registry/agents/subagent-literature-patent-analyst.md +5 -1
- package/registry/agents/subagent-market-intelligence-analyst.md +5 -1
- package/registry/agents/subagent-marketing-campaign-specialist.md +6 -2
- package/registry/agents/subagent-marketing-content-strategist.md +6 -2
- package/registry/agents/subagent-marketing-conversion-specialist.md +6 -2
- package/registry/agents/subagent-marketing-creative-designer.md +6 -2
- package/registry/agents/subagent-marketing-growth-strategist.md +6 -2
- package/registry/agents/subagent-ml-platform-engineer.md +48 -2
- package/registry/agents/subagent-operations-strategist.md +5 -1
- package/registry/agents/subagent-paid-acquisition-specialist.md +5 -1
- package/registry/agents/subagent-plg-strategist.md +5 -1
- package/registry/agents/subagent-prototype-tester.md +5 -1
- package/registry/agents/subagent-qa-automation-lead.md +35 -78
- package/registry/agents/subagent-repo-index.md +27 -1
- package/registry/agents/subagent-security-engineer.md +37 -1
- package/registry/agents/subagent-seo-specialist.md +6 -2
- package/registry/agents/subagent-socratic-mentor.md +5 -1
- package/registry/agents/subagent-statistical-analyst.md +5 -1
- package/registry/agents/subagent-sysops-sre-lead.md +7 -1
- package/registry/agents/subagent-system-architect.md +6 -1
- package/registry/agents/subagent-ui-designer.md +5 -1
- package/registry/agents/subagent-ux-strategist.md +5 -1
- package/registry/bundles.json +89 -17
- package/registry/core/orchestrator-engineering.core.md +1 -0
- package/registry/core/subagent-backend-architect.core.md +20 -22
- package/registry/core/subagent-code-reviewer.core.md +1 -0
- package/registry/core/subagent-frontend-architect.core.md +8 -6
- package/registry/core/subagent-repo-index.core.md +1 -0
- package/registry/skills/ai-prototype-refactoring/SKILL.md +24 -0
- package/registry/skills/ai-prototype-refactoring/references/backend-frontend-devops-exemplars.md +104 -0
- package/registry/skills/azure-infrastructure-bicep/SKILL.md +24 -0
- package/registry/skills/azure-infrastructure-bicep/references/backend-frontend-devops-exemplars.md +173 -0
- package/registry/skills/banner-design/SKILL.md +170 -0
- package/registry/skills/banner-design/references/banner-sizes-and-styles.md +66 -0
- package/registry/skills/brand-identity/SKILL.md +212 -0
- package/registry/skills/brand-identity/references/approval-checklist.md +17 -0
- package/registry/skills/brand-identity/references/asset-organization.md +30 -0
- package/registry/skills/brand-identity/references/brand-guideline-template.md +57 -0
- package/registry/skills/brand-identity/references/color-palette-management.md +37 -0
- package/registry/skills/brand-identity/references/consistency-checklist.md +26 -0
- package/registry/skills/brand-identity/references/logo-usage-rules.md +23 -0
- package/registry/skills/brand-identity/references/messaging-framework.md +22 -0
- package/registry/skills/brand-identity/references/typography-specifications.md +29 -0
- package/registry/skills/brand-identity/references/visual-identity.md +23 -0
- package/registry/skills/brand-identity/references/voice-framework.md +27 -0
- package/registry/skills/brand-identity/scripts/extract-colors.mjs +104 -0
- package/registry/skills/brand-identity/scripts/inject-brand-context.mjs +112 -0
- package/registry/skills/brand-identity/scripts/lib/confirm-gate.mjs +28 -0
- package/registry/skills/brand-identity/scripts/sync-brand-to-tokens.mjs +205 -0
- package/registry/skills/brand-identity/scripts/validate-asset.mjs +137 -0
- package/registry/skills/clickhouse-architecture-advisor/SKILL.md +202 -0
- package/registry/skills/codeql-scanning/LICENSE +427 -0
- package/registry/skills/codeql-scanning/NOTICE.md +31 -0
- package/registry/skills/codeql-scanning/SKILL.md +136 -0
- package/registry/skills/codeql-scanning/references/build-fixes.md +105 -0
- package/registry/skills/codeql-scanning/references/diagnostic-query-templates.md +325 -0
- package/registry/skills/codeql-scanning/references/extension-yaml-format.md +202 -0
- package/registry/skills/codeql-scanning/references/important-only-suite.md +119 -0
- package/registry/skills/codeql-scanning/references/language-details.md +220 -0
- package/registry/skills/codeql-scanning/references/macos-arm64e-workaround.md +201 -0
- package/registry/skills/codeql-scanning/references/performance-tuning.md +81 -0
- package/registry/skills/codeql-scanning/references/quality-assessment.md +197 -0
- package/registry/skills/codeql-scanning/references/ruleset-catalog.md +68 -0
- package/registry/skills/codeql-scanning/references/run-all-suite.md +106 -0
- package/registry/skills/codeql-scanning/references/sarif-processing.md +82 -0
- package/registry/skills/codeql-scanning/references/threat-models.md +36 -0
- package/registry/skills/codeql-scanning/references/upstream-method.md +288 -0
- package/registry/skills/codeql-scanning/references/workflow-build-database.md +338 -0
- package/registry/skills/codeql-scanning/references/workflow-create-data-extensions.md +275 -0
- package/registry/skills/codeql-scanning/references/workflow-run-analysis.md +327 -0
- package/registry/skills/codeql-scanning/scripts/build_log.py +91 -0
- package/registry/skills/codeql-scanning/scripts/check_db_quality.py +366 -0
- package/registry/skills/codeql-scanning/scripts/find_databases.py +90 -0
- package/registry/skills/codeql-scanning/scripts/generate_suite.py +101 -0
- package/registry/skills/codeql-scanning/scripts/verify_query_suite.py +86 -0
- package/registry/skills/edge-security-audit/SKILL.md +225 -0
- package/registry/skills/expo-cicd-workflows/SKILL.md +228 -0
- package/registry/skills/hf-managed-jobs/SKILL.md +198 -0
- package/registry/skills/hf-model-training/SKILL.md +204 -0
- package/registry/skills/mutation-testing/LICENSE +427 -0
- package/registry/skills/mutation-testing/NOTICE.md +31 -0
- package/registry/skills/mutation-testing/SKILL.md +122 -0
- package/registry/skills/mutation-testing/references/blockchain-patterns.md +103 -0
- package/registry/skills/mutation-testing/references/equivalent-mutants.md +101 -0
- package/registry/skills/mutation-testing/references/input-formats.md +84 -0
- package/registry/skills/mutation-testing/references/optimization-strategies.md +327 -0
- package/registry/skills/mutation-testing/references/report-template.md +140 -0
- package/registry/skills/mutation-testing/references/severity-classification.md +132 -0
- package/registry/skills/mutation-testing/references/upstream-method.md +105 -0
- package/registry/skills/mutation-testing/references/workflow-analyzing-results.md +123 -0
- package/registry/skills/mutation-testing/references/workflow-bug-hunter.md +139 -0
- package/registry/skills/mutation-testing/references/workflow-configuration.md +338 -0
- package/registry/skills/playwright-best-practices/SKILL.md +5 -0
- package/registry/skills/playwright-best-practices/references/conversion-funnel-test.md +79 -0
- package/registry/skills/postgres-best-practices/SKILL.md +205 -0
- package/registry/skills/property-based-testing/LICENSE +427 -0
- package/registry/skills/property-based-testing/NOTICE.md +31 -0
- package/registry/skills/property-based-testing/SKILL.md +119 -0
- package/registry/skills/property-based-testing/references/generating.md +82 -0
- package/registry/skills/property-based-testing/references/interpreting-failures.md +83 -0
- package/registry/skills/property-based-testing/references/libraries.md +80 -0
- package/registry/skills/property-based-testing/references/refactoring.md +123 -0
- package/registry/skills/property-based-testing/references/reviewing.md +81 -0
- package/registry/skills/property-based-testing/references/upstream-method.md +65 -0
- package/registry/skills/react-best-practices/SKILL.md +5 -0
- package/registry/skills/react-best-practices/references/nextjs-server-actions-and-isr.md +85 -0
- package/registry/skills/sarif-triage/LICENSE +427 -0
- package/registry/skills/sarif-triage/NOTICE.md +31 -0
- package/registry/skills/sarif-triage/SKILL.md +117 -0
- package/registry/skills/sarif-triage/references/jq-queries.md +210 -0
- package/registry/skills/sarif-triage/references/upstream-method.md +490 -0
- package/registry/skills/sarif-triage/scripts/sarif_helpers.py +400 -0
- package/registry/skills/security-best-practices/LICENSE +201 -0
- package/registry/skills/security-best-practices/NOTICE.md +30 -0
- package/registry/skills/security-best-practices/SKILL.md +116 -0
- package/registry/skills/security-best-practices/references/golang-general-backend-security.md +829 -0
- package/registry/skills/security-best-practices/references/javascript-express-web-server-security.md +1161 -0
- package/registry/skills/security-best-practices/references/javascript-general-web-frontend-security.md +750 -0
- package/registry/skills/security-best-practices/references/javascript-jquery-web-frontend-security.md +681 -0
- package/registry/skills/security-best-practices/references/javascript-typescript-nextjs-web-server-security.md +1147 -0
- package/registry/skills/security-best-practices/references/javascript-typescript-react-web-frontend-security.md +993 -0
- package/registry/skills/security-best-practices/references/javascript-typescript-vue-web-frontend-security.md +794 -0
- package/registry/skills/security-best-practices/references/python-django-web-server-security.md +885 -0
- package/registry/skills/security-best-practices/references/python-fastapi-web-server-security.md +1039 -0
- package/registry/skills/security-best-practices/references/python-flask-web-server-security.md +708 -0
- package/registry/skills/security-best-practices/references/upstream-method.md +86 -0
- package/registry/skills/security-diff-review/LICENSE +427 -0
- package/registry/skills/security-diff-review/NOTICE.md +31 -0
- package/registry/skills/security-diff-review/SKILL.md +125 -0
- package/registry/skills/security-diff-review/references/adversarial.md +206 -0
- package/registry/skills/security-diff-review/references/methodology.md +237 -0
- package/registry/skills/security-diff-review/references/patterns.md +303 -0
- package/registry/skills/security-diff-review/references/reporting.md +372 -0
- package/registry/skills/security-diff-review/references/upstream-method.md +222 -0
- package/registry/skills/semgrep-scanning/LICENSE +427 -0
- package/registry/skills/semgrep-scanning/NOTICE.md +31 -0
- package/registry/skills/semgrep-scanning/SKILL.md +139 -0
- package/registry/skills/semgrep-scanning/references/rulesets.md +165 -0
- package/registry/skills/semgrep-scanning/references/scan-modes.md +153 -0
- package/registry/skills/semgrep-scanning/references/upstream-method.md +262 -0
- package/registry/skills/semgrep-scanning/references/workflow-scan-workflow.md +467 -0
- package/registry/skills/semgrep-scanning/scripts/merge_sarif.py +339 -0
- package/registry/skills/semgrep-scanning/scripts/run_scans.py +482 -0
- package/registry/skills/sentry-incident-triage/SKILL.md +193 -0
- package/registry/skills/supabase-backend-architecture/SKILL.md +24 -0
- package/registry/skills/supabase-backend-architecture/references/backend-frontend-devops-exemplars.md +140 -0
- package/registry/skills/supply-chain-risk-audit/LICENSE +427 -0
- package/registry/skills/supply-chain-risk-audit/NOTICE.md +31 -0
- package/registry/skills/supply-chain-risk-audit/SKILL.md +119 -0
- package/registry/skills/supply-chain-risk-audit/references/upstream-method.md +123 -0
- package/registry/skills/supply-chain-risk-audit/scripts/collect.py +1568 -0
- package/registry/skills/supply-chain-risk-audit/scripts/model.py +402 -0
- package/registry/skills/supply-chain-risk-audit/scripts/pyproject.toml +20 -0
- package/registry/skills/supply-chain-risk-audit/scripts/render.py +809 -0
- package/registry/skills/supply-chain-risk-audit/scripts/sources.py +683 -0
- package/registry/skills/supply-chain-risk-audit/scripts/uv.lock +12 -0
- package/registry/skills/terraform-style-guide/LICENSE +373 -0
- package/registry/skills/terraform-style-guide/NOTICE.md +31 -0
- package/registry/skills/terraform-style-guide/SKILL.md +126 -0
- package/registry/skills/terraform-style-guide/references/security.md +167 -0
- package/registry/skills/terraform-style-guide/references/style-conventions.md +312 -0
- package/registry/skills/terraform-test-patterns/LICENSE +373 -0
- package/registry/skills/terraform-test-patterns/NOTICE.md +31 -0
- package/registry/skills/terraform-test-patterns/SKILL.md +133 -0
- package/registry/skills/terraform-test-patterns/references/ci-cd.md +83 -0
- package/registry/skills/terraform-test-patterns/references/examples.md +317 -0
- package/registry/skills/terraform-test-patterns/references/mock-providers.md +174 -0
- package/registry/skills/terraform-test-patterns/references/test-syntax.md +445 -0
- package/registry/skills/threat-modeling/LICENSE +201 -0
- package/registry/skills/threat-modeling/NOTICE.md +31 -0
- package/registry/skills/threat-modeling/SKILL.md +136 -0
- package/registry/skills/threat-modeling/references/prompt-template.md +258 -0
- package/registry/skills/threat-modeling/references/security-controls-and-assets.md +35 -0
- package/registry/skills/threat-modeling/references/upstream-method.md +81 -0
- package/registry/skills/turso-distributed-sqlite/SKILL.md +24 -0
- package/registry/skills/turso-distributed-sqlite/references/backend-frontend-devops-exemplars.md +92 -0
- package/registry/skills/ux-writing/SKILL.md +183 -0
- package/registry/skills/ux-writing/references/interface-patterns.md +41 -0
- package/registry/skills/ux-writing/references/localization-accessibility.md +31 -0
- package/registry/skills/ux-writing/references/research-measurement.md +27 -0
- package/registry/skills/ux-writing/references/source-runtime-workflow.md +31 -0
- package/registry/skills/ux-writing/references/voice-tone-terminology.md +26 -0
- package/registry/skills/variant-analysis/LICENSE +427 -0
- package/registry/skills/variant-analysis/NOTICE.md +31 -0
- package/registry/skills/variant-analysis/SKILL.md +119 -0
- package/registry/skills/variant-analysis/assets/codeql/cpp.ql +119 -0
- package/registry/skills/variant-analysis/assets/codeql/go.ql +69 -0
- package/registry/skills/variant-analysis/assets/codeql/java.ql +71 -0
- package/registry/skills/variant-analysis/assets/codeql/javascript.ql +63 -0
- package/registry/skills/variant-analysis/assets/codeql/python.ql +80 -0
- package/registry/skills/variant-analysis/assets/semgrep/cpp.yaml +98 -0
- package/registry/skills/variant-analysis/assets/semgrep/go.yaml +63 -0
- package/registry/skills/variant-analysis/assets/semgrep/java.yaml +61 -0
- package/registry/skills/variant-analysis/assets/semgrep/javascript.yaml +60 -0
- package/registry/skills/variant-analysis/assets/semgrep/python.yaml +72 -0
- package/registry/skills/variant-analysis/references/reporting.md +41 -0
- package/registry/skills/variant-analysis/references/root-cause.md +101 -0
- package/registry/skills/variant-analysis/references/searching.md +162 -0
- package/registry/skills/variant-analysis/references/triage.md +95 -0
- package/registry/skills/variant-analysis/references/upstream-method.md +74 -0
- package/registry/skills/variant-analysis/references/variant-report-template.md +78 -0
- package/registry/skills/vercel-deploy-best-practices/SKILL.md +24 -0
- package/registry/skills/vercel-deploy-best-practices/references/backend-frontend-devops-exemplars.md +109 -0
- package/registry/translation-ledger.json +48 -5
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/core/registry.ts","../src/core/installer.ts","../src/core/adapter.ts","../src/core/hosts.ts","../src/core/projector.ts","../src/core/cline-projector.ts","../src/core/claude-projector.ts","../src/core/guard.ts","../src/core/residue-patterns.ts","../src/core/overlays.ts","../src/core/types.ts","../src/core/uninstaller.ts","../src/core/inventory.ts","../src/core/updater.ts","../src/core/doctor.ts","../src/core/claude-capabilities.ts","../src/core/cline-capabilities.ts","../src/core/cline-launcher.ts","../src/core/claude-launcher.ts","../src/core/prerequisites.ts","../src/core/mcp-locations.ts"],"sourcesContent":["import { cac } from 'cac';\nimport pc from 'picocolors';\nimport { intro, outro, spinner, note, log, select, multiselect, confirm, text } from '@clack/prompts';\nimport fs from 'fs-extra';\nimport path from 'node:path';\nimport { RegistryResolver } from './core/registry.js';\nimport { InstallEngine } from './core/installer.js';\nimport { UninstallEngine } from './core/uninstaller.js';\nimport { InventoryScanner } from './core/inventory.js';\nimport { UpdateEngine } from './core/updater.js';\nimport { DoctorEngine } from './core/doctor.js';\nimport { ClineLauncher } from './core/cline-launcher.js';\nimport { ClineCapabilityProbe } from './core/cline-capabilities.js';\nimport { ClaudeLauncher } from './core/claude-launcher.js';\nimport type { ClaudeActivationPlan } from './core/claude-launcher.js';\nimport { ClaudeCapabilityProbe } from './core/claude-capabilities.js';\nimport { PrerequisiteChecker } from './core/prerequisites.js';\nimport { McpLocationRegistry } from './core/mcp-locations.js';\nimport { isKnownHost, HOST_REGISTRY, KNOWN_HOST_IDS, planInstallTargets, hostAvailabilityNotice, SUPPORTED_HOST_IDS } from './core/hosts.js';\nimport type { InstallScope, InstallMethod, AgentHost, BundleDefinition, BundleTier, InstalledPackageRecord, ProjectionInfo, ExecutionMode, ClaudeCapabilityReport } from './core/types.js';\n\nconst cli = cac('agents-united');\nconst registry = new RegistryResolver();\nconst installer = new InstallEngine(registry);\nconst uninstaller = new UninstallEngine(registry);\nconst scanner = new InventoryScanner(registry);\nconst updater = new UpdateEngine(registry, scanner, installer);\n\nexport function detectWorkspaceHosts(cwd: string = process.cwd()): AgentHost[] {\n const detected: AgentHost[] = [];\n for (const host of Object.values(HOST_REGISTRY)) {\n const found = host.detectionMarkers.some(marker => fs.pathExistsSync(path.join(cwd, marker)));\n if (found) detected.push(host.id as AgentHost);\n }\n return detected;\n}\n\nexport function getTerminalContentWidth(): number {\n const cols = typeof process !== 'undefined' && process.stdout?.columns ? process.stdout.columns : 80;\n return Math.max(40, Math.min(cols - 8, 68));\n}\n\nexport function wrapText(text: string, maxLen?: number, indent: string = ''): string[] {\n if (!text) return [];\n const limit = maxLen ?? getTerminalContentWidth();\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let current = indent;\n\n for (const word of words) {\n if (!word) continue;\n if (current.length > indent.length && (current.length + 1 + word.length > limit)) {\n lines.push(current);\n current = indent + word;\n } else {\n current = current.length === indent.length ? current + word : current + ' ' + word;\n }\n }\n\n if (current.trim().length > 0) {\n lines.push(current);\n }\n\n return lines;\n}\n\nexport function formatWrappedList(\n items: string[],\n indent: string = ' ',\n maxLineLen?: number\n): string[] {\n if (!items || items.length === 0) return [];\n\n const limit = maxLineLen ?? getTerminalContentWidth();\n const lines: string[] = [];\n let currentLine = indent;\n\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const isLast = i === items.length - 1;\n const token = isLast ? item : `${item}, `;\n\n if (currentLine.length > indent.length && (currentLine.length + token.length > limit)) {\n lines.push(currentLine.trimEnd());\n currentLine = indent + token;\n } else {\n currentLine += token;\n }\n }\n\n if (currentLine.trim().length > 0) {\n lines.push(currentLine.trimEnd());\n }\n\n return lines;\n}\n\nexport interface InstallationSummaryOptions {\n bundleName: string;\n scope: string;\n method: string;\n hosts: string[];\n agents: string[];\n skills: string[];\n targetDirs: string[];\n projections?: ProjectionInfo[];\n}\n\nexport function formatInstallationSummary(options: InstallationSummaryOptions): string {\n const { bundleName, scope, method, hosts, agents, skills, targetDirs, projections } = options;\n const limit = getTerminalContentWidth();\n\n const lines: string[] = [\n `Bundle: ${bundleName}`,\n `Scope: ${scope}`,\n `Method: ${method}`,\n `Targets: ${hosts.join(', ')}`,\n ];\n\n // Agents\n if (agents.length === 0) {\n lines.push(`Agents: None`);\n } else {\n const inlineAgents = `Agents (${agents.length}): ${agents.join(', ')}`;\n if (inlineAgents.length <= limit) {\n lines.push(inlineAgents);\n } else {\n lines.push(`Agents (${agents.length}):`);\n lines.push(...formatWrappedList(agents, ' ', limit));\n }\n }\n\n // Skills\n if (skills.length === 0) {\n lines.push(`Skills: None`);\n } else {\n const inlineSkills = `Skills (${skills.length}): ${skills.join(', ')}`;\n if (inlineSkills.length <= limit) {\n lines.push(inlineSkills);\n } else {\n lines.push(`Skills (${skills.length}):`);\n lines.push(...formatWrappedList(skills, ' ', limit));\n }\n }\n\n // Target Directories\n if (targetDirs.length === 0) {\n lines.push('Target Directories: None');\n } else if (targetDirs.length === 1) {\n const singleDirLine = `Target Directories: ${targetDirs[0]}`;\n if (singleDirLine.length <= limit) {\n lines.push(singleDirLine);\n } else {\n lines.push('Target Directories:');\n lines.push(` ${targetDirs[0]}`);\n }\n } else {\n lines.push(`Target Directories (${targetDirs.length}):`);\n for (const dir of targetDirs) {\n lines.push(` ${dir}`);\n }\n }\n\n // Projections summary\n if (projections && projections.length > 0) {\n const byHost = new Map<string, number>();\n for (const p of projections) {\n byHost.set(p.host, (byHost.get(p.host) ?? 0) + 1);\n }\n const hostSummaries: string[] = [];\n for (const [host, count] of byHost) {\n const label = HOST_REGISTRY[host]?.label ?? host;\n hostSummaries.push(`${label} (${count} file${count > 1 ? 's' : ''})`);\n }\n lines.push(`Projections: ${hostSummaries.join(', ')}`);\n }\n\n return lines.join('\\n');\n}\n\nexport function renderProjections(projections: ProjectionInfo[]): string {\n const byHost = new Map<string, ProjectionInfo[]>();\n for (const p of projections) {\n const list = byHost.get(p.host) ?? [];\n list.push(p);\n byHost.set(p.host, list);\n }\n const lines: string[] = [];\n for (const [host, items] of byHost) {\n lines.push(`${HOST_REGISTRY[host]?.label ?? host} — ${items.length} file${items.length > 1 ? 's' : ''}`);\n for (const p of items) {\n lines.push(` → ${p.path}`);\n for (const w of p.warnings) {\n const wrapped = wrapText(`⚠ ${w}`, 68, ' ');\n for (const wl of wrapped) {\n lines.push(pc.yellow(wl));\n }\n }\n }\n }\n return lines.join('\\n');\n}\n\nconst BUNDLE_DISPLAY_NAMES: Record<string, { title: string; summary: string }> = {\n 'software-engineering': {\n title: 'Software Engineering Team',\n summary: 'Autonomous dev lead, backend/frontend architects, TDD & git guardrails',\n },\n 'mobile-development': {\n title: 'Mobile Development Team',\n summary: 'iOS (SwiftUI), Android (Compose) & Cross-Platform (React Native/Flutter)',\n },\n 'frontend-engineering': {\n title: 'Frontend Architecture Team',\n summary: 'Next.js/React App Router, Server Components & Web Vitals',\n },\n 'backend-distributed-systems': {\n title: 'Backend & Distributed Systems Team',\n summary: 'Microservices, Kafka/RabbitMQ event streams & DB migrations',\n },\n 'qa-automation': {\n title: 'QA & Test Automation Team',\n summary: 'Playwright E2E automation, test matrix planning & chaos engineering',\n },\n 'devops-engineering': {\n title: 'DevOps & Delivery Pipeline Team',\n summary: 'CI/CD automation, Docker/K8s, Infrastructure as Code & release engineering',\n },\n 'ai-ml-engineering': {\n title: 'AI & Machine Learning Engineering Team',\n summary: 'Serverless GPU deployment, LLM fine-tuning, RAG vector pipelines & AI safety guardrails',\n },\n 'sysops-sre': {\n title: 'SysOps & Site Reliability Team',\n summary: '99.999% uptime, Prometheus telemetry, incident triage & disaster recovery',\n },\n 'system-architecture': {\n title: 'System Architecture Team',\n summary: 'High-level distributed systems, API schemas, and ADR planning',\n },\n 'product-design': {\n title: 'Product Design Team',\n summary: 'UI/UX designers, design systems architect, and prototyping',\n },\n 'growth-marketing': {\n title: 'Growth & Marketing Team',\n summary: 'Growth strategists, creative visual designer, content pipeline & conversion optimization',\n },\n 'seo-content-marketing': {\n title: 'SEO & Content Marketing Team',\n summary: 'Programmatic SEO, technical SEO audits, content pipeline automation & schema markup',\n },\n 'performance-paid-acquisition': {\n title: 'Performance & Paid Acquisition Team',\n summary: 'Multi-channel PPC (Google/Meta/LinkedIn), ROAS/CAC attribution & ad copy testing',\n },\n 'product-led-growth': {\n title: 'Product-Led Growth Team',\n summary: 'Onboarding CRO, signup funnel optimization, viral referral loops & paywalls',\n },\n 'lifecycle-email-marketing': {\n title: 'Lifecycle & Email Marketing Team',\n summary: 'Automated email drip sequences, churn prevention playbooks & newsletter workflows',\n },\n 'security-operations': {\n title: 'Security Operations Team',\n summary: 'AppSec engineer, threat modeling, and vulnerability audits',\n },\n 'deep-research': {\n title: 'Deep Research Team',\n summary: 'Technical research lead, literature review, and Socratic mentor',\n },\n 'business-strategy': {\n title: 'Business Strategy Team',\n summary: 'Market analysts, monetization experts, and executive spec panels',\n },\n 'digital-agency': {\n title: 'Digital Agency',\n summary: 'Full-service digital product agency with web dev, mobile, design, SEO, and growth marketing',\n },\n 'universal-orchestration': {\n title: 'Universal Orchestration',\n summary: 'Prime Orchestrator front door: routes to the correct department Essentials bundle and hands off',\n },\n 'universal-skills': {\n title: 'Universal Meta-Skills',\n summary: 'Domain-agnostic Socratic grilling, spec generation, handoff, and domain modeling',\n },\n 'design-systems-ops': {\n title: 'Design Systems & Ops Team',\n summary: 'Token governance, component libraries, design handoff & version control workflows',\n },\n 'design-research-testing': {\n title: 'Design Research & Testing Team',\n summary: 'Usability testing, user journey mapping, interactive prototypes & AI prototype refactoring',\n },\n 'full': {\n title: 'All-in-One Autonomous Department',\n summary: 'Complete suite with all 7 team leads, 38 agents, and all 160 modular skills & workflows',\n },\n};\n\ncli\n .command('add [identifier]', 'Add a bundle, agent, skill, or workflow to project or global configuration')\n .option('-g, --global', 'Install globally into home directory (~/.agents/)')\n .option('-s, --symlink', 'Create symbolic links to central registry cache (default / recommended)')\n .option('--copy', 'Create independent standalone copies of asset files')\n .option('-t, --target <hosts>', 'Which assistants to set up (agents = main library; claude, cursor, cline, opencode, codex get translated copies)', { default: 'agents' })\n .option('--fanout <hosts>', 'Also make translated copies for these assistants: claude, cline. Under Development hosts (cursor, opencode, codex) are refused')\n .option('--plugin', 'Claude lane only: also emit the distribution-only plugin package (.agents/plugins/<bundle>/.claude-plugin/plugin.json + agents/) for `claude --plugin-dir`. Adds nothing when --fanout claude is absent; never the behavioural source. Sticky: the opt-in is recorded in the lockfile, so `agents update` keeps it. Use --no-plugin to turn it back off.')\n .option('--mode <mode>', 'Execution mode for organization bundles (operational | brainstorming)', { default: 'operational' })\n .option('--allow-missing-prereqs', 'Proceed with installation even if some prerequisites are missing')\n .option('--allow-under-construction', 'Allow installation of bundles marked as under construction')\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('-f, --force', 'Force overwrite user modified files')\n .option('--start', 'Start the installed team in Cline immediately after setup')\n .option('--dry-run', 'Simulate installation without writing files')\n .action(async (targetIdentifier?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — AI Agent Ecosystem'));\n\n let identifier = targetIdentifier;\n let scope: InstallScope = options.global ? 'global' : 'project';\n let method: InstallMethod = options.copy ? 'copy' : 'symlink';\n let hosts: AgentHost[] = options.target\n ? (Array.isArray(options.target) ? options.target : options.target.split(',')).map(\n (h: string) => h.trim().toLowerCase()\n )\n : ['agents'];\n // Warn + drop unknown host ids instead of silently casting them to a type.\n const unknownHosts = hosts.filter(h => !isKnownHost(h));\n if (unknownHosts.length > 0) {\n note(`Ignoring unknown host id(s): ${unknownHosts.join(', ')}`, 'Invalid target');\n hosts = hosts.filter(isKnownHost);\n if (hosts.length === 0) hosts = ['agents'];\n }\n\n // Turn the target list into a plan: the main library (.agents/) plus translated\n // copies for each assistant that can't read it directly. Never installs\n // untranslated Antigravity frontmatter into another assistant's folder.\n const flagPlan = planInstallTargets(hosts);\n hosts = flagPlan.hosts;\n if (flagPlan.addedCanonicalStore) {\n note(\n 'Added .agents/ — the main library your assistants share.\\n' +\n 'Each assistant you picked gets its own translated copy. Edit only .agents/.',\n 'Main library'\n );\n }\n\n // Parse --fanout like hosts above but validated against HOST_REGISTRY; only\n // projection-capable host ids are honored. Warn + drop invalid ids, never a silent cast.\n let fanout: string[] = flagPlan.fanout;\n if (options.fanout) {\n const rawFanout: string[] = Array.isArray(options.fanout) ? options.fanout : String(options.fanout).split(',');\n const parsedFanout: string[] = rawFanout.map((h: string) => h.trim().toLowerCase());\n const invalidFanout: string[] = parsedFanout.filter(h => !isKnownHost(h) || !HOST_REGISTRY[h].projectionCapable);\n if (invalidFanout.length > 0) {\n note(\n `Ignoring invalid fanout host id(s): ${invalidFanout.join(', ')}. Valid ids: ${KNOWN_HOST_IDS.filter(h => HOST_REGISTRY[h].projectionCapable).join(', ')}`,\n 'Invalid fanout'\n );\n }\n fanout = Array.from(new Set([...fanout, ...parsedFanout.filter(h => isKnownHost(h) && HOST_REGISTRY[h].projectionCapable)]));\n const underDevFanout = Array.from(new Set(parsedFanout.filter((h) => isKnownHost(h) && HOST_REGISTRY[h].status === 'under-development')));\n if (underDevFanout.length > 0) {\n note(\n `Refusing --fanout host(s): ${underDevFanout.join(', ')} — they are listed as Under Development and unavailable. Supported --fanout ids: ${SUPPORTED_HOST_IDS.filter((h) => HOST_REGISTRY[h].projectionCapable).join(', ')}. Drop ${underDevFanout.join(', ')} from --fanout and run again.`,\n 'Host unavailable'\n );\n process.exit(1);\n }\n }\n\n // Interactive Wizard when running interactively without flags\n const isInteractive = process.stdout.isTTY && !options.yes;\n\n if (isInteractive && !options.global && !options.copy && !options.symlink && options.target === 'agents') {\n const detectedHosts = detectWorkspaceHosts();\n if (detectedHosts.length > 0) {\n note(\n detectedHosts.map(h => ` ✔ Detected .${HOST_REGISTRY[h].projectDir === '.' ? '' : '/'}${HOST_REGISTRY[h].projectDir === '.' ? 'AGENTS.md' : HOST_REGISTRY[h].projectDir}`).join('\\n'),\n 'Workspace Environment Discovery'\n );\n }\n\n // Step 1: Which AI tools should we configure agent teams & personas for?\n // The master library (.agents/) is always included when another tool is\n // chosen — it is the single source every translated copy is generated from.\n // Availability: only supported hosts are selectable here; the 🚧 Under\n // Development and 🗓 Planned hosts are listed in the availability note.\n note(hostAvailabilityNotice(), 'Host availability');\n const hostSelection = await multiselect({\n message: '1. Which AI tools should we configure agent teams & personas for?',\n options: [\n {\n value: 'agents',\n label: HOST_REGISTRY.agents.label,\n hint: detectedHosts.includes('agents') ? 'found in this project' : 'the master library where all skills & agents live — always included',\n },\n {\n value: 'claude',\n label: HOST_REGISTRY.claude.label,\n hint: detectedHosts.includes('claude') ? 'found in this project' : 'orchestrator & subagent personas for Claude Code',\n },\n {\n value: 'cline',\n label: HOST_REGISTRY.cline.label,\n hint: detectedHosts.includes('cline') ? 'found in this project' : 'configured agents, skills, rules, workflows & team manifests for Cline',\n },\n {\n value: 'gemini',\n label: HOST_REGISTRY.gemini.label,\n hint: detectedHosts.includes('gemini') ? 'found in this project' : 'older Antigravity 1.0 / Gemini folder',\n },\n ],\n initialValues: detectedHosts.length > 0 ? detectedHosts.filter((h) => HOST_REGISTRY[h]?.status === 'supported') : ['agents'],\n required: true,\n });\n\n if (Array.isArray(hostSelection) && hostSelection.length > 0) {\n const wizardPlan = planInstallTargets(hostSelection as string[]);\n hosts = wizardPlan.hosts;\n // Merge with any explicitly-passed --fanout rather than discarding it.\n fanout = Array.from(new Set([...fanout, ...wizardPlan.fanout]));\n if (wizardPlan.addedCanonicalStore) {\n note(\n 'Added .agents/ — the master repository library your tools share.\\n' +\n 'Each tool you selected gets its own orchestrators and subagents. Edit only .agents/.',\n 'Master library'\n );\n }\n }\n\n // Step 2: Scope Selection with Clear Guidance\n const scopeSelection = await select({\n message: '2. Select Installation Scope:',\n options: [\n {\n value: 'project',\n label: 'Project Scope (Recommended)',\n hint: 'Workspace directory; tracked in Git & shared with team via lockfile',\n },\n {\n value: 'global',\n label: 'Global Scope (-g / --global)',\n hint: 'User home directory (~/.agents/); available across all workspaces on machine',\n },\n ],\n });\n\n if (typeof scopeSelection === 'string') {\n scope = scopeSelection as InstallScope;\n }\n\n // Step 3: Installation Method\n const methodSelection = await select({\n message: '3. Select Installation Method:',\n options: [\n {\n value: 'symlink',\n label: 'Symlink Mode (Recommended)',\n hint: 'Single source of truth; package updates reflect instantly',\n },\n {\n value: 'copy',\n label: 'Copy Mode',\n hint: 'Independent standalone files; supports offline isolated modifications',\n },\n ],\n });\n\n if (typeof methodSelection === 'string') {\n method = methodSelection as InstallMethod;\n }\n }\n\n // Step 4: Two-Stage Hierarchical Department & Bundle Selection\n if (!identifier) {\n const bundles = await registry.listBundles();\n\n const domainMeta: Record<string, { label: string; icon: string }> = {\n universal: { label: 'Universal Autonomous Department', icon: '🌐 ' },\n engineering: { label: 'Software Engineering & Delivery', icon: '🛠️ ' },\n architecture: { label: 'System Architecture & SRE', icon: '🏛️ ' },\n design: { label: 'Product Design & UI/UX', icon: '🎨 ' },\n marketing: { label: 'Growth & Marketing Operations', icon: '📈 ' },\n security: { label: 'Security Operations', icon: '🔒 ' },\n research: { label: 'Deep Technical Research', icon: '🔬 ' },\n business: { label: 'Business Strategy & Economics', icon: '💼 ' },\n organization: { label: 'Organization Bundles (Experimental / Cross-Functional)', icon: '🏢 ' },\n };\n\n let selectedBundle: string | undefined;\n\n while (!selectedBundle) {\n // Stage 4a: Department Domain Selection\n const domainOptions = Object.entries(domainMeta).map(([domainKey, meta]) => {\n const count = bundles.filter(b => (b.domain === domainKey || (domainKey === 'organization' && b.tier === 'organization'))).length;\n return {\n value: domainKey,\n label: `${meta.icon} ${meta.label}`,\n hint: domainKey === 'universal' ? 'meta-skills baseline + full suite' : domainKey === 'organization' ? 'cross-functional teams with prerequisites' : `${count} specialized team${count > 1 ? 's' : ''}`,\n };\n });\n\n domainOptions.push({\n value: '__search__',\n label: '🔍 Search by name / keyword...',\n hint: 'custom keyword search',\n });\n\n const selectedDomain = await select({\n message: '4. Select Department Domain / Category:',\n options: domainOptions,\n });\n\n if (typeof selectedDomain !== 'string') {\n outro(pc.yellow('Installation cancelled.'));\n return;\n }\n\n if (selectedDomain === '__search__') {\n const searchQuery = await text({\n message: 'Enter keyword to search:',\n placeholder: 'e.g. mobile, playwright, react, backend, agency',\n });\n\n if (typeof searchQuery !== 'string' || !searchQuery.trim()) {\n continue;\n }\n\n const searchResults = await registry.find(searchQuery.trim());\n const matchOptions: Array<{ value: string; label: string; hint?: string }> = [\n ...searchResults.bundles.map((b: BundleDefinition) => ({\n value: b.name,\n label: `[Bundle] ${BUNDLE_DISPLAY_NAMES[b.name]?.title || b.name} (${b.name})`,\n hint: b.description,\n })),\n ...searchResults.agents.map((a: string) => ({\n value: a.replace(/\\.md$/, ''),\n label: `[Agent] ${a}`,\n hint: 'autonomous agent',\n })),\n ...searchResults.skills.map((s: string) => ({\n value: s,\n label: `[Skill] ${s}`,\n hint: 'specialized skill',\n })),\n ...searchResults.workflows.map((w: string) => ({\n value: w.replace(/\\.md$/, ''),\n label: `[Workflow] ${w}`,\n hint: 'guided workflow',\n })),\n {\n value: '__back__',\n label: '🔙 Back to Department Selection',\n hint: '',\n },\n ];\n\n if (matchOptions.length === 1) {\n note(`No items found matching \"${searchQuery}\".`, 'Search Results');\n continue;\n }\n\n const chosenMatch = await select({\n message: `Search Results for \"${searchQuery}\":`,\n options: matchOptions,\n });\n\n if (typeof chosenMatch === 'string' && chosenMatch !== '__back__') {\n selectedBundle = chosenMatch;\n break;\n }\n continue;\n }\n\n const domainBundles = bundles.filter(b => b.domain === selectedDomain || (selectedDomain === 'organization' && b.tier === 'organization'));\n\n // Stage 4b: Sub-Team Selection inside Selected Domain\n const subTeamOptions: Array<{ value: string; label: string; hint?: string }> = [];\n\n // Option to install entire department if multiple bundles exist (exclude organization and universal)\n if (domainBundles.length > 1 && selectedDomain !== 'organization' && selectedDomain !== 'universal') {\n subTeamOptions.push({\n value: `__all_domain__:${selectedDomain}`,\n label: `🌟 Install Entire ${domainMeta[selectedDomain]?.label || selectedDomain} (${domainBundles.length} Bundles)`,\n hint: 'installs all sub-teams under this department',\n });\n }\n\n // Sort so Essentials/universal-skills are always at the top\n const sortedBundles = [...domainBundles].sort((a, b) => {\n if (a.name === 'universal-orchestration') return -1;\n if (b.name === 'universal-orchestration') return 1;\n if (a.name === 'universal-skills') return -1;\n if (b.name === 'universal-skills') return 1;\n if (!a.parentBundle && b.parentBundle) return -1;\n if (a.parentBundle && !b.parentBundle) return 1;\n return a.name.localeCompare(b.name);\n });\n\n sortedBundles.forEach((b, idx) => {\n const isLast = idx === sortedBundles.length - 1;\n const branch = sortedBundles.length > 1 ? (isLast ? '└── ' : '├── ') : '';\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n const isEssentials = !b.parentBundle && b.name !== 'full' && b.tier !== 'organization' && b.name !== 'universal-skills' && b.name !== 'universal-orchestration';\n const title = meta ? meta.title : b.name;\n\n let statusBadge = '';\n if (b.name === 'universal-skills') statusBadge = pc.green(' ⭐ [Recommended Baseline]');\n else if (b.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction]');\n else if (b.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n\n const labelText = isEssentials ? `Essentials: ${title}${statusBadge}` : `${title}${statusBadge}`;\n const summary = meta ? meta.summary : b.description;\n subTeamOptions.push({\n value: b.name,\n label: `${branch}📦 ${labelText} (${b.name})`,\n hint: summary,\n });\n });\n\n subTeamOptions.push({\n value: '__back__',\n label: '🔙 Back to Department Selection',\n hint: '',\n });\n\n const chosenSubTeam = await select({\n message: `Select Package / Team Bundle to install in ${domainMeta[selectedDomain]?.label || selectedDomain}:`,\n options: subTeamOptions,\n });\n\n if (typeof chosenSubTeam !== 'string') {\n outro(pc.yellow('Installation cancelled.'));\n return;\n }\n\n if (chosenSubTeam === '__back__') {\n continue;\n }\n\n if (chosenSubTeam.startsWith('__all_domain__:')) {\n const dName = chosenSubTeam.replace('__all_domain__:', '');\n const dTitle = domainMeta[dName]?.label || dName;\n const proceed = await confirm({\n message: `⚠️ You are about to install ALL ${domainBundles.length} sub-teams under \"${dTitle}\". Proceed?`,\n initialValue: true,\n });\n\n if (!proceed || typeof proceed !== 'boolean') {\n continue;\n }\n\n selectedBundle = `domain:${dName}`;\n break;\n }\n\n selectedBundle = chosenSubTeam;\n break;\n }\n\n identifier = selectedBundle;\n }\n\n if (!identifier) {\n outro(pc.yellow('No package specified.'));\n return;\n }\n\n const targetBundleDef = await registry.getBundle(identifier);\n\n // 1. Under Construction Gate Evaluation\n if (targetBundleDef && targetBundleDef.status === 'under-construction') {\n if (isInteractive) {\n note(\n `The bundle \"${targetBundleDef.name}\" is currently under active construction (status: under-construction).\\n` +\n `Its orchestrators, workflows, and specialized skills are being authored and are not ready for production use.\\n\\n` +\n `Planned Capabilities:\\n` +\n `• Lead Orchestrator with Firecrawl & GitHub MCP tool calling\\n` +\n `• Full-stack web, design & SEO delivery workflows\\n` +\n `• Dual Execution Modes (Operational / Brainstorming)`,\n '🚧 Under Construction Gate'\n );\n\n const underConstructionChoice = await select({\n message: pc.yellow(`\"${targetBundleDef.name}\" is currently under construction. How would you like to proceed?`),\n options: [\n {\n value: 'abort',\n label: '🛑 Abort installation (Recommended)',\n hint: 'return without modifying workspace files',\n },\n {\n value: 'allow',\n label: '⚠️ Install in-development draft anyway (--allow-under-construction)',\n hint: 'proceed with in-progress placeholder assets',\n },\n ],\n });\n\n if (underConstructionChoice === 'abort' || typeof underConstructionChoice !== 'string') {\n outro(pc.yellow(`Installation cancelled. \"${targetBundleDef.name}\" is under construction.`));\n return;\n }\n } else {\n // Headless / Non-interactive\n if (!options.allowUnderConstruction && !options.force) {\n outro(\n pc.red(\n `Error: Cannot install \"${targetBundleDef.name}\" — this bundle is currently under construction.\\n` +\n `To bypass this gate and install draft assets anyway, pass: --allow-under-construction or --force`\n )\n );\n process.exit(1);\n }\n }\n }\n\n // 2. Prerequisite Gate Evaluation & Informative Visibility\n let executionMode: ExecutionMode = (options.mode as ExecutionMode) || 'operational';\n\n if (targetBundleDef && (targetBundleDef.prerequisites || targetBundleDef.tier === 'organization')) {\n const checker = new PrerequisiteChecker();\n const prereqEval = await checker.evaluate(targetBundleDef, { cwd: process.cwd(), targetHosts: hosts });\n\n if (prereqEval.hasPrerequisites) {\n const checkLines: string[] = [];\n for (const item of prereqEval.items) {\n const typeLabel = item.type === 'mcp' ? 'MCP' : item.type === 'env' ? 'Env' : 'Pkg';\n let icon = pc.green('✓');\n let statusText = pc.green('Detected');\n if (!item.satisfied) {\n if (item.status === 'partial') {\n icon = pc.yellow('~');\n statusText = pc.yellow('Partial');\n } else {\n icon = pc.red('✗');\n statusText = pc.red('Missing');\n }\n }\n const details = pc.dim(`(${item.details || ''})`);\n checkLines.push(` ${icon} [${typeLabel}] ${pc.bold(item.name)}: ${statusText} ${details}`);\n }\n\n note(\n checkLines.join('\\n'),\n `Prerequisite Evaluation: ${targetBundleDef.name} (${targetBundleDef.tier === 'organization' ? 'Organization Bundle' : 'Prerequisites Required'})`\n );\n\n if (prereqEval.allSatisfied) {\n executionMode = (options.mode as ExecutionMode) || 'operational';\n note(pc.green('All prerequisites are satisfied! Running in Fully Operational Mode.'), 'Prerequisites Ready');\n } else {\n executionMode = (options.mode as ExecutionMode) || 'limited-operational';\n note(\n pc.cyan(\n '⚡ Adaptive Tooling: Limited Operational / Brainstorming Mode ready.\\n' +\n 'Your Lead Orchestrator will automatically detect active tools and guide in-session configuration seamlessly.'\n ),\n 'Operational Envelope'\n );\n }\n }\n }\n\n const s = spinner();\n s.start(`Resolving \"${identifier}\"...`);\n\n try {\n const result = await installer.install(identifier, {\n scope,\n method,\n hosts,\n fanout,\n // Plan 016 decision 13 — opt-in Claude plugin lane (distribution-only; ignored unless the\n // claude lane runs). `--plugin` opts in, `--no-plugin` opts out explicitly, and an omitted\n // flag inherits the recorded choice so `agents update` cannot prune the package.\n pluginLane: typeof options.plugin === 'boolean' ? options.plugin : undefined,\n mode: executionMode,\n allowMissingPrereqs: options.allowMissingPrereqs,\n yes: options.yes,\n force: options.force,\n dryRun: options.dryRun,\n });\n\n s.stop(`Resolved assets for \"${identifier}\"`);\n\n if (options.dryRun) {\n outro(pc.yellow(`[DRY RUN] Would install ${result.installed.agents.length} agents, ${result.installed.skills.length} skills to ${result.targetDirs.join(', ')}`));\n if (result.projections.length > 0) {\n note(renderProjections(result.projections), 'Projection Plan (dry run)');\n }\n if (options.start && result.projections.some(p => p.host === 'cline')) {\n const bundleName = result.installed.targetBundle || identifier;\n note(`Would start Cline team for bundle \"${bundleName}\".`, 'Start in Cline (dry run)');\n }\n return;\n }\n\n note(\n formatInstallationSummary({\n bundleName: result.installed.targetBundle || 'Single Item',\n scope,\n method: result.method,\n hosts,\n agents: result.installed.agents,\n skills: result.installed.skills,\n targetDirs: result.targetDirs,\n projections: result.projections,\n }),\n 'Installation Success'\n );\n\n if (result.projections.length > 0) {\n note(renderProjections(result.projections), 'Installed Projections');\n }\n\n const hasClineProjection = result.projections.some(p => p.host === 'cline');\n\n if (hasClineProjection && !options.dryRun) {\n note(\n pc.green(\n `Already active: any Cline session in this workspace now sees this bundle's\\n` +\n `skills, subagent_* agent tools, rules & workflow commands (ADR 0013 native discovery).`\n ),\n 'Native Activation'\n );\n }\n\n if (options.start && !hasClineProjection) {\n throw new Error('--start requires Cline projection. Add -t cline or --fanout cline.');\n }\n\n if (hasClineProjection) {\n const bundleName = result.installed.targetBundle || identifier;\n if (options.start) {\n if (options.dryRun) {\n note(`Would start Cline team for bundle \"${bundleName}\".`, 'Start in Cline (dry run)');\n } else {\n note(`Launching Cline team for \"${bundleName}\"...`, 'Starting Cline');\n const launcher = new ClineLauncher();\n const probe = new ClineCapabilityProbe();\n const probeReport = await probe.probe();\n if (probeReport.installed) {\n const targetBundleDef = await registry.getBundle(bundleName!);\n const plan = launcher.planActivation({\n bundleName: bundleName!,\n workspace: process.cwd(),\n scope,\n report: probeReport,\n orchestrator: targetBundleDef?.orchestrator,\n });\n await launcher.launch(plan);\n } else {\n note(pc.yellow('Cline executable not detected. Install Cline CLI to run: agents start ' + bundleName), 'Cline Not Found');\n }\n }\n } else if (isInteractive && !options.dryRun) {\n const startChoice = await select({\n message: `Start the ${bundleName} team in Cline now?`,\n options: [\n { value: 'start', label: '🚀 Start in Cline' },\n { value: 'copy', label: `📋 Copy command (agents start ${bundleName})` },\n { value: 'later', label: '⏳ Later' },\n ],\n });\n\n if (startChoice === 'start') {\n const launcher = new ClineLauncher();\n const probe = new ClineCapabilityProbe();\n const probeReport = await probe.probe();\n if (probeReport.installed) {\n const targetBundleDef = await registry.getBundle(bundleName!);\n const plan = launcher.planActivation({\n bundleName: bundleName!,\n workspace: process.cwd(),\n scope,\n report: probeReport,\n orchestrator: targetBundleDef?.orchestrator,\n });\n await launcher.launch(plan);\n } else {\n note(pc.yellow('Cline executable not detected. Install Cline CLI to run: agents start ' + bundleName), 'Cline Not Found');\n }\n } else if (startChoice === 'copy') {\n note(`Run 'agents start ${bundleName}' to launch the team in Cline anytime.`, 'Start Command');\n }\n } else if (!options.dryRun) {\n note(pc.cyan(`Tip: Run 'agents start ${bundleName}' to launch the team in Cline.`), 'Start in Cline');\n }\n }\n\n // Plain-language tip when the main library is the only thing installed and no\n // translated copies were requested — sets the right expectation up front.\n // ADR 0013: Cline natively discovers skills from .agents/skills/, so the old\n // \"only Antigravity reads the main library\" claim is no longer accurate.\n if (!options.dryRun && hosts.includes('agents') && result.projections.length === 0) {\n note(\n pc.yellow(\n `Tip: Antigravity reads the main library (.agents/) directly, and Cline natively\\n` +\n `discovers skills from .agents/skills/ (ADR 0013). For Cline configured agents,\\n` +\n `rules & workflows run: agents update ${identifier} --fanout cline\\n` +\n `(add claude, cursor, opencode, codex for other assistants)`\n ),\n 'One library, every assistant'\n );\n }\n\n if (!options.dryRun && targetBundleDef?.tier === 'organization') {\n note(\n pc.cyan(\n '💡 In-Session MCP Setup: Your Lead Orchestrator will automatically check\\n' +\n 'your runtime tools and guide configuration of live browser automation,\\n' +\n 'design tokens, or cloud APIs on demand.'\n ),\n 'Adaptive Tooling'\n );\n }\n\n // Owner Gate-7 finding (2026-09-25): hosts discover skills at session start, so tell the\n // operator how THIS session can pick up what was just installed (docs/host-skill-reload.md).\n if (!options.dryRun) {\n note(\n pc.yellow(\n 'New skills are discovered at session start. To pick them up now:\\n' +\n ' Claude Code ..... user types /reload-skills (#58733)\\n' +\n ' Antigravity CLI . user types /skills reload\\n' +\n ' Antigravity App . restart the app, or use @<skill_name>\\n' +\n ' Cline ........... agents read .cline/skills/ directly\\n' +\n 'Slash commands only fire when YOU type them; agents can read the file.'\n ),\n 'Pick up new skills'\n );\n }\n\n outro(pc.green(`✔ Installed \"${identifier}\" successfully!`));\n } catch (err: any) {\n s.stop(pc.red('Failed resolution'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('remove [identifier]', 'Remove an installed bundle, agent, skill, or workflow')\n .alias('uninstall')\n .option('-g, --global', 'Uninstall from global home directory')\n .option('-t, --target <hosts>', 'Target agent host runtimes', { default: 'agents' })\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('-f, --force', 'Force removal of modified files')\n .option('--dry-run', 'Simulate removal without unlinking files')\n .action(async (targetIdentifier?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — Remove Package'));\n\n let identifier = targetIdentifier;\n let selectedRecord: InstalledPackageRecord | undefined;\n const isInteractive = process.stdout.isTTY && !options.yes;\n\n if (!identifier) {\n const inventory = await scanner.scan({\n global: options.global,\n target: options.target,\n });\n\n if (inventory.records.length === 0) {\n outro(pc.yellow('No installed packages found in project or global configuration.'));\n return;\n }\n\n if (!isInteractive) {\n outro(pc.red('Package identifier required in non-interactive mode. Usage: agents remove <identifier>'));\n return;\n }\n\n const itemOptions = inventory.records.map(record => {\n const meta = BUNDLE_DISPLAY_NAMES[record.name];\n const title = meta?.title || record.title || record.name;\n const icon = record.type === 'bundle' ? '📦' : record.type === 'skill' ? '⚡' : '🤖';\n const typeLabel = record.type !== 'bundle' ? `[${record.type}] ` : '';\n const badge = pc.cyan(record.displayLocation);\n const versionTag = pc.dim(`(v${record.installedVersion})`);\n\n return {\n value: record.id,\n label: `${icon} ${typeLabel}${title} ${badge} ${versionTag}`,\n hint: `${record.fileCount} file${record.fileCount > 1 ? 's' : ''} — ${record.description || record.name}`,\n };\n });\n\n const selectedId = await select({\n message: 'Select an installed package to remove:',\n options: itemOptions,\n });\n\n if (typeof selectedId !== 'string') {\n outro(pc.yellow('Removal cancelled.'));\n return;\n }\n\n selectedRecord = inventory.records.find(r => r.id === selectedId);\n if (selectedRecord) {\n identifier = selectedRecord.name;\n } else {\n identifier = selectedId;\n }\n }\n\n const s = spinner();\n s.start(`Removing \"${identifier}\"...`);\n\n try {\n const result = await uninstaller.uninstall(identifier, {\n scope: selectedRecord?.scope || (options.global ? 'global' : 'project'),\n global: options.global,\n target: selectedRecord ? [selectedRecord.host] : options.target,\n targetDir: selectedRecord?.targetDir,\n yes: options.yes,\n force: options.force,\n dryRun: options.dryRun,\n });\n\n s.stop(`Uninstall processed`);\n\n if (options.dryRun) {\n outro(pc.yellow(\n `[DRY RUN] Would delete ${result.removed.length} and keep ${result.kept.length}` +\n (result.kept.length > 0 ? ` (still owned by: ${result.retainedOwners.join(', ')})` : '') +\n ` — ${result.targetDirs.join(', ')}`\n ));\n return;\n }\n\n // Honest accounting. `removed` counts only files that actually left the disk; when the\n // identifier's assets are co-owned, most or all of them survive for their other owners. The\n // old \"Successfully removed 84 files\" told the operator content vanished that did not — and\n // never said WHAT was deleted, so a bundle package quietly disappearing under\n // `.agents/plugins/` looked like nothing happened at all.\n if (result.kept.length > 0) {\n log.info(`${result.removed.length} deleted · ${result.kept.length} kept — still owned by: ${result.retainedOwners.join(', ')}`);\n }\n if (result.removed.length > 0) {\n const sample = result.removed.slice(0, 3).join(', ');\n const more = result.removed.length > 3 ? `, … +${result.removed.length - 3} more` : '';\n log.info(`deleted: ${sample}${more}`);\n }\n if (result.staleRecords.length > 0) {\n log.info(`${result.staleRecords.length} stale record(s) cleaned — bookkeeping only, those files were already gone`);\n }\n outro(pc.green(\n result.removed.length === 0 && result.kept.length > 0\n ? `✔ Removed \"${identifier}\" from this workspace — nothing was deleted, ${result.kept.length} co-owned assets kept`\n : `✔ Removed \"${identifier}\" from this workspace — ${result.removed.length} deleted, ${result.kept.length} kept`\n ));\n } catch (err: any) {\n s.stop(pc.red('Uninstall failed'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('update [identifier]', 'Update installed packages to upstream registry versions')\n .alias('upgrade')\n .option('-g, --global', 'Update global packages in home directory')\n .option('-t, --target <hosts>', 'Target agent host runtimes')\n .option('--fanout <hosts>', 'Also project the canonical .agents/ store into these runtimes during update (claude, cursor, cline, opencode, codex)')\n .option('-a, --all', 'Update all installed packages without prompting')\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('-f, --force', 'Force overwrite user modified files')\n .option('--start', 'Start the updated team in Cline immediately after update')\n .option('--dry-run', 'Simulate update without writing files')\n .action(async (targetIdentifier?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — Package Update Engine'));\n\n // Parse --fanout like the add command: validated against the registry,\n // unknown/non-projection-capable ids are dropped with a warning.\n let updateFanout: string[] | undefined;\n if (options.fanout !== undefined) {\n const rawFanout: string[] = Array.isArray(options.fanout) ? options.fanout : String(options.fanout).split(',');\n const parsedFanout: string[] = rawFanout.map((h: string) => h.trim().toLowerCase()).filter(Boolean);\n const invalidFanout: string[] = parsedFanout.filter(h => !isKnownHost(h) || !HOST_REGISTRY[h].projectionCapable);\n if (invalidFanout.length > 0) {\n note(\n pc.yellow(\n `Ignoring invalid fanout host id(s): ${invalidFanout.join(', ')}. Valid ids: ${KNOWN_HOST_IDS.filter(h => HOST_REGISTRY[h].projectionCapable).join(', ')}`\n ),\n 'Invalid fanout'\n );\n }\n const updateUnderDev = Array.from(new Set(parsedFanout.filter((h) => isKnownHost(h) && HOST_REGISTRY[h].status === 'under-development')));\n if (updateUnderDev.length > 0) {\n note(\n pc.yellow(\n `Refusing --fanout host(s): ${updateUnderDev.join(', ')} — they are listed as Under Development and unavailable. Supported --fanout ids: ${SUPPORTED_HOST_IDS.filter((h) => HOST_REGISTRY[h].projectionCapable).join(', ')}. Drop ${updateUnderDev.join(', ')} from --fanout and run again.`\n ),\n 'Host unavailable'\n );\n process.exit(1);\n }\n updateFanout = parsedFanout.filter(h => isKnownHost(h) && HOST_REGISTRY[h].projectionCapable);\n }\n\n const s = spinner();\n s.start('Checking installed package inventory & upstream drift...');\n\n const report = await updater.checkUpdates({\n global: options.global,\n target: options.target,\n });\n\n s.stop('Inventory discovery complete');\n\n if (report.totalCount === 0) {\n outro(pc.yellow('No installed packages found in project or global configuration.'));\n return;\n }\n\n const isInteractive = process.stdout.isTTY && !options.yes && !options.all;\n let targetsToUpdate: string[] | '__all__' = [];\n\n if (targetIdentifier) {\n targetsToUpdate = [targetIdentifier];\n } else if (options.all || options.yes || !isInteractive) {\n targetsToUpdate = '__all__';\n } else {\n // Interactive Mode\n const locationLines: string[] = [];\n if (report.scannedLocations && report.scannedLocations.length > 0) {\n for (const loc of report.scannedLocations) {\n const scopeLabel = loc.scope === 'project' ? 'Project' : 'Global';\n const fanoutStr = loc.fanout.length > 0 ? ` ${pc.magenta(`(projections: ${loc.fanout.join(', ')})`)}` : '';\n locationLines.push(` • ${scopeLabel} (${loc.displayLocation}): ${pc.bold(loc.packageCount)} package${loc.packageCount !== 1 ? 's' : ''}${fanoutStr}`);\n }\n } else {\n const projectCount = report.items.filter(i => i.record.scope === 'project').length;\n const globalCount = report.items.filter(i => i.record.scope === 'global').length;\n if (!options.global) {\n locationLines.push(` • Project (./.agents): ${pc.bold(projectCount)} package${projectCount !== 1 ? 's' : ''}`);\n }\n locationLines.push(` • Global (~/.agents): ${pc.bold(globalCount)} package${globalCount !== 1 ? 's' : ''}`);\n }\n\n const allDetectedFanouts = Array.from(new Set(report.items.flatMap(i => i.record.fanout || [])));\n const fanoutSummary = allDetectedFanouts.length > 0\n ? `\\nActive Projections: ${allDetectedFanouts.map(h => `${pc.cyan(h)} (./.${h}/)`).join(', ')}`\n : '';\n\n const statusMessage =\n `Locations Checked:\\n${locationLines.join('\\n')}${fanoutSummary}\\n\\n` +\n `Total Installed Packages: ${report.totalCount}\\n` +\n `Updates Available: ${report.outdatedCount > 0 ? pc.yellow(pc.bold(`${report.outdatedCount} package${report.outdatedCount > 1 ? 's' : ''} can be updated`)) : pc.green('0 (All up to date)')}`;\n\n note(statusMessage, 'Inventory Status');\n\n const menuOptions: Array<{ value: string; label: string; hint?: string }> = [];\n\n if (report.outdatedCount > 0) {\n menuOptions.push({\n value: '__all_outdated__',\n label: `⚡ Update All Outdated Packages (${report.outdatedCount} available)`,\n hint: 'batch upgrade all packages with newer upstream versions',\n });\n }\n\n menuOptions.push({\n value: '__selective__',\n label: '📦 Selectively Pick Packages to Update',\n hint: 'choose specific bundles or items from an interactive list',\n });\n\n menuOptions.push({\n value: '__resync_all__',\n label: `🔄 Re-sync / Repair All Packages (${report.totalCount})`,\n hint: 're-link or re-copy all packages to guarantee full integrity',\n });\n\n const action = await select({\n message: 'Select update action:',\n options: menuOptions,\n });\n\n if (typeof action !== 'string') {\n outro(pc.yellow('Update cancelled.'));\n return;\n }\n\n if (action === '__all_outdated__') {\n targetsToUpdate = report.items.filter(i => i.hasUpdate).map(i => i.record.name);\n } else if (action === '__resync_all__') {\n targetsToUpdate = '__all__';\n } else if (action === '__selective__') {\n const itemOptions = report.items.map(item => {\n const meta = BUNDLE_DISPLAY_NAMES[item.record.name];\n const title = meta?.title || item.record.title || item.record.name;\n const badge = pc.cyan(item.record.displayLocation);\n const versionDiff = item.hasUpdate\n ? pc.yellow(`(v${item.installedVersion} → v${item.upstreamVersion}) [UPDATE]`)\n : pc.dim(`(v${item.installedVersion}) [UP TO DATE]`);\n\n return {\n value: item.record.name,\n label: `📦 ${title} ${badge} ${versionDiff}`,\n hint: item.record.description || item.record.name,\n };\n });\n\n const initialValues = report.items.filter(i => i.hasUpdate).map(i => i.record.name);\n\n const selection = await multiselect({\n message: 'Select packages to update:',\n options: itemOptions,\n initialValues: initialValues.length > 0 ? initialValues : undefined,\n required: true,\n });\n\n if (!Array.isArray(selection) || selection.length === 0) {\n outro(pc.yellow('No packages selected for update.'));\n return;\n }\n\n targetsToUpdate = selection as string[];\n }\n }\n\n const updateSpinner = spinner();\n updateSpinner.start('Updating packages...');\n\n try {\n const result = await updater.update(targetsToUpdate, {\n global: options.global,\n target: options.target,\n force: options.force,\n dryRun: options.dryRun,\n fanout: updateFanout,\n });\n\n updateSpinner.stop('Update completed');\n\n if (options.dryRun) {\n outro(pc.yellow(`[DRY RUN] Would update ${result.updated.length} packages in ${result.targetDirs.join(', ')}`));\n if (result.projections && result.projections.length > 0) {\n note(renderProjections(result.projections), 'Projection Plan (dry run)');\n }\n return;\n }\n\n if (result.updated.length > 0) {\n // Plain-language sync tip for any updated bundle still living only in .agents/.\n const unprojected: string[] = [];\n for (const rec of result.updated) {\n try {\n const lf = await fs.readJson(path.join(rec.targetDir, 'agents-united.json'));\n if (!lf.fanout || lf.fanout.length === 0) unprojected.push(rec.name);\n } catch { /* ignore */ }\n }\n if (unprojected.length > 0) {\n note(\n pc.yellow(\n `Tip: not fully synced to other assistants yet (Antigravity reads .agents/ directly; Cline natively discovers .agents/skills/).\\n` +\n `For Cline configured agents, rules & workflows: agents update ${unprojected[0]} --fanout cline`\n ),\n 'One library, every assistant'\n );\n }\n const updatedList = result.updated\n .map(u => ` ✔ ${pc.bold(u.name)} ${pc.cyan(u.displayLocation)} ${pc.green(`(v${u.installedVersion})`)}`)\n .join('\\n');\n note(updatedList, 'Updated Packages');\n\n if (result.projections && result.projections.length > 0) {\n note(renderProjections(result.projections), 'Updated Projections');\n }\n }\n\n\n if (result.skipped.length > 0) {\n const skippedList = result.skipped\n .map(s => ` ⚠ ${pc.yellow(s.record.name)}: ${s.reason}`)\n .join('\\n');\n note(skippedList, 'Skipped Packages (User Modifications)');\n }\n\n if (result.updated.length === 0 && result.skipped.length === 0) {\n outro(pc.yellow('All packages are already up to date.'));\n } else {\n outro(pc.green(`✔ Successfully processed update for ${result.updated.length} package${result.updated.length > 1 ? 's' : ''}!`));\n }\n } catch (err: any) {\n updateSpinner.stop(pc.red('Update failed'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\nfunction renderBundleDetailTree(bundle: BundleDefinition): string {\n // Special-case full universal suite for clean, structured high-level breakdown\n if (bundle.name === 'full') {\n const lines: string[] = [];\n lines.push(`📦 ${pc.bold(pc.green('full'))} ${pc.cyan('(Universal Autonomous Department)')} ${pc.green('⭐ [Recommended]')}`);\n lines.push(`│ ${pc.white('Complete suite with all 7 lead orchestrators, 38 subagents, and 160 modular skills (91 domain skills + 69 workflow playbooks).')}`);\n lines.push(`│`);\n lines.push(`├── 🤖 Lead Orchestrators (7 department domains):`);\n lines.push(`│ ├── 🛠️ ${pc.blue('orchestrator-engineering')} ${pc.dim('(Software Engineering & Delivery)')}`);\n lines.push(`│ ├── 🏛️ ${pc.blue('orchestrator-system-architecture')} ${pc.dim('(System Architecture & SRE)')}`);\n lines.push(`│ ├── 🎨 ${pc.blue('orchestrator-design')} ${pc.dim('(Product Design & UI/UX)')}`);\n lines.push(`│ ├── 📈 ${pc.blue('orchestrator-marketing')} ${pc.dim('(Growth & Marketing Operations)')}`);\n lines.push(`│ ├── 🔒 ${pc.blue('orchestrator-security')} ${pc.dim('(Security Operations)')}`);\n lines.push(`│ ├── 🔬 ${pc.blue('orchestrator-research')} ${pc.dim('(Deep Technical Research)')}`);\n lines.push(`│ └── 💼 ${pc.blue('orchestrator-business')} ${pc.dim('(Business Strategy & Economics)')}`);\n lines.push(`├── 🤖 Specialized Sub-Agents: ${pc.blue('38 worker agents across all 8 departments')}`);\n lines.push(`├── ⚡ Skills: ${pc.yellow('91 modular domain skills & runbooks')}`);\n lines.push(`├── 🔄 Workflows: ${pc.magenta('69 guided multi-step workflow playbooks')}`);\n lines.push(`├── 🔌 Prerequisites: ${pc.dim('None (Self-contained universal suite)')}`);\n lines.push(`└── 💡 Execution Modes: ${pc.green('Operational')}`);\n return lines.join('\\n');\n }\n\n const meta = BUNDLE_DISPLAY_NAMES[bundle.name];\n const isEssentials = !bundle.parentBundle && bundle.name !== 'full' && bundle.name !== 'universal-skills' && bundle.name !== 'universal-orchestration' && bundle.tier !== 'organization';\n const titleSuffix = isEssentials ? pc.cyan(' (Essentials Base)') : '';\n const parentTag = bundle.parentBundle ? pc.gray(` [inherits: ${bundle.parentBundle}]`) : '';\n const aliasesTag = bundle.aliases && bundle.aliases.length > 0 ? pc.gray(` [alias: ${bundle.aliases.join(', ')}]`) : '';\n\n let statusBadge = '';\n if (bundle.name === 'universal-skills') statusBadge = pc.green(' ⭐ [Recommended]');\n else if (bundle.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction]');\n else if (bundle.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (bundle.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (bundle.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n else statusBadge = pc.green(' [Stable]');\n\n const lines: string[] = [];\n lines.push(`📦 ${pc.bold(pc.green(bundle.name))}${titleSuffix}${statusBadge}${parentTag}${aliasesTag}`);\n lines.push(`│ ${pc.white(bundle.description || meta?.summary || '')}`);\n lines.push(`│`);\n\n // Lead / Orchestrator\n if (bundle.orchestrator) {\n const orchName = bundle.orchestrator.replace(/\\.md$/, '');\n lines.push(`├── 🤖 Lead: ${pc.blue(pc.bold(orchName))}`);\n } else {\n lines.push(`├── 🤖 Lead: ${pc.dim('None (Self-directed meta-skills)')}`);\n }\n\n // Subagents\n if (bundle.agents && bundle.agents.length > 0) {\n const subNames = bundle.agents.map(a => a.replace(/^subagent-/, '').replace(/\\.md$/, ''));\n lines.push(`├── 🤖 Sub-agents (${bundle.agents.length}):`);\n if (subNames.length <= 5) {\n subNames.forEach((name, sIdx) => {\n const isLastSub = sIdx === subNames.length - 1;\n const subBranch = isLastSub ? '└──' : '├──';\n lines.push(`│ ${subBranch} 🤖 ${pc.blue(name)}`);\n });\n } else {\n subNames.slice(0, 4).forEach(name => {\n lines.push(`│ ├── 🤖 ${pc.blue(name)}`);\n });\n lines.push(`│ └── 🤖 ${pc.dim(`(+${subNames.length - 4} more: ${subNames.slice(4).join(', ')})`)}`);\n }\n } else {\n lines.push(`├── 🤖 Sub-agents: ${pc.dim('None')}`);\n }\n\n // Partition skills into domain skills and workflow playbooks (ADR 0016)\n const domainSkills = (bundle.skills || []).filter(s => !s.startsWith('workflow-'));\n const workflowSkills = [\n ...(bundle.skills || []).filter(s => s.startsWith('workflow-')),\n ...(bundle.workflows || []),\n ];\n\n // Skills\n if (domainSkills.length > 0) {\n lines.push(`├── ⚡ Skills (${domainSkills.length}):`);\n if (domainSkills.length <= 5) {\n lines.push(`│ └── ${pc.yellow(domainSkills.join(', '))}`);\n } else {\n lines.push(`│ ├── ${pc.yellow(domainSkills.slice(0, 5).join(', '))}`);\n lines.push(`│ └── ${pc.dim(`(+${domainSkills.length - 5} more: ${domainSkills.slice(5).join(', ')})`)}`);\n }\n } else if (!bundle.parentBundle && workflowSkills.length === 0) {\n lines.push(`├── ⚡ Skills: ${pc.dim('None')}`);\n } else if (bundle.parentBundle && domainSkills.length === 0) {\n lines.push(`├── ⚡ Skills: ${pc.dim('Inherited from base bundle')}`);\n }\n\n // Workflows\n if (workflowSkills.length > 0) {\n const wfNames = workflowSkills.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n lines.push(`├── 🔄 Workflows (${workflowSkills.length}):`);\n if (wfNames.length <= 4) {\n lines.push(`│ └── ${pc.magenta(wfNames.join(', '))}`);\n } else {\n lines.push(`│ ├── ${pc.magenta(wfNames.slice(0, 4).join(', '))}`);\n lines.push(`│ └── ${pc.dim(`(+${wfNames.length - 4} more: ${wfNames.slice(4).join(', ')})`)}`);\n }\n } else if (bundle.parentBundle) {\n lines.push(`├── 🔄 Workflows: ${pc.dim('Inherited from base bundle')}`);\n }\n\n // Prerequisites\n if (bundle.prerequisites) {\n const prereqParts: string[] = [];\n if (bundle.prerequisites.requiredMcps && bundle.prerequisites.requiredMcps.length > 0) {\n prereqParts.push(`MCPs: ${bundle.prerequisites.requiredMcps.map(m => m.name).join(', ')}`);\n }\n if (bundle.prerequisites.requiredPackages && bundle.prerequisites.requiredPackages.length > 0) {\n prereqParts.push(`Packages: ${bundle.prerequisites.requiredPackages.join(', ')}`);\n }\n if (bundle.prerequisites.requiredEnvVars && bundle.prerequisites.requiredEnvVars.length > 0) {\n prereqParts.push(`Env: ${bundle.prerequisites.requiredEnvVars.join(', ')}`);\n }\n if (prereqParts.length > 0) {\n lines.push(`├── 🔌 Prerequisites: ${pc.yellow(prereqParts.join(' | '))}`);\n }\n } else {\n lines.push(`├── 🔌 Prerequisites: ${pc.dim('None (Self-contained domain bundle)')}`);\n }\n\n // Execution Modes\n if (bundle.modes) {\n lines.push(`└── 💡 Execution Modes: ${pc.green('Operational')} (live MCPs) / ${pc.cyan('Brainstorming')} (advisory fallback)`);\n } else {\n lines.push(`└── 💡 Execution Modes: ${pc.green('Operational')}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction renderFullCatalogTree(bundles: BundleDefinition[]): void {\n intro(pc.cyan('Agents United — Registry Catalog Tree'));\n\n const domainTitles: Record<string, string> = {\n engineering: '🛠️ Software Engineering & Delivery',\n architecture: '🏛️ System Architecture & SRE',\n design: '🎨 Product Design & UI/UX',\n marketing: '📈 Growth & Marketing Operations',\n security: '🔒 Security Operations',\n research: '🔬 Deep Technical Research',\n business: '💼 Business Strategy & Economics',\n universal: '🌐 Universal Autonomous Department',\n };\n\n const domainOrder = [\n 'universal',\n 'engineering',\n 'architecture',\n 'design',\n 'marketing',\n 'security',\n 'research',\n 'business',\n ];\n\n const grouped: Record<string, typeof bundles> = {};\n const orgBundles: typeof bundles = [];\n\n for (const b of bundles) {\n if (b.tier === 'organization' || b.domain === 'organization') {\n orgBundles.push(b);\n continue;\n }\n const d = b.domain || 'other';\n if (!grouped[d]) grouped[d] = [];\n grouped[d].push(b);\n }\n\n for (const domainKey of domainOrder) {\n const items = grouped[domainKey];\n if (!items || items.length === 0) continue;\n\n const header = domainTitles[domainKey] || `📁 ${domainKey.toUpperCase()}`;\n console.log(`\\n${pc.bold(pc.magenta(header))} ${pc.dim(`(${items.length} bundle${items.length > 1 ? 's' : ''})`)}`);\n\n items.forEach((b: BundleDefinition, bIdx: number) => {\n const isLastBundle = bIdx === items.length - 1;\n const bBranch = isLastBundle ? '└──' : '├──';\n const subIndent = isLastBundle ? ' ' : '│ ';\n\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n const isEssentials = !b.parentBundle && b.name !== 'full' && b.name !== 'universal-skills' && b.name !== 'universal-orchestration';\n const titleSuffix = isEssentials ? pc.cyan(' (Essentials)') : '';\n const parentTag = b.parentBundle ? pc.gray(` [inherits: ${b.parentBundle}]`) : '';\n const aliasesTag = b.aliases && b.aliases.length > 0 ? pc.gray(` [alias: ${b.aliases.join(', ')}]`) : '';\n\n let statusBadge = '';\n if (b.name === 'universal-skills') statusBadge = pc.green(' ⭐ [Recommended]');\n else if (b.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction]');\n else if (b.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n\n console.log(`${bBranch} 📦 ${pc.bold(pc.green(b.name))}${titleSuffix}${statusBadge}${parentTag}${aliasesTag}`);\n console.log(`${subIndent}│ ${pc.white(b.description)}`);\n\n // Lead / Orchestrator\n if (b.orchestrator) {\n const orchName = b.orchestrator.replace(/\\.md$/, '');\n console.log(`${subIndent}├── 🤖 Lead: ${pc.blue(orchName)}`);\n }\n\n // Subagents\n if (b.agents && b.agents.length > 0) {\n const subNames = b.agents.map(a => a.replace(/^subagent-/, '').replace(/\\.md$/, ''));\n const displaySubs =\n subNames.length > 3 ? `${subNames.slice(0, 3).join(', ')} (+${subNames.length - 3} more)` : subNames.join(', ');\n console.log(`${subIndent}├── 🤖 Sub-agents: ${pc.blue(displaySubs)}`);\n }\n\n // Skills & Workflows (ADR 0016)\n const domainSkills = (b.skills || []).filter(s => !s.startsWith('workflow-'));\n const workflowSkills = [\n ...(b.skills || []).filter(s => s.startsWith('workflow-')),\n ...(b.workflows || []),\n ];\n\n // Skills\n if (domainSkills.length > 0) {\n const displaySkills =\n domainSkills.length > 3 ? `${domainSkills.slice(0, 3).join(', ')} (+${domainSkills.length - 3} more)` : domainSkills.join(', ');\n console.log(`${subIndent}├── ⚡ Skills: ${pc.yellow(displaySkills)}`);\n }\n\n // Workflows\n if (workflowSkills.length > 0) {\n const wfNames = workflowSkills.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n const displayWfs =\n wfNames.length > 3 ? `${wfNames.slice(0, 3).join(', ')} (+${wfNames.length - 3} more)` : wfNames.join(', ');\n console.log(`${subIndent}└── 🔄 Workflows: ${pc.magenta(displayWfs)}`);\n } else if (b.parentBundle) {\n console.log(`${subIndent}└── 🔄 Workflows: ${pc.dim('Inherited from parent')}`);\n }\n\n if (!isLastBundle) {\n console.log(`${subIndent}`);\n }\n });\n }\n\n // Dedicated Organization Bundles Section\n if (orgBundles.length > 0) {\n console.log(`\\n${pc.bold(pc.cyan('🏢 Organization Bundles (Experimental / Cross-Functional)'))} ${pc.dim(`(${orgBundles.length} bundle${orgBundles.length > 1 ? 's' : ''})`)}`);\n console.log(pc.dim(' Cross-domain teams modeled after real organizations. Require runtime prerequisites (MCPs/packages).'));\n\n orgBundles.forEach((b: BundleDefinition, bIdx: number) => {\n const isLastBundle = bIdx === orgBundles.length - 1;\n const bBranch = isLastBundle ? '└──' : '├──';\n const subIndent = isLastBundle ? ' ' : '│ ';\n\n let statusBadge = '';\n if (b.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction (TBA)]');\n else if (b.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n else statusBadge = pc.green(' [Stable]');\n\n const prereqBadge = pc.dim(' [Prerequisites Required]');\n\n console.log(`${bBranch} 🏢 ${pc.bold(pc.cyan(b.name))}${statusBadge}${prereqBadge}`);\n console.log(`${subIndent}│ ${pc.white(b.description)}`);\n\n if (b.orchestrator) {\n const orchName = b.orchestrator.replace(/\\.md$/, '');\n console.log(`${subIndent}├── 🤖 Lead: ${pc.blue(orchName)}`);\n }\n\n if (b.agents && b.agents.length > 0) {\n const subNames = b.agents.map(a => a.replace(/^subagent-/, '').replace(/\\.md$/, ''));\n const displaySubs =\n subNames.length > 3 ? `${subNames.slice(0, 3).join(', ')} (+${subNames.length - 3} more)` : subNames.join(', ');\n console.log(`${subIndent}├── 🤖 Sub-agents: ${pc.blue(displaySubs)}`);\n }\n\n // Skills & Workflows (ADR 0016)\n const orgDomainSkills = (b.skills || []).filter(s => !s.startsWith('workflow-'));\n const orgWorkflowSkills = [\n ...(b.skills || []).filter(s => s.startsWith('workflow-')),\n ...(b.workflows || []),\n ];\n\n if (orgDomainSkills.length > 0) {\n const displaySkills =\n orgDomainSkills.length > 3 ? `${orgDomainSkills.slice(0, 3).join(', ')} (+${orgDomainSkills.length - 3} more)` : orgDomainSkills.join(', ');\n console.log(`${subIndent}├── ⚡ Skills: ${pc.yellow(displaySkills)}`);\n }\n\n if (orgWorkflowSkills.length > 0) {\n const wfNames = orgWorkflowSkills.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n const displayWfs =\n wfNames.length > 3 ? `${wfNames.slice(0, 3).join(', ')} (+${wfNames.length - 3} more)` : wfNames.join(', ');\n console.log(`${subIndent}├── 🔄 Workflows: ${pc.magenta(displayWfs)}`);\n }\n\n // Prerequisites Summary\n if (b.prerequisites) {\n const prereqParts: string[] = [];\n if (b.prerequisites.requiredMcps && b.prerequisites.requiredMcps.length > 0) {\n prereqParts.push(`MCPs: ${b.prerequisites.requiredMcps.map(m => m.name).join(', ')}`);\n }\n if (b.prerequisites.requiredPackages && b.prerequisites.requiredPackages.length > 0) {\n prereqParts.push(`Packages: ${b.prerequisites.requiredPackages.join(', ')}`);\n }\n if (b.prerequisites.requiredEnvVars && b.prerequisites.requiredEnvVars.length > 0) {\n prereqParts.push(`Env: ${b.prerequisites.requiredEnvVars.join(', ')}`);\n }\n if (prereqParts.length > 0) {\n console.log(`${subIndent}├── 🔌 Prerequisites: ${pc.yellow(prereqParts.join(' | '))}`);\n }\n }\n\n // Modes Summary\n if (b.modes) {\n console.log(`${subIndent}└── 💡 Execution Modes: ${pc.green('Operational')} (live MCPs) / ${pc.cyan('Brainstorming')} (advisory fallback)`);\n } else {\n console.log(`${subIndent}└── 💡 Execution Modes: ${pc.green('Operational')}`);\n }\n\n if (!isLastBundle) {\n console.log(`${subIndent}`);\n }\n });\n }\n\n outro(pc.cyan('\\nRun \"agents add <bundle>\" or select interactively to install.'));\n}\n\nasync function handleBundleDetailView(bundle: BundleDefinition): Promise<'__back_bundle__' | '__back_dept__' | '__exit__'> {\n const treeOutput = renderBundleDetailTree(bundle);\n console.log(`\\n${pc.bold(pc.cyan('┌── 📋 Bundle Detail: ' + pc.green(bundle.name) + ' ' + '─'.repeat(Math.max(2, 40 - bundle.name.length))))}`);\n console.log(treeOutput);\n console.log(`${pc.bold(pc.cyan('└' + '─'.repeat(60)))}\\n`);\n\n const actionOptions = [\n {\n value: 'install',\n label: `🚀 Install \"${bundle.name}\" bundle`,\n hint: `run installer for ${bundle.name}`,\n },\n {\n value: 'back_bundle',\n label: `🔙 Back to ${bundle.domain || 'Department'} bundle list`,\n hint: 'explore other bundles in this category',\n },\n {\n value: 'back_dept',\n label: `🏛️ Back to Department selection`,\n hint: 'explore other departments',\n },\n {\n value: 'exit',\n label: `🚪 Exit explorer`,\n hint: 'return to shell',\n },\n ];\n\n const action = await select({\n message: `Action for ${pc.bold(pc.green(bundle.name))}:`,\n options: actionOptions,\n });\n\n if (action === 'install') {\n // 1. Under Construction Gate Evaluation\n if (bundle.status === 'under-construction') {\n note(\n `The bundle \"${bundle.name}\" is currently under active construction (status: under-construction).\\n` +\n `Its orchestrators, workflows, and specialized skills are being authored and are not ready for production use.\\n\\n` +\n `Planned Capabilities:\\n` +\n `• Lead Orchestrator with Firecrawl & GitHub MCP tool calling\\n` +\n `• Full-stack web, design & SEO delivery workflows\\n` +\n `• Dual Execution Modes (Operational / Brainstorming)`,\n '🚧 Under Construction Gate'\n );\n\n const underConstructionChoice = await select({\n message: pc.yellow(`\"${bundle.name}\" is currently under construction. How would you like to proceed?`),\n options: [\n {\n value: 'abort',\n label: '🛑 Abort installation (Recommended)',\n hint: 'return without modifying workspace files',\n },\n {\n value: 'allow',\n label: '⚠️ Install in-development draft anyway (--allow-under-construction)',\n hint: 'proceed with in-progress placeholder assets',\n },\n ],\n });\n\n if (underConstructionChoice === 'abort' || typeof underConstructionChoice !== 'string') {\n outro(pc.yellow(`Installation cancelled. \"${bundle.name}\" is under construction.`));\n return '__back_bundle__';\n }\n }\n\n // 2. Prerequisite Gate Evaluation\n let executionMode: ExecutionMode = 'operational';\n\n if (bundle.prerequisites || bundle.tier === 'organization') {\n const checker = new PrerequisiteChecker();\n const prereqEval = await checker.evaluate(bundle);\n\n if (prereqEval.hasPrerequisites) {\n const checkLines: string[] = [];\n for (const item of prereqEval.items) {\n const typeLabel = item.type === 'mcp' ? 'MCP' : item.type === 'env' ? 'Env' : 'Pkg';\n const icon = item.satisfied ? pc.green('✓') : pc.red('✗');\n const details = pc.dim(`(${item.details || ''})`);\n checkLines.push(` ${icon} [${typeLabel}] ${pc.bold(item.name)}: ${item.satisfied ? pc.green('Detected') : pc.red('Missing')} ${details}`);\n }\n\n note(\n checkLines.join('\\n'),\n `Prerequisite Evaluation: ${bundle.name} (${bundle.tier === 'organization' ? 'Organization Bundle' : 'Prerequisites Required'})`\n );\n\n if (!prereqEval.allSatisfied) {\n const gateChoice = await select({\n message: pc.yellow(`Prerequisites not fully satisfied for \"${bundle.name}\". How would you like to proceed?`),\n options: [\n {\n value: 'abort',\n label: '🛑 Abort and configure missing prerequisites (Recommended)',\n hint: 'exit and configure MCP servers, packages, or environment variables',\n },\n {\n value: 'brainstorming',\n label: '💡 Install in Brainstorming Mode (Advisory & Spec generation only)',\n hint: 'runs in idea/planning mode without requiring live MCP tool connections',\n },\n {\n value: 'force',\n label: '⚠️ Force install in Operational Mode anyway',\n hint: 'proceed despite missing prerequisites (may fail during runtime calls)',\n },\n ],\n });\n\n if (gateChoice === 'abort' || typeof gateChoice !== 'string') {\n outro(pc.yellow('Installation aborted. Please configure required MCPs and environment variables, then retry.'));\n return '__back_bundle__';\n }\n\n if (gateChoice === 'brainstorming') {\n executionMode = 'brainstorming';\n note(pc.cyan('Switched execution mode to \"brainstorming\" (idea/spec fallback mode).'), 'Mode Selected');\n } else if (gateChoice === 'force') {\n executionMode = 'operational';\n note(pc.yellow('Proceeding in \"operational\" mode with missing prerequisites.'), 'Warning');\n }\n }\n }\n }\n\n // 3. Workspace Host & Fan-out Configuration\n const detectedHosts = detectWorkspaceHosts();\n let installHosts: AgentHost[] = ['agents'];\n let installFanout: string[] = [];\n\n if (detectedHosts.length > 0) {\n const projectionHosts = detectedHosts.filter(h => HOST_REGISTRY[h].projectionCapable);\n installFanout = projectionHosts;\n installHosts = detectedHosts.filter(h => !HOST_REGISTRY[h].projectionCapable) as AgentHost[];\n if (!installHosts.includes('agents')) installHosts.unshift('agents');\n }\n\n const installSpinner = spinner();\n installSpinner.start(`Installing \"${bundle.name}\"...`);\n\n try {\n const result = await installer.install(bundle.name, {\n scope: 'project',\n hosts: installHosts,\n fanout: installFanout,\n mode: executionMode,\n method: 'symlink',\n });\n\n installSpinner.stop(pc.green(`✔ Successfully installed ${bundle.name}!`));\n // Owner Gate-7 finding (2026-09-25): skills are discovered at session start.\n note(\n pc.yellow(\n 'New skills are discovered at session start. To pick them up now:\\n' +\n ' Claude Code ..... user types /reload-skills (#58733)\\n' +\n ' Antigravity CLI . user types /skills reload\\n' +\n ' Antigravity App . restart the app, or use @<skill_name>\\n' +\n ' Cline ........... agents read .cline/skills/ directly\\n' +\n 'Slash commands only fire when YOU type them; agents can read the file.'\n ),\n 'Pick up new skills'\n );\n note(\n formatInstallationSummary({\n bundleName: result.installed.targetBundle || bundle.name,\n scope: 'project',\n method: result.method,\n hosts: installHosts,\n agents: result.installed.agents,\n skills: result.installed.skills,\n targetDirs: result.targetDirs,\n projections: result.projections,\n }),\n 'Installation Success'\n );\n if (result.projections.length > 0) {\n note(renderProjections(result.projections), 'Installed Projections');\n }\n if (result.projections.some(p => p.host === 'cline')) {\n note(\n pc.green(\n `Already active: any Cline session in this workspace now sees this bundle's\\n` +\n `skills, subagent_* agent tools, rules & workflow commands (ADR 0013 native discovery).\\n` +\n `Use \"agents start ${bundle.name}\" for a pre-seeded team session.`\n ),\n 'Native Activation'\n );\n }\n outro(pc.green(`✨ Installation of \"${bundle.name}\" complete!`));\n } catch (err: any) {\n installSpinner.stop(pc.red('Installation failed'));\n outro(pc.red(`Error: ${err.message}`));\n }\n return '__exit__';\n } else if (action === 'back_dept') {\n return '__back_dept__';\n } else if (action === 'exit' || typeof action !== 'string') {\n return '__exit__';\n }\n\n return '__back_bundle__';\n}\n\ncli\n .command('list', 'List available bundles grouped by department domain')\n .alias('ls')\n .option('--json', 'Output bundles in JSON format')\n .option('--tree', 'Output full static catalog tree')\n .option('--all', 'Output full static catalog tree')\n .action(async (options: any = {}) => {\n const bundles = await registry.listBundles();\n\n if (options.json) {\n console.log(JSON.stringify(bundles, null, 2));\n return;\n }\n\n const isInteractive = process.stdout.isTTY && !options.tree && !options.all;\n\n if (!isInteractive) {\n renderFullCatalogTree(bundles);\n return;\n }\n\n // Interactive 2-Stage Catalog Explorer\n intro(pc.cyan('🌐 Agents United — Interactive Catalog Explorer'));\n\n const domainMeta: Record<string, { label: string; icon: string }> = {\n universal: { label: 'Universal Autonomous Department', icon: '🌐 ' },\n engineering: { label: 'Software Engineering & Delivery', icon: '🛠️ ' },\n architecture: { label: 'System Architecture & SRE', icon: '🏛️ ' },\n design: { label: 'Product Design & UI/UX', icon: '🎨 ' },\n marketing: { label: 'Growth & Marketing Operations', icon: '📈 ' },\n security: { label: 'Security Operations', icon: '🔒 ' },\n research: { label: 'Deep Technical Research', icon: '🔬 ' },\n business: { label: 'Business Strategy & Economics', icon: '💼 ' },\n organization: { label: 'Organization Bundles (Experimental / Cross-Functional)', icon: '🏢 ' },\n };\n\n let activeDomain: string | undefined;\n\n while (true) {\n // Stage 1: Department Domain Selection (if none selected)\n if (!activeDomain) {\n const domainOptions = Object.entries(domainMeta).map(([domainKey, meta]) => {\n const count = bundles.filter(b => (b.domain === domainKey || (domainKey === 'organization' && b.tier === 'organization'))).length;\n return {\n value: domainKey,\n label: `${meta.icon} ${meta.label}`,\n hint: domainKey === 'universal' ? 'meta-skills baseline + full suite' : domainKey === 'organization' ? 'cross-functional teams with prerequisites' : `${count} specialized bundle${count > 1 ? 's' : ''}`,\n };\n });\n\n domainOptions.push({\n value: '__search__',\n label: '🔍 Search by name / keyword...',\n hint: 'find bundles, agents, skills or workflows',\n });\n\n domainOptions.push({\n value: '__full_tree__',\n label: '🌳 View Full Static Catalog Tree',\n hint: `expand all ${bundles.length} bundles and ${new Set(bundles.map(b => b.domain).filter(Boolean)).size} departments at once`,\n });\n\n const selectedDomain = await select({\n message: 'Select Department Domain to explore:',\n options: domainOptions,\n });\n\n if (typeof selectedDomain !== 'string') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n\n if (selectedDomain === '__full_tree__') {\n renderFullCatalogTree(bundles);\n continue;\n }\n\n if (selectedDomain === '__search__') {\n const query = await text({\n message: 'Enter keyword to search:',\n placeholder: 'e.g. mobile, playwright, react, backend, seo',\n });\n\n if (typeof query !== 'string' || !query.trim()) {\n continue;\n }\n\n const results = await registry.find(query.trim());\n if (results.bundles.length === 0 && results.agents.length === 0 && results.skills.length === 0 && results.workflows.length === 0) {\n note(`No items found matching \"${query.trim()}\".`, 'Search Results');\n continue;\n }\n\n const searchOptions: Array<{ value: string; label: string; hint?: string }> = [\n ...results.bundles.map((b: BundleDefinition) => ({\n value: `bundle:${b.name}`,\n label: `📦 [Bundle] ${BUNDLE_DISPLAY_NAMES[b.name]?.title || b.name} (${b.name})`,\n hint: b.description,\n })),\n {\n value: '__back__',\n label: '🔙 Back to Department Selection',\n hint: '',\n },\n ];\n\n if (searchOptions.length === 1) {\n note(`Found related agents/skills for \"${query}\", but no top-level bundles. Try browsing by department.`, 'Search Results');\n continue;\n }\n\n const chosen = await select({\n message: `Search Results for \"${query.trim()}\":`,\n options: searchOptions,\n });\n\n if (typeof chosen === 'string' && chosen.startsWith('bundle:')) {\n const bundleName = chosen.replace(/^bundle:/, '');\n const b = await registry.getBundle(bundleName);\n if (b) {\n const action = await handleBundleDetailView(b);\n if (action === '__exit__') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n }\n }\n continue;\n }\n\n activeDomain = selectedDomain;\n }\n\n // Stage 2: Collapsed Bundle Selection within Active Domain\n const domainBundles = bundles.filter(b => b.domain === activeDomain || (activeDomain === 'organization' && b.tier === 'organization'));\n\n // Sort so Essentials/universal-skills are first\n const sortedBundles = [...domainBundles].sort((a, b) => {\n if (a.name === 'universal-orchestration') return -1;\n if (b.name === 'universal-orchestration') return 1;\n if (a.name === 'universal-skills') return -1;\n if (b.name === 'universal-skills') return 1;\n if (!a.parentBundle && b.parentBundle) return -1;\n if (a.parentBundle && !b.parentBundle) return 1;\n return a.name.localeCompare(b.name);\n });\n\n const bundleOptions: Array<{ value: string; label: string; hint?: string }> = sortedBundles.map((b, idx) => {\n const isLast = idx === sortedBundles.length - 1;\n const branch = sortedBundles.length > 1 ? (isLast ? '└── ' : '├── ') : '';\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n const isEssentials = !b.parentBundle && b.name !== 'full' && b.name !== 'universal-skills' && b.name !== 'universal-orchestration' && b.tier !== 'organization';\n const titleSuffix = isEssentials ? pc.cyan(' (Essentials Base)') : '';\n const parentTag = b.parentBundle ? pc.gray(` [inherits: ${b.parentBundle}]`) : '';\n\n let badge = '';\n if (b.name === 'universal-skills') badge = pc.green(' ⭐ [Recommended]');\n else if (b.status === 'under-construction') badge = pc.yellow(' 🚧 [Under Construction]');\n else if (b.status === 'needs-audit') badge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') badge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') badge = pc.red(' [Deprecated]');\n\n return {\n value: b.name,\n label: `${branch}📦 ${meta?.title || b.name}${titleSuffix}${badge}${parentTag}`,\n hint: b.description || meta?.summary || b.name,\n };\n });\n\n bundleOptions.push({\n value: '__back_domain__',\n label: '🔙 Back to Department Selection',\n hint: 'choose another department domain',\n });\n\n const selectedBundleName = await select({\n message: `${domainMeta[activeDomain]?.label || activeDomain} — Select bundle to open:`,\n options: bundleOptions,\n });\n\n if (typeof selectedBundleName !== 'string') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n\n if (selectedBundleName === '__back_domain__') {\n activeDomain = undefined;\n continue;\n }\n\n const bundle = await registry.getBundle(selectedBundleName);\n if (!bundle) continue;\n\n // Stage 3: Render Open Tree View & Handle Action\n const action = await handleBundleDetailView(bundle);\n if (action === '__exit__') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n if (action === '__back_dept__') {\n activeDomain = undefined;\n }\n // If action === '__back_bundle__', stays in activeDomain loop\n }\n });\n\ncli\n .command('find [query]', 'Search for agents, skills, workflows, or bundles in the registry')\n .alias('search')\n .option('-c, --category <domain>', 'Filter search by domain (e.g. engineering, architecture, design)')\n .option('-t, --type <type>', 'Filter by item type (bundle, agent, skill, workflow)')\n .option('--json', 'Output results in JSON format')\n .option('-i, --interactive', 'Interactive selection to install matching item')\n .action(async (query?: string, options: any = {}) => {\n const q = query || '';\n const results = await registry.find(q, {\n domain: options.category || options.domain,\n type: options.type,\n });\n\n if (options.json) {\n console.log(JSON.stringify(results, null, 2));\n return;\n }\n\n const totalCount =\n results.bundles.length + results.agents.length + results.skills.length + results.workflows.length;\n\n intro(pc.cyan(`Agents United - Search Results: \"${q || '*'}\" (${totalCount} found)`));\n\n if (results.bundles.length > 0) {\n console.log(pc.bold(`\\n📦 Bundles (${results.bundles.length}):`));\n results.bundles.forEach((b: BundleDefinition) => {\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n console.log(` - ${pc.green(pc.bold(b.name))}: ${pc.white(meta?.title || b.name)} — ${pc.dim(b.description)}`);\n });\n }\n\n if (results.agents.length > 0) {\n console.log(pc.bold(`\\n🤖 Agents (${results.agents.length}):`));\n results.agents.forEach((a: string) => {\n const stem = a.replace(/\\.md$/, '');\n console.log(` - ${pc.blue(stem)} ${pc.gray(`(${a})`)}`);\n });\n }\n\n if (results.skills.length > 0) {\n console.log(pc.bold(`\\n⚡ Skills (${results.skills.length}):`));\n results.skills.forEach((s: string) => console.log(` - ${pc.yellow(s)}`));\n }\n\n if (results.workflows.length > 0) {\n console.log(pc.bold(`\\n🔄 Workflows (${results.workflows.length}):`));\n results.workflows.forEach((w: string) => {\n const stem = w.replace(/\\.md$/, '');\n console.log(` - ${pc.magenta(stem)} ${pc.gray(`(${w})`)}`);\n });\n }\n\n if (totalCount === 0) {\n console.log(pc.yellow(`\\nNo matching items found for \"${q}\". Try searching without filters or using \"agents list\".`));\n }\n\n if (options.interactive && totalCount > 0) {\n const items: Array<{ value: string; label: string }> = [\n ...results.bundles.map((b: BundleDefinition) => ({ value: b.name, label: `[Bundle] ${b.name} — ${b.description}` })),\n ...results.agents.map((a: string) => ({ value: a.replace(/\\.md$/, ''), label: `[Agent] ${a}` })),\n ...results.skills.map((s: string) => ({ value: s, label: `[Skill] ${s}` })),\n ...results.workflows.map((w: string) => ({ value: w.replace(/\\.md$/, ''), label: `[Workflow] ${w}` })),\n ];\n\n const selected = await select({\n message: 'Select an item to install:',\n options: items,\n });\n\n if (typeof selected === 'string') {\n const s = spinner();\n s.start(`Installing \"${selected}\"...`);\n try {\n const res = await installer.install(selected, { scope: 'project' });\n s.stop(`Installed ${selected}`);\n outro(pc.green(`✔ Successfully installed \"${selected}\"!`));\n } catch (err: any) {\n s.stop(pc.red('Installation failed'));\n outro(pc.red(`Error: ${err.message}`));\n }\n return;\n }\n }\n\n outro(pc.cyan('\\nUse \"agents add <name>\" to install any match.'));\n });\n\ncli\n .command('init', 'Initialize project workspace directory and install recommended bundle')\n .option('-b, --bundle <bundle>', 'Default bundle to install', { default: 'software-engineering' })\n .option('-s, --symlink', 'Use symlinks (default / recommended)')\n .option('--copy', 'Use standalone copies')\n .option('-t, --target <hosts>', 'Target agent hosts', { default: 'agents' })\n .action(async (options: any) => {\n intro(pc.cyan('Agents United - Initialize Workspace'));\n const s = spinner();\n s.start(`Initializing workspace with bundle \"${options.bundle}\"...`);\n\n try {\n const initTargets = (Array.isArray(options.target) ? options.target : String(options.target || 'agents').split(','))\n .map((h: string) => h.trim().toLowerCase());\n const initPlan = planInstallTargets(initTargets);\n const result = await installer.install(options.bundle, {\n scope: 'project',\n symlink: options.symlink,\n copy: options.copy,\n hosts: initPlan.hosts,\n fanout: initPlan.fanout,\n });\n s.stop(`Initialized ${result.targetDirs.join(', ')}`);\n outro(pc.green(`✔ Initialized workspace with \"${options.bundle}\" bundle!`));\n } catch (err: any) {\n s.stop(pc.red('Initialization failed'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('start <bundle> [prompt]', 'Start an installed bundle team in its host runtime (e.g. Cline, Claude Code)')\n .option('--host <host>', 'Host runtime (default: auto-detect from lockfile fanout)')\n .option('-g, --global', 'Select global installation')\n .option('--team <name>', 'Override generated team name')\n .option('--allow-addons', 'Pre-authorize recommended addon installations for this session')\n .option('--headless', 'Run non-interactively without interactive TUI')\n .option('--bg', 'Run the Claude Code session in the background (claude host only)')\n .option('--teams', 'Force the experimental agent-teams scaffold on (claude host only). Default: ON for organization-tier (Tier 2) bundles, OFF for domain-tier (Tier 1) bundles — pass --no-teams to opt out. Ephemeral env only, nothing persisted')\n .option('--plugin', 'Pass --plugin-dir with the bundle plugin root (claude host only)')\n .option('--dry-run', 'Print activation resolution and argv summary without launching')\n .action(async (bundle: string, prompt?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — Runtime Activation'));\n\n const launcher = new ClineLauncher();\n const probe = new ClineCapabilityProbe();\n\n try {\n // ADR 0018 / Plan 016 (Step 6): an explicit --host wins; otherwise inherit the fanout recorded in\n // the lockfile for the resolved scope/workspace. Falling back to Cline when no claude signal exists\n // keeps the existing Cline UX byte-identical.\n const effectiveHost = await resolveStartHost(bundle, options);\n if (effectiveHost === 'claude') {\n await runClaudeStart(bundle, prompt, options);\n return;\n }\n if (effectiveHost === 'unsupported') {\n note(pc.yellow(`Host '${options.host}' has no activation launcher yet; falling back to the Cline lane.`), 'Host Runtime');\n }\n const resolution = await launcher.resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n\n const probeReport = await probe.probe();\n if (!probeReport.installed && !options.dryRun) {\n outro(pc.red(`Cline executable was not found on PATH or via CLINE_BIN_PATH. Please install Cline CLI or ensure it is accessible.`));\n process.exit(1);\n }\n\n const bundleDef = await registry.getBundle(bundle);\n // Plan 016 post-gate: Tier 2 (organization) is a *Claude-runtime* posture. Agent Teams is a Claude\n // Code feature behind CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, so this lane reports the tier instead of\n // half-applying it — nothing here changes argv, and the session keeps Cline's own strategy with the\n // projected specialist tools under `.cline/agents/`. `--teams` on this host is a no-op by design.\n const organizationTier = bundleDef?.tier === 'organization';\n const plan = launcher.planActivation({\n bundleName: bundle,\n workspace: resolution.workspace,\n scope: resolution.scope,\n report: probeReport,\n prompt,\n teamName: options.team,\n allowAddons: options.allowAddons,\n headless: options.headless,\n orchestrator: bundleDef?.orchestrator,\n });\n\n if (options.dryRun) {\n note(\n `Bundle: ${plan.bundleName}\\n` +\n `Tier: ${bundleDef?.tier ?? 'not declared (Tier-1 domain default)'}\\n` +\n `Agent teams: ${organizationTier ? 'not available on this host (claude-only runtime feature)' : 'no'}\\n` +\n `Scope: ${plan.scope}\\n` +\n `Workspace: ${plan.workspace}\\n` +\n `Team Name: ${plan.teamName}\\n` +\n `Strategy: ${plan.strategy}\\n` +\n `Executable: ${plan.executable}\\n` +\n `Argv: ${plan.argv.map(a => (a.includes(' ') || a.includes('\\n') ? `\"${a.replace(/\\n/g, '\\\\n')}\"` : a)).join(' ')}`,\n 'Activation Plan (dry run)'\n );\n outro(pc.yellow('Dry run complete. No processes launched.'));\n return;\n }\n\n if (organizationTier) {\n note(\n pc.yellow(\n `\"${bundle}\" is an organization-tier (Tier 2) bundle. Agent Teams is a Claude Code runtime\\n` +\n `feature and is not available on this host, so '--teams' is claude-only. This session runs\\n` +\n `Cline's ${plan.strategy} strategy with the projected specialist tools under .cline/agents/.`\n ),\n 'Tier 2 (organization)'\n );\n }\n\n note(\n `Team: ${pc.bold(plan.teamName)}\\n` +\n `Strategy: ${pc.cyan(plan.strategy)}\\n` +\n `Workspace: ${plan.workspace}`,\n 'Starting Cline Team'\n );\n\n await launcher.launch(plan);\n outro(pc.green(`✔ Cline session finished.`));\n } catch (err: any) {\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('doctor', 'Verify health of installed agents, frontmatter schemas, and hooks')\n .option('--host <host>', 'Audit specific host runtime (e.g. cline, claude)')\n .action(async (options: any = {}) => {\n intro(pc.cyan('🩺 Agents United — Health Doctor'));\n const report = await DoctorEngine.runDoctor(undefined, options.host);\n\n if (!report.isInitialized || (report.agentsCount === 0 && report.skillsCount === 0 && report.workflowsCount === 0 && report.issues.length === 0)) {\n console.log(` ${pc.bold('📦 Status:')} ${pc.yellow('No agents or bundles installed in this workspace.')}`);\n console.log(` ${pc.bold('📍 Location:')} ${pc.dim(report.targetDir)}\\n`);\n\n console.log(pc.bold(pc.cyan('💡 Get Started:')));\n console.log(` 👉 ${pc.bold('agents add')} Launch the interactive installation wizard`);\n console.log(` 👉 ${pc.bold('agents add software-engineering')} Install the engineering essentials team`);\n const bundleCount = (await registry.listBundles()).length;\n console.log(` 👉 ${pc.bold('agents list')} Browse all ${bundleCount} bundles by department\\n`);\n\n if (report.clineCapability) {\n console.log(pc.bold(pc.cyan('Cline Runtime & Native Discovery Audit:')));\n console.log(` Installed: ${report.clineCapability.installed ? pc.green('✔ Detected') : pc.yellow('✖ Not Found')}`);\n if (report.clineCapability.version) {\n console.log(` Version: ${report.clineCapability.version}`);\n }\n console.log(` Named Teams: ${report.clineCapability.namedTeams ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported (Adaptive fallback)')}\\n`);\n }\n\n if (report.claudeCapability) {\n renderClaudeCapabilityBlock(report.claudeCapability);\n for (const diagnostic of report.claudeCapability.diagnostics) {\n console.log(` ${pc.dim(diagnostic)}`);\n }\n console.log();\n }\n\n if (report.warnings.length > 0) {\n console.log(pc.yellow(pc.bold('⚠️ Warnings:')));\n report.warnings.forEach(w => console.log(` ⚠ ${w}`));\n console.log();\n }\n\n outro(pc.blue('✨ Workspace is ready for initialization.'));\n return;\n }\n\n console.log(` 🤖 Installed Agents: ${pc.bold(report.agentsCount.toString())}`);\n console.log(` ⚡ Installed Skills: ${pc.bold(report.skillsCount.toString())}`);\n console.log(` 🔄 Installed Workflow Skills: ${pc.bold(report.workflowsCount.toString())}\\n`);\n\n if (report.clineCapability) {\n console.log(pc.bold(pc.cyan('Cline Runtime & Native Discovery Audit:')));\n console.log(` Installed: ${report.clineCapability.installed ? pc.green('✔ Detected') : pc.yellow('✖ Not Found')}`);\n if (report.clineCapability.version) {\n console.log(` Version: ${report.clineCapability.version}`);\n }\n console.log(` Named Teams: ${report.clineCapability.namedTeams ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported (Adaptive fallback)')}`);\n console.log(` Configured Agents: ${report.agentsCount} active natively in any Cline session (\"agents start\" = optional team-session launcher)\\n`);\n }\n\n if (report.claudeCapability) {\n renderClaudeCapabilityBlock(report.claudeCapability);\n console.log(` Configured Agents: ${report.agentsCount} projected into .claude/agents/ (\"agents start --host claude\" = optional launcher)\\n`);\n }\n\n if (report.issues.length > 0) {\n console.log(pc.red(pc.bold('❌ Issues Found:')));\n report.issues.forEach(i => console.log(` ✖ ${i}`));\n console.log();\n }\n\n if (report.warnings.length > 0) {\n console.log(pc.yellow(pc.bold('⚠️ Warnings:')));\n report.warnings.forEach(w => console.log(` ⚠ ${w}`));\n console.log();\n }\n\n if (report.valid && report.issues.length === 0) {\n outro(pc.green('✔ All installed agents and frontmatter schemas are healthy!'));\n } else {\n outro(pc.red('✖ Doctor found issues in workspace configuration.'));\n process.exit(1);\n }\n });\n\n/**\n * Plan 016 (Step 6) — resolve the activation host for `agents start`.\n *\n * - an explicit `--host` wins (`claude` selects the Claude lane, anything else falls back to Cline, which\n * is the pre-Step-6 behaviour where `--host` was ignored entirely);\n * - otherwise the fanout recorded in the lockfile for the resolved scope/workspace is inherited, so an\n * install projected to Claude activates the Claude lane and an install with no claude signal keeps the\n * existing Cline UX unchanged.\n *\n * Detection is deliberately best-effort: any resolution error (bundle not installed, not projected) yields\n * no claude signal, and the selected lane then reports its own actionable error exactly as before.\n */\nasync function resolveStartHost(\n bundle: string,\n options: { host?: string; global?: boolean }\n): Promise<'cline' | 'claude' | 'unsupported'> {\n const explicitHost = typeof options.host === 'string' ? options.host.trim().toLowerCase() : '';\n if (explicitHost === 'claude') {\n return 'claude';\n }\n if (explicitHost === 'cline') {\n return 'cline';\n }\n if (explicitHost.length > 0) {\n return 'unsupported';\n }\n\n let recordedFanout: string[] = [];\n try {\n const detection = await new ClaudeLauncher().resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n recordedFanout = detection.lockfile.fanout || [];\n } catch {\n recordedFanout = [];\n }\n return recordedFanout.includes('claude') ? 'claude' : 'cline';\n}\n\n/** Why the Agent-Teams scaffold is on or off for a Claude session. */\nexport type ClaudeTeamsReason = 'explicit' | 'tier-default' | 'opt-out' | 'domain-tier' | 'unresolved-tier';\n\nexport interface ClaudeTeamsPosture {\n /** Whether the ephemeral agent-teams scaffold will be injected into the spawned session. */\n active: boolean;\n reason: ClaudeTeamsReason;\n /** The resolved bundle tier that drove the decision, when the bundle could be resolved. */\n tier?: BundleTier;\n}\n\n/**\n * Tier-aware Agent-Teams posture for `agents start --host claude` (Plan 016 decision 14 + the Tier-1/Tier-2\n * split recorded in CONTEXT.md).\n *\n * - Tier 1 (`tier: 'domain'`) is a single-discipline hub-and-spoke team, so it keeps the ordinary\n * parallel-subagent model: teams stay opt-in via `--teams`.\n * - Tier 2 (`tier: 'organization'`) is cross-functional by construction, so it runs with Agent Teams logic\n * by default. `--no-teams` (cac parses it into `options.teams === false`) is the explicit opt-out and\n * always wins over the tier default.\n *\n * Pure and exported so the `--dry-run` plan and the tests can assert the decision without spawning `claude`.\n */\nexport function resolveClaudeTeamsPosture(\n teamsOption: boolean | undefined,\n tier: BundleTier | undefined\n): ClaudeTeamsPosture {\n if (teamsOption === true) return { active: true, reason: 'explicit', tier };\n if (teamsOption === false) return { active: false, reason: 'opt-out', tier };\n if (tier === 'organization') return { active: true, reason: 'tier-default', tier };\n if (tier === 'domain') return { active: false, reason: 'domain-tier', tier };\n return { active: false, reason: 'unresolved-tier' };\n}\n\n/** One-line, honest explanation of why teams is on or off — shared by the live notice and `--dry-run`. */\nexport function describeClaudeTeamsPosture(posture: ClaudeTeamsPosture): string {\n switch (posture.reason) {\n case 'explicit':\n return 'explicit --teams';\n case 'tier-default':\n return \"default for tier 'organization'\";\n case 'opt-out':\n return '--no-teams opt-out';\n case 'domain-tier':\n return \"tier 'domain' — pass --teams to enable\";\n case 'unresolved-tier':\n return 'no declared tier (Tier-1 domain default) — pass --teams to enable';\n }\n}\n\n/**\n * Plan 016 (Step 6) — the Claude Code lane for `agents start --host claude`.\n *\n * `--dry-run` prints the full plan (one argv element per line, plus the active flags and the env keys that\n * would be injected) and returns without spawning anything or writing anything to disk. A real session\n * spawns `claude` with `shell: false` and the ephemeral env merged over `process.env`; the teams opt-in is\n * never persisted (no settings.json write, nothing under `~/.claude/`).\n *\n * Teams posture is tier-derived (`resolveClaudeTeamsPosture`): an organization-tier (Tier 2) bundle enables\n * Agent Teams by default, a domain-tier (Tier 1) bundle only with an explicit `--teams`, and `--no-teams`\n * always wins over the tier default.\n */\nasync function runClaudeStart(bundle: string, prompt: string | undefined, options: any): Promise<void> {\n const launcher = new ClaudeLauncher();\n const probe = new ClaudeCapabilityProbe();\n\n const resolution = await launcher.resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n\n const probeReport = await probe.probe();\n if (!probeReport.installed && !options.dryRun) {\n outro(pc.red(`Claude Code executable was not found on PATH or via CLAUDE_BIN_PATH. Please install Claude Code or ensure it is accessible.`));\n process.exit(1);\n }\n\n const bundleDef = await registry.getBundle(bundle);\n // Tier-aware Agent-Teams posture: an organization-tier (Tier 2) bundle runs with Agent Teams logic by\n // default, a domain-tier (Tier 1) bundle keeps the ordinary parallel-subagent model unless `--teams`,\n // and an explicit `--no-teams` always wins (Plan 016 decision 14).\n const teamsPosture = resolveClaudeTeamsPosture(options.teams, bundleDef?.tier);\n const teamsActive = teamsPosture.active;\n // ADR 0018 decision 6 keeps ONE host-neutral team manifest under the organization package, which\n // the Cline half of the compound lane writes. A claude-only fanout has none, so the prompt must\n // not order the coordinator to read a path that does not exist.\n const manifestAvailable = await fs.pathExists(resolution.manifestPath);\n // `--plugin` points Claude at the bundle's plugin root. The path is workspace-relative because the session\n // is spawned with `cwd: workspace`; Step 7 emits the plugin manifest inside it.\n const pluginDir = options.plugin\n ? path.join('.agents', 'plugins', bundle).split(path.sep).join('/')\n : undefined;\n\n const plan = launcher.planActivation({\n bundleName: bundle,\n workspace: resolution.workspace,\n scope: resolution.scope,\n report: probeReport,\n prompt,\n orchestrator: bundleDef?.orchestrator,\n allowAddons: options.allowAddons,\n background: options.bg,\n teams: teamsActive,\n pluginDir,\n manifestAvailable,\n });\n\n const recordedFanout = resolution.lockfile.fanout || [];\n\n if (options.dryRun) {\n note(renderClaudeActivationPlan(plan, probeReport, recordedFanout, teamsPosture), 'Claude Activation Plan (dry run)');\n outro(pc.yellow('Dry run complete. No processes launched.'));\n return;\n }\n\n if (!recordedFanout.includes('claude')) {\n note(\n pc.yellow(\n `This workspace records fanout [${recordedFanout.join(', ') || 'none'}]. Run\\n` +\n `'agents update ${bundle} --fanout claude' to project .claude/agents/ before the session needs it.`\n ),\n 'Claude Projection'\n );\n }\n if (teamsActive && teamsPosture.reason === 'tier-default') {\n note(\n pc.yellow(\n `Agent Teams is ON by default for this organization-tier bundle (tier 'organization').\\n` +\n `--no-teams falls back to ordinary parallel subagents.`\n ),\n 'Agent Teams'\n );\n } else if (teamsActive) {\n note(pc.cyan('Agent Teams explicitly requested with --teams; the scaffold stays experimental.'), 'Agent Teams');\n }\n if (teamsActive && !probeReport.agentTeamsExperimental) {\n note(pc.yellow('The capability probe could not confirm agent-team support from --help; the scaffold stays experimental and unverified.'), 'Agent Teams');\n }\n if (pluginDir && !probeReport.pluginSupport) {\n note(pc.yellow('The capability probe could not confirm --plugin-dir support from --help.'), 'Plugin Dir');\n }\n\n note(\n `Host: ${pc.cyan('claude')}\\n` +\n `Executable: ${plan.executable}\\n` +\n `Workspace: ${plan.workspace}\\n` +\n `Background: ${options.bg ? 'yes (--bg)' : 'no'}\\n` +\n `Teams scaffold: ${teamsActive ? `yes (${describeClaudeTeamsPosture(teamsPosture)}; experimental, ephemeral env only)` : `no (${describeClaudeTeamsPosture(teamsPosture)})`}\\n` +\n `Plugin dir: ${pluginDir || '(none)'}`,\n 'Starting Claude Code Session'\n );\n\n // ADR 0018 decision 3: a main-thread `--agent` session is bounded by the projected coordinator\n // definition's `Agent(...)` allowlist, so that file must exist for the session to be meaningful.\n // `resolveInstallation` accepts either a recorded claude fanout OR the host-neutral manifest, and\n // the manifest is a Cline artifact — so a cline-only workspace can pass the gate. Fail loudly here\n // rather than spawning a session whose `--agent` target does not exist.\n const coordinatorRel = `.claude/agents/${ClaudeLauncher.resolveCoordinatorName(bundleDef?.orchestrator)}.md`;\n if (!await fs.pathExists(path.join(resolution.workspace, coordinatorRel))) {\n outro(\n pc.red(\n `Claude projection \"${coordinatorRel}\" was not found in ${resolution.workspace}.\\n` +\n `Run 'agents update ${bundle} --fanout claude' before starting an --agent session.`\n )\n );\n process.exit(1);\n }\n\n\n await launcher.launch(plan);\n outro(pc.green(`✔ Claude Code session finished.`));\n}\n\n/**\n * Shared Claude capability block for `agents doctor`.\n *\n * `cli.ts` prints this twice — once on the empty-workspace early exit and once in the main report — and the\n * duplication already drifted once (a capability line landed in one branch only). Both call sites share this\n * renderer so a new capability is reported everywhere.\n */\nfunction renderClaudeCapabilityBlock(capability: ClaudeCapabilityReport): void {\n console.log(pc.bold(pc.cyan('Claude Code Runtime & Native Discovery Audit:')));\n console.log(` Installed: ${capability.installed ? pc.green('✔ Detected') : pc.yellow('✖ Not Found')}`);\n if (capability.version) {\n console.log(` Version: ${capability.version}`);\n }\n console.log(` Plugin Support (--plugin-dir): ${capability.pluginSupport ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported')}`);\n console.log(` Agent Teams (experimental): ${capability.agentTeamsExperimental ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported')}`);\n console.log(` Subagent hand-off (SubagentHandback): ${capability.subagentHandback ? pc.green('✔ Supported') : pc.yellow('✖ Needs v2.1.271+ (auto mode)')}`);\n}\n\n/** Render the `--dry-run` Claude plan: one argv element per line so each flag/value pair is unambiguous. */\nfunction renderClaudeActivationPlan(\n plan: ClaudeActivationPlan,\n report: ClaudeCapabilityReport,\n recordedFanout: string[],\n posture: ClaudeTeamsPosture\n): string {\n const envEntries = Object.keys(plan.env);\n const pluginFlagIndex = plan.argv.indexOf('--plugin-dir');\n const teamsActive = envEntries.includes('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS');\n return [\n `Bundle: ${plan.bundleName}`,\n `Host: claude`,\n `Bundle tier: ${posture.tier ?? \"not declared (Tier-1 'domain' default)\"}`,\n `Scope: ${plan.scope}`,\n `Workspace: ${plan.workspace}`,\n `Executable: ${plan.executable}`,\n `Background (--bg): ${plan.argv.includes('--bg') ? 'yes' : 'no'}`,\n teamsActive\n ? `Agent teams (--teams): yes (${describeClaudeTeamsPosture(posture)} — experimental; ephemeral env only, nothing persisted)`\n : `Agent teams (--teams): no (${describeClaudeTeamsPosture(posture)})`,\n `Plugin (--plugin-dir): ${pluginFlagIndex >= 0 ? plan.argv[pluginFlagIndex + 1] : '(none)'}`,\n `Env injected (merged over process.env): ${envEntries.length > 0 ? envEntries.map((k) => `${k}=${plan.env[k]}`).join(', ') : '(none)'}`,\n `Capability probe: installed=${report.installed ? `yes${report.version ? ` (${report.version})` : ''}` : 'no'}, --plugin-dir=${report.pluginSupport ? 'yes' : 'no'}, agent teams=${report.agentTeamsExperimental ? 'yes' : 'no'}, subagent handback=${report.subagentHandback ? 'yes' : 'no'}`,\n `Recorded fanout: [${recordedFanout.join(', ')}]`,\n `Argv (${plan.argv.length} elements, one element per line, spawned with shell: false):`,\n ...plan.argv.map((arg, index) => ` [${index}] ${arg.replace(/\\r?\\n/g, '\\\\n')}`),\n ].join('\\n');\n}\n\ncli.help();\ncli.version('1.0.0');\n\ncli.parse();\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport yaml from 'yaml';\nimport { fileURLToPath } from 'node:url';\nimport type { BundlesManifest, BundleDefinition, ResolvedAssets, SearchOptions, SearchResults, PlanningLoopMode } from './types.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport class RegistryResolver {\n /**\n * Host entrypoint rules (Plan 015 §0/C7). `GEMINI.md` is always resolved so\n * Antigravity-family hosts keep their entrypoint; it is never declared in an\n * agent's frontmatter.\n */\n private static readonly BASELINE_RULES = ['GEMINI.md'];\n\n private registryDir: string;\n private bundlesManifest: BundlesManifest | null = null;\n /** Memoized agent file -> declared rules (Plan 015 §0/C6). */\n private agentRuleCache = new Map<string, string[]>();\n\n constructor(customRegistryDir?: string) {\n if (customRegistryDir) {\n this.registryDir = path.resolve(customRegistryDir);\n } else {\n // Check candidate paths for registry folder\n const candidatePaths = [\n path.resolve(__dirname, '../registry'),\n path.resolve(__dirname, '../../registry'),\n path.resolve(process.cwd(), 'registry'),\n ];\n\n const found = candidatePaths.find(p => fs.existsSync(path.join(p, 'bundles.json')));\n this.registryDir = found || candidatePaths[0];\n }\n }\n\n public getRegistryDir(): string {\n return this.registryDir;\n }\n\n public async loadBundles(): Promise<BundlesManifest> {\n if (this.bundlesManifest) {\n return this.bundlesManifest;\n }\n\n const manifestPath = path.join(this.registryDir, 'bundles.json');\n if (!await fs.pathExists(manifestPath)) {\n throw new Error(`Registry bundles.json not found at ${manifestPath}`);\n }\n\n this.bundlesManifest = await fs.readJson(manifestPath);\n this.validateBundles(this.bundlesManifest!);\n return this.bundlesManifest!;\n }\n\n public async getBundle(bundleName: string): Promise<BundleDefinition | null> {\n const manifest = await this.loadBundles();\n if (manifest.bundles[bundleName]) {\n return manifest.bundles[bundleName];\n }\n const found = Object.values(manifest.bundles).find(\n b => b.aliases?.includes(bundleName)\n );\n return found || null;\n }\n\n public async listBundles(): Promise<BundleDefinition[]> {\n const manifest = await this.loadBundles();\n return Object.values(manifest.bundles);\n }\n\n public async getBundlesByDomain(domain: string): Promise<BundleDefinition[]> {\n const manifest = await this.loadBundles();\n const d = domain.toLowerCase();\n return Object.values(manifest.bundles).filter(b => b.domain?.toLowerCase() === d);\n }\n\n public async resolve(identifier: string): Promise<ResolvedAssets> {\n // Check if identifier refers to an entire department domain (e.g. \"domain:engineering\")\n if (identifier.startsWith('domain:')) {\n const domainName = identifier.replace(/^domain:/, '').toLowerCase();\n const domainBundles = await this.getBundlesByDomain(domainName);\n if (domainBundles.length > 0) {\n const agents = new Set<string>();\n const skills = new Set<string>();\n const workflows = new Set<string>();\n const rules = new Set<string>(RegistryResolver.BASELINE_RULES);\n\n for (const b of domainBundles) {\n const resolved = await this.resolve(b.name);\n resolved.agents.forEach(a => agents.add(a));\n resolved.skills.forEach(s => skills.add(s));\n resolved.workflows.forEach(w => workflows.add(w));\n resolved.rules.forEach(r => rules.add(r));\n }\n\n return {\n targetBundle: `domain:${domainName}`,\n agents: Array.from(agents),\n skills: Array.from(skills),\n workflows: Array.from(workflows),\n rules: Array.from(rules).sort(),\n };\n }\n }\n\n const bundle = await this.getBundle(identifier);\n\n if (bundle) {\n const agents = new Set<string>();\n const skills = new Set<string>(bundle.skills || []);\n const workflows = new Set<string>(bundle.workflows || []);\n const rules = new Set<string>(RegistryResolver.BASELINE_RULES);\n\n // Forward-compatible only: no bundle in registry/bundles.json declares\n // `rules` today (verified: 0 occurrences); the type allows it (types.ts:369).\n (bundle.rules || []).forEach(r => rules.add(r));\n\n if (bundle.parentBundle) {\n const parent = await this.getBundle(bundle.parentBundle);\n if (parent) {\n if (parent.orchestrator) agents.add(parent.orchestrator);\n if (parent.agents) parent.agents.forEach(a => agents.add(a));\n if (parent.skills) parent.skills.forEach(s => skills.add(s));\n if (parent.workflows) parent.workflows.forEach(w => workflows.add(w));\n (parent.rules || []).forEach(r => rules.add(r));\n }\n }\n\n if (bundle.orchestrator) agents.add(bundle.orchestrator);\n if (bundle.agents) bundle.agents.forEach(a => agents.add(a));\n\n // Plan 015 §0/C6 — agent frontmatter `rules:` bindings are the single\n // source of truth and were previously ignored entirely. Collect them from\n // the orchestrator, every subagent, and the inherited parent's agents so\n // `resolved.agents` and `resolved.rules` can never disagree.\n for (const agentFile of agents) {\n for (const rule of await this.extractRulesFromAgent(agentFile)) {\n rules.add(rule);\n }\n }\n\n // Plan 015 §0/D2 — fail fast instead of letting installer.ts silently skip\n // a rule file that does not exist under registry/rules/.\n const sortedRules = Array.from(rules).sort();\n this.assertRulesExist(sortedRules, `bundle \"${bundle.name}\"`);\n\n return {\n targetBundle: bundle.name,\n agents: Array.from(agents),\n skills: Array.from(skills),\n workflows: Array.from(workflows),\n rules: sortedRules,\n };\n }\n\n // Check if identifier refers to a specific single item (agent, skill, or workflow)\n const agentPath = path.join(this.registryDir, 'agents', identifier.endsWith('.md') ? identifier : `${identifier}.md`);\n if (await fs.pathExists(agentPath)) {\n return {\n agents: [path.basename(agentPath)],\n skills: [],\n workflows: [],\n rules: [],\n };\n }\n\n const sanitizedSkillId = identifier.replace(/\\.md$/, '').replace(/--/g, '-');\n const skillPath = path.join(this.registryDir, 'skills', identifier);\n const sanitizedSkillPath = path.join(this.registryDir, 'skills', sanitizedSkillId);\n if (await fs.pathExists(skillPath)) {\n return {\n agents: [],\n skills: [identifier],\n workflows: [],\n rules: [],\n };\n } else if (await fs.pathExists(sanitizedSkillPath)) {\n return {\n agents: [],\n skills: [sanitizedSkillId],\n workflows: [],\n rules: [],\n };\n }\n\n const workflowSkillPath = path.join(this.registryDir, 'skills', `workflow-${sanitizedSkillId}`);\n if (await fs.pathExists(workflowSkillPath)) {\n return {\n agents: [],\n skills: [`workflow-${sanitizedSkillId}`],\n workflows: [],\n rules: [],\n };\n }\n\n // Legacy fallback check for standalone workflow file if present\n const workflowFileName = identifier.startsWith('workflow-') ? `${identifier}.md` : `workflow-${identifier}.md`;\n const workflowPath = path.join(this.registryDir, 'workflows', workflowFileName);\n if (await fs.pathExists(workflowPath)) {\n return {\n agents: [],\n skills: [],\n workflows: [path.basename(workflowPath)],\n rules: [],\n };\n }\n\n throw new Error(`Item or bundle \"${identifier}\" not found in registry.`);\n }\n\n public async find(query: string = '', options?: SearchOptions): Promise<SearchResults> {\n const manifest = await this.loadBundles();\n const q = query.trim().toLowerCase();\n\n let matchedBundles: BundleDefinition[] = [];\n if (!options?.type || options.type === 'bundle') {\n matchedBundles = Object.values(manifest.bundles).filter(b => {\n if (options?.domain && b.domain?.toLowerCase() !== options.domain.toLowerCase()) {\n return false;\n }\n if (!q) return true;\n return (\n b.name.toLowerCase().includes(q) ||\n b.description.toLowerCase().includes(q) ||\n b.category?.toLowerCase().includes(q) ||\n b.domain?.toLowerCase().includes(q) ||\n b.aliases?.some(a => a.toLowerCase().includes(q))\n );\n });\n }\n\n const agentsDir = path.join(this.registryDir, 'agents');\n let matchedAgents: string[] = [];\n if (!options?.type || options.type === 'agent') {\n if (await fs.pathExists(agentsDir)) {\n const files = await fs.readdir(agentsDir);\n matchedAgents = files.filter(f => {\n if (!q) return true;\n return f.toLowerCase().includes(q);\n });\n }\n }\n\n const skillsDir = path.join(this.registryDir, 'skills');\n let matchedSkills: string[] = [];\n if (!options?.type || options.type === 'skill' || options.type === 'workflow') {\n if (await fs.pathExists(skillsDir)) {\n const dirs = await fs.readdir(skillsDir);\n matchedSkills = dirs.filter(d => {\n if (!q) return true;\n return d.toLowerCase().includes(q);\n });\n }\n }\n\n // Support workflow search: matches skills with workflow- prefix or any legacy workflows folder\n let matchedWorkflows: string[] = [];\n if (!options?.type || options.type === 'workflow') {\n matchedWorkflows = matchedSkills.filter(s => s.startsWith('workflow-'));\n const workflowsDir = path.join(this.registryDir, 'workflows');\n if (await fs.pathExists(workflowsDir)) {\n const files = await fs.readdir(workflowsDir);\n const legacyMatches = files.filter(f => f.endsWith('.md')).filter(f => {\n if (!q) return true;\n return f.toLowerCase().includes(q);\n });\n legacyMatches.forEach(f => {\n if (!matchedWorkflows.includes(f)) matchedWorkflows.push(f);\n });\n }\n }\n\n return {\n bundles: matchedBundles,\n agents: matchedAgents,\n skills: matchedSkills,\n workflows: matchedWorkflows,\n };\n }\n\n /**\n * Plan 015 Step 1 / §0/C6 — extract the `rules:` binding from an agent's YAML\n * frontmatter. Rules are declared as a BLOCK SEQUENCE:\n * rules:\n * - git-guardrails.md\n * Never regex for an inline `rules: [a, b]`. Returns `[]` (never throws) when\n * the file is missing, has no frontmatter, or the YAML is unparsable so that\n * resolution stays resilient; existence of the referenced rule files is\n * enforced separately by `assertRulesExist`.\n */\n private async extractRulesFromAgent(agentFileName: string): Promise<string[]> {\n const cached = this.agentRuleCache.get(agentFileName);\n if (cached) {\n return cached;\n }\n\n let declared: string[] = [];\n const agentPath = path.join(this.registryDir, 'agents', agentFileName);\n if (await fs.pathExists(agentPath)) {\n const content = await fs.readFile(agentPath, 'utf8');\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (match) {\n try {\n const meta = (yaml.parse(match[1]) as { rules?: unknown } | null) ?? {};\n if (Array.isArray(meta.rules)) {\n declared = meta.rules.filter((r): r is string => typeof r === 'string');\n }\n } catch {\n declared = [];\n }\n }\n }\n\n this.agentRuleCache.set(agentFileName, declared);\n return declared;\n }\n\n /**\n * Plan 015 §0/D2 — a declared rule binding that cannot be satisfied is a\n * configuration defect, not something to skip silently: installer.ts guards\n * its copy loop with `pathExists`, so a typo would otherwise deploy no rule at\n * all with no error surfaced anywhere.\n */\n private assertRulesExist(rules: string[], context: string): void {\n for (const rule of rules) {\n if (!fs.existsSync(path.join(this.registryDir, 'rules', rule))) {\n throw new Error(\n `Registry validation error: ${context} references rule \"${rule}\" which does not exist in registry/rules/.`\n );\n }\n }\n }\n\n /**\n * ADR 0015 — fail-fast validation of planningLoop configuration.\n * @throws if any bundle violates planner-orchestrator invariants.\n */\n private validateBundles(manifest: BundlesManifest): void {\n const validModes: string[] = ['subagent-first', 'planner-orchestrator'];\n\n for (const [name, bundle] of Object.entries(manifest.bundles)) {\n // Plan 015 §0/D2 — declared rule bindings must resolve on disk.\n if (Array.isArray(bundle.rules)) {\n for (const rule of bundle.rules) {\n if (!fs.existsSync(path.join(this.registryDir, 'rules', rule))) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" references rule \"${rule}\" which does not exist in registry/rules/.`\n );\n }\n }\n }\n\n const pl = bundle.planningLoop;\n if (!pl || !pl.enabled) continue; // no planning → skip\n\n // resolve mode: absent → subagent-first (ADR 0014 backward compat)\n const mode: string = pl.mode ?? 'subagent-first';\n\n if (!validModes.includes(mode)) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has unknown planningLoop.mode \"${mode}\". ` +\n `Valid modes: ${validModes.join(', ')}`\n );\n }\n\n // Plan 022 H1 (owner decision 2026-09-25): iteration caps are Tier-2-only. Only an\n // organization-tier coordinator may carry a Consultation Budget (rendered as maxTurns);\n // Tier-1 domain agents stay uncapped.\n if (pl.budget) {\n if (bundle.tier !== 'organization') {\n throw new Error(\n `Registry validation error: bundle \"${name}\" declares a Consultation Budget but is not an organization-tier bundle. ` +\n 'Iteration caps (planningLoop.budget.maxIterations) are Tier-2-only.'\n );\n }\n const cap = pl.budget.maxIterations;\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has planningLoop.budget.maxIterations ${String(cap)}; expected a positive integer.`\n );\n }\n }\n\n if (mode === 'planner-orchestrator') {\n if (pl.budget) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has planningLoop.mode \"planner-orchestrator\" ` +\n 'but also declares a Consultation Budget (budget). Planner-orchestrator bundles must not declare budget.'\n );\n }\n if (pl.sidekicks) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has planningLoop.mode \"planner-orchestrator\" ` +\n 'but also declares sidekicks. Planner-orchestrator bundles must not declare sidekicks.'\n );\n }\n }\n }\n }\n}\n\n/**\n * Plan 021 (ADR 0021 decision 9) — loads the Declared-Delta Registry\n * (`registry/translation-ledger.json`, the Translation Ledger repurposed: dispositions now\n * classify host-native deltas above the Contract Floor). Fail-fast: an entry without a valid\n * classification (`mapped|approximated|degraded|unsupported`) or without a rationale throws.\n */\nexport function loadTranslationLedger(\n registryDir = 'registry',\n): import('./types.js').TranslationLedgerEntry[] {\n const ledgerPath = path.join(registryDir, 'translation-ledger.json');\n const parsed: unknown = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));\n // Accept both the seed shape ({ semantics, entries }) and a bare entries array (fixtures).\n const entries = Array.isArray(parsed) ? parsed : (parsed as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n throw new Error(`Declared-Delta Registry error: ${ledgerPath} must be a JSON array of entries or carry an \"entries\" array.`);\n }\n const validDispositions = new Set(['mapped', 'approximated', 'degraded', 'unsupported']);\n return entries.map((raw, index) => {\n const entry = raw as Record<string, unknown>;\n const feature = entry.feature;\n const host = entry.host;\n const disposition = entry.disposition;\n const rationale = entry.rationale;\n if (typeof feature !== 'string' || feature.trim() === '') {\n throw new Error(`Declared-Delta Registry error: entries[${index}] needs a non-empty feature.`);\n }\n if (typeof host !== 'string' || host.trim() === '') {\n throw new Error(`Declared-Delta Registry error: entries[${index}] (\"${feature}\") needs a non-empty host.`);\n }\n if (typeof disposition !== 'string' || !validDispositions.has(disposition)) {\n throw new Error(\n `Declared-Delta Registry error: entries[${index}] (\"${feature}\") needs disposition mapped|approximated|degraded|unsupported.`,\n );\n }\n if (typeof rationale !== 'string' || rationale.trim() === '') {\n throw new Error(`Declared-Delta Registry error: entries[${index}] (\"${feature}\") needs a rationale.`);\n }\n return { feature, host, disposition, rationale } as import('./types.js').TranslationLedgerEntry;\n });\n}\n","import path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { AgentHostAdapter } from './adapter.js';\nimport { isKnownHost, HOST_REGISTRY, resolveHostProjectDir } from './hosts.js';\nimport { HostProjector } from './projector.js';\nimport type { IndexableAsset } from './projector.js';\nimport { ClineProjector } from './cline-projector.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport YAML from 'yaml';\nimport type { BundleDefinition, InstallOptions, LockfileManifest, ResolvedAssets, InstallScope, InstallMethod, AgentHost, PlannedProjectionArtifact, ProjectionInfo } from './types.js';\nimport { assetOwners, mergeAssetOwners } from './types.js';\n\nexport class InstallEngine {\n private registry: RegistryResolver;\n\n constructor(registry?: RegistryResolver) {\n this.registry = registry || new RegistryResolver();\n }\n\n private async calculateHash(filePath: string): Promise<string> {\n const buffer = await fs.readFile(filePath);\n return 'sha256:' + crypto.createHash('sha256').update(buffer).digest('hex');\n }\n\n private async readLockfile(lockfilePath: string): Promise<LockfileManifest> {\n if (await fs.pathExists(lockfilePath)) {\n try {\n return await fs.readJson(lockfilePath);\n } catch {\n // Fallback to empty manifest on corrupt file\n }\n }\n\n return {\n $schema: 'https://agents-united.dev/schema/lockfile.v1.json',\n version: 1,\n installed: {\n bundles: [],\n agents: [],\n skills: [],\n workflows: [],\n },\n files: {},\n };\n }\n\n private parseHosts(options: InstallOptions): AgentHost[] {\n if (options.hosts && options.hosts.length > 0) {\n return options.hosts;\n }\n\n if (options.target) {\n const raw = Array.isArray(options.target) ? options.target.join(',') : options.target;\n const parsed = raw.split(',').map(s => s.trim().toLowerCase()) as AgentHost[];\n const valid: AgentHost[] = [];\n for (const h of parsed) {\n if (isKnownHost(h)) {\n valid.push(h);\n }\n }\n if (valid.length > 0) return valid;\n }\n\n return ['agents'];\n }\n\n private parseMethod(options: InstallOptions): InstallMethod {\n if (options.copy) return 'copy';\n if (options.symlink || options.method === 'symlink') return 'symlink';\n return options.method || 'symlink';\n }\n\n private parseScope(options: InstallOptions): InstallScope {\n if (options.global) return 'global';\n return options.scope || 'project';\n }\n\n private async deployFile(src: string, dest: string, method: InstallMethod, force?: boolean): Promise<'symlink' | 'copy'> {\n await fs.ensureDir(path.dirname(dest));\n\n if (await fs.pathExists(dest) || await fs.pathExists(dest).catch(() => false)) {\n if (force) {\n await fs.remove(dest);\n }\n }\n\n if (method === 'symlink') {\n try {\n const stat = await fs.stat(src);\n const type = stat.isDirectory() ? (process.platform === 'win32' ? 'junction' : 'dir') : 'file';\n await fs.ensureSymlink(src, dest, type);\n return 'symlink';\n } catch {\n // Fallback to copy if OS restricts symlinks\n await fs.copy(src, dest, { overwrite: true });\n return 'copy';\n }\n }\n\n await fs.copy(src, dest, { overwrite: true });\n return 'copy';\n }\n\n/**\n * Writes a projection copy (never a symlink). Projections are always translated\n * copies of canonical assets, so their bytes differ from the source.\n */\n private async deployProjection(dest: string, content: string): Promise<void> {\n await fs.ensureDir(path.dirname(dest));\n await fs.writeFile(dest, content, 'utf8');\n }\n\n /**\n * Computes the canonical `.agents/` target dir and the workspace root that contains\n * it. Projections are recorded relative to this root (e.g. '.claude/agents/x.md').\n */\n private static projectionRoot(scope: InstallScope, targetDir?: string): { agentsTarget: string; root: string } {\n const agentsTarget = AgentHostAdapter.resolveHostDir(scope, 'agents', targetDir);\n return { agentsTarget, root: path.resolve(path.dirname(agentsTarget)) };\n }\nprivate toPosix(p: string): string {\n return p.split(path.sep).join('/');\n }\n\n private canonicalRelAgent(agentFile: string): string {\n return `.agents/agents/${agentFile}`;\n }\n\n private lockRel(subdir: string, file: string): string {\n return path.join(subdir, file);\n }\n\n private destForProjection(host: string, root: string, file: string): string {\n const def = HOST_REGISTRY[host];\n const base = resolveHostProjectDir(host, root);\n if (def.agentsSubdir) return path.join(base, def.agentsSubdir, file);\n return base; // agentsmd hosts (codex) use the root AGENTS.md bridge, handled separately\n }\n\n private recordProjectedTo(lockfile: LockfileManifest, relKey: string, projPath: string): void {\n const normProj = this.toPosix(projPath);\n const posixKey = relKey.replace(/\\\\/g, '/');\n const sysKey = relKey.replace(/\\//g, path.sep);\n const targetKey = lockfile.files[posixKey] ? posixKey : (lockfile.files[sysKey] ? sysKey : relKey);\n if (!lockfile.files[targetKey]) {\n lockfile.files[targetKey] = { hash: '', installedAt: new Date().toISOString() };\n }\n const asset = lockfile.files[targetKey];\n asset.projectedTo = asset.projectedTo || [];\n if (!asset.projectedTo.includes(normProj)) {\n asset.projectedTo.push(normProj);\n }\n }\n\n private removeProjectedTo(lockfile: LockfileManifest, canonicalRelPath: string, projectedRelPath: string): void {\n const normProj = this.toPosix(projectedRelPath);\n const posixKey = canonicalRelPath.replace(/\\\\/g, '/');\n const sysKey = canonicalRelPath.replace(/\\//g, path.sep);\n const targetKey = lockfile.files[posixKey] ? posixKey : (lockfile.files[sysKey] ? sysKey : canonicalRelPath);\n const asset = lockfile.files[targetKey];\n if (asset && asset.projectedTo) {\n asset.projectedTo = asset.projectedTo.filter(p => p !== normProj);\n if (asset.projectedTo.length === 0) {\n delete asset.projectedTo;\n }\n }\n }\n\n /**\n * Plan 015c / §5.7 — host-scoped projection namespaces.\n *\n * A re-projection run is authoritative only for the paths it produces inside\n * its own host namespace. Bundle-scoped lanes (`.agents/plugins/<bundle>/`) are\n * additionally narrowed to the bundle that owns them, so re-projecting bundle A\n * never drops bundle B's plugin-lane entries.\n */\n private static projectionNamespacePrefixes(host: string, bundleName: string): string[] {\n switch (host) {\n case 'cline':\n return ['.cline/', `.agents/plugins/${bundleName}/`];\n case 'claude':\n return ['.claude/'];\n case 'cursor':\n return ['.cursor/'];\n case 'gemini':\n return ['.gemini/'];\n case 'opencode':\n return ['.opencode/'];\n case 'codex':\n return ['AGENTS.md'];\n default:\n return [];\n }\n }\n\n /**\n * Plan 015c / §5.7 — reconcile `projectedTo` instead of only appending.\n *\n * `recordProjectedTo()` appends and is never told when a projection *path*\n * changes (e.g. the ADR 0016 workflow slug rename from\n * `.cline/workflows/implement-feature-or-fix.md` to\n * `.cline/workflows/workflow-implement.md`). The obsolete-projection cleanup\n * iterates `lockfile.projections`, which no longer contains the legacy path, so\n * the stale pointer in `files[canonical].projectedTo` survived forever and\n * `agents doctor` warned \"Missing projection ... Re-run: agents add ... --fanout\"\n * — a remediation that provably cannot clear it.\n *\n * For every canonical this run actually produced projections for, drop the\n * entries inside this run's namespace that the current plan did not produce.\n * Entries for other hosts and for other bundles survive untouched.\n */\n private reconcileProjectedTo(\n lockfile: LockfileManifest,\n host: string,\n bundleName: string,\n producedByCanonical: Map<string, string[]>\n ): void {\n const prefixes = InstallEngine.projectionNamespacePrefixes(host, bundleName);\n if (prefixes.length === 0 || producedByCanonical.size === 0) return;\n\n for (const [canonical, producedPaths] of producedByCanonical) {\n const posixKey = canonical.replace(/\\\\/g, '/');\n const sysKey = canonical.replace(/\\//g, path.sep);\n const targetKey = lockfile.files[posixKey] ? posixKey : (lockfile.files[sysKey] ? sysKey : null);\n if (!targetKey) continue;\n\n const asset = lockfile.files[targetKey];\n if (!asset.projectedTo || asset.projectedTo.length === 0) continue;\n\n const produced = new Set(producedPaths.map(p => this.toPosix(p)));\n const kept = asset.projectedTo.filter(\n p => !(prefixes.some(prefix => p.startsWith(prefix)) && !produced.has(p))\n );\n\n if (kept.length === asset.projectedTo.length) continue;\n if (kept.length === 0) {\n delete asset.projectedTo;\n } else {\n asset.projectedTo = kept;\n }\n }\n }\n\n /**\n * ADR 0018 — the shared compound-lane body used by every host that owns a\n * dedicated projector (Cline per ADR 0013, Claude per ADR 0018).\n *\n * Parameterising by `host` instead of forking the body is deliberate: the two\n * lanes must stay behaviourally identical in pruning, refcounting and\n * reconcile semantics, and the Cline path is provably unchanged because it\n * passes the exact same literal `'cline'` (and the same `declared` set, plan\n * artifacts and force flag) it previously used inline.\n *\n * The host-specific plan (the projector call) stays at the call site; this body\n * is purely mechanical: prune superseded projections, deploy artifacts, record\n * refcounted projection entries, reconcile `projectedTo`, surface `projections`.\n */\n private async applyCompoundLane(\n host: AgentHost,\n bundleName: string,\n artifacts: PlannedProjectionArtifact[],\n context: {\n root: string;\n lockfile: LockfileManifest;\n declared: Set<string>;\n projections: ProjectionInfo[];\n now: string;\n force?: boolean;\n }\n ): Promise<void> {\n const { root, lockfile, declared, projections, now, force } = context;\n const newPaths = new Set(artifacts.map(a => a.relPath));\n\n // Clean up legacy or obsolete projections previously owned by this bundle.\n // This is the load-bearing migration for renames: the ADR 0016 workflow slug\n // rename, and (ADR 0018 decision 2) the `subagent-` prefix strip that moves\n // `.claude/agents/subagent-<role>.md` to `.claude/agents/<role>.md`.\n if (lockfile.projections) {\n for (const [projRelPath, proj] of Object.entries(lockfile.projections)) {\n if (proj.host === host && !newPaths.has(projRelPath) && proj.owners.includes(bundleName)) {\n proj.owners = proj.owners.filter(o => o !== bundleName);\n if (proj.owners.length === 0) {\n const absProjection = path.join(root, projRelPath);\n if (await fs.pathExists(absProjection)) {\n await fs.remove(absProjection);\n await this.removeEmptyProjectionDirs(root, projRelPath);\n }\n delete lockfile.projections[projRelPath];\n }\n if (proj.canonical) {\n this.removeProjectedTo(lockfile, proj.canonical, projRelPath);\n }\n }\n }\n }\n\n for (const artifact of artifacts) {\n const dest = path.join(root, artifact.relPath);\n if (await fs.pathExists(dest) && !force) {\n const existing = await fs.readFile(dest, 'utf8').catch(() => null);\n if (existing !== null) {\n if (artifact.managedMarker && !HostProjector.hasManagedMarker(existing)) {\n throw new Error(\n `Projection target ${artifact.relPath} already exists and is not managed by agents-united. Use --force to overwrite.`\n );\n } else if (!artifact.managedMarker) {\n const registeredProj = lockfile.projections?.[artifact.relPath];\n if (!registeredProj) {\n throw new Error(\n `Projection target ${artifact.relPath} already exists and is not managed by agents-united. Use --force to overwrite.`\n );\n }\n }\n }\n }\n\n if (artifact.content !== undefined) {\n await this.deployProjection(dest, artifact.content);\n } else if (artifact.sourceFilePath) {\n await fs.ensureDir(path.dirname(dest));\n await fs.copy(artifact.sourceFilePath, dest, { overwrite: true });\n }\n\n const deployedHash = await this.calculateHash(dest);\n lockfile.projections = lockfile.projections || {};\n const existingProj = lockfile.projections[artifact.relPath];\n const declares = artifact.kind === 'rule' || artifact.kind === 'team-manifest'\n || artifact.kind === 'plugin-manifest'\n || (artifact.canonical ? declared.has(artifact.canonical) : false);\n // A projection of a shared canonical is shared. Seed its owners from the canonical's owners,\n // or the creating bundle becomes sole owner and removing it deletes projections another owner\n // still needs (reported: `remove software-engineering` wiped the domain's `.claude/skills/*`\n // and `.claude/rules/*`, leaving \"Missing projection\" storms in doctor). Bundle-scoped lanes\n // (`.agents/plugins/<bundle>/`) stay owned by the shipping bundle alone (A6: each bundle\n // packages its own skills — an addon ships its OWN mirror, so the parent's package is not\n // needed by it); their SURVIVAL is governed separately by the Universal Coverage Rule\n // (ADR 0019) in the uninstaller, which is what keeps the package under a standing domain.\n const bundleScoped = artifact.relPath.startsWith('.agents/plugins/');\n const canonicalOwners = !bundleScoped && artifact.canonical\n ? (lockfile.files[artifact.canonical]?.owners ?? [])\n : [];\n const priorOwners = existingProj?.owners ?? [];\n const owners = Array.from(new Set([\n ...priorOwners,\n ...canonicalOwners,\n ...(declares ? [bundleName] : []),\n ]));\n\n lockfile.projections[artifact.relPath] = {\n host,\n kind: artifact.kind,\n canonical: artifact.canonical,\n owners,\n hash: deployedHash,\n installedAt: existingProj?.installedAt ?? now,\n managedMarker: artifact.managedMarker,\n };\n\n projections.push({ host, path: artifact.relPath, kind: artifact.kind, warnings: [] });\n\n // ADR 0018 decision 12 — a distribution-only artifact (the opt-in Claude plugin lane) is\n // deployed and tracked in `lockfile.projections` so doctor can see presence and drift, but\n // it is deliberately NOT a `projectedTo` target. `projectionNamespacePrefixes('claude')` is\n // `['.claude/']` on purpose: `.agents/plugins/<bundle>/` belongs to the *cline* reconcile\n // pass, and a claude pointer recorded inside it would be dropped by that pass on the next\n // Cline install — healthy artifacts turned into orphaned lockfile state.\n if (artifact.canonical && !artifact.distributionOnly) {\n this.recordProjectedTo(lockfile, artifact.canonical, artifact.relPath);\n }\n }\n\n // Plan 015c / §5.7 — authoritative reconcile pass. `recordProjectedTo` above\n // only appends, so a canonical whose projection path changed (e.g. the ADR 0016\n // workflow slug rename) kept a dangling pointer forever and `agents doctor`\n // warned about a file that can never come back. Derive the produced set from\n // this run's plan and drop this namespace's stale pointers for the canonicals\n // we just re-projected.\n const producedByCanonical = new Map<string, string[]>();\n for (const artifact of artifacts) {\n // Distribution-only artifacts are excluded here as well: they exist to be *packaged*,\n // not to serve a canonical asset, so they must not widen the produced set of this\n // namespace (which would keep a stale `.claude/**` pointer alive).\n if (!artifact.canonical || artifact.distributionOnly) continue;\n const producedPaths = producedByCanonical.get(artifact.canonical);\n if (producedPaths) {\n producedPaths.push(artifact.relPath);\n } else {\n producedByCanonical.set(artifact.canonical, [artifact.relPath]);\n }\n }\n this.reconcileProjectedTo(lockfile, host, bundleName, producedByCanonical);\n }\n\n /**\n * Plan 016 / ADR 0018 decision 12 — resolve the effective plugin-lane opt-in.\n *\n * An explicit `InstallOptions.pluginLane` always wins (the CLI passes `true` for `--plugin` and\n * `false` for `--no-plugin`); an unset flag inherits the recorded choice so that `agents update`\n * — which re-runs the installer without the flag — cannot silently prune an opted-in package.\n */\n private static effectivePluginLane(\n options: InstallOptions,\n lockfile?: LockfileManifest | null\n ): boolean {\n if (typeof options.pluginLane === 'boolean') return options.pluginLane;\n return lockfile?.pluginLane === true;\n }\n\n /**\n * ADR 0018 — the host-specific projection plan, the single input that differs per host once\n * `applyCompoundLane` shared the mechanics. `pluginLane` (Plan 016 decision 13) is honoured for\n * the **Claude lane only**: the Cline package must stay byte-identical with the flag on and off,\n * so the flag is inert for `cline`.\n */\n private static async planCompoundArtifacts(\n host: AgentHost,\n bundleDef: BundleDefinition,\n scope: InstallScope,\n resolved: ResolvedAssets,\n registryDir: string,\n pluginLane: boolean\n ): Promise<PlannedProjectionArtifact[]> {\n if (host === 'cline') {\n return ClineProjector.planCompoundProjection(bundleDef, scope, resolved, registryDir);\n }\n const artifacts = await ClaudeProjector.planCompoundProjection(bundleDef, scope, resolved, registryDir);\n if (pluginLane) {\n // Distribution-only extras (ADR 0018 decision 12): deployed and tracked through the same\n // lane, but never recorded as a `projectedTo` target (`distributionOnly` artifacts).\n artifacts.push(...await ClaudeProjector.planPluginLane(bundleDef, resolved, registryDir));\n }\n return artifacts;\n }\n\n private async removeEmptyProjectionDirs(workspaceRoot: string, projPath: string): Promise<void> {\n let dir = path.dirname(path.join(workspaceRoot, projPath));\n while (dir !== workspaceRoot && dir.startsWith(workspaceRoot)) {\n try {\n const entries = await fs.readdir(dir);\n if (entries.length > 0) break;\n await fs.rmdir(dir);\n } catch {\n break;\n }\n dir = path.dirname(dir);\n }\n }\n\n // ADR 0016: Silent auto-migration of legacy .agents/workflows/*.md into\n // .agents/skills/workflow-<name>/SKILL.md, synchronizing lockfiles and pruning empty dirs.\n public async migrateLegacyWorkspaceWorkflows(targetDir: string, lockfile?: LockfileManifest): Promise<number> {\n const subPaths = AgentHostAdapter.getSubPaths(targetDir);\n let migratedCount = 0;\n\n let targetLockfile: LockfileManifest | undefined = lockfile;\n let lockfileLoadedFromDisk = false;\n\n if (!targetLockfile && (await fs.pathExists(subPaths.lockfile))) {\n try {\n targetLockfile = await fs.readJson(subPaths.lockfile);\n lockfileLoadedFromDisk = true;\n } catch {}\n }\n\n if (await fs.pathExists(subPaths.workflowsDir)) {\n const entries = await fs.readdir(subPaths.workflowsDir).catch(() => []);\n for (const entry of entries) {\n if (entry.endsWith('.md')) {\n const legacyPath = path.join(subPaths.workflowsDir, entry);\n let skillName = entry.replace(/\\.md$/, '').replace(/--/g, '-');\n if (!skillName.startsWith('workflow-')) {\n skillName = `workflow-${skillName}`;\n }\n const targetSkillDir = path.join(subPaths.skillsDir, skillName);\n const targetSkillFile = path.join(targetSkillDir, 'SKILL.md');\n\n if (!(await fs.pathExists(targetSkillFile))) {\n await fs.ensureDir(targetSkillDir);\n const legacyContent = await fs.readFile(legacyPath, 'utf8');\n let skillContent = legacyContent;\n const fmMatch = legacyContent.match(/^---\\r?\\n([\\s\\S]+?)\\r?\\n---/);\n if (fmMatch) {\n try {\n const meta = YAML.parse(fmMatch[1]) || {};\n meta.name = skillName;\n if (!meta.metadata) {\n meta.metadata = {\n author: 'Agents United',\n version: '1.0.0',\n icon: '🔄',\n };\n }\n const rest = legacyContent.replace(/^---\\r?\\n[\\s\\S]+?\\r?\\n---/, '');\n skillContent = `---\\n${YAML.stringify(meta).trim()}\\n---${rest}`;\n } catch {}\n }\n await fs.writeFile(targetSkillFile, skillContent, 'utf8');\n }\n await fs.remove(legacyPath).catch(() => {});\n migratedCount++;\n\n if (targetLockfile) {\n const legacyRel = this.toPosix(path.relative(targetDir, legacyPath));\n const newRel = this.toPosix(path.relative(targetDir, targetSkillFile));\n if (targetLockfile.files && targetLockfile.files[legacyRel]) {\n targetLockfile.files[newRel] = targetLockfile.files[legacyRel];\n delete targetLockfile.files[legacyRel];\n }\n if (targetLockfile.installed && targetLockfile.installed.skills) {\n if (!targetLockfile.installed.skills.includes(skillName)) {\n targetLockfile.installed.skills.push(skillName);\n }\n }\n }\n }\n }\n const remaining = await fs.readdir(subPaths.workflowsDir).catch(() => []);\n if (remaining.length === 0) {\n await fs.remove(subPaths.workflowsDir).catch(() => {});\n }\n }\n\n if (targetLockfile && targetLockfile.installed && targetLockfile.installed.workflows && targetLockfile.installed.workflows.length > 0) {\n for (const w of targetLockfile.installed.workflows) {\n let skillName = w.replace(/\\.md$/, '').replace(/--/g, '-');\n if (!skillName.startsWith('workflow-')) {\n skillName = `workflow-${skillName}`;\n }\n if (targetLockfile.installed.skills && !targetLockfile.installed.skills.includes(skillName)) {\n targetLockfile.installed.skills.push(skillName);\n }\n }\n targetLockfile.installed.workflows = [];\n }\n\n if (targetLockfile && (lockfileLoadedFromDisk || (await fs.pathExists(subPaths.lockfile)))) {\n await fs.writeJson(subPaths.lockfile, targetLockfile, { spaces: 2 });\n }\n\n return migratedCount;\n }\n\n /**\n * Dry-run: compute the projection plan (paths + warnings) without writing anything.\n */\n private async buildProjections(\n fanoutHosts: string[],\n resolved: ResolvedAssets,\n registryDir: string,\n scope: InstallScope,\n targetDir?: string,\n pluginLane = false\n ): Promise<ProjectionInfo[]> {\n const infos: ProjectionInfo[] = [];\n if (fanoutHosts.length === 0) return infos;\n const { root } = InstallEngine.projectionRoot(scope, targetDir);\n\n for (const host of fanoutHosts) {\n if (host === 'codex') {\n infos.push({ host, path: 'AGENTS.md', kind: 'bridge', warnings: [] });\n continue;\n }\n\n if (host === 'cline' || host === 'claude') {\n const bundleDef = resolved.targetBundle ? await this.registry.getBundle(resolved.targetBundle) : undefined;\n if (bundleDef) {\n const artifacts = await InstallEngine.planCompoundArtifacts(\n host as AgentHost,\n bundleDef,\n scope,\n resolved,\n registryDir,\n pluginLane\n );\n for (const artifact of artifacts) {\n infos.push({ host, path: artifact.relPath, kind: artifact.kind, warnings: [] });\n }\n continue;\n }\n }\n\n const base = resolveHostProjectDir(host, root);\n const subdir = HOST_REGISTRY[host].agentsSubdir ?? 'agents';\n for (const agentFile of resolved.agents) {\n const content = await fs.readFile(path.join(registryDir, 'agents', agentFile), 'utf8');\n const res = HostProjector.projectAgent(content, HOST_REGISTRY[host].profile, this.canonicalRelAgent(agentFile));\n const dest = path.join(base, subdir, agentFile);\n infos.push({ host, path: this.toPosix(path.relative(root, dest)), kind: 'role', warnings: res.warnings });\n }\n }\n return infos;\n }\n\n /**\n * Real fan-out: project canonical `.agents/` agents into each non-bridge host, build\n * the root AGENTS.md bridge for `codex`, and record every projection in the lockfile\n * of the canonical `.agents/` store that `targetDir` points at.\n */\n private async applyFanout(\n fanoutHosts: string[],\n resolved: ResolvedAssets,\n registryDir: string,\n scope: InstallScope,\n targetDir: string,\n lockfile: LockfileManifest,\n options: InstallOptions,\n projections: ProjectionInfo[]\n ): Promise<void> {\n if (fanoutHosts.length === 0) return;\n const { root } = InstallEngine.projectionRoot(scope, options.targetDir);\n const now = new Date().toISOString();\n\n // Plan 016 / ADR 0018 decision 12 — the plugin-lane opt-in is sticky. `agents update` re-runs\n // the installer without `--plugin`, so an unset flag must mean \"keep the recorded choice\"\n // rather than \"prune the opted-in package\"; only an explicit `false` (CLI `--no-plugin`) turns\n // it off. Persisted for the same reason `fanout` is.\n const pluginLane = InstallEngine.effectivePluginLane(options, lockfile);\n if (fanoutHosts.includes('claude')) {\n if (pluginLane) {\n lockfile.pluginLane = true;\n } else if (options.pluginLane === false) {\n delete lockfile.pluginLane;\n }\n }\n\n for (const host of fanoutHosts) {\n if (host === 'codex') {\n const assets: IndexableAsset[] = [];\n resolved.agents.forEach(f => assets.push({ name: f.replace(/\\.md$/, ''), type: 'agent', relPath: `.agents/agents/${f}` }));\n resolved.workflows.forEach(f => assets.push({ name: f.replace(/\\.md$/, ''), type: 'workflow', relPath: `.agents/workflows/${f}` }));\n resolved.skills.forEach(s => assets.push({ name: s, type: 'skill', relPath: `.agents/skills/${s}/SKILL.md` }));\n const bridge = HostProjector.buildAgentsMdIndex(assets);\n const bridgeDest = path.join(root, 'AGENTS.md');\n if (await fs.pathExists(bridgeDest) && !options.force) {\n const existing = await fs.readFile(bridgeDest, 'utf8');\n if (!HostProjector.hasManagedMarker(existing)) {\n throw new Error(\n 'File AGENTS.md already exists at the workspace root and is not managed by agents-united. Use --force to overwrite.'\n );\n }\n // Ours (managed marker present): deterministic content — regenerate silently.\n }\n await this.deployProjection(bridgeDest, bridge);\n projections.push({ host, path: 'AGENTS.md', kind: 'bridge', warnings: [] });\n resolved.agents.forEach(f => this.recordProjectedTo(lockfile, this.lockRel('agents', f), 'AGENTS.md'));\n resolved.workflows.forEach(f => this.recordProjectedTo(lockfile, this.lockRel('workflows', f), 'AGENTS.md'));\n resolved.skills.forEach(s => this.recordProjectedTo(lockfile, this.lockRel('skills', path.join(s, 'SKILL.md')), 'AGENTS.md'));\n continue;\n }\n\n if (host === 'cline' || host === 'claude') {\n const bundleDef = resolved.targetBundle ? await this.registry.getBundle(resolved.targetBundle) : undefined;\n if (bundleDef) {\n // Declared Asset Set of this bundle (its own bundles.json fields, NOT the\n // inherited/resolved superset). Projections for inherited artifacts are not\n // owned by this bundle — only those it actually declares (plus its own\n // coordinator rule and team manifest).\n const declared = new Set<string>();\n if (bundleDef.orchestrator) declared.add(`agents/${bundleDef.orchestrator}`);\n (bundleDef.agents || []).forEach(a => declared.add(`agents/${a}`));\n (bundleDef.skills || []).forEach(s => declared.add(`skills/${s}/SKILL.md`));\n (bundleDef.workflows || []).forEach(w => declared.add(`workflows/${w}`));\n\n // ADR 0018 - the per-host plan is the only host-specific input; pruning,\n // refcounting, deployment and reconcile are shared via applyCompoundLane.\n const artifacts = await InstallEngine.planCompoundArtifacts(\n host as AgentHost,\n bundleDef,\n scope,\n resolved,\n registryDir,\n pluginLane\n );\n\n await this.applyCompoundLane(host, bundleDef.name, artifacts, {\n root,\n lockfile,\n declared,\n projections,\n now,\n force: options.force,\n });\n\n // Installed-addon freshness (plan 003): when the installed bundle extends a\n // parent essentials with its own coordinator rule + team manifest already\n // projected, re-render those two coordination artifacts excluding every\n // installed bundle listed in the lockfile, so the coordinator stops prompting\n // for addons already present. Ownership is left untouched (the parent stays\n // the sole owner). If the parent rule/manifest don't exist yet (parent not\n // installed as its own bundle), skip silently.\n if (host === 'cline' && bundleDef.parentBundle) {\n const parentDef = await this.registry.getBundle(bundleDef.parentBundle);\n if (parentDef) {\n const parentProjection = await ClineProjector.planCompoundProjection(\n parentDef,\n scope,\n resolved,\n registryDir,\n lockfile.installed.bundles\n );\n for (const artifact of parentProjection) {\n if (artifact.kind !== 'rule' && artifact.kind !== 'team-manifest') continue;\n if (artifact.content === undefined) continue;\n const dest = path.join(root, artifact.relPath);\n if (!await fs.pathExists(dest)) continue; // parent not installed as its own bundle\n await this.deployProjection(dest, artifact.content);\n const deployedHash = await this.calculateHash(dest);\n lockfile.projections = lockfile.projections || {};\n const existingProj = lockfile.projections[artifact.relPath];\n lockfile.projections[artifact.relPath] = {\n host: 'cline',\n kind: artifact.kind,\n canonical: artifact.canonical,\n // Preserve existing ownership; the parent remains the sole owner.\n owners: existingProj?.owners ?? [],\n hash: deployedHash,\n installedAt: existingProj?.installedAt ?? now,\n managedMarker: artifact.managedMarker,\n };\n }\n }\n }\n continue;\n }\n }\n\n const base = resolveHostProjectDir(host, root);\n const subdir = HOST_REGISTRY[host].agentsSubdir ?? 'agents';\n for (const agentFile of resolved.agents) {\n const content = await fs.readFile(path.join(registryDir, 'agents', agentFile), 'utf8');\n const canonicalRel = this.canonicalRelAgent(agentFile);\n // ADR 0018: the Claude dialect renderer is the only correct writer for `.claude/agents/`.\n // This fallback runs whenever a fanout cannot resolve a bundle definition — the `domain:*`\n // pseudo-entries (registry.ts resolves them to `targetBundle: 'domain:<name>'`, which is not\n // in bundles.json), addon identifiers, and bundles absent from the registry. The legacy\n // generic projector only knows the small TOOL_NAME_MAP, so it dropped `invoke_subagent` and\n // `send_message` outright; a coordinator projected that way had NO `Agent` tool at all and\n // could not delegate. Rendering through the dialect keeps the tool vocabulary, the frontmatter\n // translation and the ledger dispositions identical to the compound lane's.\n // A coordinator projected without a bundle definition still needs a real allowlist: `Agent`\n // with no parentheses grants *any* subagent, which is not the bound ADR 0018 decision 3\n // describes. The peer roster of this projection run is the best available bound — exactly the\n // specialists this run made available in this workspace.\n const isCoordinatorRole = /^\\s*type:\\s*orchestrator\\s*$/m.test(content)\n || /^\\s*mainAgent:\\s*true\\s*$/m.test(content);\n const peerRoles = resolved.agents\n .filter(f => f !== agentFile)\n .map(f => ClaudeProjector.stripSubagentPrefix(f.replace(/\\.md$/i, '')));\n const res = host === 'claude'\n ? ClaudeProjector.renderRole(content, canonicalRel, {\n allowlist: isCoordinatorRole ? peerRoles : undefined,\n })\n : HostProjector.projectAgent(content, HOST_REGISTRY[host].profile, canonicalRel);\n // ADR 0013 / ADR 0018: the compound-lane hosts (Cline, Claude) name their\n // projected roles by stripping the canonical `subagent-` prefix, so the\n // unbundled fallback must use the same names or the two writers would\n // disagree about the same role (`.cline/agents/<role>.yml`,\n // `.claude/agents/<role>.md`).\n const strippedRoleName = agentFile.replace(/\\.md$/i, '').replace(/^subagent-/, '');\n const projName = host === 'cline'\n ? `${strippedRoleName}.yml`\n : (host === 'claude' ? `${strippedRoleName}.md` : agentFile);\n const dest = path.join(base, subdir, projName);\n const projPath = this.toPosix(path.relative(root, dest));\n\n // ADR 0017 / ADR 0018: a COMPOUND-lane role is authoritative and must never be replaced by\n // this fallback. Ownership is read from the recorded canonical: the compound planner stores\n // the store-relative `agents/<file>`, while this fallback stores the `.agents/`-prefixed form\n // (`canonicalRelAgent`). The earlier broad guard — \"any role entry exists\" — also froze roles\n // that THIS fallback had written with the legacy projector, which made the degradation\n // permanent: re-projection skipped them forever, so a `domain:*` install could never be\n // repaired. Cline deliberately keeps the broad guard, because its two writers render\n // genuinely different artifacts (configured-agent YAML vs the generic translation).\n const existingRoleProj = lockfile.projections?.[projPath];\n if (existingRoleProj?.kind === 'role') {\n const compoundOwned = !(existingRoleProj.canonical ?? '').startsWith('.agents/');\n if (host === 'cline' || (host === 'claude' && compoundOwned)) {\n continue;\n }\n }\n\n if (await fs.pathExists(dest) && !options.force) {\n const existing = await fs.readFile(dest, 'utf8');\n if (!HostProjector.hasManagedMarker(existing)) {\n throw new Error(\n `Projection target ${this.toPosix(path.relative(root, dest))} already exists and is not managed by agents-united. Use --force to overwrite.`\n );\n }\n // Ours (managed marker present): deterministic content — regenerate silently.\n }\n await this.deployProjection(dest, res.content);\n // `ClaudeRenderResult` reports translation losses through its ledger, not a warnings array.\n projections.push({\n host,\n path: projPath,\n kind: 'role',\n warnings: 'warnings' in res ? res.warnings : [],\n });\n this.recordProjectedTo(lockfile, this.lockRel('agents', agentFile), projPath);\n\n // ADR 0017 / ADR 0018: record a projection entry with a matching hash for anything\n // this fallback writes, so the freshness check never reports phantom drift and the\n // bookkeeping stays consistent with the compound lane. Host value comes from the\n // loop variable, never a literal, so both compound-lane hosts are covered without\n // changing Cline semantics.\n if (host === 'cline' || host === 'claude') {\n lockfile.projections = lockfile.projections || {};\n // Projection ownership is refcounted: a projection shared with an earlier install must\n // keep that owner too. Replacing the list silently drops the first bundle's claim, after\n // which its removal strands or deletes a projection another bundle still needs.\n const existingProj = lockfile.projections[projPath];\n // Same sharing rule as the compound lane: a projection of a shared canonical is shared.\n // The fallback records canonicals as `.agents/<sub>/<file>` while the files map uses\n // `<sub>/<file>` — resolve both spellings.\n const canonicalRecord = lockfile.files[canonicalRel] ?? lockfile.files[canonicalRel.replace(/^\\.agents\\//, '')];\n lockfile.projections[projPath] = {\n host,\n kind: 'role',\n canonical: canonicalRel,\n owners: mergeAssetOwners(existingProj, resolved.targetBundle ?? undefined)\n .concat(canonicalRecord?.owners ?? [])\n .filter((o, i, arr) => arr.indexOf(o) === i),\n hash: await this.calculateHash(dest),\n installedAt: existingProj?.installedAt ?? new Date().toISOString(),\n managedMarker: true,\n };\n }\n }\n }\n }\n\n public async install(identifier: string, options: InstallOptions = {}): Promise<{ installed: ResolvedAssets; targetDirs: string[]; dryRun: boolean; method: InstallMethod; projections: ProjectionInfo[] }> {\n const scope = this.parseScope(options);\n const method = this.parseMethod(options);\n const hosts = this.parseHosts(options);\n\n const resolved = await this.registry.resolve(identifier);\n const registryDir = this.registry.getRegistryDir();\n\n const targetDirs: string[] = hosts.map(h => AgentHostAdapter.resolveHostDir(scope, h, options.targetDir));\n // Fan-out only from the canonical `.agents/` store, and only to projection-capable hosts.\n const hasCanonicalAgents = hosts.includes('agents');\n const fanoutHosts = (options.fanout || [])\n .map(h => (typeof h === 'string' ? h.trim().toLowerCase() : h))\n .filter(h => isKnownHost(h) && HOST_REGISTRY[h]?.projectionCapable);\n\n if (options.dryRun) {\n let effectiveDryFanout = fanoutHosts;\n let effectiveDryPluginLane = options.pluginLane === true;\n const agentsTarget = AgentHostAdapter.resolveHostDir(scope, 'agents', options.targetDir);\n const lockfilePath = path.join(agentsTarget, 'agents-united.json');\n if (await fs.pathExists(lockfilePath)) {\n const lockfile = await fs.readJson(lockfilePath).catch(() => null);\n if (options.fanout === undefined && hasCanonicalAgents && lockfile?.fanout) {\n effectiveDryFanout = (lockfile.fanout as string[])\n .filter(h => isKnownHost(h) && HOST_REGISTRY[h]?.projectionCapable);\n }\n // The plugin-lane opt-in is sticky (see `effectivePluginLane`), so the dry-run plan must\n // reflect the recorded choice rather than reporting a package it would not prune.\n if (options.pluginLane === undefined && lockfile?.pluginLane === true) {\n effectiveDryPluginLane = true;\n }\n }\n const projections = hasCanonicalAgents\n ? await this.buildProjections(effectiveDryFanout, resolved, registryDir, scope, options.targetDir, effectiveDryPluginLane)\n : [];\n return { installed: resolved, targetDirs, dryRun: true, method, projections };\n }\n\n\n const now = new Date().toISOString();\n // Collect projections across target-dir iterations (dedup by host+path).\n const projections: ProjectionInfo[] = [];\n const agentsTarget = AgentHostAdapter.resolveHostDir(scope, 'agents', options.targetDir);\n\n for (const targetDir of targetDirs) {\n const subPaths = AgentHostAdapter.getSubPaths(targetDir);\n\n await fs.ensureDir(subPaths.agentsDir);\n await fs.ensureDir(subPaths.skillsDir);\n if (resolved.workflows && resolved.workflows.length > 0) {\n await fs.ensureDir(subPaths.workflowsDir);\n }\n await fs.ensureDir(subPaths.rulesDir);\n\n const lockfile = await this.readLockfile(subPaths.lockfile);\n await this.migrateLegacyWorkspaceWorkflows(targetDir, lockfile);\n lockfile.scope = scope;\n lockfile.method = method;\n lockfile.hosts = hosts;\n\n // Fan-out resolution: an explicit --fanout wins and is persisted to the lockfile;\n // otherwise the fan-out recorded at the original install is inherited, so\n // `agents update` / plain re-install regenerate projections without the flag.\n const effectiveFanout = (options.fanout !== undefined ? fanoutHosts : (lockfile.fanout ?? []))\n .filter(h => isKnownHost(h) && HOST_REGISTRY[h]?.projectionCapable);\n if (options.fanout !== undefined) {\n lockfile.fanout = effectiveFanout;\n }\n\n // Declared Asset Set of the bundle being installed (its own bundles.json fields,\n // NOT the inherited/resolved superset). Inherited parent assets are deployed but\n // are NOT owned by this bundle, so a child install never over-claims provenance.\n const declared = new Set<string>();\n // A real bundle definition draws the Declared Asset Set line; a Domain-Atlas pseudo-entry\n // (`domain:*`) or unknown identifier has no definition to draw it from, so everything it\n // resolves is its declared set. Without this, the ownership gate below stamps `owners: []`\n // on every record of an unbundled install and the assets become unremovable residue.\n let hasDeclaredRoster = false;\n if (resolved.targetBundle) {\n const bundleDef = await this.registry.getBundle(resolved.targetBundle);\n if (bundleDef) {\n hasDeclaredRoster = true;\n if (bundleDef.orchestrator) declared.add(`agents/${bundleDef.orchestrator}`);\n (bundleDef.agents || []).forEach(a => declared.add(`agents/${a}`));\n (bundleDef.skills || []).forEach(s => declared.add(`skills/${s}/SKILL.md`));\n (bundleDef.workflows || []).forEach(w => declared.add(`workflows/${w}`));\n }\n }\n const declaresAsset = (assetKey: string): boolean => !hasDeclaredRoster || declared.has(assetKey);\n\n // Copy/Symlink Agents\n for (const agentFile of resolved.agents) {\n const src = path.join(registryDir, 'agents', agentFile);\n const dest = path.join(subPaths.agentsDir, agentFile);\n\n if (await fs.pathExists(dest) && !options.force && method !== 'symlink') {\n const existingHash = await this.calculateHash(dest).catch(() => null);\n const relPath = path.relative(targetDir, dest);\n if (existingHash && lockfile.files[relPath] && lockfile.files[relPath].hash !== existingHash) {\n throw new Error(`File ${relPath} has user modifications. Use --force to overwrite.`);\n }\n }\n\n const actualMethod = await this.deployFile(src, dest, method, options.force);\n const hash = await this.calculateHash(src);\n const relPath = this.toPosix(path.relative(targetDir, dest));\n // Preserve projection tracking and co-ownership across re-installs;\n // applyFanout re-records the current fan-out below (deduplicated).\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n const owners = resolved.targetBundle && declaresAsset(`agents/${agentFile}`)\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n\n if (!lockfile.installed.agents.includes(agentFile)) {\n lockfile.installed.agents.push(agentFile);\n }\n }\n\n // Copy/Symlink Skills\n for (const skillName of resolved.skills) {\n const src = path.join(registryDir, 'skills', skillName);\n const dest = path.join(subPaths.skillsDir, skillName);\n\n const actualMethod = await this.deployFile(src, dest, method, options.force);\n const skillFile = path.join(src, 'SKILL.md');\n if (await fs.pathExists(skillFile)) {\n const hash = await this.calculateHash(skillFile);\n const relPath = this.toPosix(path.relative(targetDir, path.join(subPaths.skillsDir, skillName, 'SKILL.md')));\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n const owners = resolved.targetBundle && declaresAsset(`skills/${skillName}/SKILL.md`)\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n }\n\n // Gate 7 sidecar fix (2026-09-25, ADR 0017 amendment): skill folders ship sidecar\n // files (LICENSE.txt, references/**) alongside SKILL.md. Every deployed file gets a\n // lockfile record with owners — an unrecorded sidecar is an uninstall orphan.\n const sidecarStack: string[] = [dest];\n while (sidecarStack.length > 0) {\n const dir = sidecarStack.pop() as string;\n for (const entry of await fs.readdir(dir, { withFileTypes: true })) {\n const abs = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n sidecarStack.push(abs);\n continue;\n }\n const sideRel = this.toPosix(path.relative(targetDir, abs));\n if (abs === path.join(dest, 'SKILL.md')) continue;\n const existingSide = lockfile.files[sideRel];\n const existingSideOwners = existingSide?.owners ?? [];\n const sideOwners = resolved.targetBundle && declaresAsset(`skills/${skillName}/SKILL.md`)\n ? Array.from(new Set([...existingSideOwners, resolved.targetBundle]))\n : existingSideOwners;\n lockfile.files[sideRel] = {\n hash: await this.calculateHash(abs),\n bundle: existingSide?.bundle ?? resolved.targetBundle,\n owners: sideOwners,\n method: actualMethod,\n installedAt: existingSide?.installedAt ?? now,\n ...(existingSide?.projectedTo ? { projectedTo: existingSide.projectedTo } : {}),\n };\n }\n }\n\n if (!lockfile.installed.skills.includes(skillName)) {\n lockfile.installed.skills.push(skillName);\n }\n }\n\n // Copy/Symlink Workflows\n for (const workflowFile of resolved.workflows) {\n const src = path.join(registryDir, 'workflows', workflowFile);\n const dest = path.join(subPaths.workflowsDir, workflowFile);\n\n const actualMethod = await this.deployFile(src, dest, method, options.force);\n const hash = await this.calculateHash(src);\n const relPath = this.toPosix(path.relative(targetDir, dest));\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n const owners = resolved.targetBundle && declaresAsset(`workflows/${workflowFile}`)\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n\n lockfile.installed.workflows = lockfile.installed.workflows || [];\n if (!lockfile.installed.workflows.includes(workflowFile)) {\n lockfile.installed.workflows.push(workflowFile);\n }\n }\n\n // Copy/Symlink Rules\n for (const ruleFile of resolved.rules) {\n const src = path.join(registryDir, 'rules', ruleFile);\n const dest = path.join(subPaths.rulesDir, ruleFile);\n\n if (await fs.pathExists(src)) {\n const actualMethod = await this.deployFile(src, dest, method, options.force);\n const hash = await this.calculateHash(src);\n const relPath = this.toPosix(path.relative(targetDir, dest));\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n // Rule files are bundle-derived coordination artifacts, not members of the\n // declared asset set: every installing bundle always owns the rule it deploys.\n const owners = resolved.targetBundle\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n }\n }\n\n // Update Lockfile Bundles\n if (resolved.targetBundle) {\n if (!lockfile.installed.bundles.includes(resolved.targetBundle)) {\n lockfile.installed.bundles.push(resolved.targetBundle);\n }\n lockfile.bundleVersions = lockfile.bundleVersions || {};\n const bundleDef = await this.registry.getBundle(resolved.targetBundle);\n lockfile.bundleVersions[resolved.targetBundle] = bundleDef?.version || '1.0.0';\n\n if (options.mode) {\n lockfile.bundleModes = lockfile.bundleModes || {};\n lockfile.bundleModes[resolved.targetBundle] = options.mode;\n }\n }\n\n // Fan-out canonical `.agents/` assets into selected runtimes (only when this\n // iteration is the canonical agents store AND a fan-out is in effect — either\n // passed explicitly or inherited from the lockfile).\n if (hasCanonicalAgents && effectiveFanout.length > 0 && path.resolve(targetDir) === path.resolve(agentsTarget)) {\n await this.applyFanout(effectiveFanout, resolved, registryDir, scope, targetDir, lockfile, options, projections);\n }\n\n await fs.writeJson(subPaths.lockfile, lockfile, { spaces: 2 });\n }\n\n return { installed: resolved, targetDirs, dryRun: false, method, projections };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport type { InstallScope, AgentHost } from './types.js';\nimport {\n isKnownHost,\n resolveHostProjectDir,\n resolveHostGlobalDir,\n} from './hosts.js';\n\nexport class AgentHostAdapter {\n public static resolveHostDir(scope: InstallScope = 'project', host: AgentHost = 'agents', overrideDir?: string): string {\n if (overrideDir) {\n return path.resolve(overrideDir);\n }\n\n // Behaviour back-compat: default to the canonical 'agents' dir for unknown ids.\n if (!isKnownHost(host)) {\n host = 'agents';\n }\n\n const home = os.homedir();\n const cwd = process.cwd();\n\n if (scope === 'global') {\n return resolveHostGlobalDir(host, home);\n }\n\n // Project scope\n return resolveHostProjectDir(host, cwd);\n }\n\n public static getSubPaths(targetDir: string) {\n return {\n agentsDir: path.join(targetDir, 'agents'),\n skillsDir: path.join(targetDir, 'skills'),\n workflowsDir: path.join(targetDir, 'workflows'),\n rulesDir: path.join(targetDir, 'rules'),\n lockfile: path.join(targetDir, 'agents-united.json'),\n };\n }\n}\n\n// Backward compatibility facade\nexport class TargetAdapter {\n public static resolveTargetDir(scope: InstallScope = 'project', overrideDir?: string): string {\n return AgentHostAdapter.resolveHostDir(scope, 'agents', overrideDir);\n }\n\n public static getSubPaths(targetDir: string) {\n return AgentHostAdapter.getSubPaths(targetDir);\n }\n}\n","import path from 'node:path';\nimport type { AgentHost } from './types.js';\n\nexport type ProjectionProfile =\n | 'antigravity'\n | 'claude-code'\n | 'cursor'\n | 'cline'\n | 'opencode'\n | 'agentsmd';\n\nexport type HostStatus = 'supported' | 'under-development';\n\nexport interface HostDefinition {\n id: string;\n label: string;\n projectDir: string; // '.claude' | '.cline' | '.opencode' | '.agents' | ...\n globalDirSegments: string[]; // joined under homedir, e.g. ['.claude'] or ['.config','opencode']\n agentsSubdir?: string; // 'agents' | 'agent' | undefined (agentsmd-only hosts)\n detectionMarkers: string[]; // ['.cline', '.clinerules'], ['.claude'], ...\n profile: ProjectionProfile;\n projectionCapable: boolean; // false for 'agents' (it IS the canonical) & 'gemini'\n /** Product availability. 'supported' hosts are selectable in the TUI; 'under-development' hosts are listed but unavailable (display + docs only). */\n status: HostStatus;\n}\n\nexport const HOST_REGISTRY: Record<string, HostDefinition> = {\n agents: {\n id: 'agents',\n label: 'Google Antigravity & Master Library (📁 .agents/)',\n projectDir: '.agents',\n globalDirSegments: ['.agents'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.agents'],\n profile: 'antigravity',\n projectionCapable: false,\n status: 'supported',\n },\n gemini: {\n id: 'gemini',\n label: 'Antigravity legacy (📁 .gemini/)',\n projectDir: '.gemini',\n globalDirSegments: ['.gemini', 'config'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.gemini'],\n profile: 'antigravity',\n projectionCapable: false,\n status: 'supported',\n },\n claude: {\n id: 'claude',\n label: 'Anthropic Claude Code (📁 .claude/)',\n projectDir: '.claude',\n globalDirSegments: ['.claude'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.claude'],\n profile: 'claude-code',\n projectionCapable: true,\n status: 'supported',\n },\n cursor: {\n id: 'cursor',\n label: 'Cursor IDE (📁 .cursor/)',\n projectDir: '.cursor',\n globalDirSegments: ['.cursor'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.cursor'],\n profile: 'cursor',\n projectionCapable: true,\n status: 'under-development',\n },\n cline: {\n id: 'cline',\n label: 'Cline (📁 .cline/)',\n projectDir: '.cline',\n globalDirSegments: ['.cline'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.cline', '.clinerules'],\n profile: 'cline',\n projectionCapable: true,\n status: 'supported',\n },\n opencode: {\n id: 'opencode',\n label: 'OpenCode (📁 .opencode/)',\n projectDir: '.opencode',\n globalDirSegments: ['.config', 'opencode'],\n agentsSubdir: 'agent',\n detectionMarkers: ['.opencode', 'opencode.json'],\n profile: 'opencode',\n projectionCapable: true,\n status: 'under-development',\n },\n codex: {\n id: 'codex',\n label: 'OpenAI Codex, Copilot, Aider & Zed (📄 ./AGENTS.md)',\n projectDir: '.',\n globalDirSegments: ['.codex'],\n agentsSubdir: undefined,\n detectionMarkers: ['AGENTS.md', '.codex'],\n profile: 'agentsmd',\n projectionCapable: true,\n status: 'under-development',\n },\n};\n\nexport const KNOWN_HOST_IDS = Object.keys(HOST_REGISTRY);\nexport function isKnownHost(id: string): id is keyof typeof HOST_REGISTRY {\n return Object.prototype.hasOwnProperty.call(HOST_REGISTRY, id);\n}\n/** Hosts on the product's supported focus list (Antigravity, Cline, Claude Code). */\nexport const SUPPORTED_HOST_IDS = Object.values(HOST_REGISTRY)\n .filter((h) => h.status === 'supported')\n .map((h) => h.id);\n\n/** Listed in the TUI as 🚧 Under Development: projections still render, but the host is not on the supported focus list and is unavailable in the wizard. */\nexport const UNDER_DEVELOPMENT_HOST_IDS = Object.values(HOST_REGISTRY)\n .filter((h) => h.status === 'under-development')\n .map((h) => h.id);\n\n/** Display-only: announced on the TUI but deliberately absent from HOST_REGISTRY — target formats are unverified, so they are never stubbed (Plan 017 R3). */\nexport const PLANNED_HOSTS: ReadonlyArray<{ id: string; label: string }> = [\n { id: 'kimi', label: 'Kimi / Moonshot' },\n];\n\n/** TUI availability notice: supported focus list, 🚧 Under Development tags, and planned hosts. */\nexport function hostAvailabilityNotice(): string {\n const supported = SUPPORTED_HOST_IDS.map((id) => HOST_REGISTRY[id].label).join(' · ');\n const underDev = UNDER_DEVELOPMENT_HOST_IDS.map((id) => HOST_REGISTRY[id].label).join(' · ');\n const planned = PLANNED_HOSTS.map((h) => h.label).join(' · ');\n return [\n `✅ Supported: ${supported}`,\n `🚧 Under Development (unavailable): ${underDev}`,\n `🗓 Planned: ${planned} (projector on the planning list)`,\n ].join('\\n');\n}\n\nexport function resolveHostProjectDir(host: string, cwd: string): string {\n return path.resolve(cwd, HOST_REGISTRY[host].projectDir);\n}\nexport function resolveHostGlobalDir(host: string, home: string): string {\n return path.join(home, ...HOST_REGISTRY[host].globalDirSegments);\n}\n\n/**\n * The result of turning a user-facing \"which assistants do you use?\" selection into\n * an install plan: which directories get direct installs, and which get translated\n * copies fanned out from the main library (.agents/).\n */\nexport interface InstallTargetPlan {\n /** Direct install targets. Contains 'agents' whenever any translated copy is needed. */\n hosts: AgentHost[];\n /** Projection-capable runtimes that receive translated copies from the main library. */\n fanout: string[];\n /** True when .agents/ was not selected but had to be added as the shared source. */\n addedCanonicalStore: boolean;\n}\n\n/**\n * Maps a user selection of assistants/IDEs to an install plan (Option B):\n * - `agents` (main library) and `gemini` (legacy Antigravity) install directly.\n * - Every other assistant (Claude Code, Cursor, Cline, OpenCode, Codex) receives a\n * translated copy projected from the main library — never an untranslated direct\n * install, so no runtime ever gets Antigravity-only frontmatter it cannot parse.\n * - When any translated copy is needed, the main library is added automatically.\n */\nexport function planInstallTargets(selected: string[]): InstallTargetPlan {\n const normalized = Array.from(\n new Set(selected.map(s => (typeof s === 'string' ? s.trim().toLowerCase() : '')).filter(Boolean))\n );\n const known = normalized.filter(isKnownHost);\n\n const fanout = known.filter(h => HOST_REGISTRY[h].projectionCapable);\n const hosts = known.filter(h => !HOST_REGISTRY[h].projectionCapable) as AgentHost[];\n\n let addedCanonicalStore = false;\n if (fanout.length > 0 && !hosts.includes('agents')) {\n hosts.unshift('agents');\n addedCanonicalStore = true;\n }\n if (hosts.length === 0 && fanout.length === 0) {\n hosts.push('agents');\n }\n\n return { hosts, fanout, addedCanonicalStore };\n}","import YAML from 'yaml';\nimport type { ProjectionProfile } from './hosts.js';\nimport { ClineProjector } from './cline-projector.js';\n\n/**\n * Error raised by {@link HostProjector} when a canonical file cannot be projected:\n * missing frontmatter, invalid YAML, or a serialization failure. Always carries the\n * canonical file name (relative path) and, when known, the underlying cause.\n */\nexport class ProjectionError extends Error {\n public readonly fileName: string;\n public readonly cause?: unknown;\n\n constructor(message: string, fileName: string, cause?: unknown) {\n super(message, { cause });\n this.name = 'ProjectionError';\n this.fileName = fileName;\n this.cause = cause;\n }\n}\n\n/** Result of projecting one canonical asset into a host runtime's dialect. */\nexport interface ProjectionResult {\n /** Full output file: frontmatter + managed marker + verbatim body. */\n content: string;\n /** Dropped tools, degraded orchestrator notices, etc. */\n warnings: string[];\n}\n\n/** A canonical asset destined for the root AGENTS.md bridge index. */\nexport interface IndexableAsset {\n name: string;\n type: 'agent' | 'skill' | 'workflow';\n relPath: string;\n}\n\n/**\n * Antigravity tool name -> host-native tool name. Anything not present here is\n * **unknown**: it is dropped from the output and reported in `warnings` — never kept\n * in its original form and never assigned an invented mapping. The set covers every\n * documented tool in plan 007 §5; unknown tools (e.g. invoke_subagent) are dropped.\n */\nexport const TOOL_NAME_MAP: Record<string, string> = {\n view_file: 'Read',\n replace_file_content: 'Edit',\n write_to_file: 'Write',\n run_command: 'Bash',\n grep_search: 'Grep',\n list_dir: 'Glob',\n read_file: 'Read',\n search_file_content: 'Grep',\n apply_diff: 'Edit',\n web_search: 'WebSearch',\n};\n\n/** Antigravity-only keys that must never be projected into other runtimes. */\nconst ANTIGRAVITY_ONLY_KEYS = [\n 'version',\n 'type',\n 'permissionMode',\n 'commandExecutionPolicy',\n 'mainAgent',\n 'subagent',\n 'hooks',\n 'inheritCustomizations',\n 'rules',\n 'effort',\n] as const;\n\n/** Reused from src/core/doctor.ts:48. */\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]+?)\\r?\\n---/;\n\nexport class HostProjector {\n /**\n * Splits a canonical file into its YAML frontmatter metadata and markdown body.\n * The returned body starts right after the closing `---` delimiter so callers can\n * insert a managed marker as the very first body line.\n */\n public static parseFrontmatter(\n content: string,\n fileName = '<memory>'\n ): { meta: Record<string, unknown>; body: string } {\n const match = content.match(FRONTMATTER_REGEX);\n if (!match) {\n throw new ProjectionError(\n `No YAML frontmatter found in ${fileName}. Expected a leading \"---\" block.`,\n fileName\n );\n }\n let parsed: unknown;\n try {\n parsed = YAML.parse(match[1]);\n } catch (cause) {\n const err =\n cause instanceof Error ? cause : new Error(typeof cause === 'string' ? cause : '');\n throw new ProjectionError(\n `Invalid YAML frontmatter in ${fileName}: ${err.message}`,\n fileName,\n err\n );\n }\n const meta =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n // Strip the single line terminator that ends the closing `---` delimiter so a\n // projected managed marker becomes the true first line of the returned body.\n const body = content.slice(match[0].length).replace(/^\\r?\\n/, '');\n return { meta, body };\n }\n/**\n * Projects a canonical `.agents/` file into the given {@link ProjectionProfile}'s\n * native dialect, stamping it with the managed marker and preserving the body\n * verbatim (line endings normalized to `\\n`).\n */\n public static projectAgent(\n md: string,\n profile: ProjectionProfile,\n canonicalRelPath: string\n ): ProjectionResult {\n const { meta, body } = HostProjector.parseFrontmatter(md, canonicalRelPath);\n const warnings: string[] = [];\n const normalizedBody = body.replace(/\\r\\n/g, '\\n');\n const marker = `<!-- managed-by: agents-united | profile: ${profile} | canonical: ${canonicalRelPath} | do not edit -->`;\n\n // agentsmd: AGENTS.md bridge entry (name -> link text, description -> table cell,\n // body -> link to the canonical path).\n if (profile === 'agentsmd') {\n const name = typeof meta.name === 'string' ? meta.name : '(unnamed)';\n const description =\n typeof meta.description === 'string'\n ? meta.description.replace(/[\\r\\n]+/g, ' ').replace(/\\|/g, '\\\\|')\n : '';\n const link = canonicalRelPath.replace(/\\\\/g, '/');\n const content = [\n `## ${name}`,\n '',\n `| ${name} | ${description} |`,\n '| --- | --- |',\n '',\n `[View source](${link})`,\n '',\n marker,\n '',\n ].join('\\n');\n return { content, warnings };\n }\n\n if (profile === 'cline') {\n // ADR 0013: Cline consumes configured-agent YAML (.cline/agents/<role>.yml),\n // not markdown role copies.\n const content = ClineProjector.renderConfiguredAgent(md, canonicalRelPath);\n return { content, warnings };\n }\n\n // Frontmatter profiles: claude-code, cursor, opencode. Keep name/description;\n // keep model unless `inherit`; translate tools; drop all Antigravity-only keys\n // (see field policy, plan 007 §5 step 3).\n const out: Record<string, unknown> = {};\n out.name = meta.name;\n if (typeof meta.description === 'string') {\n out.description = meta.description;\n }\n if (meta.model !== undefined && meta.model !== 'inherit') {\n out.model = meta.model;\n }\n // Explicitness guard: never let an Antigravity-only key leak into a native profile,\n // even if a future refactor stops building `out` from a clean object map.\n for (const key of ANTIGRAVITY_ONLY_KEYS) {\n delete out[key];\n }\n if (Array.isArray(meta.tools)) {\n const translated: string[] = [];\n for (const raw of meta.tools) {\n if (typeof raw !== 'string') {\n continue;\n }\n const mapped = TOOL_NAME_MAP[raw];\n if (mapped !== undefined) {\n translated.push(mapped);\n } else {\n warnings.push(\n `Dropping unknown tool \"${raw}\" for profile ${profile}: no known name mapping (never kept, never invented).`\n );\n }\n }\n out.tools = translated;\n }\n\n let yamlStr: string;\n try {\n yamlStr = YAML.stringify(out).replace(/\\r\\n/g, '\\n').trimEnd();\n } catch (cause) {\n const err = cause instanceof Error ? cause : new Error(String(cause));\n throw new ProjectionError(\n `Failed to serialize frontmatter for ${canonicalRelPath}: ${err.message}`,\n canonicalRelPath,\n err\n );\n }\n const content = `---\\n${yamlStr}\\n---\\n${marker}\\n${normalizedBody}`;\n return { content, warnings };\n }\n\n /**\n * Returns true when `content` is one of our managed projections. Agent projections\n * carry the marker as the first body line after the frontmatter; the AGENTS.md\n * bridge has no frontmatter, so the whole document is checked. Used to distinguish\n * \"our own deterministic projection\" (safe to regenerate) from foreign user files\n * (never overwritten without --force).\n */\n public static hasManagedMarker(content: string): boolean {\n const match = content.match(FRONTMATTER_REGEX);\n if (match) {\n const rest = content.slice(match[0].length).replace(/^\\r?\\n/, '');\n const firstLine = rest.split(/\\r?\\n/)[0] || '';\n return firstLine.includes('managed-by: agents-united');\n }\n return content.includes('managed-by: agents-united');\n }\n\n /**\n * Builds the root AGENTS.md bridge index, grouping canonical assets by type and\n * linking each to its canonical `.agents/` path. Deterministic for identical input.\n */\n public static buildAgentsMdIndex(\n assets: IndexableAsset[]\n ): string {\n const sections: Array<'agent' | 'skill' | 'workflow'> = ['agent', 'skill', 'workflow'];\n const lines: string[] = [];\n lines.push('# agents-united — Managed Agents Index');\n lines.push('');\n lines.push('<!-- managed-by: agents-united | profile: agentsmd | do not edit -->');\n lines.push('');\n lines.push(\n 'This index links the canonical `.agents/` store for runtimes without a subagent loader. Files under `.claude/`, `.cursor/`, `.cline/`, and `.opencode/` are machine-managed projections (see marker lines).'\n );\n lines.push('');\n for (const type of sections) {\n const heading =\n type === 'agent' ? '## Agents' : type === 'skill' ? '## Skills' : '## Workflows';\n lines.push(heading);\n lines.push('');\n const items = assets\n .filter((a) => a.type === type)\n .map((a) => ({ ...a, relPath: a.relPath.replace(/\\\\/g, '/') }));\n if (items.length === 0) {\n lines.push('_none_');\n lines.push('');\n continue;\n }\n for (const item of items) {\n lines.push(`- [${item.name}](${item.relPath})`);\n }\n lines.push('');\n }\n return lines.join('\\n');\n }\n}","import yaml from 'yaml';\nimport path from 'node:path';\nimport fs from 'fs-extra';\nimport type {\n AgentPluginManifest,\n BundleDefinition,\n ClineTeamManifest,\n InstallScope,\n PlanningLoopMode,\n ProjectionKind,\n ResolvedAssets,\n} from './types.js';\n\nexport interface PlannedClineArtifact {\n kind: ProjectionKind;\n canonical?: string;\n relPath: string; // posix root-relative path\n content?: string;\n sourceFilePath?: string; // for byte-for-byte binary/resource copy\n managedMarker: boolean;\n}\n\nexport class ClineProjector {\n /**\n * Managed marker inserted after YAML frontmatter in every rendered artifact.\n */\n private static marker(canonicalRelPath: string): string {\n const normCanonical = canonicalRelPath.replace(/\\\\/g, '/');\n return `<!-- managed-by: agents-united | profile: cline | canonical: ${normCanonical} | do not edit -->`;\n }\n\n private static runtimeNote = `## Cline runtime note\\n\\nUse the equivalent capabilities available in this Cline session. Canonical tool names describe\\nintent and may differ from Cline's runtime tool names. For delegation, prefer the configured\\nsubagent_* agent tools (projected under .cline/agents/), then session subagents; otherwise\\ncomplete the role in the main session.`;\n\n /**\n * Strip the canonical `subagent-` prefix. Cline prefixes configured-agent tool\n * names with `subagent_` itself, so keeping the prefix would produce names like\n * `subagent_subagent_marketing_growth_strategist`.\n */\n static stripSubagentPrefix(name: string): string {\n return name.trim().replace(/^subagent-/, '');\n }\n\n /**\n * Slugify a workflow display name into a usable slash-command name\n * (e.g. \"Digital Agency Full-Funnel Campaign Orchestration\" -> \"digital-agency-full-funnel-campaign-orchestration\").\n */\n static slugifyWorkflowName(name: string): string {\n return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');\n }\n\n /**\n * Render a Cline Configured Agent definition (.cline/agents/<role>.yml) from\n * canonical agent markdown content. Cline 3.x consumes YAML files with\n * frontmatter (name, description) and treats the body as the agent system prompt.\n */\n static renderConfiguredAgent(canonicalContent: string, canonicalRelPath: string, defaultMaxIterations?: number): string {\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) {\n throw new Error(`Canonical agent ${canonicalRelPath} is missing YAML frontmatter.`);\n }\n\n let parsed: Record<string, unknown> = {};\n try {\n parsed = (yaml.parse(match[1]) as Record<string, unknown>) || {};\n } catch {\n parsed = {};\n }\n\n const baseName = canonicalRelPath.replace(/\\\\/g, '/').split('/').pop() ?? '';\n const rawName = typeof parsed.name === 'string' && parsed.name.trim().length > 0\n ? parsed.name.trim()\n : baseName.replace(/\\.md$/i, '');\n const cleanFrontmatter: Record<string, unknown> = {\n name: this.stripSubagentPrefix(rawName),\n };\n if (typeof parsed.description === 'string' && parsed.description.trim().length > 0) {\n cleanFrontmatter.description = parsed.description.trim();\n }\n // ADR 0014 — canonical frontmatter is the single source of truth; the bundle\n // Consultation Budget `maxIterations` is only a default when frontmatter omits it.\n if (typeof parsed.maxIterations === 'number') {\n cleanFrontmatter.maxIterations = parsed.maxIterations;\n } else if (typeof defaultMaxIterations === 'number') {\n cleanFrontmatter.maxIterations = defaultMaxIterations;\n }\n\n const frontmatterStr = yaml.stringify(cleanFrontmatter).trim();\n const bodyStr = match[2].trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${this.marker(canonicalRelPath)}\\n\\n${this.runtimeNote}\\n\\n${bodyStr}\\n`;\n }\n\n /**\n * Derive the slash-command slug for a workflow from its frontmatter name,\n * falling back to the canonical filename. Kept separate from the renderer so the\n * projection filename and the frontmatter `name` are guaranteed to match.\n */\n static workflowSlug(canonicalContent: string, canonicalRelPath: string): string {\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n let humanName: string | undefined;\n if (match) {\n try {\n const parsed = (yaml.parse(match[1]) as Record<string, unknown>) || {};\n if (typeof parsed.name === 'string' && parsed.name.trim().length > 0) {\n humanName = parsed.name.trim();\n }\n } catch {\n // fall through to filename fallback\n }\n }\n const baseName = canonicalRelPath.replace(/\\\\/g, '/').split('/').pop() ?? '';\n return this.slugifyWorkflowName(humanName ?? baseName.replace(/\\.md$/i, ''));\n }\n\n /**\n * Render a Cline workflow projection (.cline/workflows/<slug>.md). The frontmatter\n * `name` is slugified so the workflow surfaces as a usable /<slug> command; the\n * human-readable title stays in `description` and the untouched body.\n */\n static renderWorkflowProjection(canonicalContent: string, canonicalRelPath: string): string {\n const slug = this.workflowSlug(canonicalContent, canonicalRelPath);\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n let description: string | undefined;\n if (match) {\n try {\n const parsed = (yaml.parse(match[1]) as Record<string, unknown>) || {};\n if (typeof parsed.description === 'string' && parsed.description.trim().length > 0) {\n description = parsed.description.trim();\n }\n } catch {\n // description stays undefined\n }\n }\n\n const cleanFrontmatter: Record<string, unknown> = { name: slug };\n if (description) cleanFrontmatter.description = description;\n\n const frontmatterStr = yaml.stringify(cleanFrontmatter).trim();\n const bodyStr = match ? match[2].trim() : canonicalContent.trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${this.marker(canonicalRelPath)}\\n\\n${bodyStr}\\n`;\n }\n\n /**\n * Render a Cline SKILL.md preserving frontmatter and placing managed marker after delimiter.\n */\n static renderSkillMd(canonicalContent: string, canonicalRelPath: string): string {\n const normCanonical = canonicalRelPath.replace(/\\\\/g, '/');\n const marker = `<!-- managed-by: agents-united | profile: cline | canonical: ${normCanonical} | do not edit -->`;\n\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) {\n return `${marker}\\n\\n${canonicalContent.trim()}`;\n }\n\n const rawYaml = match[1];\n const rawBody = match[2];\n\n let parsed: Record<string, unknown> = {};\n try {\n parsed = (yaml.parse(rawYaml) as Record<string, unknown>) || {};\n } catch {\n parsed = {};\n }\n\n const frontmatterStr = yaml.stringify(parsed).trim();\n const bodyStr = rawBody.trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${marker}\\n\\n${bodyStr}\\n`;\n }\n\n /**\n * Render Team Manifest YAML matching ClineTeamManifest schema.\n * @param excludeAddons optional addon names to omit from `recommendedAddons`\n * (used to stop advertising bundles already present in the workspace).\n */\n static renderTeamManifest(bundle: BundleDefinition, scope: InstallScope, excludeAddons: string[] = []): string {\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n const coordinatorName = coordinatorFile.replace(/\\.md$/, '');\n const coordinatorCanonical = `agents/${coordinatorFile}`;\n\n const roles = (bundle.agents || []).map((agentFile) => ({\n name: agentFile.replace(/\\.md$/, ''),\n canonicalPath: `agents/${agentFile}`,\n }));\n\n const sortedSkills = [...(bundle.skills || [])].sort();\n const rawWorkflows = bundle.workflows && bundle.workflows.length > 0\n ? bundle.workflows\n : (bundle.skills || []).filter(s => s.startsWith('workflow-'));\n const sortedWorkflows = [...rawWorkflows].sort();\n const recommendedAddons = (bundle.recommendedAddons || []).filter(a => !excludeAddons.includes(a));\n\n const manifest: ClineTeamManifest = {\n schemaVersion: 1,\n bundle: bundle.name,\n scope,\n coordinator: {\n name: coordinatorName,\n canonicalPath: coordinatorCanonical,\n },\n roles,\n skills: sortedSkills,\n workflows: sortedWorkflows,\n recommendedAddons,\n activation: {\n preferred: 'named-team',\n fallbacks: ['adaptive-session', 'single-orchestrator'],\n },\n };\n\n // ADR 0014/0015 — planning-loop bundles declare the loop config and persona map.\n // ADR 0015 defense-in-depth: omit budget/sidekicks from manifest YAML for\n // planner-orchestrator bundles (loader validation should already reject these).\n if (bundle.planningLoop?.enabled) {\n const mode = bundle.planningLoop.mode ?? 'subagent-first';\n manifest.planningLoop = {\n enabled: true,\n mode,\n // Only emit budget/sidekicks for subagent-first bundles\n ...(mode === 'subagent-first' && bundle.planningLoop.budget ? { budget: bundle.planningLoop.budget } : {}),\n ...(mode === 'subagent-first' && bundle.planningLoop.sidekicks ? { sidekicks: bundle.planningLoop.sidekicks } : {}),\n };\n if (bundle.personaAliases && Object.keys(bundle.personaAliases).length > 0) {\n manifest.personas = Object.entries(bundle.personaAliases).map(([persona, role]) => ({ persona, role }));\n }\n }\n\n return yaml.stringify(manifest);\n }\n\n /**\n * Render the coordinator rule file (.agents/plugins/<bundle>/rules/agents-united-<bundle>.md).\n * @param excludeAddons optional addon names to omit from the \"Recommended Addon\n * Policy\" list (used to stop advertising bundles already installed).\n */\n static renderCoordinatorRule(bundle: BundleDefinition, scope: InstallScope, excludeAddons: string[] = []): string {\n const marker = `<!-- managed-by: agents-united | profile: cline | bundle: ${bundle.name} | do not edit -->`;\n const manifestRelPath = scope === 'global'\n ? `~/.agents/plugins/${bundle.name}/agents-united/teams/${bundle.name}.yaml`\n : `.agents/plugins/${bundle.name}/agents-united/teams/${bundle.name}.yaml`;\n\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n const coordinatorName = coordinatorFile.replace(/\\.md$/, '');\n const coordinatorCanonical = `agents/${coordinatorFile}`;\n\n // Plan 016 post-gate fix — the roster must name the host projection as well as the canonical\n // definition. The Cline runtime discovers configured agents at `.cline/agents/<role>.yml` with the\n // `subagent-` prefix stripped (ADR 0013), so a canonical-only line sent the coordinator looking for a\n // file name that does not exist under that namespace. Mirrors the dual-path shape of the\n // \"Installed Workflows & Workflow Skills\" section directly below.\n const specialistLines = (bundle.agents || []).map((agentFile) => {\n const name = agentFile.replace(/\\.md$/, '');\n const projected = this.stripSubagentPrefix(name);\n return `- **${name}**: \\`.cline/agents/${projected}.yml\\` | \\`.agents/agents/${agentFile}\\``;\n });\n\n const rawWorkflows = [\n ...((bundle.workflows || []).map(w => w.replace(/\\.md$/i, ''))),\n ...((bundle.skills || []).filter(s => s.startsWith('workflow-'))),\n ];\n const uniqueWorkflows = Array.from(new Set(rawWorkflows)).sort();\n const workflowSection = uniqueWorkflows.length > 0\n ? `\\n### Installed Workflows & Workflow Skills\\n` +\n `Execute multi-step engineering procedures by consulting the corresponding workflow skill runbook (\\`.agents/skills/<name>/SKILL.md\\`) or triggering its slash command (\\`/<name>\\`):\\n` +\n uniqueWorkflows.map(w => `- **${w}**: \\`.cline/workflows/${w}.md\\` | \\`.agents/skills/${w}/SKILL.md\\``).join('\\n') +\n '\\n'\n : '';\n\n const addons = (bundle.recommendedAddons || []).filter(a => !excludeAddons.includes(a));\n const addonSection = addons.length > 0\n ? `\\n### Recommended Addon Policy\\nWhen user tasks require capabilities from: ${addons.join(', ')}, explain the capability and request user confirmation to install via \\`agents add <addon> -t cline -y\\` before running the installation.`\n : '';\n\n // ADR 0014/0015 — planning-loop bundles replace the soft delegation hint with a\n // mandatory planning policy. Bundles without the flag render byte-identical\n // output to the legacy rule. Mode determines which planning policy is rendered.\n const planning = bundle.planningLoop?.enabled === true ? bundle.planningLoop : undefined;\n const mode: PlanningLoopMode = planning?.mode ?? 'subagent-first';\n const budget = planning?.budget;\n const delegationStep = planning\n ? (mode === 'subagent-first'\n ? '2. **Subagent-First Delegation Policy (ADR 0014)**: execute specialist work through the configured `subagent_*` agent tools (projected under `.cline/agents/`), assigning non-overlapping scopes. Complete specialist work in the main session ONLY if the subagent tools are genuinely absent from this runtime or the task is trivial (single-file read, one-line answer, formatting) — never as a convenience or speed choice.'\n : '2. **Planner-Orchestrator Delegation Policy (ADR 0015)**: execute specialist work through the configured `subagent_*` agent tools (projected under `.cline/agents/`), assigning non-overlapping scopes. Complete specialist work in the main session ONLY if the subagent tools are genuinely absent from this runtime or the task is trivial (single-file read, one-line answer, formatting) — never as a convenience or speed choice.')\n : '2. Delegate specialist tasks using the configured `subagent_*` agent tools (projected under `.cline/agents/`) when available, assigning non-overlapping scopes; fall back to Agent Teams (`team_spawn_teammate`) or session subagents as needed.';\n\n \n \n const planningSection = planning\n ? (mode === 'subagent-first'\n ? '\\n\\n## Subagent-First Planning Dialogue Loop (ADR 0014)' +\n 'Run this loop BEFORE any substantive execution on a non-trivial task. Delegation-first is mandatory, not advisory.\\n\\n' +\n '### Phase 0 — User Alignment\\n' +\n 'If the user\\'s brief is ambiguous, grill it Socratically with the user first: `/grill-me` (strategy / non-code) or `/grill-with-docs` (code & docs; writes ADRs and updates CONTEXT.md).\\n\\n' +\n '### Phase 0.5 — Sidekick Clarification\\n' +\n 'Spawn at most ' + (planning.sidekicks?.max ?? 2) + ' relevant specialists (spawnable `subagent_*` tools) INTO this planning conversation to resolve remaining ambiguity. Sidekicks advise you; you relay their questions to the user.\\n\\n' +\n '### Phase 1 — Specialist Council\\n' +\n 'Have every relevant specialist return a Scope-of-Work Statement (max ' + (budget?.summaryWordCap ?? 150) + ' words): (1) my scope, (2) inputs I need from peers, (3) my deliverable per my own workflows, (4) at most 2 open questions.\\n\\n' +\n '### Phase 2 — Delegation Map\\n' +\n 'Synthesize the council output into a task → specialist map and present it to the user BEFORE execution. Then delegate per the map.\\n\\n' +\n '### Consultation Budget (hard caps)\\n' +\n '- Planning rounds (orchestrator ↔ council): max ' + (budget?.maxPlanningRounds ?? 2) + '\\n' +\n '- Peer exchanges per specialist pair: max ' + (budget?.maxPeerExchangesPerPair ?? 2) + ' directed questions\\n' +\n '- Scope-of-Work statement length: max ' + (budget?.summaryWordCap ?? 150) + ' words\\n' +\n '- Specialist per-invocation iteration cap: maxIterations: ' + (budget?.maxIterations ?? 8) + ' (rendered into .cline/agents/*.yml)'\n : '\\n\\n## Planner-Orchestrator Policy (ADR 0015)' +\n 'Plan solo, delegate execution. This mode replaces the Subagent-First Planning Dialogue Loop for single-discipline domain bundles.\\n\\n' +\n '### Phase 0 — User Alignment (solo)\\n' +\n 'If the user\\'s brief is ambiguous, grill it Socratically yourself: `/grill-me` (strategy / non-code) or `/grill-with-docs` (code & docs). Consult the bundle\\'s skills directly whenever they help you plan — you have the same skill access as your specialists. Do NOT spawn specialists during planning.\\n\\n' +\n '### Planning Aid Boundary\\n' +\n 'While planning you may consult skills and reason to give the user PROVISIONAL answers and estimates. A concrete deliverable — data analysis, code, assets, documents — is specialist work: defer it to the delegation map, never produce it yourself during planning.\\n\\n' +\n '### Phase 2 — Delegation Map (solo-composed)\\n' +\n 'Compose the task → specialist map from your own domain expertise and the skill runbooks, and present it to the user BEFORE execution.\\n\\n' +\n '### Execution\\n' +\n 'Delegate every deliverable to the configured `subagent_*` agent tools (projected under `.cline/agents/`), assigning non-overlapping scopes. Complete specialist work in the main session ONLY if the subagent tools are genuinely absent from this runtime or the task is trivial (single-file read, one-line answer, formatting) — never as a convenience or speed choice.')\n : '';\n\n const personaSection = planning && bundle.personaAliases && Object.keys(bundle.personaAliases).length > 0\n ? `\n\n### Persona → Spawnable Tool Map\n| Persona | Role / Spawnable tool |\n|---|---|\n${Object.entries(bundle.personaAliases).map(([persona, role]) => {\n const target = role.startsWith('subagent-')\n ? `${role} → \\`subagent_${this.stripSubagentPrefix(role).replace(/-/g, '_')}\\``\n : `${role} (you, the coordinator)`;\n return `| ${persona} | ${target} |`;\n}).join('\\n')}`\n : '';\n\n return `# Agents United — ${bundle.name} Coordinator Rule\n${marker}\n\n> Installed bundle: **${bundle.name}** (${scope} scope)\n> Team Manifest: \\`${manifestRelPath}\\`\n> Coordinator role: \\`${coordinatorName}\\` (\\`.agents/${coordinatorCanonical}\\`)\n\n## Activation Protocol\n1. At session start, read the Team Manifest (\\`${manifestRelPath}\\`) and coordinator role prompt (\\`.agents/${coordinatorCanonical}\\`).\n${delegationStep}\n3. For lightweight read-only research, use session subagents.\n4. Only specialist roles declared in the Team Manifest are active in this workspace.\n${planningSection}${personaSection}\n${specialistLines.length > 0 ? `\\n### Installed Specialist Roles\\n${specialistLines.join('\\n')}` : ''}\n${workflowSection}${addonSection}\n`;\n }\n\n /**\n * Plan all compound artifacts for a bundle installation into Cline.\n * @param excludeAddons optional addon names forwarded to the coordinator rule and\n * team manifest renderers so already-installed bundles are not advertised.\n */\n static async planCompoundProjection(\n bundle: BundleDefinition,\n scope: InstallScope,\n resolved: ResolvedAssets,\n registryDir: string,\n excludeAddons: string[] = []\n ): Promise<PlannedClineArtifact[]> {\n const artifacts: PlannedClineArtifact[] = [];\n const baseDir = `.agents/plugins/${bundle.name}`;\n\n // 0. Agent Plugin manifest (.agents/plugins/<bundle-name>/plugin.json)\n // agent-plugins.org v1.0.0. Its presence hard-stops Cline's code-plugin\n // scanner for this directory (isAgentPluginDirectory) and makes the package\n // portable to other Agent Plugins-conforming clients.\n const agentPluginManifest: AgentPluginManifest = {\n $schema: 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',\n name: bundle.name,\n version: bundle.version || '1.0.0',\n description: bundle.description || '',\n };\n artifacts.push({\n kind: 'plugin-manifest',\n relPath: `${baseDir}/plugin.json`.replace(/\\\\/g, '/'),\n content: JSON.stringify(agentPluginManifest, null, 2),\n managedMarker: false,\n });\n\n // 1. Configured agent roles (.cline/agents/<role>.yml) - Cline 3.x natively\n // discovers these and exposes each as a spawnable subagent_<name> tool.\n for (const agentFile of resolved.agents) {\n const canonicalRel = `agents/${agentFile}`;\n const srcPath = path.join(registryDir, 'agents', agentFile);\n if (await fs.pathExists(srcPath)) {\n const content = await fs.readFile(srcPath, 'utf8');\n const rendered = this.renderConfiguredAgent(\n content,\n canonicalRel,\n bundle.planningLoop?.enabled === true ? bundle.planningLoop.budget?.maxIterations : undefined, // ADR 0015: planner-orchestrator has no budget → undefined → key absent from .yml\n );\n const roleName = this.stripSubagentPrefix(agentFile.replace(/\\.md$/i, ''));\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `.cline/agents/${roleName}.yml`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // 2. Skills (.agents/plugins/<bundle-name>/skills/<skill>/**) - kept inside the\n // Agent Plugin package for cross-client portability (ADR 0013, decision 1).\n // Cline discovers the canonical .agents/skills/ copies natively, so no\n // additional Cline-side skill projection is emitted.\n for (const skillName of resolved.skills) {\n const skillSrcDir = path.join(registryDir, 'skills', skillName);\n if (await fs.pathExists(skillSrcDir)) {\n const entries = await fs.readdir(skillSrcDir, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n const entryRel = path.relative(skillSrcDir, path.join(entry.parentPath || skillSrcDir, entry.name)).replace(/\\\\/g, '/');\n const canonicalRel = `skills/${skillName}/${entryRel}`;\n const targetRel = `${baseDir}/skills/${skillName}/${entryRel}`.replace(/\\\\/g, '/');\n const fullSrcPath = path.join(skillSrcDir, entryRel);\n\n if (entry.name === 'SKILL.md') {\n const content = await fs.readFile(fullSrcPath, 'utf8');\n const rendered = this.renderSkillMd(content, canonicalRel);\n artifacts.push({\n kind: 'skill',\n canonical: canonicalRel,\n relPath: targetRel,\n content: rendered,\n managedMarker: true,\n });\n } else {\n // Auxiliary resource: byte-for-byte copy\n artifacts.push({\n kind: 'skill',\n canonical: canonicalRel,\n relPath: targetRel,\n sourceFilePath: fullSrcPath,\n managedMarker: false,\n });\n }\n }\n }\n }\n }\n\n // 3. Workflows (.cline/workflows/<slug>.md) - natively surfaced as /<slug>\n // slash commands by Cline 3.x.\n // ADR 0016: Project workflow skills (name starting with workflow-) into .cline/workflows/\n // retaining the workflow-* prefix so Cline users retain /workflow-* slash commands.\n const workflowSkillNames = resolved.skills.filter(s => s.startsWith('workflow-'));\n for (const skillName of workflowSkillNames) {\n const canonicalRel = `skills/${skillName}/SKILL.md`;\n const skillFilePath = path.join(registryDir, 'skills', skillName, 'SKILL.md');\n if (await fs.pathExists(skillFilePath)) {\n const content = await fs.readFile(skillFilePath, 'utf8');\n const slug = skillName;\n const rendered = this.renderWorkflowProjection(content, canonicalRel);\n artifacts.push({\n kind: 'workflow',\n canonical: canonicalRel,\n relPath: `.cline/workflows/${slug}.md`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // Fallback for any legacy resolved.workflows entries\n for (const workflowFile of resolved.workflows || []) {\n const canonicalRel = `workflows/${workflowFile}`;\n const srcPath = path.join(registryDir, 'workflows', workflowFile);\n if (await fs.pathExists(srcPath)) {\n const content = await fs.readFile(srcPath, 'utf8');\n const slug = this.workflowSlug(content, canonicalRel);\n const rendered = this.renderWorkflowProjection(content, canonicalRel);\n artifacts.push({\n kind: 'workflow',\n canonical: canonicalRel,\n relPath: `.cline/workflows/${slug}.md`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // 4. Coordinator Rule (.cline/rules/agents-united-<bundle>.md) - natively\n // loaded as an always-active rule by Cline 3.x.\n const ruleContent = this.renderCoordinatorRule(bundle, scope, excludeAddons);\n artifacts.push({\n kind: 'rule',\n relPath: `.cline/rules/agents-united-${bundle.name}.md`.replace(/\\\\/g, '/'),\n content: ruleContent,\n managedMarker: true,\n });\n\n // 5. Projected Domain Rules (.cline/rules/<rule-file>)\n // Plan 015 Step 2 / §0/C6d + §0/C7. Cline has no per-agent rule scoping,\n // so `.cline/rules/` is the only lane available: project ONLY the\n // deduplicated, agent-referenced rule set (never the whole registry/rules\n // tree), sorted for byte-stable lockfile hashes and `agents doctor`.\n // Host entrypoint rules belong to their own hosts and are skipped.\n const hostEntrypointRules = new Set(['GEMINI.md', 'AGENTS.md', 'CLAUDE.md', 'CURSOR.md']);\n for (const ruleFile of [...(resolved.rules || [])].sort()) {\n if (hostEntrypointRules.has(ruleFile)) continue;\n const ruleSrcPath = path.join(registryDir, 'rules', ruleFile);\n if (await fs.pathExists(ruleSrcPath)) {\n const ruleFileContent = await fs.readFile(ruleSrcPath, 'utf8');\n // Rule modules carry no YAML frontmatter, so the managed marker is line 1.\n // HostProjector.hasManagedMarker() accepts that (its no-frontmatter path is\n // a plain includes('managed-by: agents-united')).\n artifacts.push({\n kind: 'rule',\n canonical: `rules/${ruleFile}`,\n relPath: `.cline/rules/${ruleFile}`.replace(/\\\\/g, '/'),\n content: `${ClineProjector.marker(`rules/${ruleFile}`)}\\n\\n${ruleFileContent.trim()}\\n`,\n managedMarker: true,\n });\n }\n }\n\n // 6. Team Manifest (.agents/plugins/<bundle-name>/agents-united/teams/<bundle>.yaml)\n const manifestContent = this.renderTeamManifest(bundle, scope, excludeAddons);\n artifacts.push({\n kind: 'team-manifest',\n relPath: `${baseDir}/agents-united/teams/${bundle.name}.yaml`.replace(/\\\\/g, '/'),\n content: manifestContent,\n managedMarker: false,\n });\n\n return artifacts;\n }\n}\n","import yaml from 'yaml';\nimport { managedGuardHooks } from './guard.js';\nimport path from 'node:path';\nimport fs from 'fs-extra';\nimport type {\n BundleDefinition,\n ClaudePluginManifest,\n\n InstallScope,\n LedgerDisposition,\n ProjectionKind,\n ResolvedAssets,\n TranslationLedgerEntry,\n} from './types.js';\nimport type { ClaudeDialect } from './types.js';\nimport { RESIDUE_PATTERNS_BY_HOST } from './residue-patterns.js';\nimport { CLAUDE_FIELD_POLICY, validateProjectionOverlays } from './overlays.js';\n\n/** Result of rendering one canonical asset into the Claude dialect. */\nexport interface ClaudeRenderResult {\n content: string;\n ledger: TranslationLedgerEntry[];\n}\n\n/** A planned Claude projection artifact (workspace-root-relative POSIX path). */\nexport interface PlannedClaudeArtifact {\n kind: ProjectionKind;\n canonical?: string;\n relPath: string;\n content?: string;\n sourceFilePath?: string;\n /** ADR 0018 decision 12 — distribution-only artifact: tracked, but never a `projectedTo` target. */\n distributionOnly?: boolean;\n\n managedMarker: boolean;\n}\n\n/** Canonical frontmatter keys that map 1:1 into a Claude field (no loss, no ledger row). */\nconst INLINE_KEYS = new Set([\n 'name',\n 'description',\n 'model',\n 'permissionMode',\n 'effort',\n 'tools',\n 'maxIterations',\n 'projections',\n]);\n\n/**\n * ADR 0018 decision 9 — every canonical feature that cannot survive verbatim carries exactly one\n * disposition. A drop with no entry here is a hard error, never a silent warning.\n */\nconst FEATURE_LEDGER: Record<string, { disposition: LedgerDisposition; rationale: string }> = {\n version: { disposition: 'mapped', rationale: 'Authoring metadata for the canonical store; no Claude field needed.' },\n type: { disposition: 'mapped', rationale: 'Canonical role discriminator; Claude distinguishes roles by file location.' },\n mainAgent: { disposition: 'mapped', rationale: 'Canonical masthead flag; Claude decides main-thread status at launch (--agent).' },\n subagent: { disposition: 'mapped', rationale: 'Canonical masthead flag; every file under .claude/agents/ is a subagent.' },\n inheritCustomizations: { disposition: 'mapped', rationale: 'Claude loads CLAUDE.md and project memory unless omitClaudeMd is set (flag-gated).' },\n commandExecutionPolicy: { disposition: 'unsupported', rationale: 'Antigravity shell policy has no Claude frontmatter equivalent; Bash permissions cover it.' },\n hooks: { disposition: 'unsupported', rationale: 'Antigravity hook schema (PreInvocation/PostInvocation matchers) differs from Claude hook events; canonical prose hooks are not translated and stay advisory. The one enforced hook is the managed PreToolUse guard every role carries (Plan 022 H5).' },\n rules: { disposition: 'mapped', rationale: 'Agent-referenced rules project into the lean .claude/rules/ lane.' },\n effort: { disposition: 'mapped', rationale: 'Reasoning effort passes through to the Claude effort field.' },\n invoke_subagent: { disposition: 'mapped', rationale: 'Delegation maps to the Claude Agent tool (allowlist on coordinators).' },\n send_message: { disposition: 'approximated', rationale: 'Maps to the Claude SendMessage tool; cross-session reach differs from Antigravity messaging.' },\n manage_task: { disposition: 'approximated', rationale: 'Maps to the Claude task tools (TaskCreate/TaskUpdate), but the live tools reference says they are \"provided by default only on the models listed under Task tool availability, and on other models when you opt in\" — so the grant can resolve to nothing depending on the model.' },\n schedule: { disposition: 'approximated', rationale: 'Maps to Cron tools, but Antigravity reactive liveness timers are event-driven rather than cron-scheduled.' },\n define_subagent: { disposition: 'approximated', rationale: 'Claude agents are pre-defined: runtime subagent definition is unavailable, so the prompt delegates via the Agent tool.' },\n manage_subagents: { disposition: 'approximated', rationale: 'Claude manages subagent lifecycle itself; the roster is static and the prompt delegates via the Agent tool.' },\n ask_question: { disposition: 'approximated', rationale: 'Claude exposes AskUserQuestion only in the main conversation (excluded from subagents by default).' },\n generate_image: { disposition: 'unsupported', rationale: 'Claude Code exposes no image-generation tool; asset creation must happen outside the agent run.' },\n skills: { disposition: 'degraded', rationale: 'Claude subagents discover project skills and can invoke them; the canonical preload list is not injected to avoid paying its token cost on every spawn.' },\n mcpServers: { disposition: 'degraded', rationale: 'Claude supports per-subagent mcpServers, but the canonical descriptor dialect differs; MCP wiring stays host-configured via the MCP location registry (translation deferred).' },\n};\n\nconst MARKER_PROFILE = 'claude';\n/**\n * The marker string `HostProjector.hasManagedMarker()` greps for. Kept as one constant because\n * the JSON plugin manifest (which cannot carry the HTML-comment form) must contain exactly this\n * substring to be recognised as ours by both `applyCompoundLane` and `agents doctor`.\n */\nconst MARKER_PREFIX = 'managed-by: agents-united';\n\nconst HOST = 'claude';\nconst ENTRYPOINT_RULES = new Set(['CLAUDE.md', 'CLAUDE.local.md', 'GEMINI.md', 'AGENTS.md', 'CURSOR.md']);\n\n/**\n * ADR 0018 decision 3 — a coordinator is the delegation hub, so its projected tool set is the\n * translated canonical list unioned with this baseline. Specialists keep exactly their declared\n * (translated) tools plus `Agent`, so a read-mostly specialist is never silently granted write tools.\n */\nconst COORDINATOR_BASELINE_TOOLS = ['Read', 'Write', 'Edit', 'Bash', 'Grep', 'Glob'];\n\n/** Plan 022 H3 — tools a `plan` (read-only) role never holds on this host. */\nconst READ_ONLY_EXCLUDED_TOOLS: ReadonlySet<string> = new Set(['Write', 'Edit', 'NotebookEdit', 'Bash']);\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/;\n\nconst RUNTIME_NOTE = `## Claude runtime note\n\nDelegation runs through the Agent tool: the coordinator spawns the specialists named in its own tools\nallowlist; specialists hold no Agent tool and never spawn peers (the coordinator relays and wakes them). Canonical tool names in this prompt were rewritten to their\nClaude equivalents; a fenced code block may still show the original spelling because code is preserved\nbyte-for-byte. A subagent does not hand results to a peer: its final report is returned to the\nconversation that spawned it, and on Claude Code v2.1.271+ in auto mode the runtime delivers it through the\nSubagentHandback tool.\n\nEnforced guard: a PreToolUse hook in this file's frontmatter blocks \\`git push --force\\`, \\`.env\\` writes and\n\\`vercel --prod\\` (exit 2, with the reason); ask the user to run those steps themselves.\nAll other lifecycle hooks described in this prompt are advisory: this host does not fire them.`;\n\n/** Plan 022 H5 / Plan 023 A0 — the managed PreToolUse guard (single source: guard.ts). */\nconst MANAGED_HOOKS = managedGuardHooks();\n\nexport class ClaudeProjector {\n /** Pure data (Plan 017 lifts this object into a shared HostDialectSpec). */\n public static readonly CLAUDE_DIALECT: ClaudeDialect = {\n id: 'claude',\n nameRegex: /^[a-z0-9]+(-[a-z0-9]+)*$/,\n toolVocabulary: {\n view_file: 'Read',\n read_file: 'Read',\n replace_file_content: 'Edit',\n apply_diff: 'Edit',\n multi_replace_file_content: 'Edit',\n write_to_file: 'Write',\n run_command: 'Bash',\n grep_search: 'Grep',\n search_file_content: 'Grep',\n list_dir: 'Glob',\n find_by_name: 'Glob',\n web_search: 'WebSearch',\n search_web: 'WebSearch',\n read_url_content: 'WebFetch',\n invoke_subagent: 'Agent',\n define_subagent: 'Agent',\n manage_subagents: 'Agent',\n send_message: 'SendMessage',\n manage_task: 'TaskCreate',\n schedule: 'CronCreate',\n ask_question: 'AskUserQuestion',\n // The runtime's own hand-off channel for subagents (Claude Code v2.1.271+, auto mode): it delivers\n // a subagent's final report to whichever conversation receives that subagent's result. It has no\n // Antigravity-dialect equivalent, so the lane grants it to specialists directly (see renderRole);\n // the token exists so a canonical agent could also name it explicitly.\n subagent_handback: 'SubagentHandback',\n },\n bodyToolVocabulary: {\n view_file: 'Read',\n read_file: 'Read',\n write_to_file: 'Write',\n replace_file_content: 'Edit',\n apply_diff: 'Edit',\n multi_replace_file_content: 'Edit',\n run_command: 'Bash',\n grep_search: 'Grep',\n find_by_name: 'Glob',\n list_dir: 'Glob',\n search_web: 'WebSearch',\n read_url_content: 'WebFetch',\n invoke_subagent: 'Agent',\n define_subagent: 'the Agent tool',\n manage_subagents: 'the Agent tool',\n // ADR 0018 decision 8 requires canonical tool names in prose to be rewritten, not just the\n // frontmatter vocabulary: a specialist reading \"reach a peer with `send_message`\" would otherwise\n // look for a tool that does not exist on this host. Whole-word and code-fence-aware like the rest.\n send_message: 'SendMessage',\n manage_task: 'TaskCreate',\n ask_question: 'AskUserQuestion',\n generate_image: 'image generation (unsupported on this host)',\n // `schedule` is deliberately absent: it is an ordinary English word, so rewriting it in prose\n // would corrupt sentences. Its loss is recorded once at frontmatter level instead.\n },\n commandVocabulary: {\n team_command: 'Agent Teams (opt-in: agents start --host claude --teams)',\n deep_planning_command: '/workflow-grill',\n interview_command: '/grill-me',\n },\n permissionModeMap: {\n acceptEdits: 'acceptEdits',\n readOnly: 'plan',\n requestReview: 'default',\n strict: 'default',\n },\n modelMap: { pro: 'sonnet', flash: 'haiku' },\n // ADR 0018 decision 7, amended 2026-09-22 by the product owner. The canonical catalog declares\n // `model: inherit` on all 59 agents, which made `inherit` the de-facto value and left every\n // projection inheriting the *session* model instead of a chosen posture. The intended posture is\n // explicit — coordinators reason on Opus at high effort, specialists run on Sonnet at medium\n // effort — so `inherit` now resolves to a role default rather than being omitted. Both fields are\n // documented subagent frontmatter: `model` accepts sonnet|opus|haiku|fable|<full id>|inherit, and\n // `effort` (low|medium|high|xhigh|max) overrides the session effort level. Caveats recorded rather\n // than coded around: Opus is unavailable on some plans, so a workspace may need a different anchor;\n // and `xhigh`/`max` exist only on newer models. Both are one-constant changes here.\n roleModelDefaults: { coordinator: 'opus', specialist: 'sonnet' },\n roleEffortDefaults: { coordinator: 'high', specialist: 'medium' },\n bodySectionOverrides: [\n {\n // Plan 019 escape hatch (2026-09-25): the old anchor — \"Subagent Delegation & Host\n // Routing\" — was residue (it described OTHER runtimes: Antigravity's language_server.exe\n // limitation and Cline's subagent_* tools) and the G1 purge deleted it. Its Claude-side\n // rendering survives as this per-host overlay, keyed on the neutral \"Delegation\n // Mechanics\" stub in canonical; hosts without an overlay render the stub itself.\n heading: /^#{2,3}\\s*.*Delegation Mechanics/m,\n replacement: [\n '### ⚡ Subagent Delegation & Agent Routing (Claude Code)',\n '',\n '- **Delegation tool**: spawn specialists with the `Agent` tool. Your `tools` allowlist names exactly the specialist types you may call (the projected definitions in `.claude/agents/`, with the `subagent-` prefix stripped); calling any other type fails, so send work only to those names. There are no `TypeName`/`Role`/`Prompt` fields — `Agent` takes the specialist type and one self-contained prompt, so put the role, the scope boundaries and the acceptance criteria inside that prompt.',\n '- **Parallel work**: spawn independent specialists in one turn — each runs in its own context window and returns its result to you (delivered by `SubagentHandback` on Claude Code v2.1.271+ in auto mode). You are the single synthesis and relay point: name who reported what, and never let one specialist wait on another.',\n '- **Your allowlist is the whole domain team, not only what is installed.** A listed type whose definition is not in this workspace yet will fail to spawn: say so, recommend installing it (`agents add <addon>`), and handle that slice yourself if the user declines. Never delegate to a type outside your allowlist.',\n '- **Agent Teams (opt-in, `--teams`)**: the lead can spawn *teammates* instead of subagents and message them directly with `SendMessage`. The scaffold is experimental — one team per session, a fixed lead, no nested teams — so never make it load-bearing.',\n ].join('\\n'),\n },\n ],\n budgets: { skillDescriptionChars: 1536, agentDescriptionTokens: 15000 },\n maxRuleLines: 200,\n };\n\n /** `subagent-backend-architect` -> `backend-architect` (Step 0 proved zero collisions). */\n public static stripSubagentPrefix(name: string): string {\n return name.trim().replace(/^subagent-/, '');\n }\n\n /** Uniform managed-projection marker; always the first line of the projected body. */\n private static marker(canonicalRelPath: string): string {\n const norm = canonicalRelPath.replace(/\\\\/g, '/');\n return `<!-- managed-by: agents-united | profile: ${MARKER_PROFILE} | canonical: ${norm} | do not edit -->`;\n }\n\n /** `generative_ui` -> `generative-ui`: every dialect requires lowercase-hyphen names. */\n public static normalizeSkillName(name: string): string {\n return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');\n }\n\n private static parse(\n canonicalContent: string,\n canonicalRelPath: string\n ): { meta: Record<string, unknown>; body: string } {\n const match = canonicalContent.match(FRONTMATTER_REGEX);\n if (!match) {\n throw new Error(`Cannot project ${canonicalRelPath}: no YAML frontmatter found.`);\n }\n let parsed: unknown;\n try {\n parsed = yaml.parse(match[1]);\n } catch (cause) {\n const err = cause instanceof Error ? cause : new Error(String(cause));\n throw new Error(`Cannot project ${canonicalRelPath}: invalid YAML frontmatter (${err.message}).`);\n }\n const meta =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n return { meta, body: match[2].replace(/^\\r?\\n/, '') };\n }\n\n private static ledgerEntry(feature: string): TranslationLedgerEntry | undefined {\n const known = FEATURE_LEDGER[feature];\n if (!known) return undefined;\n return { feature, host: HOST, disposition: known.disposition, rationale: known.rationale };\n }\n\n /** Guard: an unmapped feature must never be dropped without a recorded disposition. */\n private static requireDisposition(feature: string, canonicalRelPath: string): TranslationLedgerEntry {\n const entry = ClaudeProjector.ledgerEntry(feature);\n if (!entry) {\n throw new Error(\n `No translation-ledger disposition recorded for feature \"${feature}\" in ${canonicalRelPath}. ` +\n 'Add it to FEATURE_LEDGER so translation loss is never silent (ADR 0018 decision 9).'\n );\n }\n return entry;\n }\n\n /**\n * Replace one canonical body section, matched by its heading, with a host-native rendering.\n *\n * Deterministic: the section runs from the matched heading to the next heading of the same or a higher\n * level (an `h3` stops at the next `h1`/`h2`), and trailing blank lines and the `---` separator are left\n * with the following section so the document structure is unchanged. A heading that is absent is a no-op.\n */\n private static replaceSection(body: string, heading: RegExp, replacement: string): string {\n const lines = body.split('\\n');\n const start = lines.findIndex(line => heading.test(line));\n if (start < 0) return body;\n\n let end = lines.length;\n for (let i = start + 1; i < lines.length; i += 1) {\n if (/^#{1,2}\\s/.test(lines[i])) {\n end = i;\n break;\n }\n }\n while (end > start + 1 && (lines[end - 1].trim() === '' || lines[end - 1].trim() === '---')) end -= 1;\n\n return [...lines.slice(0, start), ...replacement.split('\\n'), ...lines.slice(end)].join('\\n');\n }\n\n /**\n * Deterministically rewrite canonical tool names in prompt prose (whole-word, case-sensitive,\n * fenced code blocks byte-preserved) and report a disposition for every rewrite that loses fidelity.\n */\n /** Command tokens are ledger citizens (Plan 020 note 7) — rewritten and dispositioned. */\n private static readonly COMMAND_LEDGER: Record<string, { disposition: LedgerDisposition; rationale: string }> = {\n team_command: { disposition: 'mapped', rationale: 'Rewritten to the host team entrypoint (Agent Teams opt-in).' },\n deep_planning_command: { disposition: 'mapped', rationale: 'Rewritten to the host deep-planning command.' },\n interview_command: { disposition: 'mapped', rationale: 'Rewritten to the host interview command.' },\n };\n\n /** Plan 019 safety net: residue-headed sections never survive into a projection body. */\n private static dropResidueSections(body: string): string {\n let out = body;\n for (const pattern of RESIDUE_PATTERNS_BY_HOST.claude) {\n out = out.replace(\n new RegExp(`(^|\\\\n)#{1,6}[^\\\\n]*${pattern.source}[^\\\\n]*\\\\n[\\\\s\\\\S]*?(?=\\\\n#{1,6} |$)`, 'g'),\n '$1'\n );\n }\n return out;\n }\n\n /** Plan 019 safety net: residual residue phrases in prose are neutralized deterministically. */\n private static scrubResiduePhrases(body: string): string {\n return body\n .replace(/Cline & CLI/g, 'other hosts')\n .replace(/language_server(\\.exe)?/g, 'the runtime')\n .replace(/Nested Subagent Delegation/g, 'peer delegation')\n .replace(/Host Routing/g, 'host delegation');\n }\n\n /** Whole-word canonical tokens surviving OUTSIDE code fences after the rewrite pass. */\n private static survivingBodyTokens(body: string): string[] {\n const vocab: Record<string, string> = {\n ...ClaudeProjector.CLAUDE_DIALECT.toolVocabulary,\n ...ClaudeProjector.CLAUDE_DIALECT.commandVocabulary,\n };\n const prose = body\n .split(/(```[\\s\\S]*?```)/g)\n .filter((_, index) => index % 2 === 0)\n .join('\\n');\n return Object.keys(vocab).filter(token =>\n new RegExp(`(^|[^A-Za-z0-9_])${token}(?=[^A-Za-z0-9_]|$)`).test(prose)\n );\n }\n\n public static rewriteBody(body: string): { body: string; ledger: TranslationLedgerEntry[] } {\n const ledger = new Map<string, TranslationLedgerEntry>();\n // Plan 019 residue safety net (canonical is purge-clean since the G1 group): residue\n // sections are dropped and residual phrases neutralized so no synthetic or legacy body\n // can leak foreign-host residue into a projection.\n body = ClaudeProjector.dropResidueSections(body);\n body = ClaudeProjector.scrubResiduePhrases(body);\n // ADR 0018 decision 8: sections that describe another host's routing are re-rendered first, so the\n // vocabulary pass below only ever rewrites host-neutral prose.\n for (const override of ClaudeProjector.CLAUDE_DIALECT.bodySectionOverrides) {\n body = ClaudeProjector.replaceSection(body, override.heading, override.replacement);\n }\n // Note 7: command tokens join the tool tokens in the prose rewrite and carry dispositions.\n const vocab: Record<string, string> = {\n ...ClaudeProjector.CLAUDE_DIALECT.bodyToolVocabulary,\n ...ClaudeProjector.CLAUDE_DIALECT.commandVocabulary,\n };\n const tokens = Object.keys(vocab).sort((a, b) => b.length - a.length);\n const parts = body.split(/(```[\\s\\S]*?```)/g);\n\n const rewritten = parts.map((part, index) => {\n if (index % 2 === 1) return part; // fenced code block, preserved byte-for-byte\n let text = part;\n for (const token of tokens) {\n const re = new RegExp(`(^|[^A-Za-z0-9_])${token}(?=[^A-Za-z0-9_]|$)`, 'g');\n if (!text.match(re)) continue;\n const command = ClaudeProjector.COMMAND_LEDGER[token];\n const entry: TranslationLedgerEntry | undefined = command\n ? { feature: token, host: HOST, disposition: command.disposition, rationale: command.rationale }\n : ClaudeProjector.ledgerEntry(token);\n if (entry) ledger.set(token, entry);\n text = text.replace(re, `$1${vocab[token]}`);\n }\n return text;\n });\n\n return { body: rewritten.join(''), ledger: [...ledger.values()] };\n }\n\n /** Render `.claude/agents/<role>.md` from a canonical agent definition. */\n public static renderRole(\n canonicalContent: string,\n canonicalRelPath: string,\n opts: { allowlist?: string[]; maxTurns?: number } = {}\n ): ClaudeRenderResult {\n const { meta, body } = ClaudeProjector.parse(canonicalContent, canonicalRelPath);\n const ledger = new Map<string, TranslationLedgerEntry>();\n\n // 1. Every canonical key either maps inline or carries a recorded disposition.\n for (const key of Object.keys(meta)) {\n if (INLINE_KEYS.has(key)) continue;\n const entry = ClaudeProjector.requireDisposition(key, canonicalRelPath);\n ledger.set(entry.feature, entry);\n }\n\n const rawName =\n typeof meta.name === 'string' && meta.name.trim().length > 0\n ? meta.name.trim()\n : path.basename(canonicalRelPath).replace(/\\.md$/i, '');\n const out: Record<string, unknown> = { name: ClaudeProjector.stripSubagentPrefix(rawName) };\n\n if (typeof meta.description === 'string' && meta.description.trim().length > 0) {\n out.description = meta.description.trim();\n }\n\n // 2. Delegation first (ADR 0018 decision 3), then the translated vocabulary.\n // Coordinator-ness comes from the canonical role, not only from a caller-supplied allowlist: a\n // bundle-less fanout (`domain:*`, addons) has no bundle definition to derive specialists from, and\n // without this a projected orchestrator silently took the specialist posture (sonnet, bare `Agent`,\n // hand-back tool) — the operator saw `orchestrator-engineering.md` on Sonnet while\n // `orchestrator-digital-agency.md` was on Opus. `type: orchestrator` / `mainAgent: true` is the\n // catalog's own discriminator (9 orchestrators, 50 subagents).\n const isCoordinator = !!(opts.allowlist && opts.allowlist.length > 0)\n || meta.type === 'orchestrator'\n || meta.mainAgent === true;\n const tools: string[] = [];\n if (isCoordinator) {\n tools.push(opts.allowlist && opts.allowlist.length > 0 ? `Agent(${opts.allowlist.join(', ')})` : 'Agent');\n }\n for (const raw of Array.isArray(meta.tools) ? meta.tools : []) {\n if (typeof raw !== 'string') continue;\n const entry = ClaudeProjector.ledgerEntry(raw);\n if (entry) ledger.set(entry.feature, entry);\n const mapped = ClaudeProjector.CLAUDE_DIALECT.toolVocabulary[raw];\n if (!mapped) {\n ClaudeProjector.requireDisposition(raw, canonicalRelPath);\n continue;\n }\n if (!tools.includes(mapped)) tools.push(mapped);\n }\n\n // ADR 0018 decision 3: when the coordinator has an allowlist, `Agent(<specialists>)` IS the\n // delegation grant. Adding a bare `Agent` next to it is contradictory — the docs treat `Agent`\n // without parentheses as \"allow spawning any subagent without restrictions\" — so the allowlist\n // would be silently widened. Keep the allowlist as the single source of the bound.\n if (opts.allowlist && opts.allowlist.length > 0) {\n const withoutBareAgent = tools.filter(t => t !== 'Agent');\n tools.length = 0;\n tools.push(...withoutBareAgent);\n }\n\n // Plan 022 H2 (gate 5): specialists hold NO Agent tool. Inside a subagent definition the\n // runtime ignores an `Agent(type, …)` list, so any Agent entry is an unbounded nested-spawn\n // grant; omitting it is the only bound (Claude Code sub-agents reference, 2026-09-25). A\n // canonical `invoke_subagent`-family token on a specialist is therefore dropped here.\n if (!isCoordinator) {\n const withoutAgent = tools.filter(t => t !== 'Agent' && !t.startsWith('Agent('));\n tools.length = 0;\n tools.push(...withoutAgent);\n }\n\n // 3. Posture: permissionMode, model tier, effort, and the consultation budget.\n if (isCoordinator) {\n for (const base of COORDINATOR_BASELINE_TOOLS) {\n if (!tools.includes(base)) tools.push(base);\n }\n } else if (!tools.includes('SubagentHandback')) {\n // `SubagentHandback` is the runtime's own hand-off channel for subagents — it \"delivers a\n // subagent's final report to whichever conversation receives that subagent's result\" (Claude Code\n // v2.1.271+, auto mode). Granting it makes the documented Tier-1 hand-off explicit instead of\n // implicit; where the runtime does not provide it the entry simply does not resolve, and Claude\n // Code only refuses to launch an agent when NOTHING in its tools list resolves.\n tools.push('SubagentHandback');\n }\n const permission =\n typeof meta.permissionMode === 'string'\n ? ClaudeProjector.CLAUDE_DIALECT.permissionModeMap[meta.permissionMode] ?? 'default'\n : undefined;\n if (permission === 'plan') {\n // Plan 022 H3 (gate 6): a read-only role holds no mutating capability at all — command\n // execution included, since a shell can write files regardless of the permission mode.\n const restricted = tools.filter(t => !READ_ONLY_EXCLUDED_TOOLS.has(t));\n tools.length = 0;\n tools.push(...restricted);\n }\n out.tools = tools;\n if (permission) out.permissionMode = permission;\n\n // `inherit` is the catalog's marker for \"no opinion\" — all 59 agents declare `model: inherit` — so it\n // resolves to the role posture instead of being dropped: coordinators opus, specialists sonnet\n // (ADR 0018 d7 as amended 2026-09-22). An explicitly declared tier or effort always wins, so per-agent\n // authoring survives (eight specialists declare `effort: high` today and keep it).\n const declaredModel = typeof meta.model === 'string' ? meta.model : undefined;\n const mappedModel = declaredModel && declaredModel !== 'inherit'\n ? ClaudeProjector.CLAUDE_DIALECT.modelMap[declaredModel] ?? declaredModel\n : undefined;\n out.model = mappedModel ?? (isCoordinator\n ? ClaudeProjector.CLAUDE_DIALECT.roleModelDefaults.coordinator\n : ClaudeProjector.CLAUDE_DIALECT.roleModelDefaults.specialist);\n const declaredEffort = typeof meta.effort === 'string' ? meta.effort : undefined;\n out.effort = declaredEffort ?? (isCoordinator\n ? ClaudeProjector.CLAUDE_DIALECT.roleEffortDefaults.coordinator\n : ClaudeProjector.CLAUDE_DIALECT.roleEffortDefaults.specialist);\n if (typeof opts.maxTurns === 'number') out.maxTurns = opts.maxTurns;\n // Plan 022 H5: the managed guard (never the canonical prose hooks — those stay advisory, H7).\n out.hooks = MANAGED_HOOKS;\n\n // 4. Prose is part of the interface. A surviving canonical body token outside code\n // fences without a ledger disposition is a render-time error (decision 4) — never a\n // silent survivor.\n const rewritten = ClaudeProjector.rewriteBody(body);\n for (const entry of rewritten.ledger) ledger.set(entry.feature, entry);\n for (const token of ClaudeProjector.survivingBodyTokens(rewritten.body)) {\n ClaudeProjector.requireDisposition(token, canonicalRelPath);\n }\n\n // Plan 017 decision 3 (render application): declarative overlays win over dialect\n // defaults and canonical-derived values; invalid overlays fail fast (never silent).\n if (meta.projections !== undefined && meta.projections !== null) {\n validateProjectionOverlays(meta.projections, { id: HOST, fields: CLAUDE_FIELD_POLICY });\n const overlay = (meta.projections as Record<string, Record<string, unknown>>)[HOST];\n if (overlay) Object.assign(out, overlay);\n }\n\n const yamlStr = yaml.stringify(out).replace(/\\r\\n/g, '\\n').trimEnd();\n const content = `---\\n${yamlStr}\\n---\\n${ClaudeProjector.marker(canonicalRelPath)}\\n\\n${RUNTIME_NOTE}\\n\\n${rewritten.body.trim()}\\n`;\n return { content, ledger: [...ledger.values()] };\n }\n\n /** Render `.claude/skills/<name>/SKILL.md` from a canonical skill. */\n public static renderSkill(canonicalContent: string, canonicalRelPath: string): ClaudeRenderResult {\n const { meta, body } = ClaudeProjector.parse(canonicalContent, canonicalRelPath);\n const ledger = new Map<string, TranslationLedgerEntry>();\n\n const rawName =\n typeof meta.name === 'string' && meta.name.trim().length > 0\n ? meta.name.trim()\n : path.basename(path.dirname(canonicalRelPath));\n const normalized = ClaudeProjector.normalizeSkillName(rawName);\n if (normalized !== rawName) {\n ledger.set(`skill-name:${rawName}`, {\n feature: `skill-name:${rawName}`,\n host: HOST,\n disposition: 'mapped',\n rationale: `Skill name normalized to the dialect rule (${rawName} -> ${normalized}); body references follow the artifact name.`,\n });\n }\n\n const out: Record<string, unknown> = { name: normalized };\n if (typeof meta.description === 'string' && meta.description.trim().length > 0) {\n out.description = meta.description.trim();\n }\n if (meta['disable-slash-command'] === true || meta.disableSlashCommand === true) {\n out['user-invocable'] = false;\n ledger.set('disable-slash-command', {\n feature: 'disable-slash-command',\n host: HOST,\n disposition: 'mapped',\n rationale:\n 'Hidden from the / palette while staying model-invocable (Claude polarity: user-invocable, never disable-model-invocation).',\n });\n }\n const metadata = meta.metadata;\n if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n const allowed = ['author', 'version', 'icon', 'source', 'license'];\n const kept: Record<string, unknown> = {};\n for (const key of allowed) {\n const value = (metadata as Record<string, unknown>)[key];\n if (value !== undefined) kept[key] = value;\n }\n for (const key of Object.keys(metadata as Record<string, unknown>)) {\n if (allowed.includes(key)) continue;\n ledger.set(`metadata:${key}`, {\n feature: `metadata:${key}`,\n host: HOST,\n disposition: 'mapped',\n rationale: 'Non-standard skill metadata; stripped because the projection carries only the Agent Skills contract.',\n });\n }\n if (Object.keys(kept).length > 0) out.metadata = kept;\n }\n if (typeof meta.license === 'string') out.license = meta.license;\n\n // Any other canonical skill key needs a recorded disposition (never a silent drop).\n const HANDLED_SKILL_KEYS = new Set([\n 'name',\n 'description',\n 'metadata',\n 'license',\n 'disable-slash-command',\n 'disableSlashCommand',\n ]);\n for (const key of Object.keys(meta)) {\n if (HANDLED_SKILL_KEYS.has(key)) continue;\n const entry = ClaudeProjector.requireDisposition(key, canonicalRelPath);\n ledger.set(entry.feature, entry);\n }\n\n let rewrittenBody = body;\n if (normalized !== rawName) {\n const re = new RegExp(`(^|[^A-Za-z0-9_-])${rawName}(?![A-Za-z0-9_-])`, 'gi');\n rewrittenBody = rewrittenBody.replace(re, `$1${normalized}`);\n }\n const rewritten = ClaudeProjector.rewriteBody(rewrittenBody);\n for (const entry of rewritten.ledger) ledger.set(entry.feature, entry);\n\n const yamlStr = yaml.stringify(out).replace(/\\r\\n/g, '\\n').trimEnd();\n const content = `---\\n${yamlStr}\\n---\\n${ClaudeProjector.marker(canonicalRelPath)}\\n\\n${rewritten.body.trim()}\\n`;\n return { content, ledger: [...ledger.values()] };\n }\n\n /**\n * Render `.claude/rules/<rule>.md`. Rules load unconditionally in every Claude session, so this\n * lane is deliberately lean: optional `paths:` scoping plus a hard adherence budget (ADR 0018).\n *\n * The `paths:` block is the ONLY frontmatter field this lane emits, so it is emitted only when a\n * rule is actually scoped. The live doc is explicit — \"Rules without a `paths` field are loaded\n * unconditionally and apply to all files\" — which makes frontmatter optional; an unscoped rule is\n * therefore rendered marker-first with no frontmatter block at all, matching the Cline lane's shape\n * instead of emitting a stray empty `--- {} ---`.\n */\n public static renderRule(\n canonicalContent: string,\n canonicalRelPath: string,\n opts: { paths?: string[] } = {}\n ): ClaudeRenderResult {\n const lineCount = canonicalContent.split(/\\r?\\n/).length;\n if (lineCount > ClaudeProjector.CLAUDE_DIALECT.maxRuleLines) {\n throw new Error(\n `Rule ${canonicalRelPath} has ${lineCount} lines, exceeding the ${ClaudeProjector.CLAUDE_DIALECT.maxRuleLines}-line adherence budget (ADR 0018 decision 5).`\n );\n }\n const frontmatter: Record<string, unknown> = {};\n if (opts.paths && opts.paths.length > 0) frontmatter.paths = opts.paths;\n const head = Object.keys(frontmatter).length > 0\n ? `---\\n${yaml.stringify(frontmatter).replace(/\\r\\n/g, '\\n').trimEnd()}\\n---\\n`\n : '';\n const rewritten = ClaudeProjector.rewriteBody(canonicalContent.trim());\n const content = `${head}${ClaudeProjector.marker(canonicalRelPath)}\\n\\n${rewritten.body}\\n`;\n return { content, ledger: rewritten.ledger };\n }\n\n /**\n * The specialist roster a coordinator may delegate to: the whole **domain** team, not only the slice\n * this bundle declares or what happens to be installed.\n *\n * `software-engineering` declares 4 specialists, but the `engineering` domain has 15 — so an essentials\n * install used to leave the domain lead able to call 4 of its 15 people, with the list growing only when\n * the operator happened to install more *and* re-project. `bundles.json` already groups every bundle under\n * a `domain`, so the roster is the union of that domain's declared agents minus the coordinator itself.\n * The allowlist is then stable (independent of install state) and complete (it never silently hides a\n * teammate). The cost is that a listed type may not be installed yet — the delegation section turns that\n * into an install recommendation rather than a dead end.\n *\n * Sorted for determinism: repeated projections must be byte-identical, because `agents doctor` diffs them.\n */\n private static resolveDomainRoster(\n bundle: BundleDefinition,\n coordinatorFile: string,\n registryDir: string\n ): string[] {\n const names = new Set<string>();\n try {\n const raw = fs.readFileSync(path.join(registryDir, 'bundles.json'), 'utf8');\n const bundles = (JSON.parse(raw).bundles ?? {}) as Record<string, BundleDefinition>;\n for (const candidate of Object.values(bundles)) {\n if (!bundle.domain || candidate.domain !== bundle.domain) continue;\n for (const agentFile of candidate.agents || []) {\n if (agentFile === coordinatorFile) continue;\n names.add(ClaudeProjector.stripSubagentPrefix(agentFile.replace(/\\.md$/i, '')));\n }\n }\n } catch {\n // No registry to read: fall back to the bundle's own declared roster (the caller's).\n }\n return [...names].sort();\n }\n\n /**\n * Plan the full Claude compound projection for one bundle: roles (with a coordinator allowlist of\n * its whole domain team), skills (normalized names plus auxiliary files copied byte-for-byte), and\n * the lean deduplicated rule set. It emits **no** team-manifest duplicate and **no** workflows lane,\n * because Claude workflows are JavaScript orchestration scripts rather than markdown (ADR 0018 d14).\n */\n public static async planCompoundProjection(\n bundle: BundleDefinition,\n scope: InstallScope,\n resolved: ResolvedAssets,\n registryDir: string,\n _excludeAddons?: string[]\n ): Promise<PlannedClaudeArtifact[]> {\n void scope;\n const artifacts: PlannedClaudeArtifact[] = [];\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n // A coordinator delegates to its domain team, not just this bundle's declared slice of it.\n const domainRoster = ClaudeProjector.resolveDomainRoster(bundle, coordinatorFile, registryDir);\n const specialistNames = domainRoster.length > 0\n ? domainRoster\n : (bundle.agents || []).map(f => ClaudeProjector.stripSubagentPrefix(f.replace(/\\.md$/i, '')));\n const maxTurns = bundle.planningLoop?.budget?.maxIterations;\n\n // 1. Roles.\n for (const agentFile of resolved.agents || []) {\n const canonicalRel = `agents/${agentFile}`;\n const src = path.join(registryDir, 'agents', agentFile);\n if (!(await fs.pathExists(src))) continue;\n const content = await fs.readFile(src, 'utf8');\n const isCoordinator = coordinatorFile === agentFile;\n const roleName = ClaudeProjector.stripSubagentPrefix(agentFile.replace(/\\.md$/i, ''));\n const rendered = ClaudeProjector.renderRole(content, canonicalRel, {\n allowlist: isCoordinator ? specialistNames : undefined,\n maxTurns: isCoordinator ? maxTurns : undefined,\n });\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `.claude/agents/${roleName}.md`,\n content: rendered.content,\n managedMarker: true,\n });\n }\n\n // 2. Skills, plus every auxiliary resource copied byte-for-byte.\n for (const skillName of resolved.skills || []) {\n const skillDir = path.join(registryDir, 'skills', skillName);\n const skillFile = path.join(skillDir, 'SKILL.md');\n if (!(await fs.pathExists(skillFile))) continue;\n const canonicalRel = `skills/${skillName}/SKILL.md`;\n const normalized = ClaudeProjector.normalizeSkillName(skillName);\n artifacts.push({\n kind: 'skill',\n canonical: canonicalRel,\n relPath: `.claude/skills/${normalized}/SKILL.md`,\n content: ClaudeProjector.renderSkill(await fs.readFile(skillFile, 'utf8'), canonicalRel).content,\n managedMarker: true,\n });\n const entries = (await fs.readdir(skillDir, { withFileTypes: true }))\n .filter(entry => entry.name !== 'SKILL.md')\n .sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n if (!entry.isFile()) continue; // nested resource dirs are out of v1 scope (none exist today)\n artifacts.push({\n kind: 'skill',\n canonical: `skills/${skillName}/${entry.name}`,\n relPath: `.claude/skills/${normalized}/${entry.name}`,\n sourceFilePath: path.join(skillDir, entry.name),\n managedMarker: false,\n });\n }\n }\n\n // 3. Rules: deduplicated, agent-referenced only, host entrypoints skipped, budget-guarded.\n for (const ruleFile of [...new Set(resolved.rules || [])].sort()) {\n if (ENTRYPOINT_RULES.has(ruleFile)) continue;\n const src = path.join(registryDir, 'rules', ruleFile);\n if (!(await fs.pathExists(src))) continue;\n const canonicalRel = `rules/${ruleFile}`;\n const content = await fs.readFile(src, 'utf8');\n if (content.split(/\\r?\\n/).length > ClaudeProjector.CLAUDE_DIALECT.maxRuleLines) continue;\n artifacts.push({\n kind: 'rule',\n canonical: canonicalRel,\n relPath: `.claude/rules/${ruleFile}`,\n content: ClaudeProjector.renderRule(content, canonicalRel).content,\n managedMarker: true,\n });\n }\n\n return artifacts;\n }\n\n /** Claude plugin package name rule; every bundle in `registry/bundles.json` satisfies it today. */\n private static readonly PLUGIN_NAME_REGEX = /^[a-z0-9][a-z0-9-]*$/;\n\n /**\n * Render the Claude plugin manifest (`.claude-plugin/plugin.json`).\n *\n * Deterministic: fixed field order, two-space indent, trailing newline, and no data read\n * from the environment (a `package.json` lookup would make the bytes differ between a\n * project and a global install and would trip doctor's recorded-hash drift check).\n */\n private static renderPluginManifest(bundle: BundleDefinition, canonicalRelPath: string): string {\n if (!ClaudeProjector.PLUGIN_NAME_REGEX.test(bundle.name)) {\n throw new Error(\n `Cannot project ${canonicalRelPath}: bundle name \"${bundle.name}\" is not a valid Claude plugin ` +\n `name (must match ^[a-z0-9][a-z0-9-]*$).`\n );\n }\n\n // JSON cannot carry the `<!-- managed-by: agents-united ... -->` comment the markdown\n // renderers use, yet BOTH `InstallEngine.applyCompoundLane` (regeneration of our own\n // artifact) and `agents doctor` (drift/marker integrity) classify an artifact by that\n // marker *string* (`HostProjector.hasManagedMarker`). The manifest is declared\n // `managedMarker: true` — a machine-generated file we own and must be able to\n // regenerate and drift-check — so the marker travels inside `description`, the only\n // free-text field of the seven. Without it the second flagged install would refuse\n // with \"not managed by agents-united\" and doctor would report a false\n // \"user-modified projection\" on every run.\n const markerText = `${MARKER_PREFIX} | profile: ${MARKER_PROFILE} | do not edit`;\n const description = bundle.description\n ? `${bundle.description} [${markerText}]`\n : markerText;\n\n const manifest: ClaudePluginManifest = {\n author: '',\n description,\n homepage: '',\n license: '',\n name: bundle.name,\n repository: '',\n version: bundle.version || '1.0.0',\n };\n\n return JSON.stringify(manifest, null, 2) + '\\n';\n }\n\n /**\n * ADR 0018 decision 12 / Plan 016 decision 13 — the opt-in Claude **plugin lane**.\n *\n * Plans the `claude --plugin-dir` consumable package *inside* the organization package:\n * `.agents/plugins/<bundle>/.claude-plugin/plugin.json` plus an `agents/` subdirectory that\n * mirrors the `.claude/agents/` projection name-for-name and byte-for-byte (same `renderRole`\n * call, same coordinator allowlist, same `maxTurns`).\n *\n * **Distribution-only, never the behavioural source.** Claude has no project-local plugin\n * auto-discovery, plugin agents are namespaced (`plugin:agent`) and a plugin\n * `permissionMode` is ignored — so the `.claude/agents/` projection produced by\n * `planCompoundProjection` stays the single behavioural source. This package exists purely\n * so the same folder can be zipped and consumed elsewhere via `--plugin-dir`.\n *\n * Additive and caller-gated (`InstallOptions.pluginLane`): when the flag is off this method\n * is never called and the install plan is byte-identical to before.\n */\n public static async planPluginLane(\n bundle: BundleDefinition,\n resolved: ResolvedAssets,\n registryDir: string\n ): Promise<PlannedClaudeArtifact[]> {\n const artifacts: PlannedClaudeArtifact[] = [];\n const baseDir = `.agents/plugins/${bundle.name}`;\n\n // 1. Manifest — the discriminator `claude --plugin-dir` reads.\n artifacts.push({\n kind: 'plugin-manifest',\n relPath: `${baseDir}/.claude-plugin/plugin.json`,\n content: ClaudeProjector.renderPluginManifest(bundle, `${baseDir}/.claude-plugin/plugin.json`),\n managedMarker: true,\n distributionOnly: true,\n });\n\n // 2. Roles — mirror of the project projection. Same allowlist/maxTurns treatment as\n // `planCompoundProjection` so the package's `agents/` subdir cannot diverge from\n // `.claude/agents/` (the byte-identity is asserted in tests/claude-plugin-lane.test.ts).\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n const domainRoster = ClaudeProjector.resolveDomainRoster(bundle, coordinatorFile, registryDir);\n const specialistNames = domainRoster.length > 0\n ? domainRoster\n : (bundle.agents || []).map(f => ClaudeProjector.stripSubagentPrefix(f.replace(/\\.md$/i, '')));\n const maxTurns = bundle.planningLoop?.budget?.maxIterations;\n\n for (const agentFile of resolved.agents || []) {\n const canonicalRel = `agents/${agentFile}`;\n const src = path.join(registryDir, 'agents', agentFile);\n if (!(await fs.pathExists(src))) continue;\n const isCoordinator = coordinatorFile === agentFile;\n const roleName = ClaudeProjector.stripSubagentPrefix(agentFile.replace(/\\.md$/i, ''));\n const rendered = ClaudeProjector.renderRole(await fs.readFile(src, 'utf8'), canonicalRel, {\n allowlist: isCoordinator ? specialistNames : undefined,\n maxTurns: isCoordinator ? maxTurns : undefined,\n });\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `${baseDir}/agents/${roleName}.md`,\n content: rendered.content,\n managedMarker: true,\n distributionOnly: true,\n });\n }\n\n return artifacts;\n }\n\n}\n\n\n\n","/**\n * Plan 022 H5 / Plan 023 A0 — the managed PreToolUse guard, single-sourced for every lane that\n * wires it (role frontmatter today; the plain-session settings entry in Plan 023 A1–A2).\n *\n * Verified against the Claude Code references: frontmatter hooks fire for spawned subagents and\n * for `--agent` main sessions; a command hook exiting 2 blocks the call and its stderr is shown as\n * the reason. EXEC FORM (Plan 023 A0): `command` + `args` is spawned directly with no shell. The\n * earlier shell form (`node -e '<js>'`) runs under PowerShell on Windows without Git Bash, whose\n * native-argument quoting can mangle the script and let the guarded command through (fail open).\n * The script blocks `git push --force`/`-f` (not `--force-with-lease`), `vercel --prod`, and\n * `.env*` writes (not `.env.example`) via Write/Edit/NotebookEdit or a shell redirect.\n */\nexport const GUARD_SCRIPT = String.raw`let s=\"\";process.stdin.on(\"data\",c=>s+=c).on(\"end\",()=>{let i={};try{i=JSON.parse(s)}catch(e){}const t=i.tool_input||{},c=String(t.command||\"\"),f=String(t.file_path||\"\").replace(/\\\\/g,\"/\");let r=\"\";if(/\\bgit\\b[^;&|]*\\bpush\\b[^;&|]*(--force(?!-with-lease)\\b|(^|\\s)-f\\b)/.test(c))r=\"git push --force\";else if(/\\bvercel\\b[^;&|]*--prod\\b/.test(c))r=\"vercel --prod\";else if(/(^|\\/)\\.env(\\.(?!example$)[^\\/]+)?$/.test(f)||/>\\s*(\\S*\\/)?\\.env(\\.(?!example\\b)\\S+)?(\\s|$)/.test(c))r=\"a .env write\";if(r){process.stderr.write(\"Blocked by agents-united guard: \"+r+\" requires explicit human approval outside the agent session.\\n\");process.exit(2)}})`;\n\n/** The exec-form handler: `node -e <script>`, no shell on any OS. */\nexport function guardHandler(): { type: 'command'; command: string; args: string[] } {\n return { type: 'command', command: 'node', args: ['-e', GUARD_SCRIPT] };\n}\n\n/** The PreToolUse groups every guarded surface carries. */\nexport function managedGuardHooks(): { PreToolUse: Array<{ matcher: string; hooks: ReturnType<typeof guardHandler>[] }> } {\n return {\n PreToolUse: [\n { matcher: 'Bash', hooks: [guardHandler()] },\n { matcher: 'Write|Edit|NotebookEdit', hooks: [guardHandler()] },\n ],\n };\n}\n","/**\n * Plan 019 Step 4 — host-keyed forbidden-pattern lists (acceptance gate 4 extension).\n * Lives in a leaf module so both the body lint (dialects) and the renderer's scrub safety\n * net (claude-projector) consume ONE list without an import cycle. The list must grow with\n * every new host section (Plan 019 maintenance note).\n */\nexport const RESIDUE_PATTERNS_BY_HOST: Record<string, readonly RegExp[]> = {\n claude: [/Nested Subagent Delegation/, /Host Routing/, /language_server/, /Cline & CLI/],\n};","/**\n * Plan 017 decision 3 declarative overlays — shared validation (leaf module; consumed by\n * the catalog validator in dialects and by renderRole's overlay application without an\n * import cycle). Rule: overlay hosts must be the spec's own host; overlay fields must be\n * keep/map fields; enum-ish values must sit in the host vocabulary. Fail-fast throws.\n */\nexport const OVERLAY_FIELD_VOCAB: Record<string, readonly string[]> = {\n permissionMode: ['default', 'acceptEdits', 'bypassPermissions', 'plan', 'delegate'],\n model: ['opus', 'sonnet', 'haiku', 'inherit'],\n effort: ['low', 'medium', 'high', 'inherit'],\n};\n\n/**\n * The Claude field policy (keep/map/drop) — ONE map shared by `HOST_DIALECTS.claude.fields`\n * (catalog validation) and renderRole's overlay application (render validation).\n */\nexport const CLAUDE_FIELD_POLICY: Record<string, 'keep' | 'map' | 'drop'> = {\n name: 'keep',\n description: 'keep',\n model: 'map',\n tools: 'map',\n permissionMode: 'map',\n effort: 'map',\n skills: 'map',\n projections: 'map',\n version: 'drop',\n type: 'drop',\n commandExecutionPolicy: 'drop',\n mainAgent: 'drop',\n subagent: 'drop',\n hooks: 'drop',\n mcpServers: 'drop',\n rules: 'drop',\n inheritCustomizations: 'drop',\n};\n\ninterface OverlaySpecLike {\n id: string;\n fields: Record<string, 'keep' | 'map' | 'drop'>;\n}\n\nexport function validateProjectionOverlays(projections: unknown, spec: OverlaySpecLike): void {\n if (projections === undefined || projections === null) return;\n if (typeof projections !== 'object' || Array.isArray(projections)) {\n throw new Error('Projection overlay validation failed: projections must be an object.');\n }\n for (const [host, overlay] of Object.entries(projections as Record<string, unknown>)) {\n if (host !== spec.id) {\n throw new Error(`Projection overlay validation failed: unknown overlay host \"${host}\".`);\n }\n if (overlay === null || typeof overlay !== 'object' || Array.isArray(overlay)) {\n throw new Error(`Projection overlay validation failed: overlay for \"${host}\" must be an object.`);\n }\n for (const [field, value] of Object.entries(overlay as Record<string, unknown>)) {\n const policy = spec.fields[field];\n if (policy === undefined) {\n throw new Error(`Projection overlay validation failed: unknown overlay field \"${field}\".`);\n }\n if (policy === 'drop') {\n throw new Error(\n `Projection overlay validation failed: \"${field}\" is unsupported on host \"${host}\" and must never be introduced by an overlay.`,\n );\n }\n const vocab = OVERLAY_FIELD_VOCAB[field];\n if (vocab && (typeof value !== 'string' || !vocab.includes(value))) {\n throw new Error(\n `Projection overlay validation failed: invalid value \"${String(value)}\" for \"${field}\" (allowed: ${vocab.join(', ')}).`,\n );\n }\n }\n }\n}","export type InstallScope = 'project' | 'global';\n\n/**\n * Effective owners of a tracked asset (`AssetFileMeta` or a projection entry) at READ time.\n *\n * The type documents `owners` as \"Absent ⇒ [bundle]\", but legacy records store the installing bundle in\n * `bundle` and write `owners: []`. `??` alone does not fall back for those — `[]` is not nullish — so an\n * empty `owners` array read as \"owned by nobody\": the asset vanished from removal and became permanent\n * residue no `agents remove` could reach. Treat an empty `owners` as absent and fall back to `bundle`.\n *\n * READ-side only. At WRITE time an installer must seed from `existing?.owners` verbatim: `bundle` is who\n * *deployed* a record first, not who *declared* it, so an addon that merely deploys an inherited asset\n * must not be resurrected as its owner (the ownership contract is the Declared Asset Set — see A6 of the\n * lifecycle conformance suite).\n */\nexport function assetOwners(rec: { owners?: string[]; bundle?: string } | undefined | null): string[] {\n if (!rec) return [];\n const declared = rec.owners ?? [];\n if (declared.length > 0) return declared;\n return rec.bundle ? [rec.bundle] : [];\n}\n\n/**\n * Union an owner into a record's effective owners. Never replaces: shared assets are refcounted, so a\n * second bundle installing the same file must add itself alongside the existing owners, not overwrite\n * them (an overwrite silently drops the first bundle's claim and its removal then deletes or strands a\n * file another bundle still needs).\n */\nexport function mergeAssetOwners(\n rec: { owners?: string[]; bundle?: string } | undefined | null,\n owner: string | undefined\n): string[] {\n const owners = assetOwners(rec);\n if (!owner) return owners;\n return owners.includes(owner) ? owners : [...owners, owner];\n}\nexport type InstallMethod = 'symlink' | 'copy';\nexport type AgentHost = 'agents' | 'gemini' | 'claude' | 'cursor' | 'cline' | 'opencode' | 'codex';\n\n// Backward compatibility alias\nexport type Scope = InstallScope;\n\nexport type BundleTier = 'domain' | 'organization';\nexport type BundleStatus = 'stable' | 'experimental' | 'under-construction' | 'needs-audit' | 'deprecated';\nexport type ExecutionMode = 'operational' | 'limited-operational' | 'brainstorming';\n\nexport interface RequiredMcp {\n name: string;\n purpose?: string;\n optionalForBrainstorming?: boolean;\n}\n\nexport interface BundlePrerequisites {\n requiredMcps?: RequiredMcp[];\n requiredPackages?: string[];\n requiredEnvVars?: string[];\n}\n\nexport interface BundleModes {\n operational?: string;\n brainstorming?: string;\n}\n\nexport interface PrerequisiteItemCheck {\n type: 'mcp' | 'package' | 'env';\n name: string;\n purpose?: string;\n satisfied: boolean;\n status: 'ok' | 'missing' | 'partial';\n details?: string;\n optionalForBrainstorming?: boolean;\n detectedInHosts?: string[];\n missingInHosts?: string[];\n}\n\nexport interface PrerequisiteEvaluation {\n bundleName: string;\n tier: BundleTier;\n hasPrerequisites: boolean;\n allSatisfied: boolean;\n operationalPossible: boolean;\n items: PrerequisiteItemCheck[];\n modes?: BundleModes;\n}\n\n/** ADR 0014 — declarative caps bounding all inter-agent planning dialogue. */\nexport interface ConsultationBudget {\n maxPlanningRounds: number;\n maxPeerExchangesPerPair: number;\n summaryWordCap: number;\n maxIterations: number;\n}\n\n/** ADR 0014/0015 — declarative planning-loop posture. Mode absent ⇒ 'subagent-first' (backward compat). */\nexport type PlanningLoopMode = 'subagent-first' | 'planner-orchestrator';\n\nexport interface PlanningLoopConfig {\n enabled: boolean;\n mode?: PlanningLoopMode;\n budget?: ConsultationBudget;\n sidekicks?: { max: number };\n}\n\nexport interface BundleDefinition {\n name: string;\n version?: string;\n description: string;\n category?: string;\n domain?: string;\n tier?: BundleTier;\n status?: BundleStatus;\n parentBundle?: string;\n recommendedAddons?: string[];\n aliases?: string[];\n orchestrator?: string;\n agents?: string[];\n /** @deprecated ADR 0016: Workflows are unified into `skills`. Preserved for backward compatibility with legacy manifests. */\n workflows?: string[];\n skills?: string[];\n prerequisites?: BundlePrerequisites;\n modes?: BundleModes;\n /** ADR 0014 — opt-in Subagent-First Planning Dialogue Loop (digital-agency first). */\n planningLoop?: PlanningLoopConfig;\n /** ADR 0014 — AstrolabsAI persona → canonical roster role (`.md` stripped) map. */\n personaAliases?: Record<string, string>;\n /**\n * Plan 015 §0/C6d — optional bundle-level rule bindings. Forward-compatible:\n * no bundle in `registry/bundles.json` declares this today (agent frontmatter\n * `rules:` is the single source of truth). Adding it here keeps\n * `RegistryResolver.resolve()` ready for a future catalog-level declaration\n * without another schema change.\n */\n rules?: string[];\n}\n\nexport interface BundlesManifest {\n $schema?: string;\n version: number;\n bundles: Record<string, BundleDefinition>;\n}\n\nexport interface LockfileAsset {\n hash: string;\n bundle?: string;\n /** Every bundle whose Declared Asset Set contains this file. Absent ⇒ [bundle]. */\n owners?: string[];\n method?: InstallMethod;\n installedAt: string;\n /** Workspace-root-relative paths (forward slashes) of translated copies fanned out\n * into other host runtimes (e.g. '.claude/agents/x.md', 'AGENTS.md'). Optional so\n * pre-existing lockfiles without projections remain valid. */\n projectedTo?: string[];\n}\n\nexport type ProjectionKind = 'role' | 'skill' | 'rule' | 'team-manifest' | 'workflow' | 'bridge' | 'plugin-manifest';\n\nexport interface LockfileProjection {\n host: string;\n kind: ProjectionKind;\n canonical?: string;\n owners: string[];\n hash: string;\n installedAt: string;\n managedMarker: boolean;\n}\n\n/**\n * ADR 0018 — the structural shape every compound-lane projector emits\n * (`ClineProjector` / `ClaudeProjector`). The installer's compound lane is\n * host-parameterised against this shape, so Cline and Claude share one\n * implementation instead of a copy-paste fork.\n */\nexport interface PlannedProjectionArtifact {\n kind: ProjectionKind;\n canonical?: string;\n relPath: string;\n content?: string;\n sourceFilePath?: string;\n managedMarker: boolean;\n /**\n * ADR 0018 decision 12 — a **distribution-only** artifact (the opt-in Claude plugin lane).\n * It is deployed and tracked in `lockfile.projections`, but it is never a projection\n * *target*: no `projectedTo` pointer is recorded for it, because its namespace\n * (`.agents/plugins/<bundle>/`) belongs to the **cline** reconcile pass and a `claude`\n * pointer recorded there would be dropped on the next Cline install.\n */\n distributionOnly?: boolean;\n\n}\n\nexport interface ClineTeamManifest {\n schemaVersion: 1;\n bundle: string;\n scope: InstallScope;\n coordinator: { name: string; canonicalPath: string };\n roles: Array<{ name: string; canonicalPath: string }>;\n skills: string[];\n /** @deprecated ADR 0016: Workflows are unified into `skills`. Preserved for backward compatibility. */\n workflows?: string[];\n recommendedAddons: string[];\n activation: {\n preferred: 'named-team';\n fallbacks: Array<'adaptive-session' | 'single-orchestrator'>;\n };\n /** ADR 0014 — present when the bundle opts into the Planning Dialogue Loop. */\n planningLoop?: PlanningLoopConfig;\n /** ADR 0014 — persona → role pairs rendered from `BundleDefinition.personaAliases`. */\n personas?: Array<{ persona: string; role: string }>;\n}\n\nexport type ResolvedClineCommand =\n | { executable: string; prefixArgs: string[]; source: 'env-binary' }\n | { executable: string; prefixArgs: string[]; source: 'node-wrapper' }\n | { executable: string; prefixArgs: string[]; source: 'path-executable' };\n\nexport type ClineActivationStrategy =\n | 'named-team'\n | 'adaptive-session'\n | 'single-orchestrator';\n\nexport interface ClineCapabilityReport {\n installed: boolean;\n version?: string;\n command?: ResolvedClineCommand;\n namedTeams: boolean;\n rolePresetConsumer: 'detected' | 'not-detected' | 'unknown';\n diagnostics: string[];\n}\n\nexport type ResolvedClaudeCommand = {\n executable: string;\n prefixArgs: string[];\n source: 'env-binary' | 'node-wrapper' | 'path-executable';\n};\n\n/**\n * ADR 0018 decision 11 / Plan 016 decision 12 — the read-only Claude Code probe result.\n * `pluginSupport` and `agentTeamsExperimental` are derived from `--help` text only; both\n * default to `false` when help output is unavailable, so an unverifiable capability is\n * never reported as supported.\n */\nexport interface ClaudeCapabilityReport {\n installed: boolean;\n version?: string;\n command?: ResolvedClaudeCommand;\n pluginSupport: boolean;\n agentTeamsExperimental: boolean;\n /**\n * Whether the probed runtime provides `SubagentHandback` — the subagent hand-off tool the live tools\n * reference dates at Claude Code v2.1.271+ (and only in auto mode). Derived from `--version`, so it\n * reports the version floor rather than attempting to detect the permission mode.\n */\n subagentHandback: boolean;\n diagnostics: string[];\n}\n\nexport interface ProcessRunnerResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport type ProcessRunner = (\n executable: string,\n args: string[],\n options?: { cwd?: string; env?: Record<string, string>; timeoutMs?: number }\n) => Promise<ProcessRunnerResult>;\n\nexport interface LockfileManifest {\n $schema: string;\n version: number;\n scope?: InstallScope;\n method?: InstallMethod;\n hosts?: AgentHost[];\n /** Runtime ids this install was fanned out to (e.g. ['cline']). Persisted so that\n * `update` / re-install regenerate projections without the user re-passing --fanout. */\n fanout?: string[];\n installed: {\n bundles: string[];\n agents: string[];\n skills: string[];\n /** @deprecated ADR 0016: Workflows are unified into `skills`. Preserved for backward compatibility with existing lockfiles. */\n workflows?: string[];\n };\n bundleVersions?: Record<string, string>;\n bundleModes?: Record<string, ExecutionMode>;\n files: Record<string, LockfileAsset>;\n /** File-level projection ownership map (keyed by workspace-root-relative POSIX path). */\n projections?: Record<string, LockfileProjection>;\n /**\n * Plan 016 / ADR 0018 decision 12 — the recorded opt-in for the Claude plugin lane.\n *\n * Persisted for the same reason `fanout` is: `agents update` re-runs the installer without the\n * user re-passing `--plugin`, so without this field every update would prune the opted-in\n * `.agents/plugins/<bundle>/.claude-plugin/**` package as a superseded projection. Absent ⇒ the\n * lane was never opted into.\n */\n pluginLane?: boolean;\n}\n\nexport type VersionDriftStatus = 'up-to-date' | 'outdated' | 'modified';\n\nexport interface InstalledPackageRecord {\n id: string; // unique identifier, e.g. \"software-engineering@project:agents\"\n name: string;\n type: 'bundle' | 'agent' | 'skill' | 'workflow';\n scope: InstallScope;\n host: AgentHost;\n targetDir: string;\n displayLocation: string; // e.g. \"./.agents\" or \"~/.agents\"\n installedVersion: string;\n upstreamVersion: string;\n driftStatus: VersionDriftStatus;\n method?: InstallMethod;\n fileCount: number;\n title?: string;\n description?: string;\n fanout?: string[];\n projections?: string[];\n}\n\nexport interface ScannedLocationSummary {\n scope: InstallScope;\n targetDir: string;\n displayLocation: string;\n packageCount: number;\n fanout: string[];\n}\n\nexport interface PackageInventory {\n records: InstalledPackageRecord[];\n bundles: InstalledPackageRecord[];\n standaloneItems: InstalledPackageRecord[];\n targetDirs: string[];\n scannedScopes?: InstallScope[];\n scannedLocations?: ScannedLocationSummary[];\n}\n\nexport interface InventoryOptions {\n scope?: InstallScope;\n global?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n targetDir?: string;\n cwd?: string;\n}\n\nexport interface UpdateOptions {\n scope?: InstallScope;\n global?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n targetDir?: string;\n force?: boolean;\n dryRun?: boolean;\n yes?: boolean;\n cwd?: string;\n /** Fan the canonical store out into these runtimes during the update re-install\n * (e.g. to add Cline projections to a bundle originally installed without fanout). */\n fanout?: string[];\n}\n\nexport interface UpdateCheckItem {\n record: InstalledPackageRecord;\n hasUpdate: boolean;\n installedVersion: string;\n upstreamVersion: string;\n reason?: string;\n}\n\nexport interface UpdateCheckReport {\n items: UpdateCheckItem[];\n outdatedCount: number;\n upToDateCount: number;\n totalCount: number;\n scannedScopes?: InstallScope[];\n scannedLocations?: ScannedLocationSummary[];\n}\n\nexport interface UpdateResult {\n updated: InstalledPackageRecord[];\n skipped: Array<{ record: InstalledPackageRecord; reason: string }>;\n targetDirs: string[];\n dryRun: boolean;\n projections: ProjectionInfo[];\n}\n\n\nexport interface InstallOptions {\n scope?: InstallScope;\n global?: boolean;\n method?: InstallMethod;\n symlink?: boolean;\n copy?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n targetDir?: string;\n /** Host ids to project the canonical `.agents/` store into (validated against\n * HOST_REGISTRY; only `projectionCapable` hosts are honored). */\n fanout?: string[];\n /** Execution mode for organization bundles with prerequisites */\n mode?: ExecutionMode;\n /** Allow installation even if prerequisites are missing */\n allowMissingPrereqs?: boolean;\n /** Allow installation of bundles marked as under-construction */\n allowUnderConstruction?: boolean;\n /**\n * ADR 0018 decision 12 / Plan 016 decision 13 — opt-in **Claude plugin lane**: also emit the\n * distribution-only package (`.agents/plugins/<bundle>/.claude-plugin/plugin.json` + `agents/`)\n * for `claude --plugin-dir`. Claude lane only; the plan is byte-identical to today when absent.\n */\n pluginLane?: boolean;\n\n}\n\nexport interface ProjectionInfo {\n host: string;\n path: string;\n kind?: ProjectionKind;\n warnings: string[];\n}\n\nexport interface UninstallOptions {\n scope?: InstallScope;\n global?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n targetDir?: string;\n}\n\nexport interface ResolvedAssets {\n targetBundle?: string;\n agents: string[];\n skills: string[];\n workflows: string[];\n rules: string[];\n}\n\nexport interface SearchOptions {\n domain?: string;\n type?: 'bundle' | 'agent' | 'skill' | 'workflow';\n}\n\nexport interface SearchResults {\n bundles: BundleDefinition[];\n agents: string[];\n skills: string[];\n workflows: string[];\n}\n\nexport type ModelTier = 'inherit' | 'pro' | 'flash';\nexport type ReasoningEffort = 'low' | 'medium' | 'high';\nexport type PermissionMode = 'acceptEdits' | 'requestReview' | 'strict' | 'readOnly';\nexport type CommandExecutionPolicy = 'auto' | 'ask' | 'never';\n\nexport interface AgentHook {\n matcher: string;\n action: string;\n}\n\nexport interface AgentFrontmatter {\n name: string;\n version?: string;\n type?: 'orchestrator' | 'subagent';\n description?: string;\n model?: ModelTier;\n effort?: ReasoningEffort;\n permissionMode?: PermissionMode;\n commandExecutionPolicy?: CommandExecutionPolicy;\n mainAgent?: boolean;\n subagent?: boolean;\n inheritCustomizations?: boolean;\n rules?: string[];\n tools?: string[];\n hooks?: Record<string, AgentHook[]>;\n}\n\nexport interface SkillMetadata {\n author?: string;\n version?: string;\n icon?: string;\n source?: string;\n license?: string;\n}\n\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n 'disable-slash-command'?: boolean;\n disableSlashCommand?: boolean;\n metadata?: SkillMetadata;\n}\n\n/**\n * agent-plugins.org v1.0.0 Agent Plugin manifest (`plugin.json`) written at the root\n * of `.agents/plugins/<bundle>/`. Its presence is the discriminator Cline uses to\n * hard-stop code-plugin scanning of the directory (see `isAgentPluginDirectory` in\n * Cline's `@cline/shared/storage`), and it makes the package portable to other\n * Agent Plugins-conforming clients.\n */\nexport interface AgentPluginManifest {\n $schema: string;\n name: string;\n version: string;\n description: string;\n}\n\n/** ADR 0018 — how one canonical feature is treated when projected into a host dialect. */\nexport type LedgerDisposition = 'mapped' | 'approximated' | 'degraded' | 'unsupported';\n\n/** ADR 0018 decision 9 — a recorded disposition; a drop without one is a hard error. */\nexport interface TranslationLedgerEntry {\n feature: string;\n host: string;\n disposition: LedgerDisposition;\n rationale: string;\n}\n/**\n * Plan 016 decision 13 / ADR 0018 decision 12 — the Anthropic Claude Code plugin manifest\n * (`.claude-plugin/plugin.json`), consumed via `claude --plugin-dir`. The field set is the\n * documented seven; `author`/`homepage`/`repository`/`license` are emitted as empty strings\n * because `BundleDefinition` (and `registry/bundles.json`) declares no such metadata — the\n * keys stay present for schema completeness rather than being invented, and the manifest\n * stays deterministic across project and global installs.\n */\nexport interface ClaudePluginManifest {\n author: string;\n description: string;\n homepage: string;\n license: string;\n name: string;\n repository: string;\n version: string;\n}\n\n\n\n/**\n * ADR 0018 — the pure-data description of the Claude Code dialect that the Claude lane renders\n * against. Plan 017 (ADR 0019) lifts this shape into the shared `HostDialectSpec` so additional\n * hosts are added as data rather than as hand-wired translators.\n */\nexport interface ClaudeDialect {\n id: 'claude';\n nameRegex: RegExp;\n /** Canonical frontmatter tool token -> Claude tool name. */\n toolVocabulary: Record<string, string>;\n /** Canonical tool token -> Claude phrase used when rewriting prompt prose. */\n bodyToolVocabulary: Record<string, string>;\n /** Canonical command tokens -> host renderings (Plan 020 note 7 command bindings). */\n commandVocabulary: Record<string, string>;\n /** Canonical permissionMode -> Claude permissionMode. */\n permissionModeMap: Record<string, string>;\n /** Canonical model tier -> Claude model. */\n modelMap: Record<string, string>;\n /**\n * Model applied when the canonical declares `inherit` (ADR 0018 decision 7 as amended 2026-09-22):\n * coordinators and specialists get an explicit posture instead of inheriting the session model.\n */\n roleModelDefaults: { coordinator: string; specialist: string };\n /** Effort applied when the canonical does not declare one (coordinator vs specialist posture). */\n roleEffortDefaults: { coordinator: string; specialist: string };\n /**\n * Canonical body sections replaced wholesale with a host-native rendering (ADR 0018 decision 8).\n *\n * Tool-name rewriting alone cannot rescue a section that describes *another host's* routing (Antigravity's\n * `language_server.exe` limitation, Cline's `subagent_*` tools): the words rewrite but the meaning does\n * not. Each entry replaces the matched heading's whole section with prose the target host can act on.\n * This is a rendering, not a feature drop, so it carries no ledger disposition.\n */\n bodySectionOverrides: Array<{ heading: RegExp; replacement: string }>;\n budgets: { skillDescriptionChars: number; agentDescriptionTokens: number };\n maxRuleLines: number;\n}\n\n/**\n * ADR 0021 decision 9 — Translation Ledger dispositions survive as delta classifications;\n * a Declared Delta is an audited host-specific deviation ABOVE the Contract Floor.\n */\nexport type DeltaDisposition = LedgerDisposition;\nexport type DeclaredDelta = TranslationLedgerEntry;\n\n/**\n * Plan 021 (ADR 0021) — the tool-free definition of what an agent IS: identity, mission,\n * scope boundaries, structured output contract, safety rules, and tool-neutral behavioural\n * invariants. Authored in `registry/core/*.core.md`; contains zero host tool names,\n * command names, or host mechanics (decision 1).\n */\nexport interface SemanticCore {\n identity: string;\n mission: string;\n scope_boundaries: string;\n output_contract: string;\n safety: string;\n invariants: string[];\n}\n\n/** Plan 021 gate 4 — conformance input: what the realization binds, adds, and declares. */\nexport interface ValidateDeclaredDeltasInput {\n realization: { boundInvariants: string[]; aboveFloorScope: string[] };\n core: SemanticCore;\n deltas: DeclaredDelta[];\n}\n\n/** ADR 0021 decision 2 — an invariant BOUND to host mechanics, never translated. */\nexport interface InvariantBinding {\n /** Tool-neutral behavioural law as authored in the Semantic Core invariants. */\n invariant: string;\n /** The concrete host-native mechanic this law is bound to on this host. */\n binding: string;\n}\n\n/**\n * ADR 0021 decision 9 — `HostDialectSpec` evolves into the per-host Binding Table schema:\n * the Plan 017 codex fields survive (they are the vocabulary surface) and the realization\n * gains `capabilityProfile`, `invariantBindings`, and a `deltaRegistry` reference. One spec\n * per host; host churn is a one-host data PR.\n */\nexport interface HostDialectSpec {\n id: string;\n fields: Record<string, 'keep' | 'map' | 'drop'>;\n toolVocabulary: Record<string, string>;\n bodyToolVocabulary: Record<string, string>;\n commandVocabulary: Record<string, string>;\n features: Record<string, boolean | string>;\n budgets: { skillDescriptionChars: number; agentDescriptionTokens: number };\n nameRules: { pattern: string; subagentPrefixPolicy: string };\n launcher: { flags: string[]; notes: string };\n markerProfile: string;\n /** ADR 0021 additions — the Binding Table proper. */\n capabilityProfile: string;\n invariantBindings: InvariantBinding[];\n deltaRegistry: string;\n}\n\n/** Plan 021 Step 4 — the per-role binding view consumed by the Claude Creation Engine. */\nexport interface ClaudeCreationBindingTable {\n host: string;\n /** The native role name (e.g. `backend-architect`); optional so fixtures stay minimal. */\n roleName?: string;\n /** `invariant` (HostDialectSpec shape) or `feature` (legacy codex shape) identify the law. */\n invariantBindings?: Array<{ invariant?: string; feature?: string; binding: string }>;\n /** `rendering` (Binding Table shape) or `native` (legacy shape) give the host command. */\n commandBindings?: Array<{ command: string; rendering?: string; native?: string; rationale?: string }>;\n commandVocabulary?: Record<string, string>;\n deltas?: DeclaredDelta[];\n /**\n * Plan 022 H2/H3 — the role's own least-privilege allowlist (Realization Layer). Absent ⇒ the\n * profile's whole surface (fixtures only); every entry must exist in the profile.\n */\n tools?: string[];\n /** Plan 022 H3 — native permission mode (e.g. `plan` for read-only roles). */\n permissionMode?: string;\n}\n\n/** Plan 021 Step 4 — the versioned tool-surface snapshot the creation engine targets. */\nexport interface ClaudeCreationProfile {\n host: string;\n version: string;\n tools?: string[];\n}\n\n\n\n","import path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { AgentHostAdapter } from './adapter.js';\nimport { isKnownHost } from './hosts.js';\nimport { HostProjector } from './projector.js';\nimport { ClineProjector } from './cline-projector.js';\nimport type { UninstallOptions, LockfileManifest, InstallScope, AgentHost, BundleDefinition } from './types.js';\nimport { assetOwners } from './types.js';\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]+?)\\r?\\n---/;\n\nexport class UninstallEngine {\n private registry: RegistryResolver;\n\n constructor(registry?: RegistryResolver) {\n this.registry = registry || new RegistryResolver();\n }\n\n private async calculateHash(filePath: string): Promise<string> {\n const buffer = await fs.readFile(filePath);\n return 'sha256:' + crypto.createHash('sha256').update(buffer).digest('hex');\n }\n\n /**\n * Determines whether a projected file still carries our managed marker. Agent\n * projections have YAML frontmatter with the marker as the first body line; the\n * AGENTS.md bridge (agentsmd profile) is a plain markdown index with no\n * frontmatter, so the marker is checked against the whole content.\n */\n private async isManagedProjection(absPath: string, isAgentsMd: boolean, recordedHash?: string): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n if (HostProjector.hasManagedMarker(content)) return true;\n // ADR 0017 amendment (Gate 7, 2026-09-25): markerless sidecar artifacts (LICENSE.txt,\n // references/**) cannot carry the marker — they are managed iff their bytes still hash\n // to the value recorded at install time.\n if (recordedHash) {\n const bytes = await fs.readFile(absPath);\n return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` === recordedHash;\n }\n return false;\n }\n\n /**\n * Removes empty projection dirs left behind after deleting a projected file\n * (e.g. `.claude/agents/` and then `.claude/`). Only ever removes empty dirs.\n */\n private async removeEmptyProjectionDirs(workspaceRoot: string, projPath: string): Promise<void> {\n let dir = path.dirname(path.join(workspaceRoot, projPath));\n while (dir !== workspaceRoot && dir.startsWith(workspaceRoot)) {\n try {\n const entries = await fs.readdir(dir);\n if (entries.length > 0) break;\n await fs.rmdir(dir);\n } catch {\n break;\n }\n dir = path.dirname(dir);\n }\n }\n\n /**\n * Removes every recorded projection for a canonical asset, guarding against\n * clobbering user-modified files. Mirrors the hash-conflict error pattern.\n */\n private async removeProjections(\n workspaceRoot: string,\n projectedTo: string[],\n force?: boolean,\n projectionHashes?: Record<string, { hash?: string }>,\n ): Promise<void> {\n for (const projPath of projectedTo) {\n const absProjection = path.join(workspaceRoot, projPath);\n if (!await fs.pathExists(absProjection)) {\n continue;\n }\n\n const isAgentsMd = projPath === 'AGENTS.md';\n const managed = await this.isManagedProjection(absProjection, isAgentsMd, projectionHashes?.[projPath]?.hash);\n if (!managed && !force) {\n throw new Error(\n `Projection ${projPath} has user modifications. Use --force to remove.`\n );\n }\n\n await this.safeRemoveProjection(absProjection);\n await this.removeEmptyProjectionDirs(workspaceRoot, projPath);\n }\n }\n\n private async safeRemoveProjection(absPath: string): Promise<void> {\n try {\n const lstat = await fs.lstat(absPath);\n if (lstat.isSymbolicLink()) {\n await fs.unlink(absPath);\n return;\n }\n } catch {\n // not a symlink\n }\n await fs.remove(absPath);\n }\n\n /**\n * Installed-addon freshness (plan 003): after a child bundle (one with a\n * `parentBundle`) is removed, re-render the parent's coordinator rule + team\n * manifest excluding every remaining installed bundle in the lockfile, so the\n * removed addon returns to the parent's recommendedAddons. Presentation-free:\n * the two projection files carry the managed marker trustees inside (rule) and\n * are overwritten directly via fs-extra. If a parent artifact does not exist in\n * the workspace (parent not installed as its own bundle), it is skipped.\n */\n private async refreshParentCoordination(\n bundleName: string,\n workspaceRoot: string,\n lockfile: LockfileManifest,\n scope: InstallScope\n ): Promise<void> {\n const bundleDef: BundleDefinition | null = await this.registry.getBundle(bundleName);\n if (!bundleDef?.parentBundle) return;\n const parentDef = await this.registry.getBundle(bundleDef.parentBundle);\n if (!parentDef) return;\n const parentResolved = await this.registry.resolve(parentDef.name).catch(() => null);\n if (!parentResolved) return;\n\n const registryDir = this.registry.getRegistryDir();\n const projection = await ClineProjector.planCompoundProjection(\n parentDef,\n scope,\n parentResolved,\n registryDir,\n lockfile.installed.bundles\n );\n\n for (const artifact of projection) {\n if (artifact.kind !== 'rule' && artifact.kind !== 'team-manifest') continue;\n if (artifact.content === undefined) continue;\n const dest = path.join(workspaceRoot, artifact.relPath);\n if (!await fs.pathExists(dest)) continue; // parent not installed as its own bundle\n await fs.writeFile(dest, artifact.content, 'utf8');\n const hash = await this.calculateHash(dest);\n if (lockfile.projections?.[artifact.relPath]) {\n lockfile.projections[artifact.relPath].hash = hash;\n }\n }\n }\n\n private parseHosts(options: UninstallOptions): AgentHost[] {\n if (options.hosts && options.hosts.length > 0) return options.hosts;\n if (options.target) {\n const raw = Array.isArray(options.target) ? options.target.join(',') : options.target;\n const parsed = raw.split(',').map(s => s.trim().toLowerCase()) as AgentHost[];\n const valid = parsed.filter(isKnownHost);\n if (valid.length > 0) return valid;\n }\n return ['agents'];\n }\n\n private parseScope(options: UninstallOptions): InstallScope {\n if (options.global) return 'global';\n return options.scope || 'project';\n }\n\n private async safeRemove(targetDir: string, relPath: string): Promise<void> {\n const fullPath = path.join(targetDir, relPath);\n\n // If relPath is inside skills, check if skill directory itself is a symlink/junction\n if (relPath.startsWith('skills' + path.sep) || relPath.startsWith('skills/')) {\n const parts = relPath.split(/[/\\\\]/);\n if (parts.length >= 2) {\n const skillDir = path.join(targetDir, parts[0], parts[1]);\n try {\n const lstat = await fs.lstat(skillDir);\n if (lstat.isSymbolicLink()) {\n await fs.unlink(skillDir);\n return;\n }\n } catch {\n // not a symlink directory\n }\n }\n }\n\n try {\n const lstat = await fs.lstat(fullPath);\n if (lstat.isSymbolicLink()) {\n await fs.unlink(fullPath);\n return;\n }\n } catch {\n // not a symlink\n }\n\n await fs.remove(fullPath);\n }\n\n public async uninstall(identifier: string, options: UninstallOptions = {}): Promise<{ removed: string[]; kept: string[]; staleRecords: string[]; retainedOwners: string[]; targetDirs: string[]; dryRun: boolean }> {\n const scope = this.parseScope(options);\n const hosts = this.parseHosts(options);\n\n const targetDirs: string[] = hosts.map(h => AgentHostAdapter.resolveHostDir(scope, h, options.targetDir));\n const resolved = await this.registry.resolve(identifier).catch(() => null);\n\n const totalRemoved: string[] = [];\n const totalKept: string[] = [];\n const totalStale: string[] = [];\n const retainedOwners = new Set<string>();\n\n for (const targetDir of targetDirs) {\n const subPaths = AgentHostAdapter.getSubPaths(targetDir);\n\n if (!await fs.pathExists(subPaths.lockfile)) {\n continue;\n }\n\n const lockfile: LockfileManifest = await fs.readJson(subPaths.lockfile);\n const removedFiles: string[] = [];\n const keptFiles: string[] = [];\n const staleRecords: string[] = [];\n // Projection ownership is the UNION of its own refcount and its canonical record's owners\n // (legacy `bundle` fallback included). Deriving it only at stamping time made the sharing\n // guarantee order-dependent: a projection created BEFORE a second bundle co-owned its\n // canonical stayed single-owner, and removing that bundle deleted the projection out from\n // under the other owner (reported both ways round). Unioning here makes \"a shared canonical's\n // projections are shared\" true regardless of install order. Bundle-scoped lanes\n // (`.agents/plugins/<bundle>/`) are per-bundle distribution copies: the canonical's other\n // owners do not keep them alive.\n const projectionOwners = (projRelPath: string, proj: { owners?: string[]; canonical?: string }): string[] => {\n const own = proj.owners ?? [];\n if (projRelPath.startsWith('.agents/plugins/')) return own;\n const canonical = proj.canonical ?? '';\n const rec = lockfile.files[canonical] ?? lockfile.files[canonical.replace(/^\\.agents\\//, '')];\n return Array.from(new Set([...own, ...assetOwners(rec)]));\n };\n\n /**\n * Universal Coverage Rule (ADR 0019). An artifact is deletable only when no surviving\n * installed identifier covers its source. A surviving identifier covers:\n * - a canonical asset, when what it DECLARES contains that asset (a domain declares its\n * whole expansion; a bundle declares its own bundles.json fields — never an inherited\n * parent's extras, per the A6 Declared-Asset-Set contract); and\n * - a bundle-derived artifact (`.agents/plugins/<b>/…` — team manifest, plugin.json,\n * skill mirrors), when what it declares contains every asset `<b>` declares.\n * Owner refcounts alone answered \"does anyone still name this?\" — coverage answers \"does\n * anyone still need this?\", which is what the operator means by \"don't break my domain\".\n */\n const survivingCoverage = async (\n source: { asset?: string; declaringBundle?: string },\n removedId: string\n ): Promise<string[]> => {\n const survivors = lockfile.installed.bundles.filter(b => b !== removedId);\n const covering: string[] = [];\n for (const id of survivors) {\n try {\n // DECLARATION semantics, not resolution: a survivor covers exactly what it declares.\n // A real bundle declares its own bundles.json fields only (ADR 0006/A6 — an addon\n // must NOT keep the parent's undeclared surface alive); a domain pseudo-bundle's\n // declaration IS its expansion (the union of its members), which is what makes\n // `domain:engineering` cover everything `software-engineering` declares.\n const def = await this.registry.getBundle(id);\n const have = new Set<string>([]);\n if (def) {\n if (def.orchestrator) have.add(`agents/${def.orchestrator}`);\n (def.agents || []).forEach(a => have.add(`agents/${a}`));\n (def.skills || []).forEach(s => have.add(`skills/${s}/SKILL.md`));\n (def.workflows || []).forEach(w => have.add(`workflows/${w}`));\n (def.rules || []).forEach(rl => have.add(`rules/${rl}`));\n } else {\n const r = await this.registry.resolve(id);\n r.agents.forEach(f => have.add(`agents/${f}`));\n r.skills.forEach(s => have.add(`skills/${s}/SKILL.md`));\n (r.workflows || []).forEach(w => have.add(`workflows/${w}`));\n (r.rules || []).forEach(rl => have.add(`rules/${rl}`));\n }\n if (source.asset) {\n if (have.has(source.asset)) covering.push(id);\n } else if (source.declaringBundle) {\n const def = await this.registry.getBundle(source.declaringBundle);\n if (!def) continue;\n const want = new Set<string>([]);\n if (def.orchestrator) want.add(`agents/${def.orchestrator}`);\n (def.agents || []).forEach(a => want.add(`agents/${a}`));\n (def.skills || []).forEach(s => want.add(`skills/${s}/SKILL.md`));\n (def.workflows || []).forEach(w => want.add(`workflows/${w}`));\n (def.rules || []).forEach(rl => want.add(`rules/${rl}`));\n if (want.size > 0 && [...want].every(k => have.has(k))) covering.push(id);\n }\n } catch {\n // A survivor that no longer resolves cannot cover anything.\n }\n }\n return covering;\n };\n\n // Bundle removal mode. Triggered by a roster entry OR by owned assets: a lockfile that lost\n // its `installed.bundles` entry (older partial removals, pre-fix rosters) still has records\n // naming this owner, and those must be reachable — otherwise `agents remove` reports\n // \"No installed assets found\" for assets that are visibly right there in the lockfile.\n if (resolved && resolved.targetBundle) {\n const bundleName = resolved.targetBundle;\n const ownsSomething =\n Object.values(lockfile.files).some(m => assetOwners(m).includes(bundleName)) ||\n Object.values(lockfile.projections || {}).some(p => (p.owners ?? []).includes(bundleName));\n if (lockfile.installed.bundles.includes(bundleName) || ownsSomething) {\n if (!options.dryRun) {\n const workspaceRoot = path.resolve(path.dirname(targetDir));\n\n // Transactional validation BEFORE any write: if this bundle owns zero file\n // records and zero projections, reject without mutating the lockfile.\n const ownedFiles = Object.entries(lockfile.files)\n .filter(([, m]) => assetOwners(m).includes(bundleName));\n const ownedProjections = lockfile.projections\n ? Object.entries(lockfile.projections).filter(([p, v]) => projectionOwners(p, v).includes(bundleName)).length\n : 0;\n if (ownedFiles.length === 0 && ownedProjections === 0) {\n throw new Error(`No installed assets found matching \"${bundleName}\".`);\n }\n\n // Clean up compound projections using owner refcounting\n if (lockfile.projections) {\n for (const [projRelPath, proj] of Object.entries(lockfile.projections)) {\n const owners = projectionOwners(projRelPath, proj);\n if (owners.includes(bundleName)) {\n proj.owners = owners.filter(o => o !== bundleName);\n if (proj.owners.length === 0) {\n // Universal Coverage Rule (ADR 0019) — bundle-DERIVED coordination artifacts:\n // everything under `.agents/plugins/<b>/` (team manifest, plugin.json, skill\n // mirrors) and the bundle's own coordinator rule. Each bundle's package is its\n // OWN (A6: an addon shares skills but ships its own mirror, so it does not keep\n // the parent's package alive); what keeps these alive is a survivor that\n // DECLARES A SUPERSET of the bundle — a domain that contains it. That is\n // exactly the reported case: `remove software-engineering` under a standing\n // `domain:engineering` must delete nothing.\n const declaringMatch = /^\\.agents\\/plugins\\/([^/]+)\\//.exec(projRelPath);\n const derivedCoordination = Boolean(declaringMatch)\n || proj.kind === 'rule' || proj.kind === 'team-manifest' || proj.kind === 'plugin-manifest';\n const covering = derivedCoordination\n ? await survivingCoverage({ declaringBundle: declaringMatch ? declaringMatch[1] : bundleName }, bundleName)\n : [];\n if (covering.length > 0) {\n proj.owners = covering;\n keptFiles.push(projRelPath);\n covering.forEach(o => retainedOwners.add(o));\n continue;\n }\n const absProjection = path.join(workspaceRoot, projRelPath);\n // Capture existence BEFORE deleting: the accounting below must distinguish a\n // file that really left the disk from a ghost record that never had one.\n const existedOnDisk = await fs.pathExists(absProjection);\n if (existedOnDisk) {\n if (proj.managedMarker) {\n const managed = await this.isManagedProjection(absProjection, projRelPath === 'AGENTS.md');\n if (!managed && !options.force) {\n throw new Error(`Projection ${projRelPath} has user modifications. Use --force to remove.`);\n }\n } else {\n const currentHash = await this.calculateHash(absProjection).catch(() => null);\n if (currentHash && currentHash !== proj.hash && !options.force) {\n throw new Error(`Projection ${projRelPath} has user modifications. Use --force to remove.`);\n }\n }\n await this.safeRemoveProjection(absProjection);\n await this.removeEmptyProjectionDirs(workspaceRoot, projRelPath);\n }\n delete lockfile.projections[projRelPath];\n // Honest accounting: only a path whose FILE existed counts as \"deleted\". A\n // record without a file (ghost bookkeeping from older partial removals) is\n // stale-record cleanup — reporting it as a deleted file told operators that\n // content vanished when nothing on disk changed.\n if (existedOnDisk) {\n removedFiles.push(projRelPath);\n } else {\n staleRecords.push(projRelPath);\n }\n // Drop the pointer from its canonical record too: a surviving canonical that\n // still lists this path sends `agents doctor` hunting for a projection that is\n // deliberately gone (\"Missing projection …\" storm). The fallback lane spells\n // canonicals `.agents/<sub>/<file>`, the files map `<sub>/<file>` — try both.\n const canonicalKey = (proj.canonical ?? '').replace(/^\\.agents\\//, '');\n for (const key of new Set([proj.canonical ?? '', canonicalKey])) {\n const rec = key ? lockfile.files[key] : undefined;\n if (rec?.projectedTo) {\n rec.projectedTo = rec.projectedTo.filter(p => p !== projRelPath);\n if (rec.projectedTo.length === 0) delete rec.projectedTo;\n }\n }\n } else {\n // Survives for its remaining owners: report it as kept, not removed.\n keptFiles.push(projRelPath);\n proj.owners.forEach(o => retainedOwners.add(o));\n }\n }\n }\n }\n\n for (const [relPath, assetMeta] of Object.entries(lockfile.files)) {\n const recordOwners = assetOwners(assetMeta);\n if (!recordOwners.includes(bundleName)) continue;\n\n const newOwners = recordOwners.filter(o => o !== bundleName);\n if (newOwners.length === 0) {\n // Last owner removed: drop the recorded projections, then the canonical file.\n if (assetMeta.projectedTo && assetMeta.projectedTo.length > 0) {\n await this.removeProjections(workspaceRoot, assetMeta.projectedTo, options.force, lockfile.projections);\n }\n\n const fullPath = path.join(targetDir, relPath);\n if (await fs.pathExists(fullPath) || await fs.pathExists(fullPath).catch(() => false)) {\n if (!options.force && assetMeta.method !== 'symlink') {\n const currentHash = await this.calculateHash(fullPath).catch(() => null);\n if (currentHash && currentHash !== assetMeta.hash) {\n throw new Error(`File ${relPath} has user modifications. Use --force to remove.`);\n }\n }\n\n await this.safeRemove(targetDir, relPath);\n removedFiles.push(relPath);\n }\n\n delete lockfile.files[relPath];\n } else {\n // A surviving bundle still owns this file: keep it on disk, shrink owners.\n lockfile.files[relPath] = { ...assetMeta, owners: newOwners };\n keptFiles.push(relPath);\n newOwners.forEach(o => retainedOwners.add(o));\n }\n }\n\n // Prune the managed subdirectories once empty — a removal that leaves `.agents/agents/`\n // behind as an empty shell reads as residue to the operator even though nothing in it is\n // tracked anymore. Projections already do this via removeEmptyProjectionDirs.\n for (const dir of [subPaths.agentsDir, subPaths.skillsDir, subPaths.workflowsDir, subPaths.rulesDir]) {\n if (await fs.pathExists(dir)) {\n const entries = await fs.readdir(dir).catch(() => [] as string[]);\n if (entries.length === 0) {\n await fs.remove(dir);\n }\n }\n }\n\n lockfile.installed.bundles = lockfile.installed.bundles.filter(b => b !== bundleName);\n if (lockfile.bundleVersions) {\n delete lockfile.bundleVersions[bundleName];\n }\n // Survival set: only entries still declared by a surviving bundle stay on the\n // roster (declared asset sets, not the removed bundle's resolved superset).\n const surviving = lockfile.installed.bundles.filter(b => b !== bundleName);\n const survival = new Set<string>();\n for (const b of surviving) {\n const bdef = await this.registry.getBundle(b);\n if (!bdef) {\n // Unbundled survivor (`domain:*` pseudo-entry or unknown identifier): it has no\n // declaration to read, so what it still owns in the lockfile IS its roster.\n for (const [relPath, meta] of Object.entries(lockfile.files)) {\n if (assetOwners(meta).includes(b)) survival.add(relPath);\n }\n continue;\n }\n if (bdef.orchestrator) survival.add(`agents/${bdef.orchestrator}`);\n (bdef.agents || []).forEach(a => survival.add(`agents/${a}`));\n (bdef.skills || []).forEach(s => survival.add(`skills/${s}/SKILL.md`));\n (bdef.workflows || []).forEach(w => survival.add(`workflows/${w}`));\n }\n lockfile.installed.agents = lockfile.installed.agents.filter(a => survival.has(`agents/${a}`));\n lockfile.installed.skills = lockfile.installed.skills.filter(s => survival.has(`skills/${s}/SKILL.md`));\n if (lockfile.installed.workflows) {\n lockfile.installed.workflows = lockfile.installed.workflows.filter(w => survival.has(`workflows/${w}`));\n }\n\n // Installed-addon freshness (plan 003): a removed child bundle restores\n // its addon into the parent's recommendedAddons via a re-render here.\n await this.refreshParentCoordination(bundleName, workspaceRoot, lockfile, scope);\n\n await fs.writeJson(subPaths.lockfile, lockfile, { spaces: 2 });\n } else {\n // Dry run: report the same refcount outcome the real pass would produce, without\n // mutating anything — \"would remove 84\" when every asset is co-owned is a lie.\n for (const [relPath, m] of Object.entries(lockfile.files)) {\n const owners = assetOwners(m);\n if (!owners.includes(bundleName)) continue;\n const remaining = owners.filter(o => o !== bundleName);\n (remaining.length === 0 ? removedFiles : keptFiles).push(relPath);\n remaining.forEach(o => retainedOwners.add(o));\n }\n for (const [projRelPath, proj] of Object.entries(lockfile.projections || {})) {\n const owners = projectionOwners(projRelPath, proj);\n if (!owners.includes(bundleName)) continue;\n const remaining = owners.filter(o => o !== bundleName);\n (remaining.length === 0 ? removedFiles : keptFiles).push(projRelPath);\n remaining.forEach(o => retainedOwners.add(o));\n }\n }\n }\n } else {\n // Item removal mode\n const itemTargetRelPaths = Object.keys(lockfile.files).filter(p => p.includes(identifier));\n\n if (!options.dryRun) {\n for (const relPath of itemTargetRelPaths) {\n const fullPath = path.join(targetDir, relPath);\n if (await fs.pathExists(fullPath) || await fs.pathExists(fullPath).catch(() => false)) {\n if (!options.force && lockfile.files[relPath]?.method !== 'symlink') {\n const currentHash = await this.calculateHash(fullPath).catch(() => null);\n const assetMeta = lockfile.files[relPath];\n if (currentHash && assetMeta && currentHash !== assetMeta.hash) {\n throw new Error(`File ${relPath} has user modifications. Use --force to remove.`);\n }\n }\n await this.safeRemove(targetDir, relPath);\n removedFiles.push(relPath);\n }\n delete lockfile.files[relPath];\n }\n\n await fs.writeJson(subPaths.lockfile, lockfile, { spaces: 2 });\n } else {\n removedFiles.push(...itemTargetRelPaths);\n }\n }\n\n totalRemoved.push(...removedFiles);\n totalKept.push(...keptFiles);\n totalStale.push(...staleRecords);\n }\n\n // \"Nothing deleted\" is not \"nothing found\": a removal whose assets are all co-owned legitimately\n // deletes nothing and keeps every record for the remaining owners. Only a removal that matched\n // no records at all is an error.\n if (totalRemoved.length === 0 && totalKept.length === 0 && totalStale.length === 0 && !options.dryRun) {\n throw new Error(`No installed assets found matching \"${identifier}\".`);\n }\n\n return {\n removed: totalRemoved,\n kept: totalKept,\n staleRecords: totalStale,\n retainedOwners: [...retainedOwners].sort(),\n targetDirs,\n dryRun: options.dryRun || false,\n };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { AgentHostAdapter } from './adapter.js';\nimport { KNOWN_HOST_IDS } from './hosts.js';\nimport type {\n InventoryOptions,\n PackageInventory,\n InstalledPackageRecord,\n LockfileManifest,\n InstallScope,\n AgentHost,\n VersionDriftStatus,\n ScannedLocationSummary,\n} from './types.js';\n\nexport class InventoryScanner {\n private registry: RegistryResolver;\n\n constructor(registry?: RegistryResolver) {\n this.registry = registry || new RegistryResolver();\n }\n\n public static formatDisplayLocation(scope: InstallScope, host: AgentHost, targetDir: string, fanout?: string[]): string {\n const home = os.homedir();\n const cwd = process.cwd();\n\n let prettyPath = targetDir;\n if (targetDir.startsWith(cwd)) {\n const rel = path.relative(cwd, targetDir);\n prettyPath = rel ? `./${rel.replace(/\\\\/g, '/')}` : '.';\n } else if (targetDir.startsWith(home)) {\n const rel = path.relative(home, targetDir);\n prettyPath = `~/${rel.replace(/\\\\/g, '/')}`;\n }\n\n const fanoutSuffix = fanout && fanout.length > 0 ? ` + ${fanout.join(', ')}` : '';\n return `[${scope}: ${prettyPath}${fanoutSuffix}]`;\n }\n\n private parseHosts(options: InventoryOptions): AgentHost[] {\n if (options.hosts && options.hosts.length > 0) return options.hosts;\n if (options.target) {\n const raw = Array.isArray(options.target) ? options.target.join(',') : options.target;\n const parsed = raw.split(',').map(s => s.trim().toLowerCase()) as AgentHost[];\n const valid = parsed.filter(h => KNOWN_HOST_IDS.includes(h));\n if (valid.length > 0) return valid as AgentHost[];\n }\n return [...KNOWN_HOST_IDS] as AgentHost[];\n }\n\n public async scan(options: InventoryOptions = {}): Promise<PackageInventory> {\n const cwd = options.cwd || process.cwd();\n const hosts = this.parseHosts(options);\n\n const scopes: InstallScope[] = [];\n if (options.global || options.scope === 'global') {\n scopes.push('global');\n } else if (options.scope === 'project') {\n scopes.push('project');\n } else {\n scopes.push('project', 'global');\n }\n\n const candidateDirs: Array<{ dir: string; scope: InstallScope; host: AgentHost }> = [];\n\n if (options.targetDir) {\n candidateDirs.push({\n dir: path.resolve(options.targetDir),\n scope: options.scope || 'project',\n host: hosts[0] || 'agents',\n });\n } else {\n for (const scope of scopes) {\n for (const host of hosts) {\n const dir = AgentHostAdapter.resolveHostDir(scope, host);\n candidateDirs.push({ dir, scope, host });\n }\n }\n }\n\n const allRecords: InstalledPackageRecord[] = [];\n const bundleRecords: InstalledPackageRecord[] = [];\n const standaloneRecords: InstalledPackageRecord[] = [];\n const scannedTargetDirs: Set<string> = new Set();\n const scannedLocationsMap = new Map<string, ScannedLocationSummary>();\n\n const home = os.homedir();\n for (const scope of scopes) {\n const canonicalDir = AgentHostAdapter.resolveHostDir(scope, 'agents', options.targetDir);\n let displayLoc = canonicalDir;\n if (canonicalDir.startsWith(cwd)) {\n const rel = path.relative(cwd, canonicalDir);\n displayLoc = rel ? `./${rel.replace(/\\\\/g, '/')}` : '.';\n } else if (canonicalDir.startsWith(home)) {\n const rel = path.relative(home, canonicalDir);\n displayLoc = `~/${rel.replace(/\\\\/g, '/')}`;\n }\n scannedLocationsMap.set(`${scope}:${canonicalDir}`, {\n scope,\n targetDir: canonicalDir,\n displayLocation: displayLoc,\n packageCount: 0,\n fanout: [],\n });\n }\n\n for (const item of candidateDirs) {\n const lockfilePath = path.join(item.dir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n continue;\n }\n\n scannedTargetDirs.add(item.dir);\n let lockfile: LockfileManifest;\n try {\n lockfile = await fs.readJson(lockfilePath);\n } catch {\n continue;\n }\n\n const lockfileFanout = lockfile.fanout || [];\n const displayLocation = InventoryScanner.formatDisplayLocation(item.scope, item.host, item.dir, lockfileFanout);\n\n const locKey = `${item.scope}:${item.dir}`;\n const locSummary = scannedLocationsMap.get(locKey) || {\n scope: item.scope,\n targetDir: item.dir,\n displayLocation: InventoryScanner.formatDisplayLocation(item.scope, item.host, item.dir),\n packageCount: 0,\n fanout: [],\n };\n for (const f of lockfileFanout) {\n if (!locSummary.fanout.includes(f)) {\n locSummary.fanout.push(f);\n }\n }\n scannedLocationsMap.set(locKey, locSummary);\n\n // Track all skills/agents/workflows mapped to installed bundles\n const bundleOwnedSkills = new Set<string>();\n const bundleOwnedAgents = new Set<string>();\n const bundleOwnedWorkflows = new Set<string>();\n\n // 1. Process Installed Bundles\n const installedBundleNames = lockfile.installed?.bundles || [];\n for (const bundleName of installedBundleNames) {\n const bundleDef = await this.registry.getBundle(bundleName).catch(() => null);\n const resolvedBundle = await this.registry.resolve(bundleName).catch(() => null);\n const installedVersion = lockfile.bundleVersions?.[bundleName] || '1.0.0';\n const upstreamVersion = bundleDef?.version || '1.0.0';\n\n let driftStatus: VersionDriftStatus = 'up-to-date';\n if (installedVersion !== upstreamVersion) {\n driftStatus = 'outdated';\n }\n\n // Count associated files\n let fileCount = 0;\n if (lockfile.files) {\n fileCount = Object.values(lockfile.files).filter(f => f.bundle === bundleName).length;\n }\n\n if (resolvedBundle) {\n resolvedBundle.skills?.forEach(s => bundleOwnedSkills.add(s));\n resolvedBundle.agents?.forEach(a => {\n bundleOwnedAgents.add(a);\n bundleOwnedAgents.add(a.replace(/\\.md$/, ''));\n });\n resolvedBundle.workflows?.forEach(w => {\n bundleOwnedWorkflows.add(w);\n bundleOwnedWorkflows.add(w.replace(/\\.md$/, ''));\n });\n }\n if (bundleDef) {\n if (bundleDef.orchestrator) {\n bundleOwnedAgents.add(bundleDef.orchestrator);\n bundleOwnedAgents.add(bundleDef.orchestrator.replace(/\\.md$/, ''));\n }\n bundleDef.skills?.forEach(s => bundleOwnedSkills.add(s));\n bundleDef.agents?.forEach(a => {\n bundleOwnedAgents.add(a);\n bundleOwnedAgents.add(a.replace(/\\.md$/, ''));\n });\n bundleDef.workflows?.forEach(w => {\n bundleOwnedWorkflows.add(w);\n bundleOwnedWorkflows.add(w.replace(/\\.md$/, ''));\n });\n }\n\n locSummary.packageCount++;\n\n const record: InstalledPackageRecord = {\n id: `${bundleName}@${item.scope}:${item.host}`,\n name: bundleName,\n type: 'bundle',\n scope: item.scope,\n host: item.host,\n targetDir: item.dir,\n displayLocation,\n installedVersion,\n upstreamVersion,\n driftStatus,\n method: lockfile.method || 'symlink',\n fileCount,\n title: bundleDef?.name || bundleName,\n description: bundleDef?.description,\n fanout: lockfileFanout,\n projections: lockfileFanout,\n };\n\n allRecords.push(record);\n bundleRecords.push(record);\n }\n\n // 2. Process Standalone Skills\n const installedSkills = lockfile.installed?.skills || [];\n for (const skillName of installedSkills) {\n if (bundleOwnedSkills.has(skillName)) continue;\n\n locSummary.packageCount++;\n\n const record: InstalledPackageRecord = {\n id: `skill:${skillName}@${item.scope}:${item.host}`,\n name: skillName,\n type: 'skill',\n scope: item.scope,\n host: item.host,\n targetDir: item.dir,\n displayLocation,\n installedVersion: '1.0.0',\n upstreamVersion: '1.0.0',\n driftStatus: 'up-to-date',\n method: lockfile.method || 'symlink',\n fileCount: 1,\n title: skillName,\n description: `Standalone skill (${skillName})`,\n fanout: lockfileFanout,\n projections: lockfileFanout,\n };\n\n allRecords.push(record);\n standaloneRecords.push(record);\n }\n\n // 3. Process Standalone Agents\n const installedAgents = lockfile.installed?.agents || [];\n for (const agentFile of installedAgents) {\n if (bundleOwnedAgents.has(agentFile)) continue;\n const agentName = agentFile.replace(/\\.md$/, '');\n\n locSummary.packageCount++;\n\n const record: InstalledPackageRecord = {\n id: `agent:${agentName}@${item.scope}:${item.host}`,\n name: agentName,\n type: 'agent',\n scope: item.scope,\n host: item.host,\n targetDir: item.dir,\n displayLocation,\n installedVersion: '1.0.0',\n upstreamVersion: '1.0.0',\n driftStatus: 'up-to-date',\n method: lockfile.method || 'symlink',\n fileCount: 1,\n title: agentName,\n description: `Standalone agent (${agentFile})`,\n fanout: lockfileFanout,\n projections: lockfileFanout,\n };\n\n allRecords.push(record);\n standaloneRecords.push(record);\n }\n }\n\n return {\n records: allRecords,\n bundles: bundleRecords,\n standaloneItems: standaloneRecords,\n targetDirs: Array.from(scannedTargetDirs),\n scannedScopes: scopes,\n scannedLocations: Array.from(scannedLocationsMap.values()),\n };\n }\n}\n\n","import path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { InventoryScanner } from './inventory.js';\nimport { InstallEngine } from './installer.js';\nimport { HostProjector } from './projector.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport type {\n UpdateOptions,\n UpdateCheckReport,\n UpdateCheckItem,\n UpdateResult,\n InstalledPackageRecord,\n LockfileManifest,\n InventoryOptions,\n ProjectionInfo,\n} from './types.js';\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]+?)\\r?\\n---/;\n\nexport class UpdateEngine {\n private registry: RegistryResolver;\n private scanner: InventoryScanner;\n private installer: InstallEngine;\n\n constructor(registry?: RegistryResolver, scanner?: InventoryScanner, installer?: InstallEngine) {\n this.registry = registry || new RegistryResolver();\n this.scanner = scanner || new InventoryScanner(this.registry);\n this.installer = installer || new InstallEngine(this.registry);\n }\n\n private deduplicateProjections(projections: ProjectionInfo[]): ProjectionInfo[] {\n const seen = new Set<string>();\n const deduplicated: ProjectionInfo[] = [];\n for (const p of projections) {\n const key = `${p.host}:${p.path}`;\n if (!seen.has(key)) {\n seen.add(key);\n deduplicated.push(p);\n }\n }\n return deduplicated;\n }\n\n private async calculateHash(filePath: string): Promise<string> {\n const buffer = await fs.readFile(filePath);\n return 'sha256:' + crypto.createHash('sha256').update(buffer).digest('hex');\n }\n\n /**\n * Determines whether a projected file still carries our managed marker (plan 007\n * M5). Agent projections place the marker as the first body line after frontmatter;\n * the AGENTS.md bridge has no frontmatter so it is checked over the whole content.\n */\n private async isManagedProjection(absPath: string, isAgentsMd: boolean, recordedHash?: string): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n if (HostProjector.hasManagedMarker(content)) return true;\n // ADR 0017 amendment (Gate 7, 2026-09-25): markerless sidecar artifacts (LICENSE.txt,\n // references/**) cannot carry the marker — they are managed iff their bytes still hash\n // to the value recorded at install time.\n if (recordedHash) {\n const bytes = await fs.readFile(absPath);\n return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` === recordedHash;\n }\n return false;\n }\n\n /**\n * Returns the first user-modified projection path belonging to a record, or '' when\n * every recorded projection still carries the managed marker.\n */\n private async staleProjection(record: InstalledPackageRecord, lockfile: LockfileManifest): Promise<string> {\n let workspaceRoot = path.dirname(record.targetDir);\n for (const assetMeta of Object.values(lockfile.files)) {\n if (assetMeta.bundle !== record.name) continue;\n if (!assetMeta.projectedTo || assetMeta.projectedTo.length === 0) continue;\n for (const projPath of assetMeta.projectedTo) {\n const absProjection = path.join(workspaceRoot, projPath);\n if (await fs.pathExists(absProjection)) {\n const managed = await this.isManagedProjection(absProjection, projPath === 'AGENTS.md', lockfile.projections?.[projPath]?.hash);\n if (!managed) {\n return projPath;\n }\n }\n }\n }\n return '';\n }\n\n /** Plan 016 Step 4 — the canonical asset whose dialect name changed (ADR 0016 pattern). */\n private static readonly LEGACY_GENERATIVE_UI_CANONICAL = 'skills/generative_ui/SKILL.md';\n private static readonly LEGACY_GENERATIVE_UI_PATH = /(^|\\/)generative_ui\\/SKILL\\.md$/;\n\n /** Removes empty projection dirs left behind by the migration (never a non-empty one). */\n private async removeEmptyProjectionDirs(workspaceRoot: string, projPath: string): Promise<void> {\n let dir = path.dirname(path.join(workspaceRoot, projPath));\n while (dir !== workspaceRoot && dir.startsWith(workspaceRoot)) {\n try {\n const entries = await fs.readdir(dir);\n if (entries.length > 0) break;\n await fs.rmdir(dir);\n } catch {\n break;\n }\n dir = path.dirname(dir);\n }\n }\n\n /** Drops one projected path from every canonical file record (host-agnostic). */\n private dropProjectedTo(lockfile: LockfileManifest, projectedRelPath: string): void {\n const normProj = projectedRelPath.replace(/\\\\/g, '/');\n for (const asset of Object.values(lockfile.files)) {\n if (!asset.projectedTo || asset.projectedTo.length === 0) continue;\n const kept = asset.projectedTo.filter(p => p !== normProj);\n if (kept.length === asset.projectedTo.length) continue;\n if (kept.length === 0) {\n delete asset.projectedTo;\n } else {\n asset.projectedTo = kept;\n }\n }\n }\n\n /**\n * Plan 016 Step 4 — silent, bounded, idempotent migration of the `generative_ui`\n * projection rename (ADR 0016 pattern).\n *\n * `registry/skills/generative_ui/` is deliberately NOT renamed: the underscore is\n * invalid in every host dialect, so the projectors normalize the name at projection\n * time (`generative_ui` -> `generative-ui`; ADR 0018 decision 2 — normalization is\n * projection-level). Projections recorded before that change therefore still point at\n * `.claude/skills/generative_ui/SKILL.md` and/or the Cline plugin copy\n * `.agents/plugins/<bundle>/skills/generative_ui/SKILL.md`, which the current renderers\n * no longer produce.\n *\n * Runs before each record's re-install so the freshly rendered normalized path is\n * registered by the normal install path. Guarantees: (a) a file that lacks the managed\n * marker is never deleted (its lockfile entries are left untouched too, so the\n * migration never lies about a file it did not remove); (b) a second run is a no-op\n * because the entries are gone; (c) it is host-agnostic, so it covers `.claude/**` and\n * the Cline plugin lane alike, and it never touches the canonical registry store.\n */\n private async migrateLegacyGenerativeUiProjections(\n workspaceRoot: string,\n lockfile: LockfileManifest\n ): Promise<string[]> {\n const projections = lockfile.projections;\n if (!projections) return [];\n\n const normalized = ClaudeProjector.normalizeSkillName('generative_ui');\n const removed: string[] = [];\n\n for (const [projRelPath, proj] of Object.entries(projections)) {\n const posixPath = projRelPath.replace(/\\\\/g, '/');\n const isLegacy = proj.canonical === UpdateEngine.LEGACY_GENERATIVE_UI_CANONICAL\n || UpdateEngine.LEGACY_GENERATIVE_UI_PATH.test(posixPath);\n if (!isLegacy) continue;\n // Already the normalized path (a re-projection landed first): nothing to migrate.\n if (posixPath.includes(`/${normalized}/`)) continue;\n\n const absProjection = path.join(workspaceRoot, projRelPath);\n if (await fs.pathExists(absProjection)) {\n const managed = await this.isManagedProjection(absProjection, posixPath === 'AGENTS.md');\n if (!managed) continue; // (a) never clobber a foreign or user-modified file\n await fs.remove(absProjection);\n await this.removeEmptyProjectionDirs(workspaceRoot, projRelPath);\n }\n\n delete projections[projRelPath];\n this.dropProjectedTo(lockfile, projRelPath);\n removed.push(projRelPath);\n }\n\n return removed;\n }\n\n public async checkUpdates(options: InventoryOptions = {}): Promise<UpdateCheckReport> {\n const inventory = await this.scanner.scan(options);\n const items: UpdateCheckItem[] = [];\n\n for (const record of inventory.records) {\n const hasUpdate = record.driftStatus === 'outdated' || record.installedVersion !== record.upstreamVersion;\n items.push({\n record,\n hasUpdate,\n installedVersion: record.installedVersion,\n upstreamVersion: record.upstreamVersion,\n reason: hasUpdate\n ? `Upstream version (${record.upstreamVersion}) is newer than installed version (${record.installedVersion})`\n : undefined,\n });\n }\n\n const outdatedCount = items.filter(i => i.hasUpdate).length;\n const upToDateCount = items.filter(i => !i.hasUpdate).length;\n\n return {\n items,\n outdatedCount,\n upToDateCount,\n totalCount: items.length,\n scannedScopes: inventory.scannedScopes,\n scannedLocations: inventory.scannedLocations,\n };\n }\n\n public async update(\n targets: string | string[] | '__all__',\n options: UpdateOptions = {}\n ): Promise<UpdateResult> {\n const inventory = await this.scanner.scan({\n scope: options.scope,\n global: options.global,\n hosts: options.hosts,\n target: options.target,\n targetDir: options.targetDir,\n cwd: options.cwd,\n });\n\n const isAll = targets === '__all__' || targets === '*' || (Array.isArray(targets) && targets.includes('__all__'));\n const targetList = Array.isArray(targets) ? targets : [targets];\n\n const recordsToUpdate: InstalledPackageRecord[] = inventory.records.filter(r => {\n if (isAll) return true;\n return targetList.includes(r.name) || targetList.includes(r.id);\n });\n\n if (recordsToUpdate.length === 0) {\n return {\n updated: [],\n skipped: [],\n targetDirs: inventory.targetDirs,\n dryRun: options.dryRun || false,\n projections: [],\n };\n }\n\n if (options.dryRun) {\n const dryProjections: ProjectionInfo[] = [];\n for (const record of recordsToUpdate) {\n const lockfilePath = path.join(record.targetDir, 'agents-united.json');\n if (await fs.pathExists(lockfilePath)) {\n const dryResult = await this.installer.install(record.name, {\n scope: record.scope,\n method: record.method,\n hosts: [record.host],\n targetDir: record.targetDir,\n fanout: options.fanout,\n dryRun: true,\n });\n if (dryResult.projections) {\n dryProjections.push(...dryResult.projections);\n }\n }\n }\n return {\n updated: recordsToUpdate,\n skipped: [],\n targetDirs: inventory.targetDirs,\n dryRun: true,\n projections: this.deduplicateProjections(dryProjections),\n };\n }\n\n\n const updated: InstalledPackageRecord[] = [];\n const skipped: Array<{ record: InstalledPackageRecord; reason: string }> = [];\n const collectedProjections: ProjectionInfo[] = [];\n\n for (const record of recordsToUpdate) {\n const lockfilePath = path.join(record.targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n continue;\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n\n // Check for user modifications in copy mode\n if (record.method === 'copy' && !options.force && lockfile.files) {\n let hasConflict = false;\n let conflictRelPath = '';\n\n for (const [relPath, assetMeta] of Object.entries(lockfile.files)) {\n if (assetMeta.bundle === record.name || relPath.includes(record.name)) {\n const fullPath = path.join(record.targetDir, relPath);\n if (await fs.pathExists(fullPath)) {\n const currentHash = await this.calculateHash(fullPath).catch(() => null);\n if (currentHash && currentHash !== assetMeta.hash) {\n hasConflict = true;\n conflictRelPath = relPath;\n break;\n }\n }\n }\n }\n\n if (hasConflict) {\n skipped.push({\n record,\n reason: `User modifications detected in ${conflictRelPath}. Use --force to overwrite.`,\n });\n continue;\n }\n }\n\n // Projection-aware guard (plan 007 M5): a stale projection whose managed\n // marker was manually removed counts as user-modified and is never clobbered\n // without --force — it lands in `skipped`.\n if (!options.force && lockfile.files) {\n const stale = await this.staleProjection(record, lockfile);\n if (stale) {\n skipped.push({\n record,\n reason: `User modifications detected in projection ${stale}. Use --force to overwrite.`,\n });\n continue;\n }\n }\n\n // Plan 016 Step 4 (ADR 0016 pattern) — silent migration of the legacy\n // `generative_ui` projection path before re-installation registers the\n // normalized one. Deliberately implemented on UpdateEngine rather than\n // InstallEngine: it is an update-path reconciliation (`agents update` is the\n // documented remediation for it) and it leaves fresh installs untouched, since\n // a fresh install can never have recorded the legacy path.\n const migratedGenerativeUi = await this.migrateLegacyGenerativeUiProjections(\n path.dirname(record.targetDir),\n lockfile\n );\n if (migratedGenerativeUi.length > 0) {\n await fs.writeJson(lockfilePath, lockfile, { spaces: 2 });\n }\n\n // Re-install with upstream version. Fan-out flows from --fanout if given,\n // otherwise the installer inherits the fanout recorded in the lockfile.\n const installResult = await this.installer.install(record.name, {\n scope: record.scope,\n method: record.method,\n hosts: [record.host],\n targetDir: record.targetDir,\n fanout: options.fanout,\n force: true, // force overwrite since we passed collision check above\n });\n\n if (installResult.projections) {\n collectedProjections.push(...installResult.projections);\n }\n\n // Synchronize bundleVersion in lockfile\n if (await fs.pathExists(lockfilePath)) {\n const updatedLockfile: LockfileManifest = await fs.readJson(lockfilePath);\n updatedLockfile.bundleVersions = updatedLockfile.bundleVersions || {};\n updatedLockfile.bundleVersions[record.name] = record.upstreamVersion;\n await fs.writeJson(lockfilePath, updatedLockfile, { spaces: 2 });\n if (updatedLockfile.fanout) {\n record.fanout = updatedLockfile.fanout;\n record.projections = updatedLockfile.fanout;\n record.displayLocation = InventoryScanner.formatDisplayLocation(\n record.scope,\n record.host,\n record.targetDir,\n updatedLockfile.fanout\n );\n }\n }\n\n record.installedVersion = record.upstreamVersion;\n record.driftStatus = 'up-to-date';\n updated.push(record);\n }\n\n return {\n updated,\n skipped,\n targetDirs: inventory.targetDirs,\n dryRun: false,\n projections: this.deduplicateProjections(collectedProjections),\n };\n\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport crypto from 'node:crypto';\nimport YAML from 'yaml';\nimport { AgentHostAdapter } from './adapter.js';\nimport { HostProjector } from './projector.js';\nimport { ClaudeCapabilityProbe } from './claude-capabilities.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport { ClineCapabilityProbe } from './cline-capabilities.js';\nimport { ClineProjector } from './cline-projector.js';\nimport { RegistryResolver } from './registry.js';\nimport { assetOwners } from './types.js';\nimport type {\n ClaudeCapabilityReport,\n ClineCapabilityReport,\n LockfileManifest,\n} from './types.js';\n\nexport interface HealthReport {\n valid: boolean;\n targetDir: string;\n isInitialized: boolean;\n issues: string[];\n warnings: string[];\n agentsCount: number;\n skillsCount: number;\n workflowsCount: number;\n clineCapability?: ClineCapabilityReport;\n claudeCapability?: ClaudeCapabilityReport;\n}\n\n/** The only hosts that own a content-derived compound lane: Cline (ADR 0013), Claude (ADR 0018). */\ntype CompoundLaneHost = 'cline' | 'claude';\n\n/** A projection that now serves the same canonical at a different path. */\ninterface SupersedingProjection {\n relPath: string;\n host: string;\n owners: string[];\n}\n\nexport class DoctorEngine {\n private static async isManagedProjection(absPath: string, isAgentsMd: boolean, recordedHash?: string): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n if (HostProjector.hasManagedMarker(content)) return true;\n // ADR 0017 amendment (Gate 7, 2026-09-25): markerless sidecar artifacts (LICENSE.txt,\n // references/**) cannot carry the marker — they are managed iff their bytes still hash\n // to the value recorded at install time.\n if (recordedHash) {\n const bytes = await fs.readFile(absPath);\n return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` === recordedHash;\n }\n return false;\n }\n\n private static isCompoundLaneHost(host: string | undefined): host is CompoundLaneHost {\n return host === 'cline' || host === 'claude';\n }\n\n /**\n * Plan 015 §5.9 item 3 / ADR 0018 decision 2 — find the projection that now serves\n * `canonical` at a *different* path and actually exists on disk. A hit turns an absent\n * recorded path into self-healing staleness (`Stale projection … (superseded by …)`)\n * instead of a user-deletion report.\n *\n * Covers every rename the lockfile can still carry: the ADR 0016 workflow slug rename\n * (`.cline/workflows/implement-feature-or-fix.md` → `…/workflow-implement.md`) and the\n * ADR 0018 prefix strip (`.claude/agents/subagent-<role>.md` → `.claude/agents/<role>.md`).\n */\n private static async findSupersedingProjection(\n projPath: string,\n canonical: string | undefined,\n manifest: LockfileManifest,\n workspaceRoot: string\n ): Promise<SupersedingProjection | null> {\n if (!canonical) return null;\n for (const [projRelPath, proj] of Object.entries(manifest.projections ?? {})) {\n if (projRelPath === projPath) continue;\n if (proj.canonical !== canonical) continue;\n if (!await fs.pathExists(path.join(workspaceRoot, projRelPath))) continue;\n return { relPath: projRelPath, host: proj.host, owners: proj.owners ?? [] };\n }\n return null;\n }\n\n /**\n * ADR 0017 — re-render the compound projections owned by the installed bundles so\n * doctor can compare what is on disk with what the current renderer produces.\n *\n * Returns projection path -> acceptable content variants **for `host` only**, or `null`\n * when the registry is unavailable (the freshness check is then skipped rather than\n * guessed).\n *\n * ADR 0018 decision 11 — the renderer is dispatched by the *recorded projection's* host.\n * Cline entries are diffed against `ClineProjector` output and Claude entries against\n * `ClaudeProjector` output; nothing else is comparable, and the Cline path is unchanged\n * because it renders exactly what it rendered before.\n *\n * Two variants are produced per path on purpose: the coordinator rule and team manifest\n * legitimately render either with or without the installed-bundle addon exclusions\n * (installer primary path vs parent-bundle refresh path). Matching *either* means the\n * projection is fresh, which keeps the check false-positive free while still catching\n * content that matches neither.\n */\n private static async renderProjectionVariants(\n owners: Set<string>,\n installedBundles: string[],\n host: CompoundLaneHost\n ): Promise<Map<string, string[]> | null> {\n if (owners.size === 0) return null;\n\n let resolver: RegistryResolver;\n try {\n resolver = new RegistryResolver();\n await resolver.loadBundles();\n } catch {\n return null;\n }\n\n const registryDir = resolver.getRegistryDir();\n const variants = new Map<string, string[]>();\n\n for (const owner of owners) {\n try {\n const bundleDef = await resolver.getBundle(owner);\n if (!bundleDef) continue; // 'domain:*' pseudo-entries and retired bundles\n\n const resolved = await resolver.resolve(bundleDef.name);\n for (const excludeAddons of [undefined, installedBundles]) {\n const artifacts = host === 'cline'\n ? await ClineProjector.planCompoundProjection(\n bundleDef,\n 'project',\n resolved,\n registryDir,\n excludeAddons\n )\n : await ClaudeProjector.planCompoundProjection(\n bundleDef,\n 'project',\n resolved,\n registryDir,\n excludeAddons\n );\n\n for (const artifact of artifacts) {\n if (artifact.content === undefined) continue;\n const list = variants.get(artifact.relPath) ?? [];\n if (!list.includes(artifact.content)) list.push(artifact.content);\n variants.set(artifact.relPath, list);\n }\n }\n } catch {\n continue; // degrade gracefully — never emit a speculative warning\n }\n }\n\n return variants;\n }\n\n public static async runDoctor(targetDir?: string, host?: string): Promise<HealthReport> {\n const root = AgentHostAdapter.resolveHostDir('project', 'agents', targetDir);\n const subPaths = AgentHostAdapter.getSubPaths(root);\n\n const issues: string[] = [];\n const warnings: string[] = [];\n\n let agentsCount = 0;\n let skillsCount = 0;\n let workflowsCount = 0;\n let manifest: LockfileManifest | undefined;\n let clineCapability: ClineCapabilityReport | undefined;\n let claudeCapability: ClaudeCapabilityReport | undefined;\n let isInitialized = false;\n\n const lockfileExists = await fs.pathExists(subPaths.lockfile);\n const agentsDirExists = await fs.pathExists(subPaths.agentsDir);\n\n // Check Lockfile\n if (lockfileExists) {\n try {\n const parsed: LockfileManifest = await fs.readJson(subPaths.lockfile);\n manifest = parsed;\n agentsCount = parsed.installed?.agents?.length || 0;\n skillsCount = parsed.installed?.skills?.length || 0;\n // ADR 0016 unified workflows into skills: `installed.workflows` is a\n // deprecated legacy field that stays empty on modern installs, so reading it\n // made the report show \"Installed Workflows: 0\" even when workflow skills\n // were installed and projected. Count workflow skills (plus any legacy\n // entries) so the number reflects reality. Note this is a SUBSET of\n // `skillsCount`, not a partition — the CLI labels it \"Workflow Skills\".\n const legacyWorkflows = parsed.installed?.workflows?.length || 0;\n const workflowSkillCount = (parsed.installed?.skills || [])\n .filter(s => String(s).startsWith('workflow-')).length;\n workflowsCount = legacyWorkflows + workflowSkillCount;\n isInitialized = true;\n } catch (err: any) {\n issues.push(`Corrupt lockfile at ${subPaths.lockfile}: ${err.message}`);\n }\n } else if (agentsDirExists) {\n warnings.push(`No lockfile found at ${subPaths.lockfile}, but agent files were detected in ${subPaths.agentsDir}. Run 'agents update' to sync.`);\n }\n\n // Validate Agents YAML Frontmatter\n if (await fs.pathExists(subPaths.agentsDir)) {\n const agentFiles = await fs.readdir(subPaths.agentsDir);\n for (const file of agentFiles) {\n if (file.endsWith('.md')) {\n const content = await fs.readFile(path.join(subPaths.agentsDir, file), 'utf8');\n const frontmatterMatch = content.match(/^---\\r?\\n([\\s\\S]+?)\\r?\\n---/);\n if (!frontmatterMatch) {\n warnings.push(`Agent ${file} is missing YAML frontmatter.`);\n } else {\n try {\n const meta = YAML.parse(frontmatterMatch[1]);\n if (!meta.name) issues.push(`Agent ${file} missing 'name' in frontmatter.`);\n if (!meta.description) warnings.push(`Agent ${file} missing 'description'.`);\n if (!meta.model) warnings.push(`Agent ${file} missing 'model' definition.`);\n } catch (err: any) {\n issues.push(`Invalid YAML in agent ${file}: ${err.message}`);\n }\n }\n }\n }\n }\n\n // Check for unmigrated legacy workflows (ADR 0016)\n if (await fs.pathExists(subPaths.workflowsDir)) {\n const remainingWorkflowFiles = (await fs.readdir(subPaths.workflowsDir)).filter(f => f.endsWith('.md'));\n if (remainingWorkflowFiles.length > 0) {\n warnings.push(`Detected ${remainingWorkflowFiles.length} legacy workflows in ${subPaths.workflowsDir}. Run 'agents update' to automatically migrate them to modern skills.`);\n }\n }\n\n // Projection checks: verify each recorded `projectedTo` and `projections` path\n if (manifest) {\n const workspaceRoot = path.resolve(path.dirname(root));\n\n // ADR 0017 decision 2 — exactly one warning per projection path. The presence, marker\n // and content passes below all inspect the same recorded paths (one path is routinely\n // present in both `files[canonical].projectedTo` and `projections`), so the first\n // cause found for a path wins and every later pass stays silent for it instead of\n // double-reporting the same defect under two names.\n const warnedProjectionPaths = new Set<string>();\n const pushProjectionWarning = (projPath: string, message: string): void => {\n if (warnedProjectionPaths.has(projPath)) return;\n warnedProjectionPaths.add(projPath);\n warnings.push(message);\n };\n\n // 1. Check legacy/compatible projectedTo\n for (const [relPath, assetMeta] of Object.entries(manifest.files)) {\n const projectedTo = assetMeta.projectedTo;\n if (!projectedTo || projectedTo.length === 0) continue;\n for (const projPath of projectedTo) {\n const absProjection = path.join(workspaceRoot, projPath);\n if (!await fs.pathExists(absProjection)) {\n // Plan 015 §5.9 item 3 — distinguish a RENAMED/superseded projection\n // (the same canonical is served by a newer path, so `agents update\n // --fanout` self-heals it) from one the user DELETED (which must keep\n // the \"Missing projection\" advice).\n const superseding = await this.findSupersedingProjection(projPath, relPath, manifest, workspaceRoot);\n\n if (superseding) {\n const owner = superseding.owners[0];\n pushProjectionWarning(\n projPath,\n `Stale projection ${projPath} for canonical ${relPath} (superseded by ${superseding.relPath}).` +\n (owner ? ` Run: agents update ${owner} --fanout ${superseding.host} to reconcile.` : '')\n );\n } else {\n pushProjectionWarning(\n projPath,\n `Missing projection ${projPath} for canonical ${relPath}. Re-run: agents add ... --fanout`\n );\n }\n continue;\n }\n const managed = await this.isManagedProjection(absProjection, projPath === 'AGENTS.md', manifest.projections?.[projPath]?.hash);\n if (!managed) {\n pushProjectionWarning(projPath, `user-modified projection ${projPath}`);\n }\n }\n }\n\n // 2. Check compound projections (ADR 0013 Cline lane, ADR 0018 Claude lane).\n // Same stale-vs-missing classification as §1: a recorded path whose canonical is\n // now served by a different, existing path is a rename this CLI can self-heal —\n // e.g. `.claude/agents/subagent-<role>.md` after the ADR 0018 decision 2 prefix\n // strip — and must never be reported as a missing file, nor under Cline's name.\n if (manifest.projections) {\n for (const [projRelPath, proj] of Object.entries(manifest.projections)) {\n const absPath = path.join(workspaceRoot, projRelPath);\n if (!await fs.pathExists(absPath)) {\n const superseding = await this.findSupersedingProjection(projRelPath, proj.canonical, manifest, workspaceRoot);\n if (superseding) {\n const owner = superseding.owners[0];\n pushProjectionWarning(\n projRelPath,\n `Stale projection ${projRelPath} for canonical ${proj.canonical} (superseded by ${superseding.relPath}).` +\n (owner ? ` Run: agents update ${owner} --fanout ${superseding.host} to reconcile.` : '')\n );\n } else {\n pushProjectionWarning(\n projRelPath,\n `Missing ${proj.host} projection ${projRelPath} (owners: ${proj.owners.join(', ')}).`\n );\n }\n continue;\n }\n if (proj.managedMarker) {\n const managed = await this.isManagedProjection(absPath, projRelPath === 'AGENTS.md', proj.hash);\n if (!managed) {\n pushProjectionWarning(projRelPath, `user-modified projection ${projRelPath}`);\n }\n }\n }\n }\n\n // 2b. ADR 0017 — renderer-backed freshness. Presence and marker integrity cannot\n // reveal a projection rendered from an older bundle definition (the on-disk\n // hash still matches what was recorded), so the only reliable check is to\n // re-render with the current registry and diff. Exactly one warning is raised\n // per path, attributed to the actual cause.\n //\n // ADR 0018 decision 11 — variants are rendered PER HOST and a recorded\n // projection is only ever diffed against its own host's renderer. Comparing a\n // `.claude/**` entry against Cline variants (or vice versa) is meaningless: it\n // made the Claude freshness check inert and risked reporting every Cline entry\n // as outdated purely because Claude variants existed.\n if (manifest.projections && manifest.installed) {\n const ownersByHost = new Map<CompoundLaneHost, Set<string>>();\n for (const proj of Object.values(manifest.projections)) {\n if (!DoctorEngine.isCompoundLaneHost(proj.host)) continue;\n const owners = ownersByHost.get(proj.host) ?? new Set<string>();\n for (const owner of proj.owners) owners.add(owner);\n ownersByHost.set(proj.host, owners);\n }\n\n const variantsByHost = new Map<CompoundLaneHost, Map<string, string[]>>();\n for (const [projHost, owners] of ownersByHost) {\n const variants = await this.renderProjectionVariants(owners, manifest.installed.bundles ?? [], projHost);\n if (variants) variantsByHost.set(projHost, variants);\n }\n\n if (variantsByHost.size > 0) {\n for (const [projRelPath, proj] of Object.entries(manifest.projections)) {\n const projHost = proj.host;\n if (!DoctorEngine.isCompoundLaneHost(projHost)) continue;\n const expectedVariants = variantsByHost.get(projHost);\n if (!expectedVariants) continue; // registry unavailable for this host — never guess\n const absPath = path.join(workspaceRoot, projRelPath);\n if (!await fs.pathExists(absPath)) continue; // missing/stale reported above\n if (!proj.managedMarker) continue; // unmanaged artifacts are not ours\n const content = await fs.readFile(absPath, 'utf8');\n if (!HostProjector.hasManagedMarker(content)) continue; // user-modified reported above\n\n // Content drift — edited after installation, marker left intact.\n if (proj.hash) {\n const diskHash = `sha256:${crypto.createHash('sha256').update(await fs.readFile(absPath)).digest('hex')}`;\n if (diskHash !== proj.hash) {\n const owner = proj.owners[0];\n pushProjectionWarning(\n projRelPath,\n `Content drift ${projRelPath} — edited after installation (recorded ${proj.hash.slice(0, 16)}…, on disk ${diskHash.slice(0, 16)}…).` +\n (owner ? ` Run: agents update ${owner} --fanout ${proj.host} to restore it.` : '')\n );\n continue;\n }\n }\n\n // Stale render — hash matches what was deployed, but the current renderer\n // would produce something different.\n const variants = expectedVariants.get(projRelPath);\n if (!variants || variants.length === 0) continue;\n const onDisk = content.replace(/\\r\\n/g, '\\n');\n if (!variants.some(variant => variant.replace(/\\r\\n/g, '\\n') === onDisk)) {\n const owner = proj.owners[0];\n pushProjectionWarning(\n projRelPath,\n `Outdated projection ${projRelPath} (content differs from the current render).` +\n (owner ? ` Run: agents update ${owner} --fanout ${proj.host} to refresh it.` : '')\n );\n }\n }\n }\n }\n\n // 3. Ownership cross-validation\n const installedBundles = manifest.installed?.bundles ?? [];\n const fileOwnersOf = (rec: { owners?: string[]; bundle?: string }): string[] =>\n assetOwners(rec);\n\n // 3a. Projection owned by a bundle absent from installed.bundles\n if (manifest.projections) {\n for (const [projRelPath, proj] of Object.entries(manifest.projections)) {\n for (const owner of proj.owners) {\n if (!installedBundles.includes(owner)) {\n warnings.push(`Projection ${projRelPath} is owned by bundle \"${owner}\" which is not in installed.bundles.`);\n }\n }\n }\n }\n // 3b. File-record owner absent from installed.bundles\n for (const [relPath, rec] of Object.entries(manifest.files)) {\n for (const owner of fileOwnersOf(rec)) {\n if (!installedBundles.includes(owner)) {\n warnings.push(`File record ${relPath} is owned by bundle \"${owner}\" which is not in installed.bundles.`);\n }\n }\n }\n // 3c. Installed bundle with zero owned file records\n for (const bundleName of installedBundles) {\n const fileCount = Object.values(manifest.files)\n .filter(m => fileOwnersOf(m).includes(bundleName)).length;\n if (fileCount === 0) {\n warnings.push(`Installed bundle \"${bundleName}\" owns zero file records.`);\n }\n }\n }\n\n // Host-specific checks (e.g. --host cline, --host claude)\n if (host === 'cline') {\n const probe = new ClineCapabilityProbe();\n clineCapability = await probe.probe();\n if (!clineCapability.installed) {\n warnings.push('Cline executable was not detected on PATH or via CLINE_BIN_PATH.');\n }\n } else if (host === 'claude') {\n // ADR 0018 decision 11 / Plan 016 decision 12 — read-only probe: `--version` and\n // `--help` only, never `claude agents --json` (daemon) and never headless `-p`.\n const probe = new ClaudeCapabilityProbe();\n claudeCapability = await probe.probe();\n if (!claudeCapability.installed) {\n warnings.push('Claude Code executable was not detected on PATH or via CLAUDE_BIN_PATH.');\n }\n }\n\n return {\n valid: issues.length === 0,\n targetDir: root,\n isInitialized,\n issues,\n warnings,\n agentsCount,\n skillsCount,\n workflowsCount,\n clineCapability,\n claudeCapability,\n };\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport { defaultProcessRunner } from './cline-capabilities.js';\nimport type {\n ClaudeCapabilityReport,\n ProcessRunner,\n ResolvedClaudeCommand,\n} from './types.js';\n\nexport interface ClaudeProbeResolverOptions {\n resolveExecutable?: () => ResolvedClaudeCommand | null;\n}\n\n/**\n * ADR 0018 decision 11 / Plan 016 decision 12 — side-effect-free Claude Code capability probe.\n *\n * The probe runs **exactly two** commands, in this order and no others:\n * 1. `<exe> [...prefixArgs, '--version']`\n * 2. `<exe> [...prefixArgs, '--help']`\n *\n * Two documented non-goals (ADR 0018 decision 11, restated as Plan 016 decision 12) are\n * deliberately never invoked:\n * - `claude agents --json` — it can start the supervisor daemon (a mutating side effect).\n * - headless `-p` runs — they cost tokens (a billed side effect).\n * `--help` text is the only source of truth for capability flags, so the probe stays free of\n * both side effects; anything it cannot verify is reported as unsupported with a diagnostic.\n *\n * The process primitive is the shared `defaultProcessRunner` (argv arrays, `shell: false`,\n * hard timeout, never throws) that the Cline probe uses, so the Windows `.cmd`/`.bat`\n * `cmd.exe` bridge added by ADR 0013 §5 applies identically here.\n */\n/**\n * The live tools reference dates `SubagentHandback` at Claude Code v2.1.271 or later, and provides it\n * only in auto mode. Only `--version` is readable here, so this reports the version floor.\n */\nconst SUBAGENT_HANDBACK_MIN = { major: 2, minor: 1, patch: 271 } as const;\n\nfunction supportsSubagentHandback(version: string | undefined): boolean {\n if (!version) return false;\n const match = version.match(/(\\d+)\\.(\\d+)\\.(\\d+)/);\n if (!match) return false;\n const [major, minor, patch] = [Number(match[1]), Number(match[2]), Number(match[3])];\n if (major !== SUBAGENT_HANDBACK_MIN.major) return major > SUBAGENT_HANDBACK_MIN.major;\n if (minor !== SUBAGENT_HANDBACK_MIN.minor) return minor > SUBAGENT_HANDBACK_MIN.minor;\n return patch >= SUBAGENT_HANDBACK_MIN.patch;\n}\n\nexport class ClaudeCapabilityProbe {\n private runner: ProcessRunner;\n private customResolver?: () => ResolvedClaudeCommand | null;\n\n constructor(runner?: ProcessRunner, options?: ClaudeProbeResolverOptions) {\n this.runner = runner || defaultProcessRunner;\n this.customResolver = options?.resolveExecutable;\n }\n\n /**\n * Safe executable resolution across POSIX and Windows layouts.\n */\n public resolveExecutable(): ResolvedClaudeCommand | null {\n if (this.customResolver) {\n return this.customResolver();\n }\n\n // 1. Explicit CLAUDE_BIN_PATH\n const envBin = process.env.CLAUDE_BIN_PATH;\n if (envBin && path.isAbsolute(envBin) && fs.existsSync(envBin)) {\n return {\n executable: envBin,\n prefixArgs: [],\n source: 'env-binary',\n };\n }\n\n // 2. PATH scanning\n const pathEnv = process.env.PATH || '';\n const pathSeparator = process.platform === 'win32' ? ';' : ':';\n const dirs = pathEnv.split(pathSeparator).filter(Boolean);\n\n if (process.platform === 'win32') {\n const exeNames = ['claude.cmd', 'claude.bat', 'claude.exe', 'claude'];\n for (const dir of dirs) {\n for (const exeName of exeNames) {\n const fullPath = path.join(dir, exeName);\n if (fs.existsSync(fullPath)) {\n // Check adjacent Node wrapper in npm / nvm / volta structure\n const adjacentWrapper1 = path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js');\n const adjacentWrapper2 = path.join(dir, 'node_modules', 'claude', 'bin', 'claude');\n\n if (fs.existsSync(adjacentWrapper1)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper1],\n source: 'node-wrapper',\n };\n }\n if (fs.existsSync(adjacentWrapper2)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper2],\n source: 'node-wrapper',\n };\n }\n\n // Windows hardening (ADR 0013 §5): Node >= 18.20 / 20.12 / 24 rejects\n // spawning .cmd/.bat shims with shell:false (EINVAL), so bridge through\n // cmd.exe while keeping the argv array shell-safe.\n const ext = path.extname(fullPath).toLowerCase();\n if (ext === '.cmd' || ext === '.bat') {\n return {\n executable: 'cmd.exe',\n prefixArgs: ['/c', fullPath],\n source: 'path-executable',\n };\n }\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n } else {\n for (const dir of dirs) {\n const fullPath = path.join(dir, 'claude');\n if (fs.existsSync(fullPath)) {\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n\n return null;\n }\n\n /**\n * Run the read-only capability probe against local Claude Code. Never throws: an absent\n * executable, a non-zero exit and a runner error are all reported as data.\n */\n public async probe(): Promise<ClaudeCapabilityReport> {\n const cmd = this.resolveExecutable();\n const diagnostics: string[] = [];\n\n if (!cmd) {\n diagnostics.push('Claude Code executable not found on PATH or via CLAUDE_BIN_PATH.');\n return {\n installed: false,\n pluginSupport: false,\n agentTeamsExperimental: false,\n subagentHandback: false,\n diagnostics,\n };\n }\n\n // 1. Version check — `--version` only (ADR 0018 decision 11).\n let version: string | undefined;\n let subagentHandback = false;\n try {\n const verRes = await this.runner(cmd.executable, [...cmd.prefixArgs, '--version'], {\n timeoutMs: 5000,\n });\n\n if (verRes.exitCode === 0) {\n version = verRes.stdout.trim().split('\\n')[0]?.trim();\n subagentHandback = supportsSubagentHandback(version);\n } else {\n diagnostics.push(`Claude Code version check failed (exit code ${verRes.exitCode}): ${verRes.stderr.trim()}`);\n return {\n installed: false,\n command: cmd,\n pluginSupport: false,\n agentTeamsExperimental: false,\n subagentHandback: false,\n diagnostics,\n };\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Error executing Claude Code version check: ${msg}`);\n return {\n installed: false,\n command: cmd,\n pluginSupport: false,\n agentTeamsExperimental: false,\n subagentHandback: false,\n diagnostics,\n };\n }\n\n // 2. Flag surface — `--help` text only. No `claude agents --json` (it can start the\n // supervisor daemon) and no headless `-p` run (it costs tokens) — see the class JSDoc.\n let pluginSupport = false;\n let agentTeamsExperimental = false;\n try {\n const helpRes = await this.runner(cmd.executable, [...cmd.prefixArgs, '--help'], {\n timeoutMs: 5000,\n });\n\n if (helpRes.exitCode === 0) {\n const help = helpRes.stdout;\n pluginSupport = help.includes('--plugin-dir');\n agentTeamsExperimental =\n /agent teams/i.test(help) || help.includes('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS');\n } else {\n diagnostics.push(\n `Claude Code help probe returned non-zero (exit code ${helpRes.exitCode}); plugin and agent-team support could not be verified.`\n );\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Claude Code help probe failed: ${msg}`);\n }\n\n return {\n installed: true,\n version,\n command: cmd,\n pluginSupport,\n agentTeamsExperimental,\n subagentHandback,\n diagnostics,\n };\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport { execFile } from 'node:child_process';\nimport type {\n ClineCapabilityReport,\n ProcessRunner,\n ProcessRunnerResult,\n ResolvedClineCommand,\n} from './types.js';\n\nexport interface ClineProbeResolverOptions {\n resolveExecutable?: () => ResolvedClineCommand | null;\n}\n\nexport const defaultProcessRunner: ProcessRunner = (\n executable: string,\n args: string[],\n options?: { cwd?: string; env?: Record<string, string>; timeoutMs?: number }\n): Promise<ProcessRunnerResult> => {\n return new Promise((resolve) => {\n const timeout = options?.timeoutMs ?? 5000;\n try {\n execFile(\n executable,\n args,\n {\n cwd: options?.cwd,\n env: options?.env ? { ...process.env, ...options.env } : process.env,\n timeout,\n shell: false,\n },\n (error, stdout, stderr) => {\n if (error) {\n const exitCode = typeof error.code === 'number' ? error.code : 1;\n resolve({\n exitCode,\n stdout: (stdout || '').toString(),\n stderr: (stderr || error.message || '').toString(),\n });\n } else {\n resolve({\n exitCode: 0,\n stdout: (stdout || '').toString(),\n stderr: (stderr || '').toString(),\n });\n }\n }\n );\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n resolve({\n exitCode: 1,\n stdout: '',\n stderr: msg,\n });\n }\n });\n};\n\nexport class ClineCapabilityProbe {\n private runner: ProcessRunner;\n private customResolver?: () => ResolvedClineCommand | null;\n\n constructor(runner?: ProcessRunner, options?: ClineProbeResolverOptions) {\n this.runner = runner || defaultProcessRunner;\n this.customResolver = options?.resolveExecutable;\n }\n\n /**\n * Safe executable resolution across POSIX and Windows layouts.\n */\n public resolveExecutable(): ResolvedClineCommand | null {\n if (this.customResolver) {\n return this.customResolver();\n }\n\n // 1. Explicit CLINE_BIN_PATH\n const envBin = process.env.CLINE_BIN_PATH;\n if (envBin && path.isAbsolute(envBin) && fs.existsSync(envBin)) {\n return {\n executable: envBin,\n prefixArgs: [],\n source: 'env-binary',\n };\n }\n\n // 2. PATH scanning\n const pathEnv = process.env.PATH || '';\n const pathSeparator = process.platform === 'win32' ? ';' : ':';\n const dirs = pathEnv.split(pathSeparator).filter(Boolean);\n\n if (process.platform === 'win32') {\n const exeNames = ['cline.cmd', 'cline.bat', 'cline.exe', 'cline'];\n for (const dir of dirs) {\n for (const exeName of exeNames) {\n const fullPath = path.join(dir, exeName);\n if (fs.existsSync(fullPath)) {\n // Check adjacent Node wrapper in npm / nvm / volta structure\n const adjacentWrapper1 = path.join(dir, 'node_modules', 'cline', 'bin', 'cline');\n const adjacentWrapper2 = path.join(dir, 'node_modules', '@cline', 'cline', 'bin', 'cline');\n\n if (fs.existsSync(adjacentWrapper1)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper1],\n source: 'node-wrapper',\n };\n }\n if (fs.existsSync(adjacentWrapper2)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper2],\n source: 'node-wrapper',\n };\n }\n\n // Windows hardening (ADR 0013 §5): Node >= 18.20 / 20.12 / 24 rejects\n // spawning .cmd/.bat shims with shell:false (EINVAL), so bridge through\n // cmd.exe while keeping the argv array shell-safe.\n const ext = path.extname(fullPath).toLowerCase();\n if (ext === '.cmd' || ext === '.bat') {\n return {\n executable: 'cmd.exe',\n prefixArgs: ['/c', fullPath],\n source: 'path-executable',\n };\n }\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n } else {\n for (const dir of dirs) {\n const fullPath = path.join(dir, 'cline');\n if (fs.existsSync(fullPath)) {\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n\n return null;\n }\n\n /**\n * Run read-only capability probe against local Cline.\n */\n public async probe(): Promise<ClineCapabilityReport> {\n const cmd = this.resolveExecutable();\n const diagnostics: string[] = [];\n\n if (!cmd) {\n diagnostics.push('Cline executable not found on PATH or via CLINE_BIN_PATH.');\n return {\n installed: false,\n namedTeams: false,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n\n // 1. Version check\n let version: string | undefined;\n try {\n const verRes = await this.runner(cmd.executable, [...cmd.prefixArgs, 'version'], {\n timeoutMs: 5000,\n });\n\n if (verRes.exitCode === 0) {\n version = verRes.stdout.trim().split('\\n')[0]?.trim();\n } else {\n diagnostics.push(`Cline version check failed (exit code ${verRes.exitCode}): ${verRes.stderr.trim()}`);\n return {\n installed: false,\n command: cmd,\n namedTeams: false,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Error executing Cline version check: ${msg}`);\n return {\n installed: false,\n command: cmd,\n namedTeams: false,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n\n // 2. Named team parser probe\n let namedTeams = false;\n try {\n const probeRes = await this.runner(\n cmd.executable,\n [...cmd.prefixArgs, '--team-name', 'agents-united-capability-probe', 'version'],\n { timeoutMs: 5000 }\n );\n\n if (probeRes.exitCode === 0) {\n namedTeams = true;\n } else {\n diagnostics.push(`Named teams probe returned non-zero (exit code ${probeRes.exitCode}). Falling back to adaptive session.`);\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Named teams probe failed: ${msg}`);\n }\n\n return {\n installed: true,\n version,\n command: cmd,\n namedTeams,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { AgentHostAdapter } from './adapter.js';\nimport { ClineCapabilityProbe, defaultProcessRunner } from './cline-capabilities.js';\nimport type {\n ClineActivationStrategy,\n ClineCapabilityReport,\n InstallScope,\n LockfileManifest,\n ProcessRunner,\n} from './types.js';\n\nexport interface ClineActivationPlan {\n bundleName: string;\n scope: InstallScope;\n workspace: string;\n teamName: string;\n strategy: ClineActivationStrategy;\n executable: string;\n argv: string[];\n bootstrapPrompt: string;\n}\n\nexport interface PlanActivationOptions {\n bundleName: string;\n workspace: string;\n scope: InstallScope;\n report: ClineCapabilityReport;\n prompt?: string;\n teamName?: string;\n allowAddons?: boolean;\n headless?: boolean;\n /** Optional coordinator agent filename (e.g. \"orchestrator-universal.md\"). Resolved from the bundle definition by the caller; defaults to orchestrator-engineering.md for backward compatibility. */\n orchestrator?: string;\n}\n\nexport interface ResolveInstallationOptions {\n scope?: InstallScope;\n global?: boolean;\n cwd?: string;\n}\n\nexport class ClineLauncher {\n private probe: ClineCapabilityProbe;\n private runner: ProcessRunner;\n\n constructor(probe?: ClineCapabilityProbe, runner?: ProcessRunner) {\n this.probe = probe || new ClineCapabilityProbe();\n this.runner = runner || defaultProcessRunner;\n }\n\n /**\n * Generate stable team name: au-<bundle>-<first-8-sha256-of-workspace>\n */\n public static generateTeamName(bundleName: string, workspace: string): string {\n const sanitizedBundle = bundleName.replace(/[^A-Za-z0-9_-]/g, '-');\n const hash = crypto.createHash('sha256').update(path.resolve(workspace)).digest('hex').slice(0, 8);\n const prefix = `au-${sanitizedBundle}`;\n const maxPrefixLen = 64 - 9; // 64 - (1 for hyphen + 8 for hash)\n const truncatedPrefix = prefix.slice(0, maxPrefixLen);\n return `${truncatedPrefix}-${hash}`;\n }\n\n /**\n * Validate custom team names against safe identifier requirements.\n */\n public static validateTeamName(name: string): boolean {\n return /^[A-Za-z0-9_-]{1,64}$/.test(name);\n }\n\n /**\n * Resolve an installed bundle for Cline activation.\n */\n public async resolveInstallation(\n bundleName: string,\n options: ResolveInstallationOptions = {}\n ): Promise<{ scope: InstallScope; workspace: string; lockfile: LockfileManifest; manifestPath: string }> {\n const cwd = options.cwd || process.cwd();\n const isGlobal = !!options.global;\n\n let targetDir: string;\n let scope: InstallScope;\n let workspace: string;\n\n if (isGlobal) {\n targetDir = AgentHostAdapter.resolveHostDir('global', 'agents');\n scope = 'global';\n workspace = os.homedir();\n } else {\n workspace = cwd;\n targetDir = path.join(cwd, '.agents');\n scope = 'project';\n }\n\n const lockfilePath = path.join(targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n if (!isGlobal) {\n // Check if global installation exists as fallback\n const globalTarget = AgentHostAdapter.resolveHostDir('global', 'agents');\n const globalLockfile = path.join(globalTarget, 'agents-united.json');\n if (await fs.pathExists(globalLockfile)) {\n const gLock: LockfileManifest = await fs.readJson(globalLockfile);\n if (gLock.installed?.bundles?.includes(bundleName)) {\n return this.resolveInstallation(bundleName, { ...options, global: true });\n }\n }\n }\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n if (!lockfile.installed?.bundles?.includes(bundleName)) {\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n // Check Cline fanout and Team Manifest presence\n const hasClineFanout = (lockfile.fanout || []).includes('cline');\n const manifestRel = `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n const manifestPath = path.join(workspace, manifestRel);\n\n if (!hasClineFanout || !await fs.pathExists(manifestPath)) {\n throw new Error(\n `Bundle '${bundleName}' is not projected to Cline. Run 'agents update ${bundleName} --fanout cline' first.`\n );\n }\n\n return {\n scope,\n workspace,\n lockfile,\n manifestPath,\n };\n }\n\n /**\n * Plan activation strategy, argv, and bootstrap prompt without launching process.\n */\n public planActivation(options: PlanActivationOptions): ClineActivationPlan {\n const {\n bundleName,\n workspace,\n scope,\n report,\n prompt,\n teamName: customTeamName,\n allowAddons,\n headless,\n orchestrator,\n } = options;\n\n const command = report.command || {\n executable: 'cline',\n prefixArgs: [],\n source: 'path-executable' as const,\n };\n\n let teamName = ClineLauncher.generateTeamName(bundleName, workspace);\n if (customTeamName) {\n if (!ClineLauncher.validateTeamName(customTeamName)) {\n throw new Error(\n `Invalid team name \"${customTeamName}\". Must match [A-Za-z0-9_-] and be at most 64 characters.`\n );\n }\n teamName = customTeamName;\n }\n\n const strategy: ClineActivationStrategy = report.namedTeams ? 'named-team' : 'adaptive-session';\n\n const manifestRel = scope === 'global'\n ? `~/.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`\n : `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n // Coordinator role = the bundle's declared orchestrator when available; fall back to\n // orchestrator-engineering.md only to preserve pre-existing platform-manifest behavior.\n const coordinatorFile = (orchestrator || 'orchestrator-engineering.md').replace(/\\.md$/, '');\n const coordinatorCanonical = `.agents/agents/${coordinatorFile}.md`;\n\n const addonPolicyText = allowAddons\n ? 'Addon auto-installation is pre-authorized for this session.'\n : `Before installing any recommended addon, explain the requirement to the user and request explicit confirmation to run: agents add <addon> -t cline ${scope === 'global' ? '-g ' : ''}-y.`;\n\n const deploymentNoteText = `Deployment note: this bundle is already projected natively for this workspace (skills, rules, workflows, and configured subagent roles) - no \"cline plugin install\" step is needed.`;\n\n const taskText = prompt && prompt.trim().length > 0\n ? `User task: ${prompt.trim()}`\n : 'Please introduce your coordinator role to the user and ask for their first task.';\n\n const bootstrapPrompt = [\n `You are coordinating the \"${bundleName}\" team in Agents United.`,\n `Read the Team Manifest at \"${manifestRel}\" and your coordinator role definition at \"${coordinatorCanonical}\" before acting.`,\n `Use specialist roles only when necessary.`,\n addonPolicyText,\n deploymentNoteText,\n taskText,\n ].join('\\n\\n');\n\n const argv: string[] = [...command.prefixArgs];\n if (strategy === 'named-team') {\n argv.push('--team-name', teamName);\n }\n argv.push('--cwd', workspace);\n if (!headless) {\n argv.push('-i');\n }\n argv.push(bootstrapPrompt);\n\n return {\n bundleName,\n scope,\n workspace,\n teamName,\n strategy,\n executable: command.executable,\n argv,\n bootstrapPrompt,\n };\n }\n\n /**\n * Launch Cline session using argument array.\n */\n public async launch(plan: ClineActivationPlan): Promise<void> {\n const { spawn } = await import('node:child_process');\n const child = spawn(plan.executable, plan.argv, {\n cwd: plan.workspace,\n stdio: 'inherit',\n shell: false,\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('error', reject);\n child.on('exit', (code) => {\n if (code === 0 || code === null) {\n resolve();\n } else {\n resolve(); // return cleanly on process exit\n }\n });\n });\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { AgentHostAdapter } from './adapter.js';\nimport { ClaudeCapabilityProbe } from './claude-capabilities.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport { defaultProcessRunner } from './cline-capabilities.js';\nimport type {\n ClaudeCapabilityReport,\n InstallScope,\n LockfileManifest,\n ProcessRunner,\n} from './types.js';\n\n/** Default coordinator when the caller could not resolve the bundle's own `orchestrator` field. */\nconst DEFAULT_COORDINATOR = 'orchestrator-engineering.md';\n\nexport interface ClaudeActivationPlan {\n bundleName: string;\n scope: InstallScope;\n workspace: string;\n executable: string;\n argv: string[];\n bootstrapPrompt: string;\n env: Record<string, string>;\n}\n\nexport interface PlanClaudeActivationOptions {\n bundleName: string;\n workspace: string;\n scope: InstallScope;\n report: ClaudeCapabilityReport;\n prompt?: string;\n /** Optional coordinator agent filename (e.g. \"orchestrator-universal.md\"). Resolved from the bundle\n * definition by the caller; defaults to orchestrator-engineering.md for backward compatibility. */\n orchestrator?: string;\n /** `--bg`: run the session in the background. */\n background?: boolean;\n /** Pre-authorize recommended addon installs for this session (mirrors `ClineLauncher`). */\n allowAddons?: boolean;\n /** Experimental agent-teams scaffold — ephemeral env + prompt instruction only (Plan 016 decision 14). */\n teams?: boolean;\n /** Plugin root for `--plugin-dir` (Step 7 emits the manifest inside it). */\n pluginDir?: string;\n /**\n * Whether the single host-neutral team manifest exists on disk for this workspace.\n *\n * ADR 0018 decision 6 keeps exactly one manifest under the organization package (never a\n * `.claude/` duplicate), and it is written by the Cline half of the compound lane. A claude-only\n * fanout therefore has none, so the caller passes `false` and the bootstrap prompt points at the\n * projected `.claude/agents/` roster instead of a dangling path. Omitted ⇒ the established\n * manifest instruction is used.\n */\n manifestAvailable?: boolean;\n}\n\nexport interface ResolveClaudeInstallationOptions {\n scope?: InstallScope;\n global?: boolean;\n cwd?: string;\n}\n\n/**\n * ADR 0018 / Plan 016 decision 12 — the Claude Code activation lane, mirroring `ClineLauncher` in shape\n * (same constructor seam, same resolve/plan/launch split, same argv-array discipline with `shell: false`).\n *\n * Two hard boundaries carried by this file:\n * 1. The launcher only ever *describes* a session. It writes no file under `.claude/**`, never touches\n * `CLAUDE.md` / `CLAUDE.local.md` / `.claude/settings.json` / `.claude/workflows/**`, and the teams\n * scaffold persists nothing anywhere (no `~/.claude/teams/`, no settings key).\n * 2. Every value is one argv element. `--agent` and its value are pushed separately, the workspace is a\n * single `--add-dir` argument, and the bootstrap prompt is a single final argument, so no prompt text\n * is ever word-split, shell-expanded or joined into a command string.\n */\nexport class ClaudeLauncher {\n private probe: ClaudeCapabilityProbe;\n private runner: ProcessRunner;\n\n constructor(probe?: ClaudeCapabilityProbe, runner?: ProcessRunner) {\n this.probe = probe || new ClaudeCapabilityProbe();\n this.runner = runner || defaultProcessRunner;\n }\n\n /**\n * The `--agent` value must equal the projected coordinator definition's basename without `.md`.\n *\n * A projected coordinator keeps its full `orchestrator-<x>` name in `.claude/agents/`: coordinators are\n * never `subagent-<x>` files, so the prefix stripping that applies to every specialist role is a no-op\n * here. We still route through the projector's own helper so the launcher and the renderer can never\n * diverge if a bundle ever declares a differently-prefixed orchestrator.\n */\n public static resolveCoordinatorName(orchestrator?: string): string {\n const file = (orchestrator && orchestrator.trim().length > 0 ? orchestrator.trim() : DEFAULT_COORDINATOR)\n .replace(/\\.md$/i, '');\n return ClaudeProjector.stripSubagentPrefix(path.basename(file));\n }\n\n /**\n * Resolve an installed bundle for Claude Code activation. Mirrors `ClineLauncher.resolveInstallation`:\n * same global→project fallback, same `.agents/agents-united.json` lockfile path, same error text.\n */\n public async resolveInstallation(\n bundleName: string,\n options: ResolveClaudeInstallationOptions = {}\n ): Promise<{ scope: InstallScope; workspace: string; lockfile: LockfileManifest; manifestPath: string }> {\n const cwd = options.cwd || process.cwd();\n const isGlobal = !!options.global;\n\n let targetDir: string;\n let scope: InstallScope;\n let workspace: string;\n\n if (isGlobal) {\n targetDir = AgentHostAdapter.resolveHostDir('global', 'agents');\n scope = 'global';\n workspace = os.homedir();\n } else {\n workspace = cwd;\n targetDir = path.join(cwd, '.agents');\n scope = 'project';\n }\n\n const lockfilePath = path.join(targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n if (!isGlobal) {\n // Check if global installation exists as fallback\n const globalTarget = AgentHostAdapter.resolveHostDir('global', 'agents');\n const globalLockfile = path.join(globalTarget, 'agents-united.json');\n if (await fs.pathExists(globalLockfile)) {\n const gLock: LockfileManifest = await fs.readJson(globalLockfile);\n if (gLock.installed?.bundles?.includes(bundleName)) {\n return this.resolveInstallation(bundleName, { ...options, global: true });\n }\n }\n }\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n if (!lockfile.installed?.bundles?.includes(bundleName)) {\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n // Host gate. The Cline lane requires both the recorded fanout and the projected artifact. The Claude\n // lane is satisfied by either signal: the host-neutral Team Manifest under `.agents/plugins/<bundle>/`\n // is the artifact the bootstrap prompt actually reads, and it is emitted by the compound lane, while\n // `fanout: ['claude']` is the recorded host signal. Requiring both would make\n // `agents start --host claude --dry-run` fail in a workspace whose install predates the Claude lane,\n // which is exactly the case the dry-run exists to preview. A workspace with neither signal is not\n // projected at all and gets the same actionable remedy the Cline lane prints.\n const hasClaudeFanout = (lockfile.fanout || []).includes('claude');\n const manifestRel = `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n const manifestPath = path.join(workspace, manifestRel);\n\n if (!hasClaudeFanout && !await fs.pathExists(manifestPath)) {\n throw new Error(\n `Bundle '${bundleName}' is not projected to Claude. Run 'agents update ${bundleName} --fanout claude' first.`\n );\n }\n\n return {\n scope,\n workspace,\n lockfile,\n manifestPath,\n };\n }\n\n /**\n * Plan the argv, bootstrap prompt and ephemeral environment for a Claude Code session. Pure: no process\n * is spawned and nothing is written to disk, so `--dry-run` can call it safely.\n */\n public planActivation(options: PlanClaudeActivationOptions): ClaudeActivationPlan {\n const {\n bundleName,\n workspace,\n scope,\n report,\n prompt,\n orchestrator,\n allowAddons,\n background,\n teams,\n pluginDir,\n manifestAvailable,\n } = options;\n\n const command = report.command || {\n executable: 'claude',\n prefixArgs: [],\n source: 'path-executable' as const,\n };\n\n const coordinatorName = ClaudeLauncher.resolveCoordinatorName(orchestrator);\n const homePrefix = scope === 'global' ? '~/' : '';\n const manifestRel = `${homePrefix}.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n // The projected coordinator definition. Read-only reference: this launcher never writes under\n // `.claude/**` — the projection engine owns that namespace.\n const coordinatorRel = `${homePrefix}.claude/agents/${coordinatorName}.md`;\n\n const addonPolicyText = allowAddons\n ? 'Addon auto-installation is pre-authorized for this session.'\n : `Before installing any recommended addon, explain the requirement to the user and request explicit confirmation to run: agents add <addon> -t claude ${scope === 'global' ? '-g ' : ''}-y.`;\n\n const deploymentNoteText =\n `Deployment note: this bundle is already projected natively for this workspace - roles in \"${homePrefix}.claude/agents/\", ` +\n `skills in \"${homePrefix}.claude/skills/\" and rules in \"${homePrefix}.claude/rules/\". The single source of truth stays the ` +\n `canonical store under \"${homePrefix}.agents/\" (ADR 0018): read the projections, edit the canonical files, never the copies.`;\n\n // Ordinary Claude sessions delegate by description; a `--agent` session runs this coordinator's own\n // projected definition on the main thread, which is the only way the real `Agent(...)` allowlist\n // (specialist type names) is enforced.\n const delegationNoteText =\n `Delegation on this host works by description: in an ordinary Claude Code session you name a specialist and Claude ` +\n `picks the matching definition from \"${homePrefix}.claude/agents/\". This session was started with \\`claude --agent ${coordinatorName}\\`, ` +\n `so your own projected coordinator definition runs on the main thread and the real \\`Agent(...)\\` allowlist in its ` +\n `frontmatter is what bounds the specialists you may delegate to - send work only to those exact agent type names.`;\n\n const taskText = prompt && prompt.trim().length > 0\n ? `User task: ${prompt.trim()}`\n : 'Please introduce your coordinator role to the user and ask for their first task.';\n\n // ADR 0018 decision 6 keeps ONE host-neutral team manifest, emitted under the organization\n // package and never duplicated into `.claude/`. That package is written by the Cline half of\n // the compound lane, so a claude-only fanout legitimately has no manifest on disk: pointing a\n // coordinator at a path that does not exist would make its first instruction fail. When the\n // caller reports the manifest is absent, the prompt falls back to the roster Claude actually\n // discovers — the projected agent definitions in `.claude/agents/`.\n const manifestInstruction = manifestAvailable === false\n ? `Read your coordinator role definition at \"${coordinatorRel}\" before acting. Specialist roles are ` +\n `discoverable by name and description from the projected definitions in \"${homePrefix}.claude/agents/\" ` +\n `(the host-neutral team manifest is not present in this workspace yet - it is written by a ` +\n `\\`--fanout cline\\` install).`\n : `Read the Team Manifest at \"${manifestRel}\" and your coordinator role definition at \"${coordinatorRel}\" before acting.`;\n\n const bootstrapLines = [\n `You are coordinating the \"${bundleName}\" team in Agents United.`,\n manifestInstruction,\n delegationNoteText,\n 'Use specialist roles only when necessary.',\n addonPolicyText,\n deploymentNoteText,\n taskText,\n ];\n\n if (teams === true) {\n // ADR 0018 decision 13 / Plan 016 decision 14 — the teams scaffold is experimental, minimal and never\n // load-bearing. This instruction text deliberately never names the opt-in environment variable: the\n // variable is injected into the spawned process environment only and must not appear in argv, so it can\n // never leak into a prompt, a shell echo or a transcript.\n bootstrapLines.push(\n `Agent teams are enabled for this session as an EXPERIMENTAL scaffold: spawn teammates from the projected agent ` +\n `types by name - the names you see in \"${homePrefix}.claude/agents/\" (specialists are projected with their ` +\n `\"subagent-\" prefix stripped, e.g. \\`backend-architect\\`). The scaffold is deliberately minimal: exactly one team per ` +\n `session, you are the fixed lead, there is no nested teams and no session resumption, and nothing about it is ` +\n `persisted to disk. Never make it load-bearing - if a teammate cannot be spawned, continue with ordinary delegated ` +\n `subagents using the Agent tool.`\n );\n }\n\n const bootstrapPrompt = bootstrapLines.join('\\n\\n');\n\n // ADR 0018 decision 13 / Plan 016 decision 14: the opt-in is injected EPHEMERALLY into the spawned\n // process environment only. It is never written to `.claude/settings.json`, never recorded in a lockfile\n // or any other workspace file, nothing is written under `~/.claude/teams/`, and the variable name must\n // never appear in argv. `env` is otherwise empty - the launcher merges it over `process.env` at spawn.\n const env: Record<string, string> = {};\n if (teams === true) {\n env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = '1';\n }\n\n const argv: string[] = [...command.prefixArgs];\n // `--agent` names the projected coordinator definition. The projected file in `.claude/agents/` keeps its\n // full `orchestrator-<x>` name - the `subagent-` prefix stripping that applies to every specialist role is\n // a no-op for coordinators - so this value MUST equal the projected file basename without `.md`.\n argv.push('--agent');\n argv.push(coordinatorName);\n argv.push('--add-dir');\n argv.push(workspace);\n if (background === true) {\n argv.push('--bg');\n }\n if (pluginDir) {\n argv.push('--plugin-dir');\n argv.push(pluginDir);\n }\n argv.push(bootstrapPrompt);\n\n return {\n bundleName,\n scope,\n workspace,\n executable: command.executable,\n argv,\n bootstrapPrompt,\n env,\n };\n }\n\n /**\n * Launch the Claude Code session from the argv array. Mirrors `ClineLauncher.launch`: `shell: false`\n * (never `shell: true`), `stdio: 'inherit'`, and the plan's ephemeral env merged over `process.env`.\n */\n public async launch(plan: ClaudeActivationPlan): Promise<void> {\n const { spawn } = await import('node:child_process');\n const child = spawn(plan.executable, plan.argv, {\n cwd: plan.workspace,\n stdio: 'inherit',\n shell: false,\n env: { ...process.env, ...plan.env },\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('error', reject);\n child.on('exit', (code) => {\n if (code === 0 || code === null) {\n resolve();\n } else {\n resolve(); // return cleanly on process exit\n }\n });\n });\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { McpLocationRegistry, type DiscoveredMcpConfig } from './mcp-locations.js';\nimport type {\n BundleDefinition,\n PrerequisiteEvaluation,\n PrerequisiteItemCheck,\n BundlePrerequisites,\n AgentHost,\n} from './types.js';\n\nexport interface PrerequisiteCheckOptions {\n cwd?: string;\n env?: Record<string, string | undefined>;\n targetHosts?: (AgentHost | string)[];\n}\n\nexport interface DiscoveredConfigFile {\n host: 'gemini' | 'cursor' | 'cline' | 'claude' | 'opencode' | 'custom' | string;\n label: string;\n path: string;\n exists: boolean;\n serverCount?: number;\n}\n\nexport interface McpCheckResult {\n configured: boolean;\n host?: string;\n location?: string;\n disabled?: boolean;\n serverKey?: string;\n foundInConfigs: Array<{ id: string; host: string; label: string; path: string; disabled?: boolean; serverKey: string }>;\n missingInConfigs: Array<{ id: string; host: string; label: string; path: string }>;\n}\n\nexport class PrerequisiteChecker {\n /**\n * Discovers all candidate and existing MCP configuration files across AI hosts\n */\n public static async discoverHostConfigFiles(cwd: string = process.cwd()): Promise<DiscoveredConfigFile[]> {\n const discovered = await McpLocationRegistry.discoverAll(cwd);\n return discovered.map(d => ({\n host: d.host,\n label: d.label,\n path: d.path,\n exists: d.exists,\n serverCount: d.serverCount,\n }));\n }\n\n /**\n * Helper that checks if a configured MCP server key or its configuration payload matches the target MCP name\n */\n public static matchesMcpServer(targetMcpName: string, serverKey: string, serverConfig: any = {}): boolean {\n const targetNorm = targetMcpName.toLowerCase().replace(/[^a-z0-9]/g, '');\n const keyNorm = serverKey.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n // 1. Direct or Substring Key Match (e.g. \"github-mcp-server\" -> \"github\", \"StitchMCP\" -> \"stitch\")\n if (keyNorm === targetNorm) return true;\n if (keyNorm.includes(targetNorm)) return true;\n if (targetNorm.includes(keyNorm)) return true;\n\n // Stripping common prefixes / suffixes: mcp, server, mcpserver, domain prefixes\n const strippedKey = keyNorm\n .replace(/^githubcom/g, '')\n .replace(/^mcp/g, '')\n .replace(/mcp$/g, '')\n .replace(/^server/g, '')\n .replace(/server$/g, '');\n if (strippedKey === targetNorm || (strippedKey.length > 2 && targetNorm.includes(strippedKey)) || (targetNorm.length > 2 && strippedKey.includes(targetNorm))) {\n return true;\n }\n\n // 2. Executable / Package Signature Match (in command or args)\n const cmd = String(serverConfig?.command || '').toLowerCase();\n const args = Array.isArray(serverConfig?.args)\n ? serverConfig.args.map((a: any) => String(a).toLowerCase()).join(' ')\n : '';\n const fullExec = `${cmd} ${args}`;\n\n if (targetMcpName === 'github') {\n if (fullExec.includes('github') || fullExec.includes('ghcr.io/github')) return true;\n }\n if (targetMcpName === 'playwright') {\n if (fullExec.includes('playwright')) return true;\n }\n if (targetMcpName === 'markitdown') {\n if (fullExec.includes('markitdown')) return true;\n }\n if (targetMcpName === 'chrome-devtools-mcp' || targetMcpName === 'chrome-devtools') {\n if (fullExec.includes('chrome-devtools')) return true;\n }\n if (targetMcpName === 'stitch') {\n if (fullExec.includes('stitch') || fullExec.includes('stitch.googleapis.com')) return true;\n }\n if (targetMcpName === 'figma') {\n if (fullExec.includes('figma')) return true;\n }\n if (targetMcpName === 'firecrawl') {\n if (fullExec.includes('firecrawl')) return true;\n }\n if (targetMcpName === 'context7') {\n if (fullExec.includes('context7')) return true;\n }\n if (targetMcpName === 'supabase') {\n if (fullExec.includes('supabase')) return true;\n }\n\n // 3. Endpoint / URL Signature Match (in url or serverUrl)\n const url = String(serverConfig?.url || serverConfig?.serverUrl || '').toLowerCase();\n if (url.includes(targetNorm)) return true;\n if (targetMcpName === 'stitch' && url.includes('stitch.googleapis.com')) return true;\n if (targetMcpName === 'context7' && url.includes('context7.com')) return true;\n if (targetMcpName === 'firecrawl' && url.includes('firecrawl.dev')) return true;\n if (targetMcpName === 'supabase' && url.includes('supabase.com')) return true;\n\n return false;\n }\n\n /**\n * Discovers whether an MCP server is configured across supported host runtimes\n * (Antigravity/Gemini, Cursor, Cline, Claude Code, etc.)\n */\n public static async isMcpConfigured(\n mcpName: string,\n cwd: string = process.cwd()\n ): Promise<McpCheckResult> {\n const discovered = await McpLocationRegistry.discoverAll(cwd);\n const foundInConfigs: McpCheckResult['foundInConfigs'] = [];\n const missingInConfigs: McpCheckResult['missingInConfigs'] = [];\n\n // 1. Check all discovered configuration files\n for (const file of discovered) {\n if (!file.exists) {\n missingInConfigs.push({\n id: file.id,\n host: file.host,\n label: file.label,\n path: file.path,\n });\n continue;\n }\n\n let matched = false;\n if (file.servers && typeof file.servers === 'object') {\n for (const [key, serverDef] of Object.entries(file.servers)) {\n if (PrerequisiteChecker.matchesMcpServer(mcpName, key, serverDef)) {\n const isDisabled = (serverDef as any)?.disabled === true;\n foundInConfigs.push({\n id: file.id,\n host: file.host,\n label: file.label,\n path: file.path,\n disabled: isDisabled,\n serverKey: key,\n });\n matched = true;\n break;\n }\n }\n }\n\n if (!matched) {\n missingInConfigs.push({\n id: file.id,\n host: file.host,\n label: file.label,\n path: file.path,\n });\n }\n }\n\n // 2. Also check directory-based MCP definitions (e.g. Antigravity folder ~/.gemini/antigravity/mcp/<serverName>)\n const homeDir = os.homedir();\n const dirCandidates = [\n path.join(cwd, '.gemini', 'antigravity', 'mcp'),\n path.join(homeDir, '.gemini', 'antigravity', 'mcp'),\n ];\n for (const dir of dirCandidates) {\n if (await fs.pathExists(dir)) {\n const entries = await fs.readdir(dir).catch(() => []);\n for (const entry of entries) {\n if (PrerequisiteChecker.matchesMcpServer(mcpName, entry, {})) {\n foundInConfigs.push({\n id: 'antigravity-dir',\n host: 'gemini',\n label: 'Google Antigravity MCP Directory',\n path: path.join(dir, entry),\n disabled: false,\n serverKey: entry,\n });\n break;\n }\n }\n }\n }\n\n const isConfigured = foundInConfigs.length > 0;\n const firstFound = foundInConfigs[0];\n\n return {\n configured: isConfigured,\n host: firstFound?.host,\n location: firstFound?.path,\n disabled: firstFound?.disabled,\n serverKey: firstFound?.serverKey,\n foundInConfigs,\n missingInConfigs,\n };\n }\n\n /**\n * Checks if an npm package is installed in node_modules or declared in package.json\n */\n public static async isPackageInstalled(\n pkgName: string,\n cwd: string = process.cwd()\n ): Promise<{ installed: boolean; location?: string }> {\n // 1. Direct node_modules check\n const modulePath = path.join(cwd, 'node_modules', ...pkgName.split('/'));\n if (await fs.pathExists(modulePath)) {\n return { installed: true, location: modulePath };\n }\n\n // 2. package.json dependencies check\n const pkgJsonPath = path.join(cwd, 'package.json');\n if (await fs.pathExists(pkgJsonPath)) {\n try {\n const pkg = await fs.readJson(pkgJsonPath);\n const deps = {\n ...pkg.dependencies,\n ...pkg.devDependencies,\n ...pkg.peerDependencies,\n };\n if (deps[pkgName]) {\n return { installed: true, location: pkgJsonPath };\n }\n } catch {\n // Ignore malformed package.json\n }\n }\n\n return { installed: false };\n }\n\n /**\n * Checks if an environment variable is defined in process.env or local .env files\n */\n public static async isEnvVarSet(\n varName: string,\n cwd: string = process.cwd(),\n customEnv?: Record<string, string | undefined>\n ): Promise<{ set: boolean; source?: string }> {\n const envSource = customEnv || process.env;\n if (envSource[varName] && envSource[varName]?.trim() !== '') {\n return { set: true, source: 'process.env' };\n }\n\n // Check local .env and .env.local in cwd\n const envFiles = [\n path.join(cwd, '.env.local'),\n path.join(cwd, '.env'),\n ];\n\n for (const envFile of envFiles) {\n if (await fs.pathExists(envFile)) {\n try {\n const content = await fs.readFile(envFile, 'utf8');\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith('#') || !trimmed.includes('=')) continue;\n const [k, ...v] = trimmed.split('=');\n if (k.trim() === varName && v.join('=').trim() !== '') {\n return { set: true, source: path.basename(envFile) };\n }\n }\n } catch {\n // Ignore read errors\n }\n }\n }\n\n return { set: false };\n }\n\n /**\n * Evaluates all prerequisites declared on a bundle, supporting target host scoping and multi-host partial breakdowns\n */\n public async evaluate(\n bundle: BundleDefinition,\n options: PrerequisiteCheckOptions = {}\n ): Promise<PrerequisiteEvaluation> {\n const cwd = options.cwd || process.cwd();\n const env = options.env || process.env;\n const tier = bundle.tier || 'domain';\n const prereqs: BundlePrerequisites = bundle.prerequisites || {};\n\n const targetHosts = options.targetHosts || ['agents'];\n const targetHostKeys = new Set(targetHosts.map(h => (h === 'agents' ? 'gemini' : h)));\n\n const items: PrerequisiteItemCheck[] = [];\n\n // 1. Evaluate Required MCPs\n if (prereqs.requiredMcps && prereqs.requiredMcps.length > 0) {\n for (const mcp of prereqs.requiredMcps) {\n const check = await PrerequisiteChecker.isMcpConfigured(mcp.name, cwd);\n\n // Discovered configs filtered by target host(s)\n const relevantFound = check.foundInConfigs.filter(c => targetHostKeys.has(c.host));\n const hostCleanNames: Record<string, string> = {\n gemini: 'Google Antigravity',\n agents: 'Google Antigravity',\n cline: 'Cline',\n cursor: 'Cursor',\n claude: 'Claude Code',\n opencode: 'OpenCode',\n windsurf: 'Windsurf',\n };\n\n const detectedHostLabels = Array.from(new Set(relevantFound.map(c => hostCleanNames[c.host] || c.host)));\n const detectedHostKeys = new Set(relevantFound.map(c => c.host));\n const missingHostKeys = Array.from(targetHostKeys).filter(h => !detectedHostKeys.has(h));\n const missingHostLabels = missingHostKeys.map(h => hostCleanNames[h] || h);\n\n let satisfied = false;\n let status: 'ok' | 'missing' | 'partial' = 'missing';\n let details = 'Not found in host MCP configuration';\n\n if (relevantFound.length > 0 && missingHostKeys.length === 0) {\n satisfied = true;\n status = 'ok';\n details = `Configured in ${detectedHostLabels.join(', ')}`;\n } else if (relevantFound.length > 0 && missingHostKeys.length > 0) {\n satisfied = false;\n status = 'partial';\n details = `Detected in ${detectedHostLabels.join(', ')}; Missing in ${missingHostLabels.join(', ')}`;\n } else if (check.foundInConfigs.length > 0 && relevantFound.length === 0) {\n const otherLabels = Array.from(new Set(check.foundInConfigs.map(c => hostCleanNames[c.host] || c.host)));\n satisfied = false;\n status = 'partial';\n details = `Detected in ${otherLabels.join(', ')}; Missing in target (${Array.from(targetHostKeys).map(h => hostCleanNames[h] || h).join(', ')})`;\n }\n\n items.push({\n type: 'mcp',\n name: mcp.name,\n purpose: mcp.purpose,\n satisfied,\n status,\n details,\n optionalForBrainstorming: mcp.optionalForBrainstorming ?? true,\n detectedInHosts: detectedHostLabels,\n missingInHosts: missingHostLabels,\n });\n }\n }\n\n // 2. Evaluate Required Packages\n if (prereqs.requiredPackages && prereqs.requiredPackages.length > 0) {\n for (const pkg of prereqs.requiredPackages) {\n const check = await PrerequisiteChecker.isPackageInstalled(pkg, cwd);\n items.push({\n type: 'package',\n name: pkg,\n satisfied: check.installed,\n status: check.installed ? 'ok' : 'missing',\n details: check.installed ? 'Installed in workspace' : 'Not found in node_modules or package.json',\n optionalForBrainstorming: false,\n });\n }\n }\n\n // 3. Evaluate Required Environment Variables\n if (prereqs.requiredEnvVars && prereqs.requiredEnvVars.length > 0) {\n for (const envVar of prereqs.requiredEnvVars) {\n const check = await PrerequisiteChecker.isEnvVarSet(envVar, cwd, env);\n items.push({\n type: 'env',\n name: envVar,\n satisfied: check.set,\n status: check.set ? 'ok' : 'missing',\n details: check.set ? `Defined in ${check.source}` : 'Environment variable not set',\n optionalForBrainstorming: true,\n });\n }\n }\n\n const hasPrerequisites = items.length > 0;\n const allSatisfied = items.length === 0 || items.every(i => i.satisfied);\n const operationalPossible = allSatisfied;\n\n return {\n bundleName: bundle.name,\n tier,\n hasPrerequisites,\n allSatisfied,\n operationalPossible,\n items,\n modes: bundle.modes,\n };\n }\n\n /**\n * Returns canonical command and environment definitions for known MCP servers\n */\n public static getMcpDefinition(\n mcpName: string,\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): { command: string; args: string[]; env?: Record<string, string> } {\n const norm = mcpName.trim().toLowerCase();\n switch (norm) {\n case 'github':\n return {\n command: 'npx',\n args: ['-y', '@modelcontextprotocol/server-github'],\n ...(mode === 'operational' && (envVars.GITHUB_PERSONAL_ACCESS_TOKEN || process.env.GITHUB_PERSONAL_ACCESS_TOKEN)\n ? { env: { GITHUB_PERSONAL_ACCESS_TOKEN: envVars.GITHUB_PERSONAL_ACCESS_TOKEN || process.env.GITHUB_PERSONAL_ACCESS_TOKEN || '' } }\n : {}),\n };\n case 'firecrawl':\n return {\n command: 'npx',\n args: ['-y', 'firecrawl-mcp'],\n ...(mode === 'operational' && (envVars.FIRECRAWL_API_KEY || process.env.FIRECRAWL_API_KEY)\n ? { env: { FIRECRAWL_API_KEY: envVars.FIRECRAWL_API_KEY || process.env.FIRECRAWL_API_KEY || '' } }\n : mode === 'limited-operational' && envVars.FIRECRAWL_API_URL\n ? { env: { FIRECRAWL_API_URL: envVars.FIRECRAWL_API_URL } }\n : {}),\n };\n case 'context7':\n return {\n command: 'npx',\n args: ['-y', '@upstash/context7-mcp'],\n ...(mode === 'operational' && envVars.UPSTASH_REDIS_REST_URL && envVars.UPSTASH_REDIS_REST_TOKEN\n ? { env: { UPSTASH_REDIS_REST_URL: envVars.UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN: envVars.UPSTASH_REDIS_REST_TOKEN } }\n : {}),\n };\n case 'playwright':\n return {\n command: 'npx',\n args: ['-y', '@executeautomation/playwright-mcp-server'],\n };\n case 'markitdown':\n return {\n command: 'uvx',\n args: ['markitdown-mcp'],\n };\n case 'chrome-devtools-mcp':\n case 'chrome-devtools':\n return {\n command: 'npx',\n args: ['-y', 'chrome-devtools-mcp'],\n };\n case 'stitch':\n return {\n command: 'npx',\n args: ['-y', 'mcp-remote', 'https://stitch.googleapis.com/mcp'],\n ...(mode === 'operational' && (envVars.STITCH_API_KEY || process.env.STITCH_API_KEY)\n ? { env: { STITCH_API_KEY: envVars.STITCH_API_KEY || process.env.STITCH_API_KEY || '' } }\n : {}),\n };\n case 'figma':\n return {\n command: 'npx',\n args: ['-y', 'ai-figma-mcp'],\n ...(mode === 'operational' && (envVars.FIGMA_ACCESS_TOKEN || process.env.FIGMA_ACCESS_TOKEN)\n ? { env: { FIGMA_ACCESS_TOKEN: envVars.FIGMA_ACCESS_TOKEN || process.env.FIGMA_ACCESS_TOKEN || '' } }\n : {}),\n };\n default:\n return {\n command: 'npx',\n args: ['-y', norm],\n };\n }\n }\n\n /**\n * Generates client-specific MCP configuration objects for Cursor, Cline, Claude, or Antigravity\n */\n public static generateClientConfig(\n client: 'cursor' | 'cline' | 'claude' | 'antigravity',\n mcpNames: string[],\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): Record<string, any> {\n const servers: Record<string, any> = {};\n\n for (const name of mcpNames) {\n const def = PrerequisiteChecker.getMcpDefinition(name, mode, envVars);\n if (client === 'cline') {\n servers[name] = {\n ...def,\n disabled: false,\n autoApprove: [],\n };\n } else {\n servers[name] = def;\n }\n }\n\n return { mcpServers: servers };\n }\n\n /**\n * Attempts to automatically provision a missing MCP server using the native CLI.\n */\n public static async provisionMcpServer(\n mcpName: string,\n options: { cwd?: string; env?: Record<string, string | undefined> } = {}\n ): Promise<{ success: boolean; output?: string }> {\n try {\n const { execSync } = await import('node:child_process');\n const cmd = `npx @antigravity/cli mcp add ${mcpName} --type stdio`;\n const output = execSync(cmd, { \n cwd: options.cwd || process.cwd(), \n env: options.env || process.env,\n encoding: 'utf8' \n });\n return { success: true, output };\n } catch (err: any) {\n return { success: false, output: err.message || String(err) };\n }\n }\n\n /**\n * Automatically configures missing MCP servers into a specific MCP JSON configuration file,\n * activating disabled servers and appending missing definitions.\n */\n public static async autoConfigureConfigFile(\n targetFilePath: string,\n mcpNames: string[],\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): Promise<{ success: boolean; targetFile: string; addedServers: string[]; enabledServers: string[] }> {\n await fs.ensureDir(path.dirname(targetFilePath));\n let existingConfig: any = {};\n if (await fs.pathExists(targetFilePath)) {\n try {\n existingConfig = await fs.readJson(targetFilePath);\n } catch {\n existingConfig = {};\n }\n }\n\n const isServersProp = Boolean(existingConfig.servers && !existingConfig.mcpServers);\n const existingServers = (isServersProp ? existingConfig.servers : existingConfig.mcpServers) || {};\n const addedServers: string[] = [];\n const enabledServers: string[] = [];\n\n for (const mcp of mcpNames) {\n let foundKey: string | null = null;\n for (const [key, serverDef] of Object.entries(existingServers)) {\n if (PrerequisiteChecker.matchesMcpServer(mcp, key, serverDef)) {\n foundKey = key;\n if ((serverDef as any)?.disabled === true) {\n (existingServers[key] as any).disabled = false;\n enabledServers.push(key);\n }\n break;\n }\n }\n\n if (!foundKey) {\n const def = PrerequisiteChecker.getMcpDefinition(mcp, mode, envVars);\n existingServers[mcp] = def;\n addedServers.push(mcp);\n }\n }\n\n if (isServersProp) {\n existingConfig.servers = existingServers;\n } else {\n existingConfig.mcpServers = existingServers;\n }\n\n await fs.writeJson(targetFilePath, existingConfig, { spaces: 2 });\n return {\n success: true,\n targetFile: targetFilePath,\n addedServers,\n enabledServers,\n };\n }\n\n /**\n * Automatically configures missing MCP servers into a specific AI host's configuration file.\n */\n public static async autoConfigureHost(\n host: string,\n mcpNames: string[],\n cwd: string = process.cwd(),\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): Promise<{ configured: boolean; targetFile: string; addedServers: string[] }> {\n const targetFile = McpLocationRegistry.getPrimaryWritePath(host as AgentHost, cwd);\n const res = await PrerequisiteChecker.autoConfigureConfigFile(targetFile, mcpNames, mode, envVars);\n return {\n configured: res.success,\n targetFile: res.targetFile,\n addedServers: [...res.addedServers, ...res.enabledServers],\n };\n }\n\n /**\n * Automatically installs missing NPM packages into the workspace.\n */\n public static async autoInstallPackages(\n packages: string[],\n cwd: string = process.cwd()\n ): Promise<{ success: boolean; output: string }> {\n try {\n const { execSync } = await import('node:child_process');\n const cmd = `npm install -D ${packages.join(' ')}`;\n const output = execSync(cmd, { cwd, encoding: 'utf8' });\n return { success: true, output };\n } catch (err: any) {\n return { success: false, output: err.message || String(err) };\n }\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport type { AgentHost } from './types.js';\n\nexport type McpClientCategory = 'cli' | 'extension' | 'desktop' | 'workspace';\n\nexport interface McpLocationDescriptor {\n id: string;\n host: AgentHost | 'gemini' | 'cline' | 'claude' | 'cursor' | 'opencode' | 'windsurf' | 'zed' | 'custom';\n category: McpClientCategory;\n label: string;\n resolvePath: (cwd: string, homeDir: string, appData: string) => string;\n isPrimary?: boolean;\n}\n\nexport interface DiscoveredMcpConfig {\n id: string;\n host: string;\n category: McpClientCategory;\n label: string;\n path: string;\n exists: boolean;\n serverCount: number;\n servers?: Record<string, any>;\n isPrimary?: boolean;\n}\n\nexport class McpLocationRegistry {\n /**\n * Declarative catalog of known MCP configuration files across AI tools, CLIs, extensions, and workspaces.\n */\n public static readonly LOCATIONS: McpLocationDescriptor[] = [\n // --- Google Antigravity & Gemini ---\n {\n id: 'antigravity-global',\n host: 'gemini',\n category: 'cli',\n label: 'Google Antigravity & Gemini Global Config',\n resolvePath: (_, home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),\n isPrimary: true,\n },\n {\n id: 'antigravity-system',\n host: 'gemini',\n category: 'desktop',\n label: 'Google Antigravity System Config',\n resolvePath: (_, home) => path.join(home, '.gemini', 'antigravity', 'mcp_config.json'),\n },\n {\n id: 'antigravity-workspace',\n host: 'gemini',\n category: 'workspace',\n label: 'Google Antigravity Local Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.gemini', 'config', 'mcp_config.json'),\n },\n {\n id: 'gemini-appdata',\n host: 'gemini',\n category: 'cli',\n label: 'Google Gemini AppData Config',\n resolvePath: (_, __, appData) => path.join(appData, 'gemini', 'config', 'mcp_config.json'),\n },\n\n // --- Cline CLI & VS Code Extension ---\n {\n id: 'cline-cli-settings',\n host: 'cline',\n category: 'cli',\n label: 'Cline CLI MCP Settings',\n resolvePath: (_, home) => path.join(home, '.cline', 'data', 'settings', 'cline_mcp_settings.json'),\n isPrimary: true,\n },\n {\n id: 'cline-extension-settings',\n host: 'cline',\n category: 'extension',\n label: 'Cline VS Code Extension Global Settings',\n resolvePath: (_, __, appData) => path.join(appData, 'Code', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-insiders-extension-settings',\n host: 'cline',\n category: 'extension',\n label: 'Cline VS Code Insiders Extension Settings',\n resolvePath: (_, __, appData) => path.join(appData, 'Code - Insiders', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-legacy-settings',\n host: 'cline',\n category: 'cli',\n label: 'Cline Home Legacy Settings',\n resolvePath: (_, home) => path.join(home, '.cline', 'settings', 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-home-flat',\n host: 'cline',\n category: 'cli',\n label: 'Cline Home Flat Settings',\n resolvePath: (_, home) => path.join(home, 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-workspace-flat',\n host: 'cline',\n category: 'workspace',\n label: 'Cline Workspace Settings',\n resolvePath: (cwd) => path.join(cwd, 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-workspace-dot',\n host: 'cline',\n category: 'workspace',\n label: 'Cline Workspace .cline/mcp.json',\n resolvePath: (cwd) => path.join(cwd, '.cline', 'mcp.json'),\n },\n\n // --- Roo Code Extension ---\n {\n id: 'roo-code-extension-settings',\n host: 'cline',\n category: 'extension',\n label: 'Roo Code VS Code Extension Settings',\n resolvePath: (_, __, appData) => path.join(appData, 'Code', 'User', 'globalStorage', 'rooveterinaryinc.roo-cline', 'settings', 'cline_mcp_settings.json'),\n },\n\n // --- Cursor IDE / CLI ---\n {\n id: 'cursor-workspace',\n host: 'cursor',\n category: 'workspace',\n label: 'Cursor Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.cursor', 'mcp.json'),\n isPrimary: true,\n },\n {\n id: 'cursor-global',\n host: 'cursor',\n category: 'desktop',\n label: 'Cursor Global User Config',\n resolvePath: (_, home) => path.join(home, '.cursor', 'mcp.json'),\n },\n\n // --- Claude Code CLI & Claude Desktop ---\n {\n id: 'claude-workspace-dot',\n host: 'claude',\n category: 'workspace',\n label: 'Claude Code Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.claude', 'mcp.json'),\n isPrimary: true,\n },\n {\n id: 'claude-workspace-flat',\n host: 'claude',\n category: 'workspace',\n label: 'Claude Workspace claude.json',\n resolvePath: (cwd) => path.join(cwd, 'claude.json'),\n },\n {\n id: 'claude-global-dot',\n host: 'claude',\n category: 'cli',\n label: 'Claude Code Global Config',\n resolvePath: (_, home) => path.join(home, '.claude', 'mcp.json'),\n },\n {\n id: 'claude-global-flat',\n host: 'claude',\n category: 'cli',\n label: 'Claude Code Global claude.json',\n resolvePath: (_, home) => path.join(home, 'claude.json'),\n },\n {\n id: 'claude-desktop-global',\n host: 'claude',\n category: 'desktop',\n label: 'Claude Desktop Global Config',\n resolvePath: (_, __, appData) => path.join(appData, 'Claude', 'claude_desktop_config.json'),\n },\n\n // --- Windsurf IDE ---\n {\n id: 'windsurf-global',\n host: 'windsurf',\n category: 'desktop',\n label: 'Windsurf Global Config',\n resolvePath: (_, home) => path.join(home, '.codeium', 'windsurf', 'mcp_config.json'),\n isPrimary: true,\n },\n {\n id: 'windsurf-appdata',\n host: 'windsurf',\n category: 'desktop',\n label: 'Windsurf AppData Config',\n resolvePath: (_, __, appData) => path.join(appData, 'Windsurf', 'mcp_config.json'),\n },\n\n // --- OpenCode & Codex ---\n {\n id: 'opencode-workspace',\n host: 'opencode',\n category: 'workspace',\n label: 'OpenCode Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.opencode', 'mcp.json'),\n isPrimary: true,\n },\n {\n id: 'opencode-global',\n host: 'opencode',\n category: 'cli',\n label: 'OpenCode Global Config',\n resolvePath: (_, home) => path.join(home, '.config', 'opencode', 'mcp.json'),\n },\n ];\n\n /**\n * Discovers all MCP configuration files across the filesystem, inspecting existence and parsing server definitions.\n */\n public static async discoverAll(cwd: string = process.cwd()): Promise<DiscoveredMcpConfig[]> {\n const homeDir = os.homedir();\n const appData = process.env.APPDATA || (process.platform === 'darwin' ? path.join(homeDir, 'Library', 'Application Support') : path.join(homeDir, '.config'));\n\n const results: DiscoveredMcpConfig[] = [];\n const seenPaths = new Set<string>();\n\n for (const desc of McpLocationRegistry.LOCATIONS) {\n const resolved = path.normalize(desc.resolvePath(cwd, homeDir, appData));\n const key = resolved.toLowerCase();\n if (seenPaths.has(key)) continue;\n seenPaths.add(key);\n\n const exists = await fs.pathExists(resolved);\n let serverCount = 0;\n let servers: Record<string, any> | undefined;\n\n if (exists) {\n try {\n const config = await fs.readJson(resolved);\n const rawServers = config?.mcpServers || config?.servers || config;\n if (rawServers && typeof rawServers === 'object') {\n servers = rawServers;\n serverCount = Object.keys(rawServers).length;\n }\n } catch {}\n }\n\n results.push({\n id: desc.id,\n host: desc.host,\n category: desc.category,\n label: desc.label,\n path: resolved,\n exists,\n serverCount,\n servers,\n isPrimary: desc.isPrimary,\n });\n }\n\n return results;\n }\n\n /**\n * Returns discovered locations filtered for specific host(s).\n */\n public static async discoverForHosts(hosts: (AgentHost | string)[], cwd: string = process.cwd()): Promise<DiscoveredMcpConfig[]> {\n const all = await McpLocationRegistry.discoverAll(cwd);\n const hostSet = new Set(hosts.map(h => (h === 'agents' ? 'gemini' : h)));\n return all.filter(loc => hostSet.has(loc.host));\n }\n\n /**\n * Resolves the primary target write path for a given host runtime.\n */\n public static getPrimaryWritePath(host: AgentHost | string, cwd: string = process.cwd()): string {\n const homeDir = os.homedir();\n const appData = process.env.APPDATA || (process.platform === 'darwin' ? path.join(homeDir, 'Library', 'Application Support') : path.join(homeDir, '.config'));\n\n const targetHost = host === 'agents' ? 'gemini' : host;\n const desc = McpLocationRegistry.LOCATIONS.find(l => l.host === targetHost && l.isPrimary);\n if (desc) {\n return path.normalize(desc.resolvePath(cwd, homeDir, appData));\n }\n return path.normalize(path.join(cwd, '.cursor', 'mcp.json'));\n }\n}\n"],"mappings":";;;AAAA,SAAS,WAAW;AACpB,OAAO,QAAQ;AACf,SAAS,OAAO,OAAO,SAAS,MAAM,KAAK,QAAQ,aAAa,SAAS,YAAY;AACrF,OAAOA,UAAQ;AACf,OAAOC,YAAU;;;ACJjB,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAG9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,KAAK,QAAQ,UAAU;AAElC,IAAM,mBAAN,MAAM,kBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,OAAwB,iBAAiB,CAAC,WAAW;AAAA,EAE7C;AAAA,EACA,kBAA0C;AAAA;AAAA,EAE1C,iBAAiB,oBAAI,IAAsB;AAAA,EAEnD,YAAY,mBAA4B;AACtC,QAAI,mBAAmB;AACrB,WAAK,cAAc,KAAK,QAAQ,iBAAiB;AAAA,IACnD,OAAO;AAEL,YAAM,iBAAiB;A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,CAAC,EAAE,EAAE,KAAK,IAAI,IAAI,QAAQ;AAAA,IACrI,+BAA+B,OAAO,YAAY,MAAM,OAAO,UAAU,KAAK,OAAO,OAAO,MAAM,EAAE,KAAK,IAAI,kBAAkB,OAAO,gBAAgB,QAAQ,IAAI,iBAAiB,OAAO,yBAAyB,QAAQ,IAAI,uBAAuB,OAAO,mBAAmB,QAAQ,IAAI;AAAA,IAC5R,qBAAqB,eAAe,KAAK,IAAI,CAAC;AAAA,IAC9C,SAAS,KAAK,KAAK,MAAM;AAAA,IACzB,GAAG,KAAK,KAAK,IAAI,CAAC,KAAK,UAAU,MAAM,KAAK,KAAK,IAAI,QAAQ,UAAU,KAAK,CAAC,EAAE;AAAA,EACjF,EAAE,KAAK,IAAI;AACb;AAEA,IAAI,KAAK;AACT,IAAI,QAAQ,OAAO;AAEnB,IAAI,MAAM;","names":["fs","path","path","fs","path","path","path","yaml","path","fs","content","yaml","path","fs","FRONTMATTER_REGEX","yaml","text","path","fs","YAML","registry","fs","path","YAML","agentsTarget","projections","relPath","path","crypto","fs","registry","fs","crypto","path","def","path","os","fs","registry","os","path","fs","path","crypto","fs","registry","scanner","installer","fs","crypto","path","path","fs","crypto","YAML","path","fs","path","fs","path","fs","fs","crypto","path","YAML","path","os","crypto","fs","crypto","path","os","fs","path","os","fs","path","os","fs","path","os","fs","path","os","fs","os","path","fs","fs","path","text","s","targetBundleDef","lines","action"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/core/registry.ts","../src/core/installer.ts","../src/core/adapter.ts","../src/core/hosts.ts","../src/core/projector.ts","../src/core/cline-projector.ts","../src/core/claude-projector.ts","../src/core/guard.ts","../src/core/residue-patterns.ts","../src/core/overlays.ts","../src/core/state-dir.ts","../src/core/session-guard.ts","../src/core/permission-preset.ts","../src/core/types.ts","../src/core/uninstaller.ts","../src/core/inventory.ts","../src/core/updater.ts","../src/core/doctor.ts","../src/core/claude-capabilities.ts","../src/core/cline-capabilities.ts","../src/core/mcp-locations.ts","../src/core/cline-launcher.ts","../src/core/claude-launcher.ts","../src/core/antigravity-launcher.ts","../src/core/antigravity-capabilities.ts","../src/core/prerequisites.ts"],"sourcesContent":["import { cac } from 'cac';\nimport pc from 'picocolors';\nimport { intro, outro, spinner, note, log, select, multiselect, confirm, text } from '@clack/prompts';\nimport fs from 'fs-extra';\nimport path from 'node:path';\nimport { RegistryResolver } from './core/registry.js';\nimport { InstallEngine } from './core/installer.js';\nimport { resolveStateDir } from './core/state-dir.js';\nimport { UninstallEngine } from './core/uninstaller.js';\nimport { InventoryScanner } from './core/inventory.js';\nimport { UpdateEngine } from './core/updater.js';\nimport { DoctorEngine } from './core/doctor.js';\nimport type { HealthReport } from './core/doctor.js';\nimport { ClineLauncher } from './core/cline-launcher.js';\nimport { ClineCapabilityProbe } from './core/cline-capabilities.js';\nimport { ClaudeLauncher } from './core/claude-launcher.js';\nimport type { ClaudeActivationPlan } from './core/claude-launcher.js';\nimport { ClaudeCapabilityProbe } from './core/claude-capabilities.js';\nimport { AntigravityLauncher } from './core/antigravity-launcher.js';\nimport type { AntigravityActivationPlan } from './core/antigravity-launcher.js';\nimport { AntigravityCapabilityProbe } from './core/antigravity-capabilities.js';\nimport { PrerequisiteChecker } from './core/prerequisites.js';\nimport { McpLocationRegistry } from './core/mcp-locations.js';\nimport { isKnownHost, HOST_REGISTRY, KNOWN_HOST_IDS, planInstallTargets, hostAvailabilityNotice, SUPPORTED_HOST_IDS, splitHostList } from './core/hosts.js';\nimport type { InstallScope, InstallMethod, AgentHost, BundleDefinition, BundleTier, InstalledPackageRecord, ProjectionInfo, ExecutionMode, ClaudeCapabilityReport } from './core/types.js';\n\nconst cli = cac('agents-united');\nconst registry = new RegistryResolver();\nconst installer = new InstallEngine(registry);\nconst uninstaller = new UninstallEngine(registry);\nconst scanner = new InventoryScanner(registry);\nconst updater = new UpdateEngine(registry, scanner, installer);\n\nexport function detectWorkspaceHosts(cwd: string = process.cwd()): AgentHost[] {\n const detected: AgentHost[] = [];\n for (const host of Object.values(HOST_REGISTRY)) {\n const found = host.detectionMarkers.some(marker => fs.pathExistsSync(path.join(cwd, marker)));\n if (found) detected.push(host.id as AgentHost);\n }\n return detected;\n}\n\nexport function getTerminalContentWidth(): number {\n const cols = typeof process !== 'undefined' && process.stdout?.columns ? process.stdout.columns : 80;\n return Math.max(40, Math.min(cols - 8, 68));\n}\n\nexport function wrapText(text: string, maxLen?: number, indent: string = ''): string[] {\n if (!text) return [];\n const limit = maxLen ?? getTerminalContentWidth();\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let current = indent;\n\n for (const word of words) {\n if (!word) continue;\n if (current.length > indent.length && (current.length + 1 + word.length > limit)) {\n lines.push(current);\n current = indent + word;\n } else {\n current = current.length === indent.length ? current + word : current + ' ' + word;\n }\n }\n\n if (current.trim().length > 0) {\n lines.push(current);\n }\n\n return lines;\n}\n\nexport function formatWrappedList(\n items: string[],\n indent: string = ' ',\n maxLineLen?: number\n): string[] {\n if (!items || items.length === 0) return [];\n\n const limit = maxLineLen ?? getTerminalContentWidth();\n const lines: string[] = [];\n let currentLine = indent;\n\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const isLast = i === items.length - 1;\n const token = isLast ? item : `${item}, `;\n\n if (currentLine.length > indent.length && (currentLine.length + token.length > limit)) {\n lines.push(currentLine.trimEnd());\n currentLine = indent + token;\n } else {\n currentLine += token;\n }\n }\n\n if (currentLine.trim().length > 0) {\n lines.push(currentLine.trimEnd());\n }\n\n return lines;\n}\n\nexport interface InstallationSummaryOptions {\n bundleName: string;\n scope: string;\n method: string;\n hosts: string[];\n agents: string[];\n skills: string[];\n targetDirs: string[];\n projections?: ProjectionInfo[];\n}\n\nexport function formatInstallationSummary(options: InstallationSummaryOptions): string {\n const { bundleName, scope, method, hosts, agents, skills, targetDirs, projections } = options;\n const limit = getTerminalContentWidth();\n\n const lines: string[] = [\n `Bundle: ${bundleName}`,\n `Scope: ${scope}`,\n `Method: ${method}`,\n `Targets: ${hosts.join(', ')}`,\n ];\n\n // Agents\n if (agents.length === 0) {\n lines.push(`Agents: None`);\n } else {\n const inlineAgents = `Agents (${agents.length}): ${agents.join(', ')}`;\n if (inlineAgents.length <= limit) {\n lines.push(inlineAgents);\n } else {\n lines.push(`Agents (${agents.length}):`);\n lines.push(...formatWrappedList(agents, ' ', limit));\n }\n }\n\n // Skills\n if (skills.length === 0) {\n lines.push(`Skills: None`);\n } else {\n const inlineSkills = `Skills (${skills.length}): ${skills.join(', ')}`;\n if (inlineSkills.length <= limit) {\n lines.push(inlineSkills);\n } else {\n lines.push(`Skills (${skills.length}):`);\n lines.push(...formatWrappedList(skills, ' ', limit));\n }\n }\n\n // Target Directories\n if (targetDirs.length === 0) {\n lines.push('Target Directories: None');\n } else if (targetDirs.length === 1) {\n const singleDirLine = `Target Directories: ${targetDirs[0]}`;\n if (singleDirLine.length <= limit) {\n lines.push(singleDirLine);\n } else {\n lines.push('Target Directories:');\n lines.push(` ${targetDirs[0]}`);\n }\n } else {\n lines.push(`Target Directories (${targetDirs.length}):`);\n for (const dir of targetDirs) {\n lines.push(` ${dir}`);\n }\n }\n\n // Projections summary\n if (projections && projections.length > 0) {\n const byHost = new Map<string, number>();\n for (const p of projections) {\n byHost.set(p.host, (byHost.get(p.host) ?? 0) + 1);\n }\n const hostSummaries: string[] = [];\n for (const [host, count] of byHost) {\n const label = HOST_REGISTRY[host]?.label ?? host;\n hostSummaries.push(`${label} (${count} file${count > 1 ? 's' : ''})`);\n }\n lines.push(`Projections: ${hostSummaries.join(', ')}`);\n }\n\n return lines.join('\\n');\n}\n\nexport function renderProjections(projections: ProjectionInfo[]): string {\n const byHost = new Map<string, ProjectionInfo[]>();\n for (const p of projections) {\n const list = byHost.get(p.host) ?? [];\n list.push(p);\n byHost.set(p.host, list);\n }\n const lines: string[] = [];\n for (const [host, items] of byHost) {\n lines.push(`${HOST_REGISTRY[host]?.label ?? host} — ${items.length} file${items.length > 1 ? 's' : ''}`);\n for (const p of items) {\n lines.push(` → ${p.path}`);\n for (const w of p.warnings) {\n const wrapped = wrapText(`⚠ ${w}`, 68, ' ');\n for (const wl of wrapped) {\n lines.push(pc.yellow(wl));\n }\n }\n }\n }\n return lines.join('\\n');\n}\n\nconst BUNDLE_DISPLAY_NAMES: Record<string, { title: string; summary: string }> = {\n 'software-engineering': {\n title: 'Software Engineering Team',\n summary: 'Autonomous dev lead, backend/frontend architects, TDD & git guardrails',\n },\n 'mobile-development': {\n title: 'Mobile Development Team',\n summary: 'iOS (SwiftUI), Android (Compose) & Cross-Platform (React Native/Flutter)',\n },\n 'frontend-engineering': {\n title: 'Frontend Architecture Team',\n summary: 'Next.js/React App Router, Server Components & Web Vitals',\n },\n 'backend-distributed-systems': {\n title: 'Backend & Distributed Systems Team',\n summary: 'Microservices, Kafka/RabbitMQ event streams & DB migrations',\n },\n 'qa-automation': {\n title: 'QA & Test Automation Team',\n summary: 'Playwright E2E automation, test matrix planning & chaos engineering',\n },\n 'devops-engineering': {\n title: 'DevOps & Delivery Pipeline Team',\n summary: 'CI/CD automation, Docker/K8s, Infrastructure as Code & release engineering',\n },\n 'ai-ml-engineering': {\n title: 'AI & Machine Learning Engineering Team',\n summary: 'Serverless GPU deployment, LLM fine-tuning, RAG vector pipelines & AI safety guardrails',\n },\n 'sysops-sre': {\n title: 'SysOps & Site Reliability Team',\n summary: '99.999% uptime, Prometheus telemetry, incident triage & disaster recovery',\n },\n 'system-architecture': {\n title: 'System Architecture Team',\n summary: 'High-level distributed systems, API schemas, and ADR planning',\n },\n 'product-design': {\n title: 'Product Design Team',\n summary: 'UI/UX designers, design systems architect, and prototyping',\n },\n 'growth-marketing': {\n title: 'Growth & Marketing Team',\n summary: 'Growth strategists, creative visual designer, content pipeline & conversion optimization',\n },\n 'seo-content-marketing': {\n title: 'SEO & Content Marketing Team',\n summary: 'Programmatic SEO, technical SEO audits, content pipeline automation & schema markup',\n },\n 'performance-paid-acquisition': {\n title: 'Performance & Paid Acquisition Team',\n summary: 'Multi-channel PPC (Google/Meta/LinkedIn), ROAS/CAC attribution & ad copy testing',\n },\n 'product-led-growth': {\n title: 'Product-Led Growth Team',\n summary: 'Onboarding CRO, signup funnel optimization, viral referral loops & paywalls',\n },\n 'lifecycle-email-marketing': {\n title: 'Lifecycle & Email Marketing Team',\n summary: 'Automated email drip sequences, churn prevention playbooks & newsletter workflows',\n },\n 'security-operations': {\n title: 'Security Operations Team',\n summary: 'AppSec engineer, threat modeling, and vulnerability audits',\n },\n 'deep-research': {\n title: 'Deep Research Team',\n summary: 'Technical research lead, literature review, and Socratic mentor',\n },\n 'business-strategy': {\n title: 'Business Strategy Team',\n summary: 'Market analysts, monetization experts, and executive spec panels',\n },\n 'digital-agency': {\n title: 'Digital Agency',\n summary: 'Full-service digital product agency with web dev, mobile, design, SEO, and growth marketing',\n },\n 'universal-orchestration': {\n title: 'Universal Orchestration',\n summary: 'Prime Orchestrator front door: routes to the correct department Essentials bundle and hands off',\n },\n 'universal-skills': {\n title: 'Universal Meta-Skills',\n summary: 'Domain-agnostic Socratic grilling, spec generation, handoff, and domain modeling',\n },\n 'design-systems-ops': {\n title: 'Design Systems & Ops Team',\n summary: 'Token governance, component libraries, design handoff & version control workflows',\n },\n 'design-research-testing': {\n title: 'Design Research & Testing Team',\n summary: 'Usability testing, user journey mapping, interactive prototypes & AI prototype refactoring',\n },\n 'full': {\n title: 'All-in-One Autonomous Department',\n summary: 'Complete suite with all 7 team leads, 38 agents, and all 160 modular skills & workflows',\n },\n};\n\ncli\n .command('add [identifier]', 'Add a bundle, agent, skill, or workflow to project or global configuration')\n .option('-g, --global', 'Install globally into home directory (~/.agents/)')\n .option('-s, --symlink', 'Create symbolic links to central registry cache (default / recommended)')\n .option('--copy', 'Create independent standalone copies of asset files')\n .option('-t, --target <hosts>', 'Which assistants to set up (agents = main library; claude, cursor, cline, opencode, codex get translated copies)', { default: 'agents' })\n .option('--fanout <hosts>', 'Also make translated copies for these assistants: claude, cline. Under Development hosts (cursor, opencode, codex) are refused')\n .option('--plugin', 'Claude lane only: also emit the distribution-only plugin package (.agents/plugins/<bundle>/.claude-plugin/plugin.json + agents/) for `claude --plugin-dir`. Adds nothing when --fanout claude is absent; never the behavioural source. Sticky: the opt-in is recorded in the lockfile, so `agents update` keeps it. Use --no-plugin to turn it back off.')\n .option('--canonical-store', 'Keep the .agents/ main library even for a Claude-only install (by default a Claude-only install is store-less: its state lives in the hidden .claude/.agents-united/ folder, ADR 0022)')\n .option('--session-guard [where]', 'Claude lane only: also guard PLAIN Claude sessions (no --agent) by adding one managed hook entry that blocks `git push --force`, `.env` writes and `vercel --prod`. where = project (.claude/settings.json, default) | local (.claude/settings.local.json) | user (~/.claude/settings.json). Everything else in the file is kept; invalid JSON is never rewritten. Sticky; --no-session-guard turns it off.')\n .option('--permission-preset [tier]', 'Opt-in only, never implied by -y: pre-approve a small, fixed set of commands in .claude/settings.local.json (never the shared/committed settings.json) so background specialists are not refused command approval outside auto mode. tier = verify (default: git status/diff/log, npx tsc/vitest/eslint) | build (adds npm install/run/test — executes project code, request explicitly). Never includes git commit/push, rm, curl/wget, or any deploy/publish command. Workspace-scoped only (ignored for --global). Sticky; --no-permission-preset turns it off. Claude only today; other hosts report \"not supported yet\".')\n .option('--mode <mode>', 'Execution mode for organization bundles (operational | brainstorming)', { default: 'operational' })\n .option('--allow-missing-prereqs', 'Proceed with installation even if some prerequisites are missing')\n .option('--allow-under-construction', 'Allow installation of bundles marked as under construction')\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('-f, --force', 'Force overwrite user modified files')\n .option('--start', 'Start the installed team in Cline immediately after setup')\n .option('--dry-run', 'Simulate installation without writing files')\n .action(async (targetIdentifier?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — AI Agent Ecosystem'));\n\n let identifier = targetIdentifier;\n let scope: InstallScope = options.global ? 'global' : 'project';\n let method: InstallMethod = options.copy ? 'copy' : 'symlink';\n let hosts: AgentHost[] = options.target\n ? (Array.isArray(options.target) ? options.target : splitHostList(String(options.target))).map(\n (h: string) => h.trim().toLowerCase()\n )\n : ['agents'];\n // Warn + drop unknown host ids instead of silently casting them to a type.\n const unknownHosts = hosts.filter(h => !isKnownHost(h));\n if (unknownHosts.length > 0) {\n note(`Ignoring unknown host id(s): ${unknownHosts.join(', ')}`, 'Invalid target');\n hosts = hosts.filter(isKnownHost);\n if (hosts.length === 0) hosts = ['agents'];\n }\n\n // Turn the target list into a plan: the main library (.agents/) plus translated\n // copies for each assistant that can't read it directly. Never installs\n // untranslated Antigravity frontmatter into another assistant's folder.\n // Plan 023 B (ADR 0022) — remember what the operator actually selected: the store-less\n // decision is made once the final fan-out is known (right before install).\n let selectedHosts: string[] = [...hosts];\n const flagPlan = planInstallTargets(hosts);\n hosts = flagPlan.hosts;\n if (flagPlan.addedCanonicalStore) {\n note(\n 'Added .agents/ — the main library your assistants share.\\n' +\n 'Each assistant you picked gets its own translated copy. Edit only .agents/.',\n 'Main library'\n );\n }\n\n // Parse --fanout like hosts above but validated against HOST_REGISTRY; only\n // projection-capable host ids are honored. Warn + drop invalid ids, never a silent cast.\n let fanout: string[] = flagPlan.fanout;\n if (options.fanout) {\n const rawFanout: string[] = Array.isArray(options.fanout) ? options.fanout : splitHostList(String(options.fanout));\n const parsedFanout: string[] = rawFanout.map((h: string) => h.trim().toLowerCase());\n const invalidFanout: string[] = parsedFanout.filter(h => !isKnownHost(h) || !HOST_REGISTRY[h].projectionCapable);\n if (invalidFanout.length > 0) {\n note(\n `Ignoring invalid fanout host id(s): ${invalidFanout.join(', ')}. Valid ids: ${KNOWN_HOST_IDS.filter(h => HOST_REGISTRY[h].projectionCapable).join(', ')}`,\n 'Invalid fanout'\n );\n }\n fanout = Array.from(new Set([...fanout, ...parsedFanout.filter(h => isKnownHost(h) && HOST_REGISTRY[h].projectionCapable)]));\n const underDevFanout = Array.from(new Set(parsedFanout.filter((h) => isKnownHost(h) && HOST_REGISTRY[h].status === 'under-development')));\n if (underDevFanout.length > 0) {\n note(\n `Refusing --fanout host(s): ${underDevFanout.join(', ')} — they are listed as Under Development and unavailable. Supported --fanout ids: ${SUPPORTED_HOST_IDS.filter((h) => HOST_REGISTRY[h].projectionCapable).join(', ')}. Drop ${underDevFanout.join(', ')} from --fanout and run again.`,\n 'Host unavailable'\n );\n process.exit(1);\n }\n }\n\n // Interactive Wizard when running interactively without flags\n const isInteractive = process.stdout.isTTY && !options.yes;\n\n if (isInteractive && !options.global && !options.copy && !options.symlink && options.target === 'agents') {\n const detectedHosts = detectWorkspaceHosts();\n if (detectedHosts.length > 0) {\n note(\n detectedHosts.map(h => ` ✔ Detected .${HOST_REGISTRY[h].projectDir === '.' ? '' : '/'}${HOST_REGISTRY[h].projectDir === '.' ? 'AGENTS.md' : HOST_REGISTRY[h].projectDir}`).join('\\n'),\n 'Workspace Environment Discovery'\n );\n }\n\n // Step 1: Which AI tools should we configure agent teams & personas for?\n // The master library (.agents/) is always included when another tool is\n // chosen — it is the single source every translated copy is generated from.\n // Availability: only supported hosts are selectable here; the 🚧 Under\n // Development and 🗓 Planned hosts are listed in the availability note.\n note(hostAvailabilityNotice(), 'Host availability');\n const hostSelection = await multiselect({\n message: '1. Which AI tools should we configure agent teams & personas for?',\n options: [\n {\n value: 'agents',\n label: HOST_REGISTRY.agents.label,\n hint: detectedHosts.includes('agents') ? 'found in this project' : 'the master library where all skills & agents live — always included',\n },\n {\n value: 'claude',\n label: HOST_REGISTRY.claude.label,\n hint: detectedHosts.includes('claude') ? 'found in this project' : 'orchestrator & subagent personas for Claude Code',\n },\n {\n value: 'cline',\n label: HOST_REGISTRY.cline.label,\n hint: detectedHosts.includes('cline') ? 'found in this project' : 'configured agents, skills, rules, workflows & team manifests for Cline',\n },\n {\n value: 'gemini',\n label: HOST_REGISTRY.gemini.label,\n hint: detectedHosts.includes('gemini') ? 'found in this project' : 'older Antigravity 1.0 / Gemini folder',\n },\n ],\n initialValues: detectedHosts.length > 0 ? detectedHosts.filter((h) => HOST_REGISTRY[h]?.status === 'supported') : ['agents'],\n required: true,\n });\n\n if (Array.isArray(hostSelection) && hostSelection.length > 0) {\n const wizardPlan = planInstallTargets(hostSelection as string[]);\n selectedHosts = [...(hostSelection as string[])];\n hosts = wizardPlan.hosts;\n // Merge with any explicitly-passed --fanout rather than discarding it.\n fanout = Array.from(new Set([...fanout, ...wizardPlan.fanout]));\n if (wizardPlan.addedCanonicalStore) {\n note(\n 'Added .agents/ — the master repository library your tools share.\\n' +\n 'Each tool you selected gets its own orchestrators and subagents. Edit only .agents/.',\n 'Master library'\n );\n }\n }\n\n // Step 2: Scope Selection with Clear Guidance\n const scopeSelection = await select({\n message: '2. Select Installation Scope:',\n options: [\n {\n value: 'project',\n label: 'Project Scope (Recommended)',\n hint: 'Workspace directory; tracked in Git & shared with team via lockfile',\n },\n {\n value: 'global',\n label: 'Global Scope (-g / --global)',\n hint: 'User home directory (~/.agents/); available across all workspaces on machine',\n },\n ],\n });\n\n if (typeof scopeSelection === 'string') {\n scope = scopeSelection as InstallScope;\n }\n\n // Step 3: Installation Method\n const methodSelection = await select({\n message: '3. Select Installation Method:',\n options: [\n {\n value: 'symlink',\n label: 'Symlink Mode (Recommended)',\n hint: 'Single source of truth; package updates reflect instantly',\n },\n {\n value: 'copy',\n label: 'Copy Mode',\n hint: 'Independent standalone files; supports offline isolated modifications',\n },\n ],\n });\n\n if (typeof methodSelection === 'string') {\n method = methodSelection as InstallMethod;\n }\n }\n\n // Plan 023 A (owner D2) — plain-session guard consent: an explicit flag wins; otherwise an\n // interactive Claude-lane install asks once (default yes) unless a decision is already recorded.\n // Non-interactive runs never write the user's settings file without the explicit flag.\n let sessionGuard: 'project' | 'local' | 'user' | false | undefined;\n if (options.sessionGuard === false) {\n sessionGuard = false;\n } else if (options.sessionGuard === true || options.sessionGuard === '') {\n sessionGuard = 'project';\n } else if (typeof options.sessionGuard === 'string') {\n const where = options.sessionGuard.trim().toLowerCase();\n if (where !== 'project' && where !== 'local' && where !== 'user') {\n note(`--session-guard accepts project, local or user (got \"${options.sessionGuard}\").`, 'Invalid option');\n process.exit(1);\n }\n sessionGuard = where;\n } else if (isInteractive && fanout.includes('claude')) {\n const recordedLockfile = path.join(resolveStateDir(scope), 'agents-united.json');\n const recorded = await fs.readJson(recordedLockfile).catch(() => null);\n if (!recorded?.sessionGuard) {\n const answer = await confirm({\n message: scope === 'global'\n ? 'Also guard plain Claude sessions on this machine? (blocks git push --force, .env writes and vercel --prod in ~/.claude/settings.json)'\n : 'Also guard plain Claude sessions in this repo? (blocks git push --force, .env writes and vercel --prod via .claude/settings.json)',\n initialValue: true,\n });\n if (typeof answer === 'boolean') sessionGuard = answer ? (scope === 'global' ? 'user' : 'project') : false;\n }\n }\n\n // Plan 024 S4 (owner E2/E4) — opt-in command-permission preset: flag only, never a prompt and\n // never implied by -y (a pre-approved command is attack surface, so consent must be explicit).\n let permissionPreset: 'verify' | 'build' | false | undefined;\n if (options.permissionPreset === false) {\n permissionPreset = false;\n } else if (options.permissionPreset === true || options.permissionPreset === '') {\n permissionPreset = 'verify';\n } else if (typeof options.permissionPreset === 'string') {\n const tier = options.permissionPreset.trim().toLowerCase();\n if (tier !== 'verify' && tier !== 'build') {\n note(`--permission-preset accepts verify or build (got \"${options.permissionPreset}\").`, 'Invalid option');\n process.exit(1);\n }\n permissionPreset = tier;\n }\n\n // Step 4: Two-Stage Hierarchical Department & Bundle Selection\n if (!identifier) {\n const bundles = await registry.listBundles();\n\n const domainMeta: Record<string, { label: string; icon: string }> = {\n universal: { label: 'Universal Autonomous Department', icon: '🌐 ' },\n engineering: { label: 'Software Engineering & Delivery', icon: '🛠️ ' },\n architecture: { label: 'System Architecture & SRE', icon: '🏛️ ' },\n design: { label: 'Product Design & UI/UX', icon: '🎨 ' },\n marketing: { label: 'Growth & Marketing Operations', icon: '📈 ' },\n security: { label: 'Security Operations', icon: '🔒 ' },\n research: { label: 'Deep Technical Research', icon: '🔬 ' },\n business: { label: 'Business Strategy & Economics', icon: '💼 ' },\n organization: { label: 'Organization Bundles (Experimental / Cross-Functional)', icon: '🏢 ' },\n };\n\n let selectedBundle: string | undefined;\n\n while (!selectedBundle) {\n // Stage 4a: Department Domain Selection\n const domainOptions = Object.entries(domainMeta).map(([domainKey, meta]) => {\n const count = bundles.filter(b => (b.domain === domainKey || (domainKey === 'organization' && b.tier === 'organization'))).length;\n return {\n value: domainKey,\n label: `${meta.icon} ${meta.label}`,\n hint: domainKey === 'universal' ? 'meta-skills baseline + full suite' : domainKey === 'organization' ? 'cross-functional teams with prerequisites' : `${count} specialized team${count > 1 ? 's' : ''}`,\n };\n });\n\n domainOptions.push({\n value: '__search__',\n label: '🔍 Search by name / keyword...',\n hint: 'custom keyword search',\n });\n\n const selectedDomain = await select({\n message: '4. Select Department Domain / Category:',\n options: domainOptions,\n });\n\n if (typeof selectedDomain !== 'string') {\n outro(pc.yellow('Installation cancelled.'));\n return;\n }\n\n if (selectedDomain === '__search__') {\n const searchQuery = await text({\n message: 'Enter keyword to search:',\n placeholder: 'e.g. mobile, playwright, react, backend, agency',\n });\n\n if (typeof searchQuery !== 'string' || !searchQuery.trim()) {\n continue;\n }\n\n const searchResults = await registry.find(searchQuery.trim());\n const matchOptions: Array<{ value: string; label: string; hint?: string }> = [\n ...searchResults.bundles.map((b: BundleDefinition) => ({\n value: b.name,\n label: `[Bundle] ${BUNDLE_DISPLAY_NAMES[b.name]?.title || b.name} (${b.name})`,\n hint: b.description,\n })),\n ...searchResults.agents.map((a: string) => ({\n value: a.replace(/\\.md$/, ''),\n label: `[Agent] ${a}`,\n hint: 'autonomous agent',\n })),\n ...searchResults.skills.map((s: string) => ({\n value: s,\n label: `[Skill] ${s}`,\n hint: 'specialized skill',\n })),\n ...searchResults.workflows.map((w: string) => ({\n value: w.replace(/\\.md$/, ''),\n label: `[Workflow] ${w}`,\n hint: 'guided workflow',\n })),\n {\n value: '__back__',\n label: '🔙 Back to Department Selection',\n hint: '',\n },\n ];\n\n if (matchOptions.length === 1) {\n note(`No items found matching \"${searchQuery}\".`, 'Search Results');\n continue;\n }\n\n const chosenMatch = await select({\n message: `Search Results for \"${searchQuery}\":`,\n options: matchOptions,\n });\n\n if (typeof chosenMatch === 'string' && chosenMatch !== '__back__') {\n selectedBundle = chosenMatch;\n break;\n }\n continue;\n }\n\n const domainBundles = bundles.filter(b => b.domain === selectedDomain || (selectedDomain === 'organization' && b.tier === 'organization'));\n\n // Stage 4b: Sub-Team Selection inside Selected Domain\n const subTeamOptions: Array<{ value: string; label: string; hint?: string }> = [];\n\n // Option to install entire department if multiple bundles exist (exclude organization and universal)\n if (domainBundles.length > 1 && selectedDomain !== 'organization' && selectedDomain !== 'universal') {\n subTeamOptions.push({\n value: `__all_domain__:${selectedDomain}`,\n label: `🌟 Install Entire ${domainMeta[selectedDomain]?.label || selectedDomain} (${domainBundles.length} Bundles)`,\n hint: 'installs all sub-teams under this department',\n });\n }\n\n // Sort so Essentials/universal-skills are always at the top\n const sortedBundles = [...domainBundles].sort((a, b) => {\n if (a.name === 'universal-orchestration') return -1;\n if (b.name === 'universal-orchestration') return 1;\n if (a.name === 'universal-skills') return -1;\n if (b.name === 'universal-skills') return 1;\n if (!a.parentBundle && b.parentBundle) return -1;\n if (a.parentBundle && !b.parentBundle) return 1;\n return a.name.localeCompare(b.name);\n });\n\n sortedBundles.forEach((b, idx) => {\n const isLast = idx === sortedBundles.length - 1;\n const branch = sortedBundles.length > 1 ? (isLast ? '└── ' : '├── ') : '';\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n const isEssentials = !b.parentBundle && b.name !== 'full' && b.tier !== 'organization' && b.name !== 'universal-skills' && b.name !== 'universal-orchestration';\n const title = meta ? meta.title : b.name;\n\n let statusBadge = '';\n if (b.name === 'universal-skills') statusBadge = pc.green(' ⭐ [Recommended Baseline]');\n else if (b.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction]');\n else if (b.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n\n const labelText = isEssentials ? `Essentials: ${title}${statusBadge}` : `${title}${statusBadge}`;\n const summary = meta ? meta.summary : b.description;\n subTeamOptions.push({\n value: b.name,\n label: `${branch}📦 ${labelText} (${b.name})`,\n hint: summary,\n });\n });\n\n subTeamOptions.push({\n value: '__back__',\n label: '🔙 Back to Department Selection',\n hint: '',\n });\n\n const chosenSubTeam = await select({\n message: `Select Package / Team Bundle to install in ${domainMeta[selectedDomain]?.label || selectedDomain}:`,\n options: subTeamOptions,\n });\n\n if (typeof chosenSubTeam !== 'string') {\n outro(pc.yellow('Installation cancelled.'));\n return;\n }\n\n if (chosenSubTeam === '__back__') {\n continue;\n }\n\n if (chosenSubTeam.startsWith('__all_domain__:')) {\n const dName = chosenSubTeam.replace('__all_domain__:', '');\n const dTitle = domainMeta[dName]?.label || dName;\n const proceed = await confirm({\n message: `⚠️ You are about to install ALL ${domainBundles.length} sub-teams under \"${dTitle}\". Proceed?`,\n initialValue: true,\n });\n\n if (!proceed || typeof proceed !== 'boolean') {\n continue;\n }\n\n selectedBundle = `domain:${dName}`;\n break;\n }\n\n selectedBundle = chosenSubTeam;\n break;\n }\n\n identifier = selectedBundle;\n }\n\n if (!identifier) {\n outro(pc.yellow('No package specified.'));\n return;\n }\n\n const targetBundleDef = await registry.getBundle(identifier);\n\n // 1. Under Construction Gate Evaluation\n if (targetBundleDef && targetBundleDef.status === 'under-construction') {\n if (isInteractive) {\n note(\n `The bundle \"${targetBundleDef.name}\" is currently under active construction (status: under-construction).\\n` +\n `Its orchestrators, workflows, and specialized skills are being authored and are not ready for production use.\\n\\n` +\n `Planned Capabilities:\\n` +\n `• Lead Orchestrator with Firecrawl & GitHub MCP tool calling\\n` +\n `• Full-stack web, design & SEO delivery workflows\\n` +\n `• Dual Execution Modes (Operational / Brainstorming)`,\n '🚧 Under Construction Gate'\n );\n\n const underConstructionChoice = await select({\n message: pc.yellow(`\"${targetBundleDef.name}\" is currently under construction. How would you like to proceed?`),\n options: [\n {\n value: 'abort',\n label: '🛑 Abort installation (Recommended)',\n hint: 'return without modifying workspace files',\n },\n {\n value: 'allow',\n label: '⚠️ Install in-development draft anyway (--allow-under-construction)',\n hint: 'proceed with in-progress placeholder assets',\n },\n ],\n });\n\n if (underConstructionChoice === 'abort' || typeof underConstructionChoice !== 'string') {\n outro(pc.yellow(`Installation cancelled. \"${targetBundleDef.name}\" is under construction.`));\n return;\n }\n } else {\n // Headless / Non-interactive\n if (!options.allowUnderConstruction && !options.force) {\n outro(\n pc.red(\n `Error: Cannot install \"${targetBundleDef.name}\" — this bundle is currently under construction.\\n` +\n `To bypass this gate and install draft assets anyway, pass: --allow-under-construction or --force`\n )\n );\n process.exit(1);\n }\n }\n }\n\n // 2. Prerequisite Gate Evaluation & Informative Visibility\n let executionMode: ExecutionMode = (options.mode as ExecutionMode) || 'operational';\n\n if (targetBundleDef && (targetBundleDef.prerequisites || targetBundleDef.tier === 'organization')) {\n const checker = new PrerequisiteChecker();\n const prereqEval = await checker.evaluate(targetBundleDef, { cwd: process.cwd(), targetHosts: hosts });\n\n if (prereqEval.hasPrerequisites) {\n const checkLines: string[] = [];\n for (const item of prereqEval.items) {\n const typeLabel = item.type === 'mcp' ? 'MCP' : item.type === 'env' ? 'Env' : 'Pkg';\n let icon = pc.green('✓');\n let statusText = pc.green('Detected');\n if (!item.satisfied) {\n if (item.status === 'partial') {\n icon = pc.yellow('~');\n statusText = pc.yellow('Partial');\n } else {\n icon = pc.red('✗');\n statusText = pc.red('Missing');\n }\n }\n const details = pc.dim(`(${item.details || ''})`);\n checkLines.push(` ${icon} [${typeLabel}] ${pc.bold(item.name)}: ${statusText} ${details}`);\n }\n\n note(\n checkLines.join('\\n'),\n `Prerequisite Evaluation: ${targetBundleDef.name} (${targetBundleDef.tier === 'organization' ? 'Organization Bundle' : 'Prerequisites Required'})`\n );\n\n if (prereqEval.allSatisfied) {\n executionMode = (options.mode as ExecutionMode) || 'operational';\n note(pc.green('All prerequisites are satisfied! Running in Fully Operational Mode.'), 'Prerequisites Ready');\n } else {\n executionMode = (options.mode as ExecutionMode) || 'limited-operational';\n note(\n pc.cyan(\n '⚡ Adaptive Tooling: Limited Operational / Brainstorming Mode ready.\\n' +\n 'Your Lead Orchestrator will automatically detect active tools and guide in-session configuration seamlessly.'\n ),\n 'Operational Envelope'\n );\n }\n }\n }\n\n // Plan 023 B (ADR 0022, D4) — Claude alone is store-less: no `.agents/`, the machine state\n // lives in the hidden `.claude/.agents-united/` sidecar. `--canonical-store`, the plugin lane or\n // any other assistant keeps the main library.\n const storeShape = planInstallTargets([...selectedHosts, ...fanout], {\n canonicalStore: options.canonicalStore === true,\n pluginLane: options.plugin === true,\n }).storeShape;\n if (storeShape === 'sidecar' && !options.dryRun) {\n note(\n 'Claude only: no .agents/ main library is created. The install state is kept in the hidden\\n' +\n '.claude/.agents-united/ folder (machine-owned — do not edit). Add --canonical-store to keep .agents/.',\n 'Claude-only install'\n );\n }\n\n const s = spinner();\n s.start(`Resolving \"${identifier}\"...`);\n\n try {\n const result = await installer.install(identifier, {\n scope,\n method,\n hosts,\n fanout,\n // Plan 016 decision 13 — opt-in Claude plugin lane (distribution-only; ignored unless the\n // claude lane runs). `--plugin` opts in, `--no-plugin` opts out explicitly, and an omitted\n // flag inherits the recorded choice so `agents update` cannot prune the package.\n pluginLane: typeof options.plugin === 'boolean' ? options.plugin : undefined,\n sessionGuard,\n permissionPreset,\n storeShape,\n mode: executionMode,\n allowMissingPrereqs: options.allowMissingPrereqs,\n yes: options.yes,\n force: options.force,\n dryRun: options.dryRun,\n });\n\n s.stop(`Resolved assets for \"${identifier}\"`);\n\n if (options.dryRun) {\n outro(pc.yellow(`[DRY RUN] Would install ${result.installed.agents.length} agents, ${result.installed.skills.length} skills to ${result.targetDirs.join(', ')}`));\n if (result.projections.length > 0) {\n note(renderProjections(result.projections), 'Projection Plan (dry run)');\n }\n if (options.start && result.projections.some(p => p.host === 'cline')) {\n const bundleName = result.installed.targetBundle || identifier;\n note(`Would start Cline team for bundle \"${bundleName}\".`, 'Start in Cline (dry run)');\n }\n return;\n }\n\n note(\n formatInstallationSummary({\n bundleName: result.installed.targetBundle || 'Single Item',\n scope,\n method: result.method,\n hosts,\n agents: result.installed.agents,\n skills: result.installed.skills,\n targetDirs: result.targetDirs,\n projections: result.projections,\n }),\n 'Installation Success'\n );\n\n if (result.projections.length > 0) {\n note(renderProjections(result.projections), 'Installed Projections');\n }\n\n const hasClineProjection = result.projections.some(p => p.host === 'cline');\n\n if (hasClineProjection && !options.dryRun) {\n note(\n pc.green(\n `Already active: any Cline session in this workspace now sees this bundle's\\n` +\n `skills, subagent_* agent tools, rules & workflow commands (ADR 0013 native discovery).`\n ),\n 'Native Activation'\n );\n }\n\n if (options.start && !hasClineProjection) {\n throw new Error('--start requires Cline projection. Add -t cline or --fanout cline.');\n }\n\n if (hasClineProjection) {\n const bundleName = result.installed.targetBundle || identifier;\n if (options.start) {\n if (options.dryRun) {\n note(`Would start Cline team for bundle \"${bundleName}\".`, 'Start in Cline (dry run)');\n } else {\n note(`Launching Cline team for \"${bundleName}\"...`, 'Starting Cline');\n const launcher = new ClineLauncher();\n const probe = new ClineCapabilityProbe();\n const probeReport = await probe.probe();\n if (probeReport.installed) {\n const targetBundleDef = await registry.getBundle(bundleName!);\n const plan = launcher.planActivation({\n bundleName: bundleName!,\n workspace: process.cwd(),\n scope,\n report: probeReport,\n orchestrator: targetBundleDef?.orchestrator,\n });\n await launcher.launch(plan);\n } else {\n note(pc.yellow('Cline executable not detected. Install Cline CLI to run: agents start ' + bundleName), 'Cline Not Found');\n }\n }\n } else if (isInteractive && !options.dryRun) {\n const startChoice = await select({\n message: `Start the ${bundleName} team in Cline now?`,\n options: [\n { value: 'start', label: '🚀 Start in Cline' },\n { value: 'copy', label: `📋 Copy command (agents start ${bundleName})` },\n { value: 'later', label: '⏳ Later' },\n ],\n });\n\n if (startChoice === 'start') {\n const launcher = new ClineLauncher();\n const probe = new ClineCapabilityProbe();\n const probeReport = await probe.probe();\n if (probeReport.installed) {\n const targetBundleDef = await registry.getBundle(bundleName!);\n const plan = launcher.planActivation({\n bundleName: bundleName!,\n workspace: process.cwd(),\n scope,\n report: probeReport,\n orchestrator: targetBundleDef?.orchestrator,\n });\n await launcher.launch(plan);\n } else {\n note(pc.yellow('Cline executable not detected. Install Cline CLI to run: agents start ' + bundleName), 'Cline Not Found');\n }\n } else if (startChoice === 'copy') {\n note(`Run 'agents start ${bundleName}' to launch the team in Cline anytime.`, 'Start Command');\n }\n } else if (!options.dryRun) {\n note(pc.cyan(`Tip: Run 'agents start ${bundleName}' to launch the team in Cline.`), 'Start in Cline');\n }\n }\n\n // Plain-language tip when the main library is the only thing installed and no\n // translated copies were requested — sets the right expectation up front.\n // ADR 0013: Cline natively discovers skills from .agents/skills/, so the old\n // \"only Antigravity reads the main library\" claim is no longer accurate.\n if (!options.dryRun && hosts.includes('agents') && result.projections.length === 0) {\n note(\n pc.yellow(\n `Tip: Antigravity reads the main library (.agents/) directly, and Cline natively\\n` +\n `discovers skills from .agents/skills/ (ADR 0013). For Cline configured agents,\\n` +\n `rules & workflows run: agents update ${identifier} --fanout cline\\n` +\n `(add claude, cursor, opencode, codex for other assistants)`\n ),\n 'One library, every assistant'\n );\n }\n\n if (!options.dryRun && targetBundleDef?.tier === 'organization') {\n note(\n pc.cyan(\n '💡 In-Session MCP Setup: Your Lead Orchestrator will automatically check\\n' +\n 'your runtime tools and guide configuration of live browser automation,\\n' +\n 'design tokens, or cloud APIs on demand.'\n ),\n 'Adaptive Tooling'\n );\n }\n\n // Owner Gate-7 finding (2026-09-25): hosts discover skills at session start, so tell the\n // operator how THIS session can pick up what was just installed (docs/host-skill-reload.md).\n if (!options.dryRun) {\n note(\n pc.yellow(\n 'New skills are discovered at session start. To pick them up now:\\n' +\n ' Claude Code ..... user types /reload-skills (#58733)\\n' +\n ' Antigravity CLI . user types /skills reload\\n' +\n ' Antigravity App . restart the app, or use @<skill_name>\\n' +\n ' Cline ........... agents read .cline/skills/ directly\\n' +\n 'Slash commands only fire when YOU type them; agents can read the file.'\n ),\n 'Pick up new skills'\n );\n }\n\n outro(pc.green(`✔ Installed \"${identifier}\" successfully!`));\n } catch (err: any) {\n s.stop(pc.red('Failed resolution'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('remove [identifier]', 'Remove an installed bundle, agent, skill, or workflow')\n .alias('uninstall')\n .option('-g, --global', 'Uninstall from global home directory')\n .option('-t, --target <hosts>', 'Target agent host runtimes', { default: 'agents' })\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('-f, --force', 'Force removal of modified files')\n .option('--dry-run', 'Simulate removal without unlinking files')\n .action(async (targetIdentifier?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — Remove Package'));\n\n let identifier = targetIdentifier;\n let selectedRecord: InstalledPackageRecord | undefined;\n const isInteractive = process.stdout.isTTY && !options.yes;\n\n if (!identifier) {\n const inventory = await scanner.scan({\n global: options.global,\n target: options.target,\n });\n\n if (inventory.records.length === 0) {\n outro(pc.yellow('No installed packages found in project or global configuration.'));\n return;\n }\n\n if (!isInteractive) {\n outro(pc.red('Package identifier required in non-interactive mode. Usage: agents remove <identifier>'));\n return;\n }\n\n const itemOptions = inventory.records.map(record => {\n const meta = BUNDLE_DISPLAY_NAMES[record.name];\n const title = meta?.title || record.title || record.name;\n const icon = record.type === 'bundle' ? '📦' : record.type === 'skill' ? '⚡' : '🤖';\n const typeLabel = record.type !== 'bundle' ? `[${record.type}] ` : '';\n const badge = pc.cyan(record.displayLocation);\n const versionTag = pc.dim(`(v${record.installedVersion})`);\n\n return {\n value: record.id,\n label: `${icon} ${typeLabel}${title} ${badge} ${versionTag}`,\n hint: `${record.fileCount} file${record.fileCount > 1 ? 's' : ''} — ${record.description || record.name}`,\n };\n });\n\n const selectedId = await select({\n message: 'Select an installed package to remove:',\n options: itemOptions,\n });\n\n if (typeof selectedId !== 'string') {\n outro(pc.yellow('Removal cancelled.'));\n return;\n }\n\n selectedRecord = inventory.records.find(r => r.id === selectedId);\n if (selectedRecord) {\n identifier = selectedRecord.name;\n } else {\n identifier = selectedId;\n }\n }\n\n const s = spinner();\n s.start(`Removing \"${identifier}\"...`);\n\n try {\n const result = await uninstaller.uninstall(identifier, {\n scope: selectedRecord?.scope || (options.global ? 'global' : 'project'),\n global: options.global,\n target: selectedRecord ? [selectedRecord.host] : options.target,\n targetDir: selectedRecord?.targetDir,\n yes: options.yes,\n force: options.force,\n dryRun: options.dryRun,\n });\n\n s.stop(`Uninstall processed`);\n\n if (options.dryRun) {\n outro(pc.yellow(\n `[DRY RUN] Would delete ${result.removed.length} and keep ${result.kept.length}` +\n (result.kept.length > 0 ? ` (still owned by: ${result.retainedOwners.join(', ')})` : '') +\n ` — ${result.targetDirs.join(', ')}`\n ));\n return;\n }\n\n // Honest accounting. `removed` counts only files that actually left the disk; when the\n // identifier's assets are co-owned, most or all of them survive for their other owners. The\n // old \"Successfully removed 84 files\" told the operator content vanished that did not — and\n // never said WHAT was deleted, so a bundle package quietly disappearing under\n // `.agents/plugins/` looked like nothing happened at all.\n if (result.kept.length > 0) {\n log.info(`${result.removed.length} deleted · ${result.kept.length} kept — still owned by: ${result.retainedOwners.join(', ')}`);\n }\n if (result.removed.length > 0) {\n const sample = result.removed.slice(0, 3).join(', ');\n const more = result.removed.length > 3 ? `, … +${result.removed.length - 3} more` : '';\n log.info(`deleted: ${sample}${more}`);\n }\n if (result.staleRecords.length > 0) {\n log.info(`${result.staleRecords.length} stale record(s) cleaned — bookkeeping only, those files were already gone`);\n }\n outro(pc.green(\n result.removed.length === 0 && result.kept.length > 0\n ? `✔ Removed \"${identifier}\" from this workspace — nothing was deleted, ${result.kept.length} co-owned assets kept`\n : `✔ Removed \"${identifier}\" from this workspace — ${result.removed.length} deleted, ${result.kept.length} kept`\n ));\n } catch (err: any) {\n s.stop(pc.red('Uninstall failed'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('update [identifier]', 'Update installed packages to upstream registry versions')\n .alias('upgrade')\n .option('-g, --global', 'Update global packages in home directory')\n .option('-t, --target <hosts>', 'Target agent host runtimes')\n .option('--fanout <hosts>', 'Also project the canonical .agents/ store into these runtimes during update (claude, cursor, cline, opencode, codex)')\n .option('-a, --all', 'Update all installed packages without prompting')\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('-f, --force', 'Force overwrite user modified files')\n .option('--start', 'Start the updated team in Cline immediately after update')\n .option('--dry-run', 'Simulate update without writing files')\n .action(async (targetIdentifier?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — Package Update Engine'));\n\n // Parse --fanout like the add command: validated against the registry,\n // unknown/non-projection-capable ids are dropped with a warning.\n let updateFanout: string[] | undefined;\n if (options.fanout !== undefined) {\n const rawFanout: string[] = Array.isArray(options.fanout) ? options.fanout : splitHostList(String(options.fanout));\n const parsedFanout: string[] = rawFanout.map((h: string) => h.trim().toLowerCase()).filter(Boolean);\n const invalidFanout: string[] = parsedFanout.filter(h => !isKnownHost(h) || !HOST_REGISTRY[h].projectionCapable);\n if (invalidFanout.length > 0) {\n note(\n pc.yellow(\n `Ignoring invalid fanout host id(s): ${invalidFanout.join(', ')}. Valid ids: ${KNOWN_HOST_IDS.filter(h => HOST_REGISTRY[h].projectionCapable).join(', ')}`\n ),\n 'Invalid fanout'\n );\n }\n const updateUnderDev = Array.from(new Set(parsedFanout.filter((h) => isKnownHost(h) && HOST_REGISTRY[h].status === 'under-development')));\n if (updateUnderDev.length > 0) {\n note(\n pc.yellow(\n `Refusing --fanout host(s): ${updateUnderDev.join(', ')} — they are listed as Under Development and unavailable. Supported --fanout ids: ${SUPPORTED_HOST_IDS.filter((h) => HOST_REGISTRY[h].projectionCapable).join(', ')}. Drop ${updateUnderDev.join(', ')} from --fanout and run again.`\n ),\n 'Host unavailable'\n );\n process.exit(1);\n }\n updateFanout = parsedFanout.filter(h => isKnownHost(h) && HOST_REGISTRY[h].projectionCapable);\n }\n\n const s = spinner();\n s.start('Checking installed package inventory & upstream drift...');\n\n const report = await updater.checkUpdates({\n global: options.global,\n target: options.target,\n });\n\n s.stop('Inventory discovery complete');\n\n if (report.totalCount === 0) {\n outro(pc.yellow('No installed packages found in project or global configuration.'));\n return;\n }\n\n const isInteractive = process.stdout.isTTY && !options.yes && !options.all;\n let targetsToUpdate: string[] | '__all__' = [];\n\n if (targetIdentifier) {\n targetsToUpdate = [targetIdentifier];\n } else if (options.all || options.yes || !isInteractive) {\n targetsToUpdate = '__all__';\n } else {\n // Interactive Mode\n const locationLines: string[] = [];\n if (report.scannedLocations && report.scannedLocations.length > 0) {\n for (const loc of report.scannedLocations) {\n const scopeLabel = loc.scope === 'project' ? 'Project' : 'Global';\n const fanoutStr = loc.fanout.length > 0 ? ` ${pc.magenta(`(projections: ${loc.fanout.join(', ')})`)}` : '';\n locationLines.push(` • ${scopeLabel} (${loc.displayLocation}): ${pc.bold(loc.packageCount)} package${loc.packageCount !== 1 ? 's' : ''}${fanoutStr}`);\n }\n } else {\n const projectCount = report.items.filter(i => i.record.scope === 'project').length;\n const globalCount = report.items.filter(i => i.record.scope === 'global').length;\n if (!options.global) {\n locationLines.push(` • Project (./.agents): ${pc.bold(projectCount)} package${projectCount !== 1 ? 's' : ''}`);\n }\n locationLines.push(` • Global (~/.agents): ${pc.bold(globalCount)} package${globalCount !== 1 ? 's' : ''}`);\n }\n\n const allDetectedFanouts = Array.from(new Set(report.items.flatMap(i => i.record.fanout || [])));\n const fanoutSummary = allDetectedFanouts.length > 0\n ? `\\nActive Projections: ${allDetectedFanouts.map(h => `${pc.cyan(h)} (./.${h}/)`).join(', ')}`\n : '';\n\n const statusMessage =\n `Locations Checked:\\n${locationLines.join('\\n')}${fanoutSummary}\\n\\n` +\n `Total Installed Packages: ${report.totalCount}\\n` +\n `Updates Available: ${report.outdatedCount > 0 ? pc.yellow(pc.bold(`${report.outdatedCount} package${report.outdatedCount > 1 ? 's' : ''} can be updated`)) : pc.green('0 (All up to date)')}`;\n\n note(statusMessage, 'Inventory Status');\n\n const menuOptions: Array<{ value: string; label: string; hint?: string }> = [];\n\n if (report.outdatedCount > 0) {\n menuOptions.push({\n value: '__all_outdated__',\n label: `⚡ Update All Outdated Packages (${report.outdatedCount} available)`,\n hint: 'batch upgrade all packages with newer upstream versions',\n });\n }\n\n menuOptions.push({\n value: '__selective__',\n label: '📦 Selectively Pick Packages to Update',\n hint: 'choose specific bundles or items from an interactive list',\n });\n\n menuOptions.push({\n value: '__resync_all__',\n label: `🔄 Re-sync / Repair All Packages (${report.totalCount})`,\n hint: 're-link or re-copy all packages to guarantee full integrity',\n });\n\n const action = await select({\n message: 'Select update action:',\n options: menuOptions,\n });\n\n if (typeof action !== 'string') {\n outro(pc.yellow('Update cancelled.'));\n return;\n }\n\n if (action === '__all_outdated__') {\n targetsToUpdate = report.items.filter(i => i.hasUpdate).map(i => i.record.name);\n } else if (action === '__resync_all__') {\n targetsToUpdate = '__all__';\n } else if (action === '__selective__') {\n const itemOptions = report.items.map(item => {\n const meta = BUNDLE_DISPLAY_NAMES[item.record.name];\n const title = meta?.title || item.record.title || item.record.name;\n const badge = pc.cyan(item.record.displayLocation);\n const versionDiff = item.hasUpdate\n ? pc.yellow(`(v${item.installedVersion} → v${item.upstreamVersion}) [UPDATE]`)\n : pc.dim(`(v${item.installedVersion}) [UP TO DATE]`);\n\n return {\n value: item.record.name,\n label: `📦 ${title} ${badge} ${versionDiff}`,\n hint: item.record.description || item.record.name,\n };\n });\n\n const initialValues = report.items.filter(i => i.hasUpdate).map(i => i.record.name);\n\n const selection = await multiselect({\n message: 'Select packages to update:',\n options: itemOptions,\n initialValues: initialValues.length > 0 ? initialValues : undefined,\n required: true,\n });\n\n if (!Array.isArray(selection) || selection.length === 0) {\n outro(pc.yellow('No packages selected for update.'));\n return;\n }\n\n targetsToUpdate = selection as string[];\n }\n }\n\n const updateSpinner = spinner();\n updateSpinner.start('Updating packages...');\n\n try {\n const result = await updater.update(targetsToUpdate, {\n global: options.global,\n target: options.target,\n force: options.force,\n dryRun: options.dryRun,\n fanout: updateFanout,\n });\n\n updateSpinner.stop('Update completed');\n\n if (options.dryRun) {\n outro(pc.yellow(`[DRY RUN] Would update ${result.updated.length} packages in ${result.targetDirs.join(', ')}`));\n if (result.projections && result.projections.length > 0) {\n note(renderProjections(result.projections), 'Projection Plan (dry run)');\n }\n return;\n }\n\n if (result.updated.length > 0) {\n // Plain-language sync tip for any updated bundle still living only in .agents/.\n const unprojected: string[] = [];\n for (const rec of result.updated) {\n try {\n const lf = await fs.readJson(path.join(rec.targetDir, 'agents-united.json'));\n if (!lf.fanout || lf.fanout.length === 0) unprojected.push(rec.name);\n } catch { /* ignore */ }\n }\n if (unprojected.length > 0) {\n note(\n pc.yellow(\n `Tip: not fully synced to other assistants yet (Antigravity reads .agents/ directly; Cline natively discovers .agents/skills/).\\n` +\n `For Cline configured agents, rules & workflows: agents update ${unprojected[0]} --fanout cline`\n ),\n 'One library, every assistant'\n );\n }\n const updatedList = result.updated\n .map(u => ` ✔ ${pc.bold(u.name)} ${pc.cyan(u.displayLocation)} ${pc.green(`(v${u.installedVersion})`)}`)\n .join('\\n');\n note(updatedList, 'Updated Packages');\n\n if (result.projections && result.projections.length > 0) {\n note(renderProjections(result.projections), 'Updated Projections');\n }\n }\n\n\n if (result.skipped.length > 0) {\n const skippedList = result.skipped\n .map(s => ` ⚠ ${pc.yellow(s.record.name)}: ${s.reason}`)\n .join('\\n');\n note(skippedList, 'Skipped Packages (User Modifications)');\n }\n\n if (result.updated.length === 0 && result.skipped.length === 0) {\n outro(pc.yellow('All packages are already up to date.'));\n } else {\n outro(pc.green(`✔ Successfully processed update for ${result.updated.length} package${result.updated.length > 1 ? 's' : ''}!`));\n }\n } catch (err: any) {\n updateSpinner.stop(pc.red('Update failed'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\nfunction renderBundleDetailTree(bundle: BundleDefinition): string {\n // Special-case full universal suite for clean, structured high-level breakdown\n if (bundle.name === 'full') {\n const lines: string[] = [];\n lines.push(`📦 ${pc.bold(pc.green('full'))} ${pc.cyan('(Universal Autonomous Department)')} ${pc.green('⭐ [Recommended]')}`);\n lines.push(`│ ${pc.white('Complete suite with all 7 lead orchestrators, 38 subagents, and 160 modular skills (91 domain skills + 69 workflow playbooks).')}`);\n lines.push(`│`);\n lines.push(`├── 🤖 Lead Orchestrators (7 department domains):`);\n lines.push(`│ ├── 🛠️ ${pc.blue('orchestrator-engineering')} ${pc.dim('(Software Engineering & Delivery)')}`);\n lines.push(`│ ├── 🏛️ ${pc.blue('orchestrator-system-architecture')} ${pc.dim('(System Architecture & SRE)')}`);\n lines.push(`│ ├── 🎨 ${pc.blue('orchestrator-design')} ${pc.dim('(Product Design & UI/UX)')}`);\n lines.push(`│ ├── 📈 ${pc.blue('orchestrator-marketing')} ${pc.dim('(Growth & Marketing Operations)')}`);\n lines.push(`│ ├── 🔒 ${pc.blue('orchestrator-security')} ${pc.dim('(Security Operations)')}`);\n lines.push(`│ ├── 🔬 ${pc.blue('orchestrator-research')} ${pc.dim('(Deep Technical Research)')}`);\n lines.push(`│ └── 💼 ${pc.blue('orchestrator-business')} ${pc.dim('(Business Strategy & Economics)')}`);\n lines.push(`├── 🤖 Specialized Sub-Agents: ${pc.blue('38 worker agents across all 8 departments')}`);\n lines.push(`├── ⚡ Skills: ${pc.yellow('91 modular domain skills & runbooks')}`);\n lines.push(`├── 🔄 Workflows: ${pc.magenta('69 guided multi-step workflow playbooks')}`);\n lines.push(`├── 🔌 Prerequisites: ${pc.dim('None (Self-contained universal suite)')}`);\n lines.push(`└── 💡 Execution Modes: ${pc.green('Operational')}`);\n return lines.join('\\n');\n }\n\n const meta = BUNDLE_DISPLAY_NAMES[bundle.name];\n const isEssentials = !bundle.parentBundle && bundle.name !== 'full' && bundle.name !== 'universal-skills' && bundle.name !== 'universal-orchestration' && bundle.tier !== 'organization';\n const titleSuffix = isEssentials ? pc.cyan(' (Essentials Base)') : '';\n const parentTag = bundle.parentBundle ? pc.gray(` [inherits: ${bundle.parentBundle}]`) : '';\n const aliasesTag = bundle.aliases && bundle.aliases.length > 0 ? pc.gray(` [alias: ${bundle.aliases.join(', ')}]`) : '';\n\n let statusBadge = '';\n if (bundle.name === 'universal-skills') statusBadge = pc.green(' ⭐ [Recommended]');\n else if (bundle.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction]');\n else if (bundle.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (bundle.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (bundle.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n else statusBadge = pc.green(' [Stable]');\n\n const lines: string[] = [];\n lines.push(`📦 ${pc.bold(pc.green(bundle.name))}${titleSuffix}${statusBadge}${parentTag}${aliasesTag}`);\n lines.push(`│ ${pc.white(bundle.description || meta?.summary || '')}`);\n lines.push(`│`);\n\n // Lead / Orchestrator\n if (bundle.orchestrator) {\n const orchName = bundle.orchestrator.replace(/\\.md$/, '');\n lines.push(`├── 🤖 Lead: ${pc.blue(pc.bold(orchName))}`);\n } else {\n lines.push(`├── 🤖 Lead: ${pc.dim('None (Self-directed meta-skills)')}`);\n }\n\n // Subagents\n if (bundle.agents && bundle.agents.length > 0) {\n const subNames = bundle.agents.map(a => a.replace(/^subagent-/, '').replace(/\\.md$/, ''));\n lines.push(`├── 🤖 Sub-agents (${bundle.agents.length}):`);\n if (subNames.length <= 5) {\n subNames.forEach((name, sIdx) => {\n const isLastSub = sIdx === subNames.length - 1;\n const subBranch = isLastSub ? '└──' : '├──';\n lines.push(`│ ${subBranch} 🤖 ${pc.blue(name)}`);\n });\n } else {\n subNames.slice(0, 4).forEach(name => {\n lines.push(`│ ├── 🤖 ${pc.blue(name)}`);\n });\n lines.push(`│ └── 🤖 ${pc.dim(`(+${subNames.length - 4} more: ${subNames.slice(4).join(', ')})`)}`);\n }\n } else {\n lines.push(`├── 🤖 Sub-agents: ${pc.dim('None')}`);\n }\n\n // Partition skills into domain skills and workflow playbooks (ADR 0016)\n const domainSkills = (bundle.skills || []).filter(s => !s.startsWith('workflow-'));\n const workflowSkills = [\n ...(bundle.skills || []).filter(s => s.startsWith('workflow-')),\n ...(bundle.workflows || []),\n ];\n\n // Skills\n if (domainSkills.length > 0) {\n lines.push(`├── ⚡ Skills (${domainSkills.length}):`);\n if (domainSkills.length <= 5) {\n lines.push(`│ └── ${pc.yellow(domainSkills.join(', '))}`);\n } else {\n lines.push(`│ ├── ${pc.yellow(domainSkills.slice(0, 5).join(', '))}`);\n lines.push(`│ └── ${pc.dim(`(+${domainSkills.length - 5} more: ${domainSkills.slice(5).join(', ')})`)}`);\n }\n } else if (!bundle.parentBundle && workflowSkills.length === 0) {\n lines.push(`├── ⚡ Skills: ${pc.dim('None')}`);\n } else if (bundle.parentBundle && domainSkills.length === 0) {\n lines.push(`├── ⚡ Skills: ${pc.dim('Inherited from base bundle')}`);\n }\n\n // Workflows\n if (workflowSkills.length > 0) {\n const wfNames = workflowSkills.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n lines.push(`├── 🔄 Workflows (${workflowSkills.length}):`);\n if (wfNames.length <= 4) {\n lines.push(`│ └── ${pc.magenta(wfNames.join(', '))}`);\n } else {\n lines.push(`│ ├── ${pc.magenta(wfNames.slice(0, 4).join(', '))}`);\n lines.push(`│ └── ${pc.dim(`(+${wfNames.length - 4} more: ${wfNames.slice(4).join(', ')})`)}`);\n }\n } else if (bundle.parentBundle) {\n lines.push(`├── 🔄 Workflows: ${pc.dim('Inherited from base bundle')}`);\n }\n\n // Prerequisites\n if (bundle.prerequisites) {\n const prereqParts: string[] = [];\n if (bundle.prerequisites.requiredMcps && bundle.prerequisites.requiredMcps.length > 0) {\n prereqParts.push(`MCPs: ${bundle.prerequisites.requiredMcps.map(m => m.name).join(', ')}`);\n }\n if (bundle.prerequisites.requiredPackages && bundle.prerequisites.requiredPackages.length > 0) {\n prereqParts.push(`Packages: ${bundle.prerequisites.requiredPackages.join(', ')}`);\n }\n if (bundle.prerequisites.requiredEnvVars && bundle.prerequisites.requiredEnvVars.length > 0) {\n prereqParts.push(`Env: ${bundle.prerequisites.requiredEnvVars.join(', ')}`);\n }\n if (prereqParts.length > 0) {\n lines.push(`├── 🔌 Prerequisites: ${pc.yellow(prereqParts.join(' | '))}`);\n }\n } else {\n lines.push(`├── 🔌 Prerequisites: ${pc.dim('None (Self-contained domain bundle)')}`);\n }\n\n // Execution Modes\n if (bundle.modes) {\n lines.push(`└── 💡 Execution Modes: ${pc.green('Operational')} (live MCPs) / ${pc.cyan('Brainstorming')} (advisory fallback)`);\n } else {\n lines.push(`└── 💡 Execution Modes: ${pc.green('Operational')}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction renderFullCatalogTree(bundles: BundleDefinition[]): void {\n intro(pc.cyan('Agents United — Registry Catalog Tree'));\n\n const domainTitles: Record<string, string> = {\n engineering: '🛠️ Software Engineering & Delivery',\n architecture: '🏛️ System Architecture & SRE',\n design: '🎨 Product Design & UI/UX',\n marketing: '📈 Growth & Marketing Operations',\n security: '🔒 Security Operations',\n research: '🔬 Deep Technical Research',\n business: '💼 Business Strategy & Economics',\n universal: '🌐 Universal Autonomous Department',\n };\n\n const domainOrder = [\n 'universal',\n 'engineering',\n 'architecture',\n 'design',\n 'marketing',\n 'security',\n 'research',\n 'business',\n ];\n\n const grouped: Record<string, typeof bundles> = {};\n const orgBundles: typeof bundles = [];\n\n for (const b of bundles) {\n if (b.tier === 'organization' || b.domain === 'organization') {\n orgBundles.push(b);\n continue;\n }\n const d = b.domain || 'other';\n if (!grouped[d]) grouped[d] = [];\n grouped[d].push(b);\n }\n\n for (const domainKey of domainOrder) {\n const items = grouped[domainKey];\n if (!items || items.length === 0) continue;\n\n const header = domainTitles[domainKey] || `📁 ${domainKey.toUpperCase()}`;\n console.log(`\\n${pc.bold(pc.magenta(header))} ${pc.dim(`(${items.length} bundle${items.length > 1 ? 's' : ''})`)}`);\n\n items.forEach((b: BundleDefinition, bIdx: number) => {\n const isLastBundle = bIdx === items.length - 1;\n const bBranch = isLastBundle ? '└──' : '├──';\n const subIndent = isLastBundle ? ' ' : '│ ';\n\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n const isEssentials = !b.parentBundle && b.name !== 'full' && b.name !== 'universal-skills' && b.name !== 'universal-orchestration';\n const titleSuffix = isEssentials ? pc.cyan(' (Essentials)') : '';\n const parentTag = b.parentBundle ? pc.gray(` [inherits: ${b.parentBundle}]`) : '';\n const aliasesTag = b.aliases && b.aliases.length > 0 ? pc.gray(` [alias: ${b.aliases.join(', ')}]`) : '';\n\n let statusBadge = '';\n if (b.name === 'universal-skills') statusBadge = pc.green(' ⭐ [Recommended]');\n else if (b.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction]');\n else if (b.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n\n console.log(`${bBranch} 📦 ${pc.bold(pc.green(b.name))}${titleSuffix}${statusBadge}${parentTag}${aliasesTag}`);\n console.log(`${subIndent}│ ${pc.white(b.description)}`);\n\n // Lead / Orchestrator\n if (b.orchestrator) {\n const orchName = b.orchestrator.replace(/\\.md$/, '');\n console.log(`${subIndent}├── 🤖 Lead: ${pc.blue(orchName)}`);\n }\n\n // Subagents\n if (b.agents && b.agents.length > 0) {\n const subNames = b.agents.map(a => a.replace(/^subagent-/, '').replace(/\\.md$/, ''));\n const displaySubs =\n subNames.length > 3 ? `${subNames.slice(0, 3).join(', ')} (+${subNames.length - 3} more)` : subNames.join(', ');\n console.log(`${subIndent}├── 🤖 Sub-agents: ${pc.blue(displaySubs)}`);\n }\n\n // Skills & Workflows (ADR 0016)\n const domainSkills = (b.skills || []).filter(s => !s.startsWith('workflow-'));\n const workflowSkills = [\n ...(b.skills || []).filter(s => s.startsWith('workflow-')),\n ...(b.workflows || []),\n ];\n\n // Skills\n if (domainSkills.length > 0) {\n const displaySkills =\n domainSkills.length > 3 ? `${domainSkills.slice(0, 3).join(', ')} (+${domainSkills.length - 3} more)` : domainSkills.join(', ');\n console.log(`${subIndent}├── ⚡ Skills: ${pc.yellow(displaySkills)}`);\n }\n\n // Workflows\n if (workflowSkills.length > 0) {\n const wfNames = workflowSkills.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n const displayWfs =\n wfNames.length > 3 ? `${wfNames.slice(0, 3).join(', ')} (+${wfNames.length - 3} more)` : wfNames.join(', ');\n console.log(`${subIndent}└── 🔄 Workflows: ${pc.magenta(displayWfs)}`);\n } else if (b.parentBundle) {\n console.log(`${subIndent}└── 🔄 Workflows: ${pc.dim('Inherited from parent')}`);\n }\n\n if (!isLastBundle) {\n console.log(`${subIndent}`);\n }\n });\n }\n\n // Dedicated Organization Bundles Section\n if (orgBundles.length > 0) {\n console.log(`\\n${pc.bold(pc.cyan('🏢 Organization Bundles (Experimental / Cross-Functional)'))} ${pc.dim(`(${orgBundles.length} bundle${orgBundles.length > 1 ? 's' : ''})`)}`);\n console.log(pc.dim(' Cross-domain teams modeled after real organizations. Require runtime prerequisites (MCPs/packages).'));\n\n orgBundles.forEach((b: BundleDefinition, bIdx: number) => {\n const isLastBundle = bIdx === orgBundles.length - 1;\n const bBranch = isLastBundle ? '└──' : '├──';\n const subIndent = isLastBundle ? ' ' : '│ ';\n\n let statusBadge = '';\n if (b.status === 'under-construction') statusBadge = pc.yellow(' 🚧 [Under Construction (TBA)]');\n else if (b.status === 'needs-audit') statusBadge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') statusBadge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') statusBadge = pc.red(' [Deprecated]');\n else statusBadge = pc.green(' [Stable]');\n\n const prereqBadge = pc.dim(' [Prerequisites Required]');\n\n console.log(`${bBranch} 🏢 ${pc.bold(pc.cyan(b.name))}${statusBadge}${prereqBadge}`);\n console.log(`${subIndent}│ ${pc.white(b.description)}`);\n\n if (b.orchestrator) {\n const orchName = b.orchestrator.replace(/\\.md$/, '');\n console.log(`${subIndent}├── 🤖 Lead: ${pc.blue(orchName)}`);\n }\n\n if (b.agents && b.agents.length > 0) {\n const subNames = b.agents.map(a => a.replace(/^subagent-/, '').replace(/\\.md$/, ''));\n const displaySubs =\n subNames.length > 3 ? `${subNames.slice(0, 3).join(', ')} (+${subNames.length - 3} more)` : subNames.join(', ');\n console.log(`${subIndent}├── 🤖 Sub-agents: ${pc.blue(displaySubs)}`);\n }\n\n // Skills & Workflows (ADR 0016)\n const orgDomainSkills = (b.skills || []).filter(s => !s.startsWith('workflow-'));\n const orgWorkflowSkills = [\n ...(b.skills || []).filter(s => s.startsWith('workflow-')),\n ...(b.workflows || []),\n ];\n\n if (orgDomainSkills.length > 0) {\n const displaySkills =\n orgDomainSkills.length > 3 ? `${orgDomainSkills.slice(0, 3).join(', ')} (+${orgDomainSkills.length - 3} more)` : orgDomainSkills.join(', ');\n console.log(`${subIndent}├── ⚡ Skills: ${pc.yellow(displaySkills)}`);\n }\n\n if (orgWorkflowSkills.length > 0) {\n const wfNames = orgWorkflowSkills.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n const displayWfs =\n wfNames.length > 3 ? `${wfNames.slice(0, 3).join(', ')} (+${wfNames.length - 3} more)` : wfNames.join(', ');\n console.log(`${subIndent}├── 🔄 Workflows: ${pc.magenta(displayWfs)}`);\n }\n\n // Prerequisites Summary\n if (b.prerequisites) {\n const prereqParts: string[] = [];\n if (b.prerequisites.requiredMcps && b.prerequisites.requiredMcps.length > 0) {\n prereqParts.push(`MCPs: ${b.prerequisites.requiredMcps.map(m => m.name).join(', ')}`);\n }\n if (b.prerequisites.requiredPackages && b.prerequisites.requiredPackages.length > 0) {\n prereqParts.push(`Packages: ${b.prerequisites.requiredPackages.join(', ')}`);\n }\n if (b.prerequisites.requiredEnvVars && b.prerequisites.requiredEnvVars.length > 0) {\n prereqParts.push(`Env: ${b.prerequisites.requiredEnvVars.join(', ')}`);\n }\n if (prereqParts.length > 0) {\n console.log(`${subIndent}├── 🔌 Prerequisites: ${pc.yellow(prereqParts.join(' | '))}`);\n }\n }\n\n // Modes Summary\n if (b.modes) {\n console.log(`${subIndent}└── 💡 Execution Modes: ${pc.green('Operational')} (live MCPs) / ${pc.cyan('Brainstorming')} (advisory fallback)`);\n } else {\n console.log(`${subIndent}└── 💡 Execution Modes: ${pc.green('Operational')}`);\n }\n\n if (!isLastBundle) {\n console.log(`${subIndent}`);\n }\n });\n }\n\n outro(pc.cyan('\\nRun \"agents add <bundle>\" or select interactively to install.'));\n}\n\nasync function handleBundleDetailView(bundle: BundleDefinition): Promise<'__back_bundle__' | '__back_dept__' | '__exit__'> {\n const treeOutput = renderBundleDetailTree(bundle);\n console.log(`\\n${pc.bold(pc.cyan('┌── 📋 Bundle Detail: ' + pc.green(bundle.name) + ' ' + '─'.repeat(Math.max(2, 40 - bundle.name.length))))}`);\n console.log(treeOutput);\n console.log(`${pc.bold(pc.cyan('└' + '─'.repeat(60)))}\\n`);\n\n const actionOptions = [\n {\n value: 'install',\n label: `🚀 Install \"${bundle.name}\" bundle`,\n hint: `run installer for ${bundle.name}`,\n },\n {\n value: 'back_bundle',\n label: `🔙 Back to ${bundle.domain || 'Department'} bundle list`,\n hint: 'explore other bundles in this category',\n },\n {\n value: 'back_dept',\n label: `🏛️ Back to Department selection`,\n hint: 'explore other departments',\n },\n {\n value: 'exit',\n label: `🚪 Exit explorer`,\n hint: 'return to shell',\n },\n ];\n\n const action = await select({\n message: `Action for ${pc.bold(pc.green(bundle.name))}:`,\n options: actionOptions,\n });\n\n if (action === 'install') {\n // 1. Under Construction Gate Evaluation\n if (bundle.status === 'under-construction') {\n note(\n `The bundle \"${bundle.name}\" is currently under active construction (status: under-construction).\\n` +\n `Its orchestrators, workflows, and specialized skills are being authored and are not ready for production use.\\n\\n` +\n `Planned Capabilities:\\n` +\n `• Lead Orchestrator with Firecrawl & GitHub MCP tool calling\\n` +\n `• Full-stack web, design & SEO delivery workflows\\n` +\n `• Dual Execution Modes (Operational / Brainstorming)`,\n '🚧 Under Construction Gate'\n );\n\n const underConstructionChoice = await select({\n message: pc.yellow(`\"${bundle.name}\" is currently under construction. How would you like to proceed?`),\n options: [\n {\n value: 'abort',\n label: '🛑 Abort installation (Recommended)',\n hint: 'return without modifying workspace files',\n },\n {\n value: 'allow',\n label: '⚠️ Install in-development draft anyway (--allow-under-construction)',\n hint: 'proceed with in-progress placeholder assets',\n },\n ],\n });\n\n if (underConstructionChoice === 'abort' || typeof underConstructionChoice !== 'string') {\n outro(pc.yellow(`Installation cancelled. \"${bundle.name}\" is under construction.`));\n return '__back_bundle__';\n }\n }\n\n // 2. Prerequisite Gate Evaluation\n let executionMode: ExecutionMode = 'operational';\n\n if (bundle.prerequisites || bundle.tier === 'organization') {\n const checker = new PrerequisiteChecker();\n const prereqEval = await checker.evaluate(bundle);\n\n if (prereqEval.hasPrerequisites) {\n const checkLines: string[] = [];\n for (const item of prereqEval.items) {\n const typeLabel = item.type === 'mcp' ? 'MCP' : item.type === 'env' ? 'Env' : 'Pkg';\n const icon = item.satisfied ? pc.green('✓') : pc.red('✗');\n const details = pc.dim(`(${item.details || ''})`);\n checkLines.push(` ${icon} [${typeLabel}] ${pc.bold(item.name)}: ${item.satisfied ? pc.green('Detected') : pc.red('Missing')} ${details}`);\n }\n\n note(\n checkLines.join('\\n'),\n `Prerequisite Evaluation: ${bundle.name} (${bundle.tier === 'organization' ? 'Organization Bundle' : 'Prerequisites Required'})`\n );\n\n if (!prereqEval.allSatisfied) {\n const gateChoice = await select({\n message: pc.yellow(`Prerequisites not fully satisfied for \"${bundle.name}\". How would you like to proceed?`),\n options: [\n {\n value: 'abort',\n label: '🛑 Abort and configure missing prerequisites (Recommended)',\n hint: 'exit and configure MCP servers, packages, or environment variables',\n },\n {\n value: 'brainstorming',\n label: '💡 Install in Brainstorming Mode (Advisory & Spec generation only)',\n hint: 'runs in idea/planning mode without requiring live MCP tool connections',\n },\n {\n value: 'force',\n label: '⚠️ Force install in Operational Mode anyway',\n hint: 'proceed despite missing prerequisites (may fail during runtime calls)',\n },\n ],\n });\n\n if (gateChoice === 'abort' || typeof gateChoice !== 'string') {\n outro(pc.yellow('Installation aborted. Please configure required MCPs and environment variables, then retry.'));\n return '__back_bundle__';\n }\n\n if (gateChoice === 'brainstorming') {\n executionMode = 'brainstorming';\n note(pc.cyan('Switched execution mode to \"brainstorming\" (idea/spec fallback mode).'), 'Mode Selected');\n } else if (gateChoice === 'force') {\n executionMode = 'operational';\n note(pc.yellow('Proceeding in \"operational\" mode with missing prerequisites.'), 'Warning');\n }\n }\n }\n }\n\n // 3. Workspace Host & Fan-out Configuration\n const detectedHosts = detectWorkspaceHosts();\n let installHosts: AgentHost[] = ['agents'];\n let installFanout: string[] = [];\n\n if (detectedHosts.length > 0) {\n const projectionHosts = detectedHosts.filter(h => HOST_REGISTRY[h].projectionCapable);\n installFanout = projectionHosts;\n installHosts = detectedHosts.filter(h => !HOST_REGISTRY[h].projectionCapable) as AgentHost[];\n if (!installHosts.includes('agents')) installHosts.unshift('agents');\n }\n\n const installSpinner = spinner();\n installSpinner.start(`Installing \"${bundle.name}\"...`);\n\n try {\n const result = await installer.install(bundle.name, {\n scope: 'project',\n hosts: installHosts,\n fanout: installFanout,\n mode: executionMode,\n method: 'symlink',\n });\n\n installSpinner.stop(pc.green(`✔ Successfully installed ${bundle.name}!`));\n // Owner Gate-7 finding (2026-09-25): skills are discovered at session start.\n note(\n pc.yellow(\n 'New skills are discovered at session start. To pick them up now:\\n' +\n ' Claude Code ..... user types /reload-skills (#58733)\\n' +\n ' Antigravity CLI . user types /skills reload\\n' +\n ' Antigravity App . restart the app, or use @<skill_name>\\n' +\n ' Cline ........... agents read .cline/skills/ directly\\n' +\n 'Slash commands only fire when YOU type them; agents can read the file.'\n ),\n 'Pick up new skills'\n );\n note(\n formatInstallationSummary({\n bundleName: result.installed.targetBundle || bundle.name,\n scope: 'project',\n method: result.method,\n hosts: installHosts,\n agents: result.installed.agents,\n skills: result.installed.skills,\n targetDirs: result.targetDirs,\n projections: result.projections,\n }),\n 'Installation Success'\n );\n if (result.projections.length > 0) {\n note(renderProjections(result.projections), 'Installed Projections');\n }\n if (result.projections.some(p => p.host === 'cline')) {\n note(\n pc.green(\n `Already active: any Cline session in this workspace now sees this bundle's\\n` +\n `skills, subagent_* agent tools, rules & workflow commands (ADR 0013 native discovery).\\n` +\n `Use \"agents start ${bundle.name}\" for a pre-seeded team session.`\n ),\n 'Native Activation'\n );\n }\n outro(pc.green(`✨ Installation of \"${bundle.name}\" complete!`));\n } catch (err: any) {\n installSpinner.stop(pc.red('Installation failed'));\n outro(pc.red(`Error: ${err.message}`));\n }\n return '__exit__';\n } else if (action === 'back_dept') {\n return '__back_dept__';\n } else if (action === 'exit' || typeof action !== 'string') {\n return '__exit__';\n }\n\n return '__back_bundle__';\n}\n\ncli\n .command('list', 'List available bundles grouped by department domain')\n .alias('ls')\n .option('--json', 'Output bundles in JSON format')\n .option('--tree', 'Output full static catalog tree')\n .option('--all', 'Output full static catalog tree')\n .action(async (options: any = {}) => {\n const bundles = await registry.listBundles();\n\n if (options.json) {\n console.log(JSON.stringify(bundles, null, 2));\n return;\n }\n\n const isInteractive = process.stdout.isTTY && !options.tree && !options.all;\n\n if (!isInteractive) {\n renderFullCatalogTree(bundles);\n return;\n }\n\n // Interactive 2-Stage Catalog Explorer\n intro(pc.cyan('🌐 Agents United — Interactive Catalog Explorer'));\n\n const domainMeta: Record<string, { label: string; icon: string }> = {\n universal: { label: 'Universal Autonomous Department', icon: '🌐 ' },\n engineering: { label: 'Software Engineering & Delivery', icon: '🛠️ ' },\n architecture: { label: 'System Architecture & SRE', icon: '🏛️ ' },\n design: { label: 'Product Design & UI/UX', icon: '🎨 ' },\n marketing: { label: 'Growth & Marketing Operations', icon: '📈 ' },\n security: { label: 'Security Operations', icon: '🔒 ' },\n research: { label: 'Deep Technical Research', icon: '🔬 ' },\n business: { label: 'Business Strategy & Economics', icon: '💼 ' },\n organization: { label: 'Organization Bundles (Experimental / Cross-Functional)', icon: '🏢 ' },\n };\n\n let activeDomain: string | undefined;\n\n while (true) {\n // Stage 1: Department Domain Selection (if none selected)\n if (!activeDomain) {\n const domainOptions = Object.entries(domainMeta).map(([domainKey, meta]) => {\n const count = bundles.filter(b => (b.domain === domainKey || (domainKey === 'organization' && b.tier === 'organization'))).length;\n return {\n value: domainKey,\n label: `${meta.icon} ${meta.label}`,\n hint: domainKey === 'universal' ? 'meta-skills baseline + full suite' : domainKey === 'organization' ? 'cross-functional teams with prerequisites' : `${count} specialized bundle${count > 1 ? 's' : ''}`,\n };\n });\n\n domainOptions.push({\n value: '__search__',\n label: '🔍 Search by name / keyword...',\n hint: 'find bundles, agents, skills or workflows',\n });\n\n domainOptions.push({\n value: '__full_tree__',\n label: '🌳 View Full Static Catalog Tree',\n hint: `expand all ${bundles.length} bundles and ${new Set(bundles.map(b => b.domain).filter(Boolean)).size} departments at once`,\n });\n\n const selectedDomain = await select({\n message: 'Select Department Domain to explore:',\n options: domainOptions,\n });\n\n if (typeof selectedDomain !== 'string') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n\n if (selectedDomain === '__full_tree__') {\n renderFullCatalogTree(bundles);\n continue;\n }\n\n if (selectedDomain === '__search__') {\n const query = await text({\n message: 'Enter keyword to search:',\n placeholder: 'e.g. mobile, playwright, react, backend, seo',\n });\n\n if (typeof query !== 'string' || !query.trim()) {\n continue;\n }\n\n const results = await registry.find(query.trim());\n if (results.bundles.length === 0 && results.agents.length === 0 && results.skills.length === 0 && results.workflows.length === 0) {\n note(`No items found matching \"${query.trim()}\".`, 'Search Results');\n continue;\n }\n\n const searchOptions: Array<{ value: string; label: string; hint?: string }> = [\n ...results.bundles.map((b: BundleDefinition) => ({\n value: `bundle:${b.name}`,\n label: `📦 [Bundle] ${BUNDLE_DISPLAY_NAMES[b.name]?.title || b.name} (${b.name})`,\n hint: b.description,\n })),\n {\n value: '__back__',\n label: '🔙 Back to Department Selection',\n hint: '',\n },\n ];\n\n if (searchOptions.length === 1) {\n note(`Found related agents/skills for \"${query}\", but no top-level bundles. Try browsing by department.`, 'Search Results');\n continue;\n }\n\n const chosen = await select({\n message: `Search Results for \"${query.trim()}\":`,\n options: searchOptions,\n });\n\n if (typeof chosen === 'string' && chosen.startsWith('bundle:')) {\n const bundleName = chosen.replace(/^bundle:/, '');\n const b = await registry.getBundle(bundleName);\n if (b) {\n const action = await handleBundleDetailView(b);\n if (action === '__exit__') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n }\n }\n continue;\n }\n\n activeDomain = selectedDomain;\n }\n\n // Stage 2: Collapsed Bundle Selection within Active Domain\n const domainBundles = bundles.filter(b => b.domain === activeDomain || (activeDomain === 'organization' && b.tier === 'organization'));\n\n // Sort so Essentials/universal-skills are first\n const sortedBundles = [...domainBundles].sort((a, b) => {\n if (a.name === 'universal-orchestration') return -1;\n if (b.name === 'universal-orchestration') return 1;\n if (a.name === 'universal-skills') return -1;\n if (b.name === 'universal-skills') return 1;\n if (!a.parentBundle && b.parentBundle) return -1;\n if (a.parentBundle && !b.parentBundle) return 1;\n return a.name.localeCompare(b.name);\n });\n\n const bundleOptions: Array<{ value: string; label: string; hint?: string }> = sortedBundles.map((b, idx) => {\n const isLast = idx === sortedBundles.length - 1;\n const branch = sortedBundles.length > 1 ? (isLast ? '└── ' : '├── ') : '';\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n const isEssentials = !b.parentBundle && b.name !== 'full' && b.name !== 'universal-skills' && b.name !== 'universal-orchestration' && b.tier !== 'organization';\n const titleSuffix = isEssentials ? pc.cyan(' (Essentials Base)') : '';\n const parentTag = b.parentBundle ? pc.gray(` [inherits: ${b.parentBundle}]`) : '';\n\n let badge = '';\n if (b.name === 'universal-skills') badge = pc.green(' ⭐ [Recommended]');\n else if (b.status === 'under-construction') badge = pc.yellow(' 🚧 [Under Construction]');\n else if (b.status === 'needs-audit') badge = pc.magenta(' ⚠️ [Needs Audit]');\n else if (b.status === 'experimental') badge = pc.cyan(' [Experimental]');\n else if (b.status === 'deprecated') badge = pc.red(' [Deprecated]');\n\n return {\n value: b.name,\n label: `${branch}📦 ${meta?.title || b.name}${titleSuffix}${badge}${parentTag}`,\n hint: b.description || meta?.summary || b.name,\n };\n });\n\n bundleOptions.push({\n value: '__back_domain__',\n label: '🔙 Back to Department Selection',\n hint: 'choose another department domain',\n });\n\n const selectedBundleName = await select({\n message: `${domainMeta[activeDomain]?.label || activeDomain} — Select bundle to open:`,\n options: bundleOptions,\n });\n\n if (typeof selectedBundleName !== 'string') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n\n if (selectedBundleName === '__back_domain__') {\n activeDomain = undefined;\n continue;\n }\n\n const bundle = await registry.getBundle(selectedBundleName);\n if (!bundle) continue;\n\n // Stage 3: Render Open Tree View & Handle Action\n const action = await handleBundleDetailView(bundle);\n if (action === '__exit__') {\n outro(pc.cyan('Catalog explorer closed.'));\n return;\n }\n if (action === '__back_dept__') {\n activeDomain = undefined;\n }\n // If action === '__back_bundle__', stays in activeDomain loop\n }\n });\n\ncli\n .command('find [query]', 'Search for agents, skills, workflows, or bundles in the registry')\n .alias('search')\n .option('-c, --category <domain>', 'Filter search by domain (e.g. engineering, architecture, design)')\n .option('-t, --type <type>', 'Filter by item type (bundle, agent, skill, workflow)')\n .option('--json', 'Output results in JSON format')\n .option('-i, --interactive', 'Interactive selection to install matching item')\n .action(async (query?: string, options: any = {}) => {\n const q = query || '';\n const results = await registry.find(q, {\n domain: options.category || options.domain,\n type: options.type,\n });\n\n if (options.json) {\n console.log(JSON.stringify(results, null, 2));\n return;\n }\n\n const totalCount =\n results.bundles.length + results.agents.length + results.skills.length + results.workflows.length;\n\n intro(pc.cyan(`Agents United - Search Results: \"${q || '*'}\" (${totalCount} found)`));\n\n if (results.bundles.length > 0) {\n console.log(pc.bold(`\\n📦 Bundles (${results.bundles.length}):`));\n results.bundles.forEach((b: BundleDefinition) => {\n const meta = BUNDLE_DISPLAY_NAMES[b.name];\n console.log(` - ${pc.green(pc.bold(b.name))}: ${pc.white(meta?.title || b.name)} — ${pc.dim(b.description)}`);\n });\n }\n\n if (results.agents.length > 0) {\n console.log(pc.bold(`\\n🤖 Agents (${results.agents.length}):`));\n results.agents.forEach((a: string) => {\n const stem = a.replace(/\\.md$/, '');\n console.log(` - ${pc.blue(stem)} ${pc.gray(`(${a})`)}`);\n });\n }\n\n if (results.skills.length > 0) {\n console.log(pc.bold(`\\n⚡ Skills (${results.skills.length}):`));\n results.skills.forEach((s: string) => console.log(` - ${pc.yellow(s)}`));\n }\n\n if (results.workflows.length > 0) {\n console.log(pc.bold(`\\n🔄 Workflows (${results.workflows.length}):`));\n results.workflows.forEach((w: string) => {\n const stem = w.replace(/\\.md$/, '');\n console.log(` - ${pc.magenta(stem)} ${pc.gray(`(${w})`)}`);\n });\n }\n\n if (totalCount === 0) {\n console.log(pc.yellow(`\\nNo matching items found for \"${q}\". Try searching without filters or using \"agents list\".`));\n }\n\n if (options.interactive && totalCount > 0) {\n const items: Array<{ value: string; label: string }> = [\n ...results.bundles.map((b: BundleDefinition) => ({ value: b.name, label: `[Bundle] ${b.name} — ${b.description}` })),\n ...results.agents.map((a: string) => ({ value: a.replace(/\\.md$/, ''), label: `[Agent] ${a}` })),\n ...results.skills.map((s: string) => ({ value: s, label: `[Skill] ${s}` })),\n ...results.workflows.map((w: string) => ({ value: w.replace(/\\.md$/, ''), label: `[Workflow] ${w}` })),\n ];\n\n const selected = await select({\n message: 'Select an item to install:',\n options: items,\n });\n\n if (typeof selected === 'string') {\n const s = spinner();\n s.start(`Installing \"${selected}\"...`);\n try {\n const res = await installer.install(selected, { scope: 'project' });\n s.stop(`Installed ${selected}`);\n outro(pc.green(`✔ Successfully installed \"${selected}\"!`));\n } catch (err: any) {\n s.stop(pc.red('Installation failed'));\n outro(pc.red(`Error: ${err.message}`));\n }\n return;\n }\n }\n\n outro(pc.cyan('\\nUse \"agents add <name>\" to install any match.'));\n });\n\ncli\n .command('init', 'Initialize project workspace directory and install recommended bundle')\n .option('-b, --bundle <bundle>', 'Default bundle to install', { default: 'software-engineering' })\n .option('-s, --symlink', 'Use symlinks (default / recommended)')\n .option('--copy', 'Use standalone copies')\n .option('-t, --target <hosts>', 'Target agent hosts', { default: 'agents' })\n .action(async (options: any) => {\n intro(pc.cyan('Agents United - Initialize Workspace'));\n const s = spinner();\n s.start(`Initializing workspace with bundle \"${options.bundle}\"...`);\n\n try {\n const initTargets = (Array.isArray(options.target) ? options.target : splitHostList(String(options.target || 'agents')))\n .map((h: string) => h.trim().toLowerCase());\n const initPlan = planInstallTargets(initTargets);\n const result = await installer.install(options.bundle, {\n scope: 'project',\n symlink: options.symlink,\n copy: options.copy,\n hosts: initPlan.hosts,\n fanout: initPlan.fanout,\n });\n s.stop(`Initialized ${result.targetDirs.join(', ')}`);\n outro(pc.green(`✔ Initialized workspace with \"${options.bundle}\" bundle!`));\n } catch (err: any) {\n s.stop(pc.red('Initialization failed'));\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('start <bundle> [prompt]', 'Start an installed bundle team in its host runtime (e.g. Cline, Claude Code)')\n .option('--host <host>', 'Host runtime (default: auto-detect from lockfile fanout)')\n .option('-g, --global', 'Select global installation')\n .option('--team <name>', 'Override generated team name')\n .option('--allow-addons', 'Pre-authorize recommended addon installations for this session')\n .option('--headless', 'Run non-interactively without interactive TUI')\n .option('--bg', 'Run the Claude Code session in the background (claude host only)')\n .option('--teams', 'Force the experimental agent-teams scaffold on (claude host only). Default: ON for organization-tier (Tier 2) bundles, OFF for domain-tier (Tier 1) bundles — pass --no-teams to opt out. Ephemeral env only, nothing persisted')\n .option('--plugin', 'Pass --plugin-dir with the bundle plugin root (claude host only)')\n .option('--dry-run', 'Print activation resolution and argv summary without launching')\n .action(async (bundle: string, prompt?: string, options: any = {}) => {\n intro(pc.cyan('Agents United — Runtime Activation'));\n\n const launcher = new ClineLauncher();\n const probe = new ClineCapabilityProbe();\n\n try {\n // ADR 0018 / Plan 016 (Step 6) + Plan 029 (Step 3): an explicit --host wins; otherwise inherit\n // the host recorded in the lockfile for the resolved scope/workspace. Plan 029 removed the\n // silent Cline fallback: a host with no launcher is reported honestly, and the Cline lane is\n // reachable only when Cline is the resolved host (explicit `--host cline` or a cline fanout).\n const effectiveHost = await resolveStartHost(bundle, options);\n if (effectiveHost === 'claude') {\n await runClaudeStart(bundle, prompt, options);\n return;\n }\n if (effectiveHost === 'antigravity') {\n await runAntigravityStart(bundle, prompt, options);\n return;\n }\n if (effectiveHost === 'unsupported') {\n note(\n pc.yellow(\n `Host '${options.host}' has no activation launcher. Launcher-capable lanes: claude, antigravity, cline.\\n` +\n `Re-run with --host claude|antigravity|cline to choose one explicitly.`\n ),\n 'Host Runtime'\n );\n outro(pc.yellow('No session launched.'));\n return;\n }\n const resolution = await launcher.resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n\n const probeReport = await probe.probe();\n if (!probeReport.installed && !options.dryRun) {\n outro(pc.red(`Cline executable was not found on PATH or via CLINE_BIN_PATH. Please install Cline CLI or ensure it is accessible.`));\n process.exit(1);\n }\n\n const bundleDef = await registry.getBundle(bundle);\n // Plan 016 post-gate: Tier 2 (organization) is a *Claude-runtime* posture. Agent Teams is a Claude\n // Code feature behind CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, so this lane reports the tier instead of\n // half-applying it — nothing here changes argv, and the session keeps Cline's own strategy with the\n // projected specialist tools under `.cline/agents/`. `--teams` on this host is a no-op by design.\n const organizationTier = bundleDef?.tier === 'organization';\n const plan = launcher.planActivation({\n bundleName: bundle,\n workspace: resolution.workspace,\n scope: resolution.scope,\n report: probeReport,\n prompt,\n teamName: options.team,\n allowAddons: options.allowAddons,\n headless: options.headless,\n orchestrator: bundleDef?.orchestrator,\n });\n\n if (options.dryRun) {\n note(\n `Bundle: ${plan.bundleName}\\n` +\n `Tier: ${bundleDef?.tier ?? 'not declared (Tier-1 domain default)'}\\n` +\n `Agent teams: ${organizationTier ? 'not available on this host (claude-only runtime feature)' : 'no'}\\n` +\n `Scope: ${plan.scope}\\n` +\n `Workspace: ${plan.workspace}\\n` +\n `Team Name: ${plan.teamName}\\n` +\n `Strategy: ${plan.strategy}\\n` +\n `Executable: ${plan.executable}\\n` +\n `Argv: ${plan.argv.map(a => (a.includes(' ') || a.includes('\\n') ? `\"${a.replace(/\\n/g, '\\\\n')}\"` : a)).join(' ')}`,\n 'Activation Plan (dry run)'\n );\n outro(pc.yellow('Dry run complete. No processes launched.'));\n return;\n }\n\n if (organizationTier) {\n note(\n pc.yellow(\n `\"${bundle}\" is an organization-tier (Tier 2) bundle. Agent Teams is a Claude Code runtime\\n` +\n `feature and is not available on this host, so '--teams' is claude-only. This session runs\\n` +\n `Cline's ${plan.strategy} strategy with the projected specialist tools under .cline/agents/.`\n ),\n 'Tier 2 (organization)'\n );\n }\n\n note(\n `Team: ${pc.bold(plan.teamName)}\\n` +\n `Strategy: ${pc.cyan(plan.strategy)}\\n` +\n `Workspace: ${plan.workspace}`,\n 'Starting Cline Team'\n );\n\n await launcher.launch(plan);\n outro(pc.green(`✔ Cline session finished.`));\n } catch (err: any) {\n outro(pc.red(`Error: ${err.message}`));\n process.exit(1);\n }\n });\n\ncli\n .command('doctor', 'Verify health of installed agents, frontmatter schemas, and hooks')\n .option('--host <host>', 'Audit specific host runtime (e.g. cline, claude)')\n .action(async (options: any = {}) => {\n intro(pc.cyan('🩺 Agents United — Health Doctor'));\n const report = await DoctorEngine.runDoctor(undefined, options.host);\n\n if (!report.isInitialized || (report.agentsCount === 0 && report.skillsCount === 0 && report.workflowsCount === 0 && report.issues.length === 0)) {\n console.log(` ${pc.bold('📦 Status:')} ${pc.yellow('No agents or bundles installed in this workspace.')}`);\n console.log(` ${pc.bold('📍 Location:')} ${pc.dim(report.targetDir)}\\n`);\n\n console.log(pc.bold(pc.cyan('💡 Get Started:')));\n console.log(` 👉 ${pc.bold('agents add')} Launch the interactive installation wizard`);\n console.log(` 👉 ${pc.bold('agents add software-engineering')} Install the engineering essentials team`);\n const bundleCount = (await registry.listBundles()).length;\n console.log(` 👉 ${pc.bold('agents list')} Browse all ${bundleCount} bundles by department\\n`);\n\n if (report.clineCapability) {\n console.log(pc.bold(pc.cyan('Cline Runtime & Native Discovery Audit:')));\n console.log(` Installed: ${report.clineCapability.installed ? pc.green('✔ Detected') : pc.yellow('✖ Not Found')}`);\n if (report.clineCapability.version) {\n console.log(` Version: ${report.clineCapability.version}`);\n }\n console.log(` Named Teams: ${report.clineCapability.namedTeams ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported (Adaptive fallback)')}\\n`);\n }\n\n if (report.claudeCapability) {\n renderClaudeCapabilityBlock(report.claudeCapability);\n for (const diagnostic of report.claudeCapability.diagnostics) {\n console.log(` ${pc.dim(diagnostic)}`);\n }\n console.log();\n }\n\n if (report.warnings.length > 0) {\n console.log(pc.yellow(pc.bold('⚠️ Warnings:')));\n report.warnings.forEach(w => console.log(` ⚠ ${w}`));\n console.log();\n }\n\n printDeclaredDeltas(report, options.host);\n\n outro(pc.blue('✨ Workspace is ready for initialization.'));\n return;\n }\n\n console.log(` 🤖 Installed Agents: ${pc.bold(report.agentsCount.toString())}`);\n console.log(` ⚡ Installed Skills: ${pc.bold(report.skillsCount.toString())}`);\n console.log(` 🔄 Installed Workflow Skills: ${pc.bold(report.workflowsCount.toString())}\\n`);\n // Plan 023 A — plain-session guard state (only when a decision was ever recorded).\n if (report.sessionGuard) {\n const label: Record<string, string> = {\n wired: pc.green('✔ Wired (plain Claude sessions guarded)'),\n off: pc.dim('Off (declined)'),\n missing: pc.yellow('✖ Missing — run agents update'),\n modified: pc.yellow('⚠ Edited by hand — left as-is'),\n 'skipped-invalid': pc.yellow('⚠ Not wired — settings file is not valid JSON (see warning)'),\n };\n console.log(` 🛡 Session Guard: ${label[report.sessionGuard]}\\n`);\n }\n // Plan 024 S4 — command-permission preset state (only when a decision was ever recorded).\n if (report.permissionPreset) {\n const label: Record<string, string> = {\n wired: pc.green('✔ Wired (npm test/tsc/vitest/eslint pre-approved)'),\n off: pc.dim('Off (declined)'),\n missing: pc.yellow('✖ Missing or partially removed — run agents update'),\n 'skipped-invalid': pc.yellow('⚠ Not wired — settings.local.json is not valid JSON (see warning)'),\n };\n console.log(` 🔑 Permission Preset: ${label[report.permissionPreset]}\\n`);\n }\n\n if (report.clineCapability) {\n console.log(pc.bold(pc.cyan('Cline Runtime & Native Discovery Audit:')));\n console.log(` Installed: ${report.clineCapability.installed ? pc.green('✔ Detected') : pc.yellow('✖ Not Found')}`);\n if (report.clineCapability.version) {\n console.log(` Version: ${report.clineCapability.version}`);\n }\n console.log(` Named Teams: ${report.clineCapability.namedTeams ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported (Adaptive fallback)')}`);\n console.log(` Configured Agents: ${report.agentsCount} active natively in any Cline session (\"agents start\" = optional team-session launcher)\\n`);\n }\n\n if (report.claudeCapability) {\n renderClaudeCapabilityBlock(report.claudeCapability);\n console.log(` Configured Agents: ${report.agentsCount} projected into .claude/agents/ (\"agents start --host claude\" = optional launcher)\\n`);\n }\n\n if (report.issues.length > 0) {\n console.log(pc.red(pc.bold('❌ Issues Found:')));\n report.issues.forEach(i => console.log(` ✖ ${i}`));\n console.log();\n }\n\n if (report.warnings.length > 0) {\n console.log(pc.yellow(pc.bold('⚠️ Warnings:')));\n report.warnings.forEach(w => console.log(` ⚠ ${w}`));\n console.log();\n }\n\n printDeclaredDeltas(report, options.host);\n\n if (report.valid && report.issues.length === 0) {\n outro(pc.green('✔ All installed agents and frontmatter schemas are healthy!'));\n } else {\n outro(pc.red('✖ Doctor found issues in workspace configuration.'));\n process.exit(1);\n }\n });\n\n/**\n * Plan 016 (Step 6) + Plan 029 (Step 3) — resolve the activation host for `agents start`.\n *\n * - an explicit `--host` wins: `claude`, `cline`, `antigravity` (also the `agents` / `gemini` ids,\n * whose `HOST_REGISTRY` entry carries the `antigravity` projection PROFILE — there is no\n * `antigravity` host key), anything else has no launcher and is reported as `unsupported`;\n * - otherwise the host recorded in the lockfile for the resolved scope/workspace is inherited,\n * so a claude fanout activates the Claude lane, a cline install keeps the Cline lane, and an\n * install whose only host is the canonical `.agents/` store (the Antigravity profile) activates\n * the Antigravity lane.\n *\n * Detection is deliberately best-effort: any resolution error (bundle not installed, not projected)\n * yields no signal, and the selected lane then reports its own actionable error exactly as before.\n * Plan 029 removed the silent Cline fallback: `unsupported` never launches another host's lane.\n */\nasync function resolveStartHost(\n bundle: string,\n options: { host?: string; global?: boolean }\n): Promise<'cline' | 'claude' | 'antigravity' | 'unsupported'> {\n const explicitHost = typeof options.host === 'string' ? options.host.trim().toLowerCase() : '';\n if (explicitHost === 'claude') {\n return 'claude';\n }\n if (explicitHost === 'cline') {\n return 'cline';\n }\n if (explicitHost.length > 0) {\n if (explicitHost === 'antigravity') {\n return 'antigravity';\n }\n // `agents` (canonical store) and `gemini` (legacy Antigravity) carry the antigravity profile.\n if (isKnownHost(explicitHost) && HOST_REGISTRY[explicitHost].profile === 'antigravity') {\n return 'antigravity';\n }\n return 'unsupported';\n }\n\n let recordedHosts: string[] = [];\n let recordedFanout: string[] = [];\n try {\n const detection = await new AntigravityLauncher().resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n recordedHosts = detection.lockfile.hosts || [];\n recordedFanout = detection.lockfile.fanout || [];\n } catch {\n recordedHosts = [];\n recordedFanout = [];\n }\n\n if (recordedFanout.includes('claude')) return 'claude';\n if (recordedHosts.includes('cline') || recordedFanout.includes('cline')) return 'cline';\n const isAntigravityProfile = (host: string): boolean =>\n isKnownHost(host) && HOST_REGISTRY[host].profile === 'antigravity';\n if (recordedHosts.length > 0 && recordedHosts.every(isAntigravityProfile)) return 'antigravity';\n\n // No unambiguous signal: keep the historical Cline lane, which reports its own actionable error.\n return 'cline';\n}\n\n/**\n * Plan 029 (Step 3) / Objectives 6–7 — the Antigravity lane for `agents start --host antigravity`.\n *\n * Three behaviours are load-bearing:\n * 1. `--dry-run` prints bundle / tier / scope / workspace / executable / argv and launches nothing;\n * 2. when `agy` cannot be resolved, the desktop route is printed (open the workspace in Antigravity\n * and @-mention the canonical coordinator file) and the command exits 0 having launched NOTHING —\n * it never falls through to another host's lane;\n * 3. the session is spawned from an argv array with `shell: false` by `AntigravityLauncher`.\n */\nasync function runAntigravityStart(bundle: string, prompt: string | undefined, options: any): Promise<void> {\n const launcher = new AntigravityLauncher();\n const probe = new AntigravityCapabilityProbe();\n\n const resolution = await launcher.resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n\n const bundleDef = await registry.getBundle(bundle);\n // The canonical coordinator file the `--agent` value names and the desktop route @-mentions.\n const coordinatorName = AntigravityLauncher.resolveCoordinatorName(bundleDef?.orchestrator);\n const coordinatorRel = path.posix.join('.agents', 'agents', `${coordinatorName}.md`);\n\n const probeReport = await probe.probe();\n\n if (!probeReport.installed) {\n note(\n pc.yellow(\n `Host: ${pc.cyan('antigravity')} — the agy CLI was not found on PATH or via AGY_BIN_PATH.\\n\\n` +\n `Desktop route (nothing was launched):\\n` +\n ` 1. Open this workspace in the Antigravity app.\\n` +\n ` 2. @-mention the coordinator definition: ${pc.bold(coordinatorRel)}\\n\\n` +\n `To use the CLI lane instead, install agy / put it on PATH, or set AGY_BIN_PATH.`\n ),\n 'Antigravity (desktop route)'\n );\n outro(pc.yellow('No session launched.'));\n return;\n }\n\n const plan = launcher.planActivation({\n bundleName: bundle,\n workspace: resolution.workspace,\n scope: resolution.scope,\n report: probeReport,\n prompt,\n orchestrator: bundleDef?.orchestrator,\n });\n\n if (options.dryRun) {\n note(\n `Bundle: ${plan.bundleName}\\n` +\n `Tier: ${bundleDef?.tier ?? 'not declared (Tier-1 domain default)'}\\n` +\n `Scope: ${plan.scope}\\n` +\n `Workspace: ${plan.workspace}\\n` +\n `Executable: ${plan.executable}\\n` +\n `Argv: ${plan.argv.map(a => (a.includes(' ') || a.includes('\\n') ? `\"${a.replace(/\\n/g, '\\\\n')}\"` : a)).join(' ')}`,\n 'Antigravity Activation Plan (dry run)'\n );\n outro(pc.yellow('Dry run complete. No processes launched.'));\n return;\n }\n\n // Plan 029 follow-up (owner gate-6: agy ≥1.2.13): workspace agents may live in the directory\n // layout (`.agents/agents/<name>/agent.md`), not only as flat `.agents/agents/<name>.md`\n // files. Accept either before spawning, so the check reflects what agy can discover.\n const coordinatorDirEntry = path.join(resolution.workspace, '.agents', 'agents', coordinatorName, 'agent.md');\n const coordinatorPath = path.join(resolution.workspace, '.agents', 'agents', `${coordinatorName}.md`);\n const coordinatorFound = (await fs.pathExists(coordinatorPath)) || (await fs.pathExists(coordinatorDirEntry));\n if (!coordinatorFound) {\n outro(\n pc.red(\n `Canonical coordinator \"${coordinatorRel}\" was not found in ${resolution.workspace}.\\n` +\n `Run 'agents add ${bundle}' before starting an Antigravity session.`\n )\n );\n process.exit(1);\n }\n\n if (!probeReport.promptInteractive) {\n // Honest capability reporting: the flag is passed regardless (dropping the user's task silently\n // would be worse), but an unverified surface is never presented as verified.\n note(\n pc.yellow('The capability probe could not confirm --prompt-interactive from `agy --help`; the opening prompt is still passed as a single argv element.'),\n 'Antigravity CLI'\n );\n }\n\n note(\n `Host: ${pc.cyan('antigravity')}\\n` +\n `Executable: ${plan.executable}\\n` +\n `Workspace: ${plan.workspace}\\n` +\n `Agent: ${coordinatorName}`,\n 'Starting Antigravity Session'\n );\n\n await launcher.launch(plan);\n outro(pc.green(`✔ Antigravity session finished.`));\n}\n\n/** Why the Agent-Teams scaffold is on or off for a Claude session. */\nexport type ClaudeTeamsReason = 'explicit' | 'tier-default' | 'opt-out' | 'domain-tier' | 'unresolved-tier';\n\nexport interface ClaudeTeamsPosture {\n /** Whether the ephemeral agent-teams scaffold will be injected into the spawned session. */\n active: boolean;\n reason: ClaudeTeamsReason;\n /** The resolved bundle tier that drove the decision, when the bundle could be resolved. */\n tier?: BundleTier;\n}\n\n/**\n * Tier-aware Agent-Teams posture for `agents start --host claude` (Plan 016 decision 14 + the Tier-1/Tier-2\n * split recorded in CONTEXT.md).\n *\n * - Tier 1 (`tier: 'domain'`) is a single-discipline hub-and-spoke team, so it keeps the ordinary\n * parallel-subagent model: teams stay opt-in via `--teams`.\n * - Tier 2 (`tier: 'organization'`) is cross-functional by construction, so it runs with Agent Teams logic\n * by default. `--no-teams` (cac parses it into `options.teams === false`) is the explicit opt-out and\n * always wins over the tier default.\n *\n * Pure and exported so the `--dry-run` plan and the tests can assert the decision without spawning `claude`.\n */\nexport function resolveClaudeTeamsPosture(\n teamsOption: boolean | undefined,\n tier: BundleTier | undefined\n): ClaudeTeamsPosture {\n if (teamsOption === true) return { active: true, reason: 'explicit', tier };\n if (teamsOption === false) return { active: false, reason: 'opt-out', tier };\n if (tier === 'organization') return { active: true, reason: 'tier-default', tier };\n if (tier === 'domain') return { active: false, reason: 'domain-tier', tier };\n return { active: false, reason: 'unresolved-tier' };\n}\n\n/** One-line, honest explanation of why teams is on or off — shared by the live notice and `--dry-run`. */\nexport function describeClaudeTeamsPosture(posture: ClaudeTeamsPosture): string {\n switch (posture.reason) {\n case 'explicit':\n return 'explicit --teams';\n case 'tier-default':\n return \"default for tier 'organization'\";\n case 'opt-out':\n return '--no-teams opt-out';\n case 'domain-tier':\n return \"tier 'domain' — pass --teams to enable\";\n case 'unresolved-tier':\n return 'no declared tier (Tier-1 domain default) — pass --teams to enable';\n }\n}\n\n/**\n * Plan 016 (Step 6) — the Claude Code lane for `agents start --host claude`.\n *\n * `--dry-run` prints the full plan (one argv element per line, plus the active flags and the env keys that\n * would be injected) and returns without spawning anything or writing anything to disk. A real session\n * spawns `claude` with `shell: false` and the ephemeral env merged over `process.env`; the teams opt-in is\n * never persisted (no settings.json write, nothing under `~/.claude/`).\n *\n * Teams posture is tier-derived (`resolveClaudeTeamsPosture`): an organization-tier (Tier 2) bundle enables\n * Agent Teams by default, a domain-tier (Tier 1) bundle only with an explicit `--teams`, and `--no-teams`\n * always wins over the tier default.\n */\nasync function runClaudeStart(bundle: string, prompt: string | undefined, options: any): Promise<void> {\n const launcher = new ClaudeLauncher();\n const probe = new ClaudeCapabilityProbe();\n\n const resolution = await launcher.resolveInstallation(bundle, {\n global: options.global,\n cwd: process.cwd(),\n });\n\n const probeReport = await probe.probe();\n if (!probeReport.installed && !options.dryRun) {\n outro(pc.red(`Claude Code executable was not found on PATH or via CLAUDE_BIN_PATH. Please install Claude Code or ensure it is accessible.`));\n process.exit(1);\n }\n\n const bundleDef = await registry.getBundle(bundle);\n // Tier-aware Agent-Teams posture: an organization-tier (Tier 2) bundle runs with Agent Teams logic by\n // default, a domain-tier (Tier 1) bundle keeps the ordinary parallel-subagent model unless `--teams`,\n // and an explicit `--no-teams` always wins (Plan 016 decision 14).\n const teamsPosture = resolveClaudeTeamsPosture(options.teams, bundleDef?.tier);\n const teamsActive = teamsPosture.active;\n // ADR 0018 decision 6 keeps ONE host-neutral team manifest under the organization package, which\n // the Cline half of the compound lane writes. A claude-only fanout has none, so the prompt must\n // not order the coordinator to read a path that does not exist.\n const manifestAvailable = await fs.pathExists(resolution.manifestPath);\n // `--plugin` points Claude at the bundle's plugin root. The path is workspace-relative because the session\n // is spawned with `cwd: workspace`; Step 7 emits the plugin manifest inside it.\n const pluginDir = options.plugin\n ? path.join('.agents', 'plugins', bundle).split(path.sep).join('/')\n : undefined;\n\n const plan = launcher.planActivation({\n bundleName: bundle,\n workspace: resolution.workspace,\n scope: resolution.scope,\n report: probeReport,\n prompt,\n orchestrator: bundleDef?.orchestrator,\n allowAddons: options.allowAddons,\n background: options.bg,\n teams: teamsActive,\n pluginDir,\n manifestAvailable,\n });\n\n const recordedFanout = resolution.lockfile.fanout || [];\n\n if (options.dryRun) {\n note(renderClaudeActivationPlan(plan, probeReport, recordedFanout, teamsPosture), 'Claude Activation Plan (dry run)');\n outro(pc.yellow('Dry run complete. No processes launched.'));\n return;\n }\n\n if (!recordedFanout.includes('claude')) {\n note(\n pc.yellow(\n `This workspace records fanout [${recordedFanout.join(', ') || 'none'}]. Run\\n` +\n `'agents update ${bundle} --fanout claude' to project .claude/agents/ before the session needs it.`\n ),\n 'Claude Projection'\n );\n }\n if (teamsActive && teamsPosture.reason === 'tier-default') {\n note(\n pc.yellow(\n `Agent Teams is ON by default for this organization-tier bundle (tier 'organization').\\n` +\n `--no-teams falls back to ordinary parallel subagents.`\n ),\n 'Agent Teams'\n );\n } else if (teamsActive) {\n note(pc.cyan('Agent Teams explicitly requested with --teams; the scaffold stays experimental.'), 'Agent Teams');\n }\n if (teamsActive && !probeReport.agentTeamsExperimental) {\n note(pc.yellow('The capability probe could not confirm agent-team support from --help; the scaffold stays experimental and unverified.'), 'Agent Teams');\n }\n if (pluginDir && !probeReport.pluginSupport) {\n note(pc.yellow('The capability probe could not confirm --plugin-dir support from --help.'), 'Plugin Dir');\n }\n\n note(\n `Host: ${pc.cyan('claude')}\\n` +\n `Executable: ${plan.executable}\\n` +\n `Workspace: ${plan.workspace}\\n` +\n `Background: ${options.bg ? 'yes (--bg)' : 'no'}\\n` +\n `Teams scaffold: ${teamsActive ? `yes (${describeClaudeTeamsPosture(teamsPosture)}; experimental, ephemeral env only)` : `no (${describeClaudeTeamsPosture(teamsPosture)})`}\\n` +\n `Plugin dir: ${pluginDir || '(none)'}`,\n 'Starting Claude Code Session'\n );\n\n // ADR 0018 decision 3: a main-thread `--agent` session is bounded by the projected coordinator\n // definition's `Agent(...)` allowlist, so that file must exist for the session to be meaningful.\n // `resolveInstallation` accepts either a recorded claude fanout OR the host-neutral manifest, and\n // the manifest is a Cline artifact — so a cline-only workspace can pass the gate. Fail loudly here\n // rather than spawning a session whose `--agent` target does not exist.\n const coordinatorRel = `.claude/agents/${ClaudeLauncher.resolveCoordinatorName(bundleDef?.orchestrator)}.md`;\n if (!await fs.pathExists(path.join(resolution.workspace, coordinatorRel))) {\n outro(\n pc.red(\n `Claude projection \"${coordinatorRel}\" was not found in ${resolution.workspace}.\\n` +\n `Run 'agents update ${bundle} --fanout claude' before starting an --agent session.`\n )\n );\n process.exit(1);\n }\n\n\n await launcher.launch(plan);\n outro(pc.green(`✔ Claude Code session finished.`));\n}\n\n/**\n * Shared Claude capability block for `agents doctor`.\n *\n * `cli.ts` prints this twice — once on the empty-workspace early exit and once in the main report — and the\n * duplication already drifted once (a capability line landed in one branch only). Both call sites share this\n * renderer so a new capability is reported everywhere.\n */\nfunction renderClaudeCapabilityBlock(capability: ClaudeCapabilityReport): void {\n console.log(pc.bold(pc.cyan('Claude Code Runtime & Native Discovery Audit:')));\n console.log(` Installed: ${capability.installed ? pc.green('✔ Detected') : pc.yellow('✖ Not Found')}`);\n if (capability.version) {\n console.log(` Version: ${capability.version}`);\n }\n console.log(` Plugin Support (--plugin-dir): ${capability.pluginSupport ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported')}`);\n console.log(` Agent Teams (experimental): ${capability.agentTeamsExperimental ? pc.green('✔ Supported') : pc.yellow('✖ Unsupported')}`);\n console.log(` Subagent hand-off (SubagentHandback): ${capability.subagentHandback ? pc.green('✔ Supported') : pc.yellow('✖ Needs v2.1.271+ (auto mode)')}`);\n}\n\n/**\n * Plan 026 Objective 3 — print the Declared-Delta Registry section for `agents doctor --host\n * <h>`: what this host does not carry over from the canonical roster, in plain words, sourced\n * from `registry/translation-ledger.json` (docs/host-primitive-matrix.md is its prose form).\n * A silent `undefined` (no `--host`, or a host the registry has no entries for) prints nothing.\n */\nfunction printDeclaredDeltas(report: HealthReport, host: string | undefined): void {\n if (!report.declaredDeltas || report.declaredDeltas.length === 0) return;\n console.log(pc.bold(pc.cyan(`Declared Deltas for --host ${host} (docs/host-primitive-matrix.md):`)));\n for (const delta of report.declaredDeltas) {\n const tag = delta.disposition === 'unsupported' ? pc.red('unsupported') : pc.yellow('degraded');\n console.log(` • ${pc.bold(delta.feature)} (${tag}): ${delta.rationale}`);\n }\n console.log();\n}\n\n/** Render the `--dry-run` Claude plan: one argv element per line so each flag/value pair is unambiguous. */\nfunction renderClaudeActivationPlan(\n plan: ClaudeActivationPlan,\n report: ClaudeCapabilityReport,\n recordedFanout: string[],\n posture: ClaudeTeamsPosture\n): string {\n const envEntries = Object.keys(plan.env);\n const pluginFlagIndex = plan.argv.indexOf('--plugin-dir');\n const teamsActive = envEntries.includes('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS');\n return [\n `Bundle: ${plan.bundleName}`,\n `Host: claude`,\n `Bundle tier: ${posture.tier ?? \"not declared (Tier-1 'domain' default)\"}`,\n `Scope: ${plan.scope}`,\n `Workspace: ${plan.workspace}`,\n `Executable: ${plan.executable}`,\n `Background (--bg): ${plan.argv.includes('--bg') ? 'yes' : 'no'}`,\n teamsActive\n ? `Agent teams (--teams): yes (${describeClaudeTeamsPosture(posture)} — experimental; ephemeral env only, nothing persisted)`\n : `Agent teams (--teams): no (${describeClaudeTeamsPosture(posture)})`,\n `Plugin (--plugin-dir): ${pluginFlagIndex >= 0 ? plan.argv[pluginFlagIndex + 1] : '(none)'}`,\n `Env injected (merged over process.env): ${envEntries.length > 0 ? envEntries.map((k) => `${k}=${plan.env[k]}`).join(', ') : '(none)'}`,\n `Capability probe: installed=${report.installed ? `yes${report.version ? ` (${report.version})` : ''}` : 'no'}, --plugin-dir=${report.pluginSupport ? 'yes' : 'no'}, agent teams=${report.agentTeamsExperimental ? 'yes' : 'no'}, subagent handback=${report.subagentHandback ? 'yes' : 'no'}`,\n `Recorded fanout: [${recordedFanout.join(', ')}]`,\n `Argv (${plan.argv.length} elements, one element per line, spawned with shell: false):`,\n ...plan.argv.map((arg, index) => ` [${index}] ${arg.replace(/\\r?\\n/g, '\\\\n')}`),\n ].join('\\n');\n}\n\ncli.help();\ncli.version('1.0.0');\n\ncli.parse();\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport yaml from 'yaml';\nimport { fileURLToPath } from 'node:url';\nimport type { BundlesManifest, BundleDefinition, ResolvedAssets, SearchOptions, SearchResults, PlanningLoopMode } from './types.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport class RegistryResolver {\n /**\n * Host entrypoint rules (Plan 015 §0/C7). `GEMINI.md` is always resolved so\n * Antigravity-family hosts keep their entrypoint; it is never declared in an\n * agent's frontmatter.\n */\n private static readonly BASELINE_RULES = ['GEMINI.md'];\n\n private registryDir: string;\n private bundlesManifest: BundlesManifest | null = null;\n /** Memoized agent file -> declared rules (Plan 015 §0/C6). */\n private agentRuleCache = new Map<string, string[]>();\n\n constructor(customRegistryDir?: string) {\n if (customRegistryDir) {\n this.registryDir = path.resolve(customRegistryDir);\n } else {\n // Check candidate paths for registry folder\n const candidatePaths = [\n path.resolve(__dirname, '../registry'),\n path.resolve(__dirname, '../../registry'),\n path.resolve(process.cwd(), 'registry'),\n ];\n\n const found = candidatePaths.find(p => fs.existsSync(path.join(p, 'bundles.json')));\n this.registryDir = found || candidatePaths[0];\n }\n }\n\n public getRegistryDir(): string {\n return this.registryDir;\n }\n\n public async loadBundles(): Promise<BundlesManifest> {\n if (this.bundlesManifest) {\n return this.bundlesManifest;\n }\n\n const manifestPath = path.join(this.registryDir, 'bundles.json');\n if (!await fs.pathExists(manifestPath)) {\n throw new Error(`Registry bundles.json not found at ${manifestPath}`);\n }\n\n this.bundlesManifest = await fs.readJson(manifestPath);\n this.validateBundles(this.bundlesManifest!);\n return this.bundlesManifest!;\n }\n\n public async getBundle(bundleName: string): Promise<BundleDefinition | null> {\n const manifest = await this.loadBundles();\n if (manifest.bundles[bundleName]) {\n return manifest.bundles[bundleName];\n }\n const found = Object.values(manifest.bundles).find(\n b => b.aliases?.includes(bundleName)\n );\n return found || null;\n }\n\n public async listBundles(): Promise<BundleDefinition[]> {\n const manifest = await this.loadBundles();\n return Object.values(manifest.bundles);\n }\n\n public async getBundlesByDomain(domain: string): Promise<BundleDefinition[]> {\n const manifest = await this.loadBundles();\n const d = domain.toLowerCase();\n return Object.values(manifest.bundles).filter(b => b.domain?.toLowerCase() === d);\n }\n\n public async resolve(identifier: string): Promise<ResolvedAssets> {\n // Check if identifier refers to an entire department domain (e.g. \"domain:engineering\")\n if (identifier.startsWith('domain:')) {\n const domainName = identifier.replace(/^domain:/, '').toLowerCase();\n const domainBundles = await this.getBundlesByDomain(domainName);\n if (domainBundles.length > 0) {\n const agents = new Set<string>();\n const skills = new Set<string>();\n const workflows = new Set<string>();\n const rules = new Set<string>(RegistryResolver.BASELINE_RULES);\n\n for (const b of domainBundles) {\n const resolved = await this.resolve(b.name);\n resolved.agents.forEach(a => agents.add(a));\n resolved.skills.forEach(s => skills.add(s));\n resolved.workflows.forEach(w => workflows.add(w));\n resolved.rules.forEach(r => rules.add(r));\n }\n\n return {\n targetBundle: `domain:${domainName}`,\n agents: Array.from(agents),\n skills: Array.from(skills),\n workflows: Array.from(workflows),\n rules: Array.from(rules).sort(),\n };\n }\n }\n\n const bundle = await this.getBundle(identifier);\n\n if (bundle) {\n const agents = new Set<string>();\n const skills = new Set<string>(bundle.skills || []);\n const workflows = new Set<string>(bundle.workflows || []);\n const rules = new Set<string>(RegistryResolver.BASELINE_RULES);\n\n // Forward-compatible only: no bundle in registry/bundles.json declares\n // `rules` today (verified: 0 occurrences); the type allows it (types.ts:369).\n (bundle.rules || []).forEach(r => rules.add(r));\n\n if (bundle.parentBundle) {\n const parent = await this.getBundle(bundle.parentBundle);\n if (parent) {\n if (parent.orchestrator) agents.add(parent.orchestrator);\n if (parent.agents) parent.agents.forEach(a => agents.add(a));\n if (parent.skills) parent.skills.forEach(s => skills.add(s));\n if (parent.workflows) parent.workflows.forEach(w => workflows.add(w));\n (parent.rules || []).forEach(r => rules.add(r));\n }\n }\n\n if (bundle.orchestrator) agents.add(bundle.orchestrator);\n if (bundle.agents) bundle.agents.forEach(a => agents.add(a));\n\n // Plan 015 §0/C6 — agent frontmatter `rules:` bindings are the single\n // source of truth and were previously ignored entirely. Collect them from\n // the orchestrator, every subagent, and the inherited parent's agents so\n // `resolved.agents` and `resolved.rules` can never disagree.\n for (const agentFile of agents) {\n for (const rule of await this.extractRulesFromAgent(agentFile)) {\n rules.add(rule);\n }\n }\n\n // Plan 015 §0/D2 — fail fast instead of letting installer.ts silently skip\n // a rule file that does not exist under registry/rules/.\n const sortedRules = Array.from(rules).sort();\n this.assertRulesExist(sortedRules, `bundle \"${bundle.name}\"`);\n\n return {\n targetBundle: bundle.name,\n agents: Array.from(agents),\n skills: Array.from(skills),\n workflows: Array.from(workflows),\n rules: sortedRules,\n };\n }\n\n // Check if identifier refers to a specific single item (agent, skill, or workflow)\n const agentPath = path.join(this.registryDir, 'agents', identifier.endsWith('.md') ? identifier : `${identifier}.md`);\n if (await fs.pathExists(agentPath)) {\n return {\n agents: [path.basename(agentPath)],\n skills: [],\n workflows: [],\n rules: [],\n };\n }\n\n const sanitizedSkillId = identifier.replace(/\\.md$/, '').replace(/--/g, '-');\n const skillPath = path.join(this.registryDir, 'skills', identifier);\n const sanitizedSkillPath = path.join(this.registryDir, 'skills', sanitizedSkillId);\n if (await fs.pathExists(skillPath)) {\n return {\n agents: [],\n skills: [identifier],\n workflows: [],\n rules: [],\n };\n } else if (await fs.pathExists(sanitizedSkillPath)) {\n return {\n agents: [],\n skills: [sanitizedSkillId],\n workflows: [],\n rules: [],\n };\n }\n\n const workflowSkillPath = path.join(this.registryDir, 'skills', `workflow-${sanitizedSkillId}`);\n if (await fs.pathExists(workflowSkillPath)) {\n return {\n agents: [],\n skills: [`workflow-${sanitizedSkillId}`],\n workflows: [],\n rules: [],\n };\n }\n\n // Legacy fallback check for standalone workflow file if present\n const workflowFileName = identifier.startsWith('workflow-') ? `${identifier}.md` : `workflow-${identifier}.md`;\n const workflowPath = path.join(this.registryDir, 'workflows', workflowFileName);\n if (await fs.pathExists(workflowPath)) {\n return {\n agents: [],\n skills: [],\n workflows: [path.basename(workflowPath)],\n rules: [],\n };\n }\n\n throw new Error(`Item or bundle \"${identifier}\" not found in registry.`);\n }\n\n public async find(query: string = '', options?: SearchOptions): Promise<SearchResults> {\n const manifest = await this.loadBundles();\n const q = query.trim().toLowerCase();\n\n let matchedBundles: BundleDefinition[] = [];\n if (!options?.type || options.type === 'bundle') {\n matchedBundles = Object.values(manifest.bundles).filter(b => {\n if (options?.domain && b.domain?.toLowerCase() !== options.domain.toLowerCase()) {\n return false;\n }\n if (!q) return true;\n return (\n b.name.toLowerCase().includes(q) ||\n b.description.toLowerCase().includes(q) ||\n b.category?.toLowerCase().includes(q) ||\n b.domain?.toLowerCase().includes(q) ||\n b.aliases?.some(a => a.toLowerCase().includes(q))\n );\n });\n }\n\n const agentsDir = path.join(this.registryDir, 'agents');\n let matchedAgents: string[] = [];\n if (!options?.type || options.type === 'agent') {\n if (await fs.pathExists(agentsDir)) {\n const files = await fs.readdir(agentsDir);\n matchedAgents = files.filter(f => {\n if (!q) return true;\n return f.toLowerCase().includes(q);\n });\n }\n }\n\n const skillsDir = path.join(this.registryDir, 'skills');\n let matchedSkills: string[] = [];\n if (!options?.type || options.type === 'skill' || options.type === 'workflow') {\n if (await fs.pathExists(skillsDir)) {\n const dirs = await fs.readdir(skillsDir);\n matchedSkills = dirs.filter(d => {\n if (!q) return true;\n return d.toLowerCase().includes(q);\n });\n }\n }\n\n // Support workflow search: matches skills with workflow- prefix or any legacy workflows folder\n let matchedWorkflows: string[] = [];\n if (!options?.type || options.type === 'workflow') {\n matchedWorkflows = matchedSkills.filter(s => s.startsWith('workflow-'));\n const workflowsDir = path.join(this.registryDir, 'workflows');\n if (await fs.pathExists(workflowsDir)) {\n const files = await fs.readdir(workflowsDir);\n const legacyMatches = files.filter(f => f.endsWith('.md')).filter(f => {\n if (!q) return true;\n return f.toLowerCase().includes(q);\n });\n legacyMatches.forEach(f => {\n if (!matchedWorkflows.includes(f)) matchedWorkflows.push(f);\n });\n }\n }\n\n return {\n bundles: matchedBundles,\n agents: matchedAgents,\n skills: matchedSkills,\n workflows: matchedWorkflows,\n };\n }\n\n /**\n * Plan 015 Step 1 / §0/C6 — extract the `rules:` binding from an agent's YAML\n * frontmatter. Rules are declared as a BLOCK SEQUENCE:\n * rules:\n * - git-guardrails.md\n * Never regex for an inline `rules: [a, b]`. Returns `[]` (never throws) when\n * the file is missing, has no frontmatter, or the YAML is unparsable so that\n * resolution stays resilient; existence of the referenced rule files is\n * enforced separately by `assertRulesExist`.\n */\n private async extractRulesFromAgent(agentFileName: string): Promise<string[]> {\n const cached = this.agentRuleCache.get(agentFileName);\n if (cached) {\n return cached;\n }\n\n let declared: string[] = [];\n const agentPath = path.join(this.registryDir, 'agents', agentFileName);\n if (await fs.pathExists(agentPath)) {\n const content = await fs.readFile(agentPath, 'utf8');\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (match) {\n try {\n const meta = (yaml.parse(match[1]) as { rules?: unknown } | null) ?? {};\n if (Array.isArray(meta.rules)) {\n declared = meta.rules.filter((r): r is string => typeof r === 'string');\n }\n } catch {\n declared = [];\n }\n }\n }\n\n this.agentRuleCache.set(agentFileName, declared);\n return declared;\n }\n\n /**\n * Plan 015 §0/D2 — a declared rule binding that cannot be satisfied is a\n * configuration defect, not something to skip silently: installer.ts guards\n * its copy loop with `pathExists`, so a typo would otherwise deploy no rule at\n * all with no error surfaced anywhere.\n */\n private assertRulesExist(rules: string[], context: string): void {\n for (const rule of rules) {\n if (!fs.existsSync(path.join(this.registryDir, 'rules', rule))) {\n throw new Error(\n `Registry validation error: ${context} references rule \"${rule}\" which does not exist in registry/rules/.`\n );\n }\n }\n }\n\n /**\n * ADR 0015 — fail-fast validation of planningLoop configuration.\n * @throws if any bundle violates planner-orchestrator invariants.\n */\n private validateBundles(manifest: BundlesManifest): void {\n const validModes: string[] = ['subagent-first', 'planner-orchestrator'];\n\n for (const [name, bundle] of Object.entries(manifest.bundles)) {\n // Plan 015 §0/D2 — declared rule bindings must resolve on disk.\n if (Array.isArray(bundle.rules)) {\n for (const rule of bundle.rules) {\n if (!fs.existsSync(path.join(this.registryDir, 'rules', rule))) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" references rule \"${rule}\" which does not exist in registry/rules/.`\n );\n }\n }\n }\n\n const pl = bundle.planningLoop;\n if (!pl || !pl.enabled) continue; // no planning → skip\n\n // resolve mode: absent → subagent-first (ADR 0014 backward compat)\n const mode: string = pl.mode ?? 'subagent-first';\n\n if (!validModes.includes(mode)) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has unknown planningLoop.mode \"${mode}\". ` +\n `Valid modes: ${validModes.join(', ')}`\n );\n }\n\n // Plan 022 H1 (owner decision 2026-09-25): iteration caps are Tier-2-only. Only an\n // organization-tier coordinator may carry a Consultation Budget (rendered as maxTurns);\n // Tier-1 domain agents stay uncapped.\n if (pl.budget) {\n if (bundle.tier !== 'organization') {\n throw new Error(\n `Registry validation error: bundle \"${name}\" declares a Consultation Budget but is not an organization-tier bundle. ` +\n 'Iteration caps (planningLoop.budget.maxIterations) are Tier-2-only.'\n );\n }\n const cap = pl.budget.maxIterations;\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has planningLoop.budget.maxIterations ${String(cap)}; expected a positive integer.`\n );\n }\n }\n\n if (mode === 'planner-orchestrator') {\n if (pl.budget) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has planningLoop.mode \"planner-orchestrator\" ` +\n 'but also declares a Consultation Budget (budget). Planner-orchestrator bundles must not declare budget.'\n );\n }\n if (pl.sidekicks) {\n throw new Error(\n `Registry validation error: bundle \"${name}\" has planningLoop.mode \"planner-orchestrator\" ` +\n 'but also declares sidekicks. Planner-orchestrator bundles must not declare sidekicks.'\n );\n }\n }\n }\n }\n}\n\n/**\n * Plan 021 (ADR 0021 decision 9) — loads the Declared-Delta Registry\n * (`registry/translation-ledger.json`, the Translation Ledger repurposed: dispositions now\n * classify host-native deltas above the Contract Floor). Fail-fast: an entry without a valid\n * classification (`mapped|approximated|degraded|unsupported`) or without a rationale throws.\n */\nexport function loadTranslationLedger(\n registryDir = 'registry',\n): import('./types.js').TranslationLedgerEntry[] {\n const ledgerPath = path.join(registryDir, 'translation-ledger.json');\n const parsed: unknown = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));\n // Accept both the seed shape ({ semantics, entries }) and a bare entries array (fixtures).\n const entries = Array.isArray(parsed) ? parsed : (parsed as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n throw new Error(`Declared-Delta Registry error: ${ledgerPath} must be a JSON array of entries or carry an \"entries\" array.`);\n }\n const validDispositions = new Set(['mapped', 'approximated', 'degraded', 'unsupported']);\n return entries.map((raw, index) => {\n const entry = raw as Record<string, unknown>;\n const feature = entry.feature;\n const host = entry.host;\n const disposition = entry.disposition;\n const rationale = entry.rationale;\n if (typeof feature !== 'string' || feature.trim() === '') {\n throw new Error(`Declared-Delta Registry error: entries[${index}] needs a non-empty feature.`);\n }\n if (typeof host !== 'string' || host.trim() === '') {\n throw new Error(`Declared-Delta Registry error: entries[${index}] (\"${feature}\") needs a non-empty host.`);\n }\n if (typeof disposition !== 'string' || !validDispositions.has(disposition)) {\n throw new Error(\n `Declared-Delta Registry error: entries[${index}] (\"${feature}\") needs disposition mapped|approximated|degraded|unsupported.`,\n );\n }\n if (typeof rationale !== 'string' || rationale.trim() === '') {\n throw new Error(`Declared-Delta Registry error: entries[${index}] (\"${feature}\") needs a rationale.`);\n }\n return { feature, host, disposition, rationale } as import('./types.js').TranslationLedgerEntry;\n });\n}\n","import path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { AgentHostAdapter } from './adapter.js';\nimport { isKnownHost, HOST_REGISTRY, resolveHostProjectDir } from './hosts.js';\nimport { HostProjector } from './projector.js';\nimport type { IndexableAsset } from './projector.js';\nimport { ClineProjector } from './cline-projector.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport { isSidecarDir, resolveStateDir, stateDirFor, workspaceRootOf } from './state-dir.js';\nimport { mergeSessionGuard, resolveSessionGuardFile, variantOfRecordedFile, sessionGuardSnippet } from './session-guard.js';\nimport { mergePermissionPreset, SUPPORTED_PERMISSION_PRESET_HOSTS } from './permission-preset.js';\nimport YAML from 'yaml';\nimport type { BundleDefinition, InstallOptions, LockfileManifest, ResolvedAssets, InstallScope, InstallMethod, AgentHost, PlannedProjectionArtifact, ProjectionInfo } from './types.js';\nimport { assetOwners, mergeAssetOwners } from './types.js';\n\nexport class InstallEngine {\n private registry: RegistryResolver;\n\n constructor(registry?: RegistryResolver) {\n this.registry = registry || new RegistryResolver();\n }\n\n private async calculateHash(filePath: string): Promise<string> {\n const buffer = await fs.readFile(filePath);\n return 'sha256:' + crypto.createHash('sha256').update(buffer).digest('hex');\n }\n\n private async readLockfile(lockfilePath: string): Promise<LockfileManifest> {\n if (await fs.pathExists(lockfilePath)) {\n try {\n return await fs.readJson(lockfilePath);\n } catch {\n // Fallback to empty manifest on corrupt file\n }\n }\n\n return {\n $schema: 'https://agents-united.dev/schema/lockfile.v1.json',\n version: 1,\n installed: {\n bundles: [],\n agents: [],\n skills: [],\n workflows: [],\n },\n files: {},\n };\n }\n\n private parseHosts(options: InstallOptions): AgentHost[] {\n if (options.hosts && options.hosts.length > 0) {\n return options.hosts;\n }\n\n if (options.target) {\n const raw = Array.isArray(options.target) ? options.target.join(',') : options.target;\n const parsed = raw.split(',').map(s => s.trim().toLowerCase()) as AgentHost[];\n const valid: AgentHost[] = [];\n for (const h of parsed) {\n if (isKnownHost(h)) {\n valid.push(h);\n }\n }\n if (valid.length > 0) return valid;\n }\n\n return ['agents'];\n }\n\n private parseMethod(options: InstallOptions): InstallMethod {\n if (options.copy) return 'copy';\n if (options.symlink || options.method === 'symlink') return 'symlink';\n return options.method || 'symlink';\n }\n\n private parseScope(options: InstallOptions): InstallScope {\n if (options.global) return 'global';\n return options.scope || 'project';\n }\n\n private async deployFile(src: string, dest: string, method: InstallMethod, force?: boolean): Promise<'symlink' | 'copy'> {\n await fs.ensureDir(path.dirname(dest));\n\n if (await fs.pathExists(dest) || await fs.pathExists(dest).catch(() => false)) {\n if (force) {\n await fs.remove(dest);\n }\n }\n\n if (method === 'symlink') {\n try {\n const stat = await fs.stat(src);\n const type = stat.isDirectory() ? (process.platform === 'win32' ? 'junction' : 'dir') : 'file';\n await fs.ensureSymlink(src, dest, type);\n return 'symlink';\n } catch {\n // Fallback to copy if OS restricts symlinks\n await fs.copy(src, dest, { overwrite: true });\n return 'copy';\n }\n }\n\n await fs.copy(src, dest, { overwrite: true });\n return 'copy';\n }\n\n/**\n * Writes a projection copy (never a symlink). Projections are always translated\n * copies of canonical assets, so their bytes differ from the source.\n */\n private async deployProjection(dest: string, content: string): Promise<void> {\n await fs.ensureDir(path.dirname(dest));\n await fs.writeFile(dest, content, 'utf8');\n }\n\n /**\n * Computes the canonical `.agents/` target dir and the workspace root that contains\n * it. Projections are recorded relative to this root (e.g. '.claude/agents/x.md').\n */\n private static projectionRoot(scope: InstallScope, targetDir?: string): { agentsTarget: string; root: string } {\n const agentsTarget = AgentHostAdapter.resolveHostDir(scope, 'agents', targetDir);\n return { agentsTarget, root: workspaceRootOf(agentsTarget) };\n }\nprivate toPosix(p: string): string {\n return p.split(path.sep).join('/');\n }\n\n private canonicalRelAgent(agentFile: string): string {\n return `.agents/agents/${agentFile}`;\n }\n\n private lockRel(subdir: string, file: string): string {\n return path.join(subdir, file);\n }\n\n private destForProjection(host: string, root: string, file: string): string {\n const def = HOST_REGISTRY[host];\n const base = resolveHostProjectDir(host, root);\n if (def.agentsSubdir) return path.join(base, def.agentsSubdir, file);\n return base; // agentsmd hosts (codex) use the root AGENTS.md bridge, handled separately\n }\n\n private recordProjectedTo(lockfile: LockfileManifest, relKey: string, projPath: string): void {\n const normProj = this.toPosix(projPath);\n const posixKey = relKey.replace(/\\\\/g, '/');\n const sysKey = relKey.replace(/\\//g, path.sep);\n const targetKey = lockfile.files[posixKey] ? posixKey : (lockfile.files[sysKey] ? sysKey : relKey);\n if (!lockfile.files[targetKey]) {\n lockfile.files[targetKey] = { hash: '', installedAt: new Date().toISOString() };\n }\n const asset = lockfile.files[targetKey];\n asset.projectedTo = asset.projectedTo || [];\n if (!asset.projectedTo.includes(normProj)) {\n asset.projectedTo.push(normProj);\n }\n }\n\n private removeProjectedTo(lockfile: LockfileManifest, canonicalRelPath: string, projectedRelPath: string): void {\n const normProj = this.toPosix(projectedRelPath);\n const posixKey = canonicalRelPath.replace(/\\\\/g, '/');\n const sysKey = canonicalRelPath.replace(/\\//g, path.sep);\n const targetKey = lockfile.files[posixKey] ? posixKey : (lockfile.files[sysKey] ? sysKey : canonicalRelPath);\n const asset = lockfile.files[targetKey];\n if (asset && asset.projectedTo) {\n asset.projectedTo = asset.projectedTo.filter(p => p !== normProj);\n if (asset.projectedTo.length === 0) {\n delete asset.projectedTo;\n }\n }\n }\n\n /**\n * Plan 015c / §5.7 — host-scoped projection namespaces.\n *\n * A re-projection run is authoritative only for the paths it produces inside\n * its own host namespace. Bundle-scoped lanes (`.agents/plugins/<bundle>/`) are\n * additionally narrowed to the bundle that owns them, so re-projecting bundle A\n * never drops bundle B's plugin-lane entries.\n */\n private static projectionNamespacePrefixes(host: string, bundleName: string): string[] {\n switch (host) {\n case 'cline':\n return ['.cline/', `.agents/plugins/${bundleName}/`];\n case 'claude':\n return ['.claude/'];\n case 'cursor':\n return ['.cursor/'];\n case 'gemini':\n return ['.gemini/'];\n case 'opencode':\n return ['.opencode/'];\n case 'codex':\n return ['AGENTS.md'];\n default:\n return [];\n }\n }\n\n /**\n * Plan 015c / §5.7 — reconcile `projectedTo` instead of only appending.\n *\n * `recordProjectedTo()` appends and is never told when a projection *path*\n * changes (e.g. the ADR 0016 workflow slug rename from\n * `.cline/workflows/implement-feature-or-fix.md` to\n * `.cline/workflows/workflow-implement.md`). The obsolete-projection cleanup\n * iterates `lockfile.projections`, which no longer contains the legacy path, so\n * the stale pointer in `files[canonical].projectedTo` survived forever and\n * `agents doctor` warned \"Missing projection ... Re-run: agents add ... --fanout\"\n * — a remediation that provably cannot clear it.\n *\n * For every canonical this run actually produced projections for, drop the\n * entries inside this run's namespace that the current plan did not produce.\n * Entries for other hosts and for other bundles survive untouched.\n */\n private reconcileProjectedTo(\n lockfile: LockfileManifest,\n host: string,\n bundleName: string,\n producedByCanonical: Map<string, string[]>\n ): void {\n const prefixes = InstallEngine.projectionNamespacePrefixes(host, bundleName);\n if (prefixes.length === 0 || producedByCanonical.size === 0) return;\n\n for (const [canonical, producedPaths] of producedByCanonical) {\n const posixKey = canonical.replace(/\\\\/g, '/');\n const sysKey = canonical.replace(/\\//g, path.sep);\n const targetKey = lockfile.files[posixKey] ? posixKey : (lockfile.files[sysKey] ? sysKey : null);\n if (!targetKey) continue;\n\n const asset = lockfile.files[targetKey];\n if (!asset.projectedTo || asset.projectedTo.length === 0) continue;\n\n const produced = new Set(producedPaths.map(p => this.toPosix(p)));\n const kept = asset.projectedTo.filter(\n p => !(prefixes.some(prefix => p.startsWith(prefix)) && !produced.has(p))\n );\n\n if (kept.length === asset.projectedTo.length) continue;\n if (kept.length === 0) {\n delete asset.projectedTo;\n } else {\n asset.projectedTo = kept;\n }\n }\n }\n\n /**\n * ADR 0018 — the shared compound-lane body used by every host that owns a\n * dedicated projector (Cline per ADR 0013, Claude per ADR 0018).\n *\n * Parameterising by `host` instead of forking the body is deliberate: the two\n * lanes must stay behaviourally identical in pruning, refcounting and\n * reconcile semantics, and the Cline path is provably unchanged because it\n * passes the exact same literal `'cline'` (and the same `declared` set, plan\n * artifacts and force flag) it previously used inline.\n *\n * The host-specific plan (the projector call) stays at the call site; this body\n * is purely mechanical: prune superseded projections, deploy artifacts, record\n * refcounted projection entries, reconcile `projectedTo`, surface `projections`.\n */\n private async applyCompoundLane(\n host: AgentHost,\n bundleName: string,\n artifacts: PlannedProjectionArtifact[],\n context: {\n root: string;\n lockfile: LockfileManifest;\n declared: Set<string>;\n projections: ProjectionInfo[];\n now: string;\n force?: boolean;\n }\n ): Promise<void> {\n const { root, lockfile, declared, projections, now, force } = context;\n const newPaths = new Set(artifacts.map(a => a.relPath));\n\n // Clean up legacy or obsolete projections previously owned by this bundle.\n // This is the load-bearing migration for renames: the ADR 0016 workflow slug\n // rename, and (ADR 0018 decision 2) the `subagent-` prefix strip that moves\n // `.claude/agents/subagent-<role>.md` to `.claude/agents/<role>.md`.\n if (lockfile.projections) {\n for (const [projRelPath, proj] of Object.entries(lockfile.projections)) {\n if (proj.host === host && !newPaths.has(projRelPath) && proj.owners.includes(bundleName)) {\n proj.owners = proj.owners.filter(o => o !== bundleName);\n if (proj.owners.length === 0) {\n const absProjection = path.join(root, projRelPath);\n if (await fs.pathExists(absProjection)) {\n await fs.remove(absProjection);\n await this.removeEmptyProjectionDirs(root, projRelPath);\n }\n delete lockfile.projections[projRelPath];\n }\n if (proj.canonical) {\n this.removeProjectedTo(lockfile, proj.canonical, projRelPath);\n }\n }\n }\n }\n\n for (const artifact of artifacts) {\n const dest = path.join(root, artifact.relPath);\n if (await fs.pathExists(dest) && !force) {\n const existing = await fs.readFile(dest, 'utf8').catch(() => null);\n if (existing !== null) {\n if (artifact.managedMarker && !HostProjector.hasManagedMarker(existing)) {\n throw new Error(\n `Projection target ${artifact.relPath} already exists and is not managed by agents-united. Use --force to overwrite.`\n );\n } else if (!artifact.managedMarker) {\n const registeredProj = lockfile.projections?.[artifact.relPath];\n if (!registeredProj) {\n throw new Error(\n `Projection target ${artifact.relPath} already exists and is not managed by agents-united. Use --force to overwrite.`\n );\n }\n }\n }\n }\n\n if (artifact.content !== undefined) {\n await this.deployProjection(dest, artifact.content);\n } else if (artifact.sourceFilePath) {\n await fs.ensureDir(path.dirname(dest));\n await fs.copy(artifact.sourceFilePath, dest, { overwrite: true });\n }\n\n const deployedHash = await this.calculateHash(dest);\n lockfile.projections = lockfile.projections || {};\n const existingProj = lockfile.projections[artifact.relPath];\n const declares = artifact.kind === 'rule' || artifact.kind === 'team-manifest'\n || artifact.kind === 'plugin-manifest'\n || (artifact.canonical ? declared.has(artifact.canonical) : false);\n // A projection of a shared canonical is shared. Seed its owners from the canonical's owners,\n // or the creating bundle becomes sole owner and removing it deletes projections another owner\n // still needs (reported: `remove software-engineering` wiped the domain's `.claude/skills/*`\n // and `.claude/rules/*`, leaving \"Missing projection\" storms in doctor). Bundle-scoped lanes\n // (`.agents/plugins/<bundle>/`) stay owned by the shipping bundle alone (A6: each bundle\n // packages its own skills — an addon ships its OWN mirror, so the parent's package is not\n // needed by it); their SURVIVAL is governed separately by the Universal Coverage Rule\n // (ADR 0019) in the uninstaller, which is what keeps the package under a standing domain.\n const bundleScoped = artifact.relPath.startsWith('.agents/plugins/');\n const canonicalOwners = !bundleScoped && artifact.canonical\n ? (lockfile.files[artifact.canonical]?.owners ?? [])\n : [];\n const priorOwners = existingProj?.owners ?? [];\n const owners = Array.from(new Set([\n ...priorOwners,\n ...canonicalOwners,\n ...(declares ? [bundleName] : []),\n ]));\n\n lockfile.projections[artifact.relPath] = {\n host,\n kind: artifact.kind,\n canonical: artifact.canonical,\n owners,\n hash: deployedHash,\n installedAt: existingProj?.installedAt ?? now,\n managedMarker: artifact.managedMarker,\n };\n\n projections.push({ host, path: artifact.relPath, kind: artifact.kind, warnings: [] });\n\n // ADR 0018 decision 12 — a distribution-only artifact (the opt-in Claude plugin lane) is\n // deployed and tracked in `lockfile.projections` so doctor can see presence and drift, but\n // it is deliberately NOT a `projectedTo` target. `projectionNamespacePrefixes('claude')` is\n // `['.claude/']` on purpose: `.agents/plugins/<bundle>/` belongs to the *cline* reconcile\n // pass, and a claude pointer recorded inside it would be dropped by that pass on the next\n // Cline install — healthy artifacts turned into orphaned lockfile state.\n if (artifact.canonical && !artifact.distributionOnly) {\n this.recordProjectedTo(lockfile, artifact.canonical, artifact.relPath);\n }\n }\n\n // Plan 015c / §5.7 — authoritative reconcile pass. `recordProjectedTo` above\n // only appends, so a canonical whose projection path changed (e.g. the ADR 0016\n // workflow slug rename) kept a dangling pointer forever and `agents doctor`\n // warned about a file that can never come back. Derive the produced set from\n // this run's plan and drop this namespace's stale pointers for the canonicals\n // we just re-projected.\n const producedByCanonical = new Map<string, string[]>();\n for (const artifact of artifacts) {\n // Distribution-only artifacts are excluded here as well: they exist to be *packaged*,\n // not to serve a canonical asset, so they must not widen the produced set of this\n // namespace (which would keep a stale `.claude/**` pointer alive).\n if (!artifact.canonical || artifact.distributionOnly) continue;\n const producedPaths = producedByCanonical.get(artifact.canonical);\n if (producedPaths) {\n producedPaths.push(artifact.relPath);\n } else {\n producedByCanonical.set(artifact.canonical, [artifact.relPath]);\n }\n }\n this.reconcileProjectedTo(lockfile, host, bundleName, producedByCanonical);\n }\n\n /**\n * Plan 016 / ADR 0018 decision 12 — resolve the effective plugin-lane opt-in.\n *\n * An explicit `InstallOptions.pluginLane` always wins (the CLI passes `true` for `--plugin` and\n * `false` for `--no-plugin`); an unset flag inherits the recorded choice so that `agents update`\n * — which re-runs the installer without the flag — cannot silently prune an opted-in package.\n */\n private static effectivePluginLane(\n options: InstallOptions,\n lockfile?: LockfileManifest | null\n ): boolean {\n if (typeof options.pluginLane === 'boolean') return options.pluginLane;\n return lockfile?.pluginLane === true;\n }\n\n /**\n * Plan 023 B (ADR 0022, D4) — resolve the state dir for this install. An explicit `targetDir`\n * is a location hint; a requested (or implied) store shape always lands in `.agents/`, and a\n * sidecar is used only when nothing needs the store: any non-Claude fan-out or the plugin lane\n * (both write under `.agents/plugins/`) forces the store (strangler-safe, ADR 0022 decision 4).\n */\n private static resolveInstallStateDir(scope: InstallScope, options: InstallOptions, fanoutHosts: string[]): string {\n const discovered = resolveStateDir(scope, options.targetDir, { preferShape: options.storeShape ?? 'store' });\n const needsStore = options.storeShape === 'store'\n || fanoutHosts.some(h => h !== 'claude')\n || options.pluginLane === true;\n if (needsStore && isSidecarDir(discovered)) return stateDirFor(workspaceRootOf(discovered), 'store');\n return discovered;\n }\n\n /** Move an existing sidecar into the store dir (ADR 0022 upgrade path); a no-op otherwise. */\n private static async upgradeSidecarToStore(stateDir: string): Promise<void> {\n if (isSidecarDir(stateDir)) return;\n const sidecar = stateDirFor(workspaceRootOf(stateDir), 'sidecar');\n if (!(await fs.pathExists(path.join(sidecar, 'agents-united.json')))) return;\n if (await fs.pathExists(path.join(stateDir, 'agents-united.json'))) return; // store already authoritative\n await fs.ensureDir(stateDir);\n for (const entry of await fs.readdir(sidecar)) {\n await fs.move(path.join(sidecar, entry), path.join(stateDir, entry), { overwrite: true });\n }\n await fs.remove(sidecar);\n }\n\n /**\n * Plan 023 A (owner D1–D2) — the plain-session guard. Runs only when the Claude lane runs.\n * An explicit `options.sessionGuard` wins and is recorded; otherwise the recorded decision is\n * re-applied (sticky yes re-merges idempotently, sticky no writes nothing); never decided ⇒\n * nothing is written (the CLI asks). `project`/`local` are workspace files and are ignored for\n * global installs; `user` (home settings) is honoured only when requested explicitly.\n */\n private async applySessionGuard(\n scope: InstallScope,\n workspaceRoot: string,\n lockfile: LockfileManifest,\n options: InstallOptions,\n projections: ProjectionInfo[],\n ): Promise<void> {\n const recorded = lockfile.sessionGuard;\n let variant: 'project' | 'local' | 'user' | false | undefined = options.sessionGuard;\n if (variant === undefined && recorded) {\n variant = 'off' in recorded ? false : variantOfRecordedFile(recorded.file);\n }\n if (variant === undefined) return;\n if (variant === false) {\n lockfile.sessionGuard = { off: true };\n return;\n }\n if (scope === 'global' && variant !== 'user') return;\n\n const file = resolveSessionGuardFile(variant, workspaceRoot);\n const recordedFile = variant === 'user' ? file : this.toPosix(path.relative(workspaceRoot, file));\n const sameFileRecord = recorded && !('off' in recorded) && recorded.file === recordedFile ? recorded : undefined;\n const existedBefore = await fs.pathExists(file);\n const result = await mergeSessionGuard(file, { replaceHash: sameFileRecord?.handlerHash });\n lockfile.sessionGuard = {\n file: recordedFile,\n handlerHash: result.handlerHash,\n createdFile: sameFileRecord ? sameFileRecord.createdFile : !existedBefore,\n };\n const warnings: string[] = [];\n if (result.status === 'skipped-invalid') {\n warnings.push(`Session guard not written: ${recordedFile} is not valid JSON (comments or trailing commas?). It was left untouched — paste this into it by hand:\\n${sessionGuardSnippet()}`);\n } else if (result.status === 'modified') {\n warnings.push(`Session guard in ${recordedFile} was edited by hand; left as-is (run with --force after removing it to restore).`);\n }\n projections.push({ host: 'claude', path: recordedFile, warnings });\n }\n\n /**\n * Plan 024 S4 (owner decisions E2/E4) — the opt-in command-permission preset. Written ONLY to\n * `.claude/settings.local.json`, never the shared `.claude/settings.json`, regardless of what\n * `sessionGuard` variant is also requested. Off by default, never implied by `-y`. Applies to\n * every fan-out host that has a verified renderer (Claude only today); any other requested host\n * gets an honest \"not supported yet\" warning instead of a guessed file.\n */\n private async applyPermissionPreset(\n scope: InstallScope,\n workspaceRoot: string,\n lockfile: LockfileManifest,\n options: InstallOptions,\n fanoutHosts: string[],\n projections: ProjectionInfo[],\n ): Promise<void> {\n const recorded = lockfile.permissionPreset;\n const tier = options.permissionPreset ?? (recorded && !('off' in recorded) ? recorded.tier : undefined);\n if (tier === undefined) return;\n if (tier === false) {\n lockfile.permissionPreset = { off: true };\n return;\n }\n if (scope === 'global') return; // Plan 024 S4: workspace-local only, never a global default.\n\n const unsupported = fanoutHosts.filter(h => h !== 'claude' && !SUPPORTED_PERMISSION_PRESET_HOSTS.includes(h));\n for (const host of unsupported) {\n projections.push({ host, path: '', warnings: [`Permission preset not supported for ${host} yet — no file written for it. Claude still received it if selected.`] });\n }\n if (!fanoutHosts.includes('claude')) return;\n\n const file = path.join(workspaceRoot, '.claude', 'settings.local.json');\n const recordedFile = this.toPosix(path.relative(workspaceRoot, file));\n const existedBefore = await fs.pathExists(file);\n const result = await mergePermissionPreset(file, tier);\n const warnings: string[] = [];\n if (result.status === 'skipped-invalid') {\n warnings.push(`Permission preset not written: ${recordedFile} is not valid JSON (comments or trailing commas?). Left untouched.`);\n } else {\n lockfile.permissionPreset = {\n tier,\n file: recordedFile,\n entries: result.entries,\n createdFile: recorded && !('off' in recorded) ? recorded.createdFile : !existedBefore,\n };\n }\n projections.push({ host: 'claude', path: recordedFile, warnings });\n }\n\n /**\n * ADR 0018 — the host-specific projection plan, the single input that differs per host once\n * `applyCompoundLane` shared the mechanics. `pluginLane` (Plan 016 decision 13) is honoured for\n * the **Claude lane only**: the Cline package must stay byte-identical with the flag on and off,\n * so the flag is inert for `cline`.\n */\n private static async planCompoundArtifacts(\n host: AgentHost,\n bundleDef: BundleDefinition,\n scope: InstallScope,\n resolved: ResolvedAssets,\n registryDir: string,\n pluginLane: boolean\n ): Promise<PlannedProjectionArtifact[]> {\n if (host === 'cline') {\n return ClineProjector.planCompoundProjection(bundleDef, scope, resolved, registryDir);\n }\n const artifacts = await ClaudeProjector.planCompoundProjection(bundleDef, scope, resolved, registryDir);\n if (pluginLane) {\n // Distribution-only extras (ADR 0018 decision 12): deployed and tracked through the same\n // lane, but never recorded as a `projectedTo` target (`distributionOnly` artifacts).\n artifacts.push(...await ClaudeProjector.planPluginLane(bundleDef, resolved, registryDir));\n }\n return artifacts;\n }\n\n private async removeEmptyProjectionDirs(workspaceRoot: string, projPath: string): Promise<void> {\n let dir = path.dirname(path.join(workspaceRoot, projPath));\n while (dir !== workspaceRoot && dir.startsWith(workspaceRoot)) {\n try {\n const entries = await fs.readdir(dir);\n if (entries.length > 0) break;\n await fs.rmdir(dir);\n } catch {\n break;\n }\n dir = path.dirname(dir);\n }\n }\n\n // ADR 0016: Silent auto-migration of legacy .agents/workflows/*.md into\n // .agents/skills/workflow-<name>/SKILL.md, synchronizing lockfiles and pruning empty dirs.\n public async migrateLegacyWorkspaceWorkflows(targetDir: string, lockfile?: LockfileManifest): Promise<number> {\n const subPaths = AgentHostAdapter.getSubPaths(targetDir);\n let migratedCount = 0;\n\n let targetLockfile: LockfileManifest | undefined = lockfile;\n let lockfileLoadedFromDisk = false;\n\n if (!targetLockfile && (await fs.pathExists(subPaths.lockfile))) {\n try {\n targetLockfile = await fs.readJson(subPaths.lockfile);\n lockfileLoadedFromDisk = true;\n } catch {}\n }\n\n if (await fs.pathExists(subPaths.workflowsDir)) {\n const entries = await fs.readdir(subPaths.workflowsDir).catch(() => []);\n for (const entry of entries) {\n if (entry.endsWith('.md')) {\n const legacyPath = path.join(subPaths.workflowsDir, entry);\n let skillName = entry.replace(/\\.md$/, '').replace(/--/g, '-');\n if (!skillName.startsWith('workflow-')) {\n skillName = `workflow-${skillName}`;\n }\n const targetSkillDir = path.join(subPaths.skillsDir, skillName);\n const targetSkillFile = path.join(targetSkillDir, 'SKILL.md');\n\n if (!(await fs.pathExists(targetSkillFile))) {\n await fs.ensureDir(targetSkillDir);\n const legacyContent = await fs.readFile(legacyPath, 'utf8');\n let skillContent = legacyContent;\n const fmMatch = legacyContent.match(/^---\\r?\\n([\\s\\S]+?)\\r?\\n---/);\n if (fmMatch) {\n try {\n const meta = YAML.parse(fmMatch[1]) || {};\n meta.name = skillName;\n if (!meta.metadata) {\n meta.metadata = {\n author: 'Agents United',\n version: '1.0.0',\n icon: '🔄',\n };\n }\n const rest = legacyContent.replace(/^---\\r?\\n[\\s\\S]+?\\r?\\n---/, '');\n skillContent = `---\\n${YAML.stringify(meta).trim()}\\n---${rest}`;\n } catch {}\n }\n await fs.writeFile(targetSkillFile, skillContent, 'utf8');\n }\n await fs.remove(legacyPath).catch(() => {});\n migratedCount++;\n\n if (targetLockfile) {\n const legacyRel = this.toPosix(path.relative(targetDir, legacyPath));\n const newRel = this.toPosix(path.relative(targetDir, targetSkillFile));\n if (targetLockfile.files && targetLockfile.files[legacyRel]) {\n targetLockfile.files[newRel] = targetLockfile.files[legacyRel];\n delete targetLockfile.files[legacyRel];\n }\n if (targetLockfile.installed && targetLockfile.installed.skills) {\n if (!targetLockfile.installed.skills.includes(skillName)) {\n targetLockfile.installed.skills.push(skillName);\n }\n }\n }\n }\n }\n const remaining = await fs.readdir(subPaths.workflowsDir).catch(() => []);\n if (remaining.length === 0) {\n await fs.remove(subPaths.workflowsDir).catch(() => {});\n }\n }\n\n if (targetLockfile && targetLockfile.installed && targetLockfile.installed.workflows && targetLockfile.installed.workflows.length > 0) {\n for (const w of targetLockfile.installed.workflows) {\n let skillName = w.replace(/\\.md$/, '').replace(/--/g, '-');\n if (!skillName.startsWith('workflow-')) {\n skillName = `workflow-${skillName}`;\n }\n if (targetLockfile.installed.skills && !targetLockfile.installed.skills.includes(skillName)) {\n targetLockfile.installed.skills.push(skillName);\n }\n }\n targetLockfile.installed.workflows = [];\n }\n\n if (targetLockfile && (lockfileLoadedFromDisk || (await fs.pathExists(subPaths.lockfile)))) {\n await fs.writeJson(subPaths.lockfile, targetLockfile, { spaces: 2 });\n }\n\n return migratedCount;\n }\n\n /**\n * Dry-run: compute the projection plan (paths + warnings) without writing anything.\n */\n private async buildProjections(\n fanoutHosts: string[],\n resolved: ResolvedAssets,\n registryDir: string,\n scope: InstallScope,\n targetDir?: string,\n pluginLane = false\n ): Promise<ProjectionInfo[]> {\n const infos: ProjectionInfo[] = [];\n if (fanoutHosts.length === 0) return infos;\n const { root } = InstallEngine.projectionRoot(scope, targetDir);\n\n for (const host of fanoutHosts) {\n if (host === 'codex') {\n infos.push({ host, path: 'AGENTS.md', kind: 'bridge', warnings: [] });\n continue;\n }\n\n if (host === 'cline' || host === 'claude') {\n const bundleDef = resolved.targetBundle ? await this.registry.getBundle(resolved.targetBundle) : undefined;\n if (bundleDef) {\n const artifacts = await InstallEngine.planCompoundArtifacts(\n host as AgentHost,\n bundleDef,\n scope,\n resolved,\n registryDir,\n pluginLane\n );\n for (const artifact of artifacts) {\n infos.push({ host, path: artifact.relPath, kind: artifact.kind, warnings: [] });\n }\n continue;\n }\n }\n\n const base = resolveHostProjectDir(host, root);\n const subdir = HOST_REGISTRY[host].agentsSubdir ?? 'agents';\n for (const agentFile of resolved.agents) {\n const content = await fs.readFile(path.join(registryDir, 'agents', agentFile), 'utf8');\n const res = HostProjector.projectAgent(content, HOST_REGISTRY[host].profile, this.canonicalRelAgent(agentFile));\n const dest = path.join(base, subdir, agentFile);\n infos.push({ host, path: this.toPosix(path.relative(root, dest)), kind: 'role', warnings: res.warnings });\n }\n }\n return infos;\n }\n\n /**\n * Real fan-out: project canonical `.agents/` agents into each non-bridge host, build\n * the root AGENTS.md bridge for `codex`, and record every projection in the lockfile\n * of the canonical `.agents/` store that `targetDir` points at.\n */\n private async applyFanout(\n fanoutHosts: string[],\n resolved: ResolvedAssets,\n registryDir: string,\n scope: InstallScope,\n targetDir: string,\n lockfile: LockfileManifest,\n options: InstallOptions,\n projections: ProjectionInfo[]\n ): Promise<void> {\n if (fanoutHosts.length === 0) return;\n const { root } = InstallEngine.projectionRoot(scope, options.targetDir);\n const now = new Date().toISOString();\n\n // Plan 016 / ADR 0018 decision 12 — the plugin-lane opt-in is sticky. `agents update` re-runs\n // the installer without `--plugin`, so an unset flag must mean \"keep the recorded choice\"\n // rather than \"prune the opted-in package\"; only an explicit `false` (CLI `--no-plugin`) turns\n // it off. Persisted for the same reason `fanout` is.\n const pluginLane = InstallEngine.effectivePluginLane(options, lockfile);\n if (fanoutHosts.includes('claude')) {\n if (pluginLane) {\n lockfile.pluginLane = true;\n } else if (options.pluginLane === false) {\n delete lockfile.pluginLane;\n }\n }\n\n for (const host of fanoutHosts) {\n if (host === 'codex') {\n const assets: IndexableAsset[] = [];\n resolved.agents.forEach(f => assets.push({ name: f.replace(/\\.md$/, ''), type: 'agent', relPath: `.agents/agents/${f}` }));\n resolved.workflows.forEach(f => assets.push({ name: f.replace(/\\.md$/, ''), type: 'workflow', relPath: `.agents/workflows/${f}` }));\n resolved.skills.forEach(s => assets.push({ name: s, type: 'skill', relPath: `.agents/skills/${s}/SKILL.md` }));\n const bridge = HostProjector.buildAgentsMdIndex(assets);\n const bridgeDest = path.join(root, 'AGENTS.md');\n if (await fs.pathExists(bridgeDest) && !options.force) {\n const existing = await fs.readFile(bridgeDest, 'utf8');\n if (!HostProjector.hasManagedMarker(existing)) {\n throw new Error(\n 'File AGENTS.md already exists at the workspace root and is not managed by agents-united. Use --force to overwrite.'\n );\n }\n // Ours (managed marker present): deterministic content — regenerate silently.\n }\n await this.deployProjection(bridgeDest, bridge);\n projections.push({ host, path: 'AGENTS.md', kind: 'bridge', warnings: [] });\n resolved.agents.forEach(f => this.recordProjectedTo(lockfile, this.lockRel('agents', f), 'AGENTS.md'));\n resolved.workflows.forEach(f => this.recordProjectedTo(lockfile, this.lockRel('workflows', f), 'AGENTS.md'));\n resolved.skills.forEach(s => this.recordProjectedTo(lockfile, this.lockRel('skills', path.join(s, 'SKILL.md')), 'AGENTS.md'));\n continue;\n }\n\n if (host === 'cline' || host === 'claude') {\n const bundleDef = resolved.targetBundle ? await this.registry.getBundle(resolved.targetBundle) : undefined;\n if (bundleDef) {\n // Declared Asset Set of this bundle (its own bundles.json fields, NOT the\n // inherited/resolved superset). Projections for inherited artifacts are not\n // owned by this bundle — only those it actually declares (plus its own\n // coordinator rule and team manifest).\n const declared = new Set<string>();\n if (bundleDef.orchestrator) declared.add(`agents/${bundleDef.orchestrator}`);\n (bundleDef.agents || []).forEach(a => declared.add(`agents/${a}`));\n (bundleDef.skills || []).forEach(s => declared.add(`skills/${s}/SKILL.md`));\n (bundleDef.workflows || []).forEach(w => declared.add(`workflows/${w}`));\n\n // ADR 0018 - the per-host plan is the only host-specific input; pruning,\n // refcounting, deployment and reconcile are shared via applyCompoundLane.\n const artifacts = await InstallEngine.planCompoundArtifacts(\n host as AgentHost,\n bundleDef,\n scope,\n resolved,\n registryDir,\n pluginLane\n );\n\n await this.applyCompoundLane(host, bundleDef.name, artifacts, {\n root,\n lockfile,\n declared,\n projections,\n now,\n force: options.force,\n });\n\n // Installed-addon freshness (plan 003): when the installed bundle extends a\n // parent essentials with its own coordinator rule + team manifest already\n // projected, re-render those two coordination artifacts excluding every\n // installed bundle listed in the lockfile, so the coordinator stops prompting\n // for addons already present. Ownership is left untouched (the parent stays\n // the sole owner). If the parent rule/manifest don't exist yet (parent not\n // installed as its own bundle), skip silently.\n if (host === 'cline' && bundleDef.parentBundle) {\n const parentDef = await this.registry.getBundle(bundleDef.parentBundle);\n if (parentDef) {\n const parentProjection = await ClineProjector.planCompoundProjection(\n parentDef,\n scope,\n resolved,\n registryDir,\n lockfile.installed.bundles\n );\n for (const artifact of parentProjection) {\n if (artifact.kind !== 'rule' && artifact.kind !== 'team-manifest') continue;\n if (artifact.content === undefined) continue;\n const dest = path.join(root, artifact.relPath);\n if (!await fs.pathExists(dest)) continue; // parent not installed as its own bundle\n await this.deployProjection(dest, artifact.content);\n const deployedHash = await this.calculateHash(dest);\n lockfile.projections = lockfile.projections || {};\n const existingProj = lockfile.projections[artifact.relPath];\n lockfile.projections[artifact.relPath] = {\n host: 'cline',\n kind: artifact.kind,\n canonical: artifact.canonical,\n // Preserve existing ownership; the parent remains the sole owner.\n owners: existingProj?.owners ?? [],\n hash: deployedHash,\n installedAt: existingProj?.installedAt ?? now,\n managedMarker: artifact.managedMarker,\n };\n }\n }\n }\n continue;\n }\n }\n\n const base = resolveHostProjectDir(host, root);\n const subdir = HOST_REGISTRY[host].agentsSubdir ?? 'agents';\n for (const agentFile of resolved.agents) {\n const content = await fs.readFile(path.join(registryDir, 'agents', agentFile), 'utf8');\n const canonicalRel = this.canonicalRelAgent(agentFile);\n // ADR 0018: the Claude dialect renderer is the only correct writer for `.claude/agents/`.\n // This fallback runs whenever a fanout cannot resolve a bundle definition — the `domain:*`\n // pseudo-entries (registry.ts resolves them to `targetBundle: 'domain:<name>'`, which is not\n // in bundles.json), addon identifiers, and bundles absent from the registry. The legacy\n // generic projector only knows the small TOOL_NAME_MAP, so it dropped `invoke_subagent` and\n // `send_message` outright; a coordinator projected that way had NO `Agent` tool at all and\n // could not delegate. Rendering through the dialect keeps the tool vocabulary, the frontmatter\n // translation and the ledger dispositions identical to the compound lane's.\n // A coordinator projected without a bundle definition still needs a real allowlist: `Agent`\n // with no parentheses grants *any* subagent, which is not the bound ADR 0018 decision 3\n // describes. The peer roster of this projection run is the best available bound — exactly the\n // specialists this run made available in this workspace.\n const isCoordinatorRole = /^\\s*type:\\s*orchestrator\\s*$/m.test(content)\n || /^\\s*mainAgent:\\s*true\\s*$/m.test(content);\n const peerRoles = resolved.agents\n .filter(f => f !== agentFile)\n .map(f => ClaudeProjector.stripSubagentPrefix(f.replace(/\\.md$/i, '')));\n const res = host === 'claude'\n ? ClaudeProjector.renderRole(content, canonicalRel, {\n allowlist: isCoordinatorRole ? peerRoles : undefined,\n })\n : HostProjector.projectAgent(content, HOST_REGISTRY[host].profile, canonicalRel);\n // ADR 0013 / ADR 0018: the compound-lane hosts (Cline, Claude) name their\n // projected roles by stripping the canonical `subagent-` prefix, so the\n // unbundled fallback must use the same names or the two writers would\n // disagree about the same role (`.cline/agents/<role>.yml`,\n // `.claude/agents/<role>.md`).\n const strippedRoleName = agentFile.replace(/\\.md$/i, '').replace(/^subagent-/, '');\n const projName = host === 'cline'\n ? `${strippedRoleName}.yml`\n : (host === 'claude' ? `${strippedRoleName}.md` : agentFile);\n const dest = path.join(base, subdir, projName);\n const projPath = this.toPosix(path.relative(root, dest));\n\n // ADR 0017 / ADR 0018: a COMPOUND-lane role is authoritative and must never be replaced by\n // this fallback. Ownership is read from the recorded canonical: the compound planner stores\n // the store-relative `agents/<file>`, while this fallback stores the `.agents/`-prefixed form\n // (`canonicalRelAgent`). The earlier broad guard — \"any role entry exists\" — also froze roles\n // that THIS fallback had written with the legacy projector, which made the degradation\n // permanent: re-projection skipped them forever, so a `domain:*` install could never be\n // repaired. Cline deliberately keeps the broad guard, because its two writers render\n // genuinely different artifacts (configured-agent YAML vs the generic translation).\n const existingRoleProj = lockfile.projections?.[projPath];\n if (existingRoleProj?.kind === 'role') {\n const compoundOwned = !(existingRoleProj.canonical ?? '').startsWith('.agents/');\n if (host === 'cline' || (host === 'claude' && compoundOwned)) {\n continue;\n }\n }\n\n if (await fs.pathExists(dest) && !options.force) {\n const existing = await fs.readFile(dest, 'utf8');\n if (!HostProjector.hasManagedMarker(existing)) {\n throw new Error(\n `Projection target ${this.toPosix(path.relative(root, dest))} already exists and is not managed by agents-united. Use --force to overwrite.`\n );\n }\n // Ours (managed marker present): deterministic content — regenerate silently.\n }\n await this.deployProjection(dest, res.content);\n // `ClaudeRenderResult` reports translation losses through its ledger, not a warnings array.\n projections.push({\n host,\n path: projPath,\n kind: 'role',\n warnings: 'warnings' in res ? res.warnings : [],\n });\n this.recordProjectedTo(lockfile, this.lockRel('agents', agentFile), projPath);\n\n // ADR 0017 / ADR 0018: record a projection entry with a matching hash for anything\n // this fallback writes, so the freshness check never reports phantom drift and the\n // bookkeeping stays consistent with the compound lane. Host value comes from the\n // loop variable, never a literal, so both compound-lane hosts are covered without\n // changing Cline semantics.\n if (host === 'cline' || host === 'claude') {\n lockfile.projections = lockfile.projections || {};\n // Projection ownership is refcounted: a projection shared with an earlier install must\n // keep that owner too. Replacing the list silently drops the first bundle's claim, after\n // which its removal strands or deletes a projection another bundle still needs.\n const existingProj = lockfile.projections[projPath];\n // Same sharing rule as the compound lane: a projection of a shared canonical is shared.\n // The fallback records canonicals as `.agents/<sub>/<file>` while the files map uses\n // `<sub>/<file>` — resolve both spellings.\n const canonicalRecord = lockfile.files[canonicalRel] ?? lockfile.files[canonicalRel.replace(/^\\.agents\\//, '')];\n lockfile.projections[projPath] = {\n host,\n kind: 'role',\n canonical: canonicalRel,\n owners: mergeAssetOwners(existingProj, resolved.targetBundle ?? undefined)\n .concat(canonicalRecord?.owners ?? [])\n .filter((o, i, arr) => arr.indexOf(o) === i),\n hash: await this.calculateHash(dest),\n installedAt: existingProj?.installedAt ?? new Date().toISOString(),\n managedMarker: true,\n };\n }\n }\n }\n }\n\n public async install(identifier: string, options: InstallOptions = {}): Promise<{ installed: ResolvedAssets; targetDirs: string[]; dryRun: boolean; method: InstallMethod; projections: ProjectionInfo[] }> {\n const scope = this.parseScope(options);\n const method = this.parseMethod(options);\n const hosts = this.parseHosts(options);\n\n const resolved = await this.registry.resolve(identifier);\n const registryDir = this.registry.getRegistryDir();\n\n // Fan-out only from the canonical state dir, and only to projection-capable hosts.\n const hasCanonicalAgents = hosts.includes('agents');\n const fanoutHosts = (options.fanout || [])\n .map(h => (typeof h === 'string' ? h.trim().toLowerCase() : h))\n .filter(h => isKnownHost(h) && HOST_REGISTRY[h]?.projectionCapable);\n // Plan 023 B (ADR 0022) — the `agents` host's directory is the STATE DIR: the `.agents/` store\n // or the store-less `.claude/.agents-united/` sidecar. Every other host keeps its own dir.\n const stateDir = InstallEngine.resolveInstallStateDir(scope, options, fanoutHosts);\n const targetDirs: string[] = hosts.map(h =>\n options.targetDir && !(h === 'agents') ? path.resolve(options.targetDir)\n : h === 'agents' ? stateDir\n : AgentHostAdapter.resolveHostDir(scope, h, options.targetDir));\n\n if (options.dryRun) {\n let effectiveDryFanout = fanoutHosts;\n let effectiveDryPluginLane = options.pluginLane === true;\n const lockfilePath = path.join(stateDir, 'agents-united.json');\n if (await fs.pathExists(lockfilePath)) {\n const lockfile = await fs.readJson(lockfilePath).catch(() => null);\n if (options.fanout === undefined && hasCanonicalAgents && lockfile?.fanout) {\n effectiveDryFanout = (lockfile.fanout as string[])\n .filter(h => isKnownHost(h) && HOST_REGISTRY[h]?.projectionCapable);\n }\n // The plugin-lane opt-in is sticky (see `effectivePluginLane`), so the dry-run plan must\n // reflect the recorded choice rather than reporting a package it would not prune.\n if (options.pluginLane === undefined && lockfile?.pluginLane === true) {\n effectiveDryPluginLane = true;\n }\n }\n const projections = hasCanonicalAgents\n ? await this.buildProjections(effectiveDryFanout, resolved, registryDir, scope, stateDir, effectiveDryPluginLane)\n : [];\n return { installed: resolved, targetDirs, dryRun: true, method, projections };\n }\n\n\n const now = new Date().toISOString();\n // Collect projections across target-dir iterations (dedup by host+path).\n const projections: ProjectionInfo[] = [];\n const agentsTarget = stateDir;\n // ADR 0022 upgrade path: a store-backed install into a workspace that so far had only the\n // sidecar moves the sidecar into `.agents/` first (keys need no rewrite: `files` are\n // state-dir-relative, `projections` root-relative). Crash-safe: the next run finishes it.\n if (hasCanonicalAgents) await InstallEngine.upgradeSidecarToStore(stateDir);\n\n for (const targetDir of targetDirs) {\n const subPaths = AgentHostAdapter.getSubPaths(targetDir);\n // The sidecar is an immutable snapshot: always copies, never symlinks into the registry.\n const iterMethod: InstallMethod = isSidecarDir(targetDir) ? 'copy' : method;\n\n await fs.ensureDir(subPaths.agentsDir);\n await fs.ensureDir(subPaths.skillsDir);\n if (resolved.workflows && resolved.workflows.length > 0) {\n await fs.ensureDir(subPaths.workflowsDir);\n }\n await fs.ensureDir(subPaths.rulesDir);\n\n const lockfile = await this.readLockfile(subPaths.lockfile);\n await this.migrateLegacyWorkspaceWorkflows(targetDir, lockfile);\n lockfile.scope = scope;\n lockfile.method = iterMethod;\n // Plan 023 B — record the shape only on a sidecar; a store-backed lockfile keeps its exact shape.\n if (isSidecarDir(targetDir)) lockfile.storeShape = 'sidecar';\n else delete lockfile.storeShape;\n lockfile.hosts = hosts;\n\n // Fan-out resolution: an explicit --fanout wins and is persisted to the lockfile;\n // otherwise the fan-out recorded at the original install is inherited, so\n // `agents update` / plain re-install regenerate projections without the flag.\n const effectiveFanout = (options.fanout !== undefined ? fanoutHosts : (lockfile.fanout ?? []))\n .filter(h => isKnownHost(h) && HOST_REGISTRY[h]?.projectionCapable);\n if (options.fanout !== undefined) {\n lockfile.fanout = effectiveFanout;\n }\n\n // Declared Asset Set of the bundle being installed (its own bundles.json fields,\n // NOT the inherited/resolved superset). Inherited parent assets are deployed but\n // are NOT owned by this bundle, so a child install never over-claims provenance.\n const declared = new Set<string>();\n // A real bundle definition draws the Declared Asset Set line; a Domain-Atlas pseudo-entry\n // (`domain:*`) or unknown identifier has no definition to draw it from, so everything it\n // resolves is its declared set. Without this, the ownership gate below stamps `owners: []`\n // on every record of an unbundled install and the assets become unremovable residue.\n let hasDeclaredRoster = false;\n if (resolved.targetBundle) {\n const bundleDef = await this.registry.getBundle(resolved.targetBundle);\n if (bundleDef) {\n hasDeclaredRoster = true;\n if (bundleDef.orchestrator) declared.add(`agents/${bundleDef.orchestrator}`);\n (bundleDef.agents || []).forEach(a => declared.add(`agents/${a}`));\n (bundleDef.skills || []).forEach(s => declared.add(`skills/${s}/SKILL.md`));\n (bundleDef.workflows || []).forEach(w => declared.add(`workflows/${w}`));\n }\n }\n const declaresAsset = (assetKey: string): boolean => !hasDeclaredRoster || declared.has(assetKey);\n\n // Copy/Symlink Agents\n for (const agentFile of resolved.agents) {\n const src = path.join(registryDir, 'agents', agentFile);\n const dest = path.join(subPaths.agentsDir, agentFile);\n\n if (await fs.pathExists(dest) && !options.force && method !== 'symlink') {\n const existingHash = await this.calculateHash(dest).catch(() => null);\n const relPath = path.relative(targetDir, dest);\n if (existingHash && lockfile.files[relPath] && lockfile.files[relPath].hash !== existingHash) {\n throw new Error(`File ${relPath} has user modifications. Use --force to overwrite.`);\n }\n }\n\n const actualMethod = await this.deployFile(src, dest, iterMethod, options.force);\n const hash = await this.calculateHash(src);\n const relPath = this.toPosix(path.relative(targetDir, dest));\n // Preserve projection tracking and co-ownership across re-installs;\n // applyFanout re-records the current fan-out below (deduplicated).\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n const owners = resolved.targetBundle && declaresAsset(`agents/${agentFile}`)\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n\n if (!lockfile.installed.agents.includes(agentFile)) {\n lockfile.installed.agents.push(agentFile);\n }\n }\n\n // Copy/Symlink Skills\n for (const skillName of resolved.skills) {\n const src = path.join(registryDir, 'skills', skillName);\n const dest = path.join(subPaths.skillsDir, skillName);\n\n const actualMethod = await this.deployFile(src, dest, iterMethod, options.force);\n const skillFile = path.join(src, 'SKILL.md');\n if (await fs.pathExists(skillFile)) {\n const hash = await this.calculateHash(skillFile);\n const relPath = this.toPosix(path.relative(targetDir, path.join(subPaths.skillsDir, skillName, 'SKILL.md')));\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n const owners = resolved.targetBundle && declaresAsset(`skills/${skillName}/SKILL.md`)\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n }\n\n // Gate 7 sidecar fix (2026-09-25, ADR 0017 amendment): skill folders ship sidecar\n // files (LICENSE.txt, references/**) alongside SKILL.md. Every deployed file gets a\n // lockfile record with owners — an unrecorded sidecar is an uninstall orphan.\n const sidecarStack: string[] = [dest];\n while (sidecarStack.length > 0) {\n const dir = sidecarStack.pop() as string;\n for (const entry of await fs.readdir(dir, { withFileTypes: true })) {\n const abs = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n sidecarStack.push(abs);\n continue;\n }\n const sideRel = this.toPosix(path.relative(targetDir, abs));\n if (abs === path.join(dest, 'SKILL.md')) continue;\n const existingSide = lockfile.files[sideRel];\n const existingSideOwners = existingSide?.owners ?? [];\n const sideOwners = resolved.targetBundle && declaresAsset(`skills/${skillName}/SKILL.md`)\n ? Array.from(new Set([...existingSideOwners, resolved.targetBundle]))\n : existingSideOwners;\n lockfile.files[sideRel] = {\n hash: await this.calculateHash(abs),\n bundle: existingSide?.bundle ?? resolved.targetBundle,\n owners: sideOwners,\n method: actualMethod,\n installedAt: existingSide?.installedAt ?? now,\n ...(existingSide?.projectedTo ? { projectedTo: existingSide.projectedTo } : {}),\n };\n }\n }\n\n if (!lockfile.installed.skills.includes(skillName)) {\n lockfile.installed.skills.push(skillName);\n }\n }\n\n // Copy/Symlink Workflows\n for (const workflowFile of resolved.workflows) {\n const src = path.join(registryDir, 'workflows', workflowFile);\n const dest = path.join(subPaths.workflowsDir, workflowFile);\n\n const actualMethod = await this.deployFile(src, dest, iterMethod, options.force);\n const hash = await this.calculateHash(src);\n const relPath = this.toPosix(path.relative(targetDir, dest));\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n const owners = resolved.targetBundle && declaresAsset(`workflows/${workflowFile}`)\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n\n lockfile.installed.workflows = lockfile.installed.workflows || [];\n if (!lockfile.installed.workflows.includes(workflowFile)) {\n lockfile.installed.workflows.push(workflowFile);\n }\n }\n\n // Copy/Symlink Rules\n for (const ruleFile of resolved.rules) {\n const src = path.join(registryDir, 'rules', ruleFile);\n const dest = path.join(subPaths.rulesDir, ruleFile);\n\n if (await fs.pathExists(src)) {\n const actualMethod = await this.deployFile(src, dest, iterMethod, options.force);\n const hash = await this.calculateHash(src);\n const relPath = this.toPosix(path.relative(targetDir, dest));\n const existing = lockfile.files[relPath];\n const existingOwners = existing?.owners ?? [];\n // Rule files are bundle-derived coordination artifacts, not members of the\n // declared asset set: every installing bundle always owns the rule it deploys.\n const owners = resolved.targetBundle\n ? Array.from(new Set([...existingOwners, resolved.targetBundle]))\n : existingOwners;\n lockfile.files[relPath] = {\n hash,\n bundle: existing?.bundle ?? resolved.targetBundle,\n owners,\n method: actualMethod,\n installedAt: existing?.installedAt ?? now,\n ...(existing?.projectedTo ? { projectedTo: existing.projectedTo } : {}),\n };\n }\n }\n\n // Update Lockfile Bundles\n if (resolved.targetBundle) {\n if (!lockfile.installed.bundles.includes(resolved.targetBundle)) {\n lockfile.installed.bundles.push(resolved.targetBundle);\n }\n lockfile.bundleVersions = lockfile.bundleVersions || {};\n const bundleDef = await this.registry.getBundle(resolved.targetBundle);\n lockfile.bundleVersions[resolved.targetBundle] = bundleDef?.version || '1.0.0';\n\n if (options.mode) {\n lockfile.bundleModes = lockfile.bundleModes || {};\n lockfile.bundleModes[resolved.targetBundle] = options.mode;\n }\n }\n\n // Fan-out canonical `.agents/` assets into selected runtimes (only when this\n // iteration is the canonical agents store AND a fan-out is in effect — either\n // passed explicitly or inherited from the lockfile).\n if (hasCanonicalAgents && effectiveFanout.length > 0 && path.resolve(targetDir) === path.resolve(agentsTarget)) {\n await this.applyFanout(effectiveFanout, resolved, registryDir, scope, targetDir, lockfile, options, projections);\n }\n\n // Plan 023 A — plain-session guard, Claude lane only (same canonical-store iteration).\n if (hasCanonicalAgents && effectiveFanout.includes('claude') && path.resolve(targetDir) === path.resolve(agentsTarget)) {\n await this.applySessionGuard(scope, workspaceRootOf(agentsTarget), lockfile, options, projections);\n }\n\n // Plan 024 S4 — opt-in command-permission preset (same canonical-store iteration).\n if (hasCanonicalAgents && effectiveFanout.length > 0 && path.resolve(targetDir) === path.resolve(agentsTarget)) {\n await this.applyPermissionPreset(scope, workspaceRootOf(agentsTarget), lockfile, options, effectiveFanout, projections);\n }\n\n await fs.writeJson(subPaths.lockfile, lockfile, { spaces: 2 });\n }\n\n return { installed: resolved, targetDirs, dryRun: false, method, projections };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport type { InstallScope, AgentHost } from './types.js';\nimport {\n isKnownHost,\n resolveHostProjectDir,\n resolveHostGlobalDir,\n} from './hosts.js';\n\nexport class AgentHostAdapter {\n public static resolveHostDir(scope: InstallScope = 'project', host: AgentHost = 'agents', overrideDir?: string): string {\n if (overrideDir) {\n return path.resolve(overrideDir);\n }\n\n // Behaviour back-compat: default to the canonical 'agents' dir for unknown ids.\n if (!isKnownHost(host)) {\n host = 'agents';\n }\n\n const home = os.homedir();\n const cwd = process.cwd();\n\n if (scope === 'global') {\n return resolveHostGlobalDir(host, home);\n }\n\n // Project scope\n return resolveHostProjectDir(host, cwd);\n }\n\n public static getSubPaths(targetDir: string) {\n return {\n agentsDir: path.join(targetDir, 'agents'),\n skillsDir: path.join(targetDir, 'skills'),\n workflowsDir: path.join(targetDir, 'workflows'),\n rulesDir: path.join(targetDir, 'rules'),\n lockfile: path.join(targetDir, 'agents-united.json'),\n };\n }\n}\n\n// Backward compatibility facade\nexport class TargetAdapter {\n public static resolveTargetDir(scope: InstallScope = 'project', overrideDir?: string): string {\n return AgentHostAdapter.resolveHostDir(scope, 'agents', overrideDir);\n }\n\n public static getSubPaths(targetDir: string) {\n return AgentHostAdapter.getSubPaths(targetDir);\n }\n}\n","import path from 'node:path';\nimport type { AgentHost } from './types.js';\n\nexport type ProjectionProfile =\n | 'antigravity'\n | 'claude-code'\n | 'cursor'\n | 'cline'\n | 'opencode'\n | 'agentsmd';\n\nexport type HostStatus = 'supported' | 'under-development';\n\nexport interface HostDefinition {\n id: string;\n label: string;\n projectDir: string; // '.claude' | '.cline' | '.opencode' | '.agents' | ...\n globalDirSegments: string[]; // joined under homedir, e.g. ['.claude'] or ['.config','opencode']\n agentsSubdir?: string; // 'agents' | 'agent' | undefined (agentsmd-only hosts)\n detectionMarkers: string[]; // ['.cline', '.clinerules'], ['.claude'], ...\n profile: ProjectionProfile;\n projectionCapable: boolean; // false for 'agents' (it IS the canonical) & 'gemini'\n /** Product availability. 'supported' hosts are selectable in the TUI; 'under-development' hosts are listed but unavailable (display + docs only). */\n status: HostStatus;\n}\n\nexport const HOST_REGISTRY: Record<string, HostDefinition> = {\n agents: {\n id: 'agents',\n label: 'Google Antigravity & Master Library (📁 .agents/)',\n projectDir: '.agents',\n globalDirSegments: ['.agents'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.agents'],\n profile: 'antigravity',\n projectionCapable: false,\n status: 'supported',\n },\n gemini: {\n id: 'gemini',\n label: 'Antigravity legacy (📁 .gemini/)',\n projectDir: '.gemini',\n globalDirSegments: ['.gemini', 'config'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.gemini'],\n profile: 'antigravity',\n projectionCapable: false,\n status: 'supported',\n },\n claude: {\n id: 'claude',\n label: 'Anthropic Claude Code (📁 .claude/)',\n projectDir: '.claude',\n globalDirSegments: ['.claude'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.claude'],\n profile: 'claude-code',\n projectionCapable: true,\n status: 'supported',\n },\n cursor: {\n id: 'cursor',\n label: 'Cursor IDE (📁 .cursor/)',\n projectDir: '.cursor',\n globalDirSegments: ['.cursor'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.cursor'],\n profile: 'cursor',\n projectionCapable: true,\n status: 'under-development',\n },\n cline: {\n id: 'cline',\n label: 'Cline (📁 .cline/)',\n projectDir: '.cline',\n globalDirSegments: ['.cline'],\n agentsSubdir: 'agents',\n detectionMarkers: ['.cline', '.clinerules'],\n profile: 'cline',\n projectionCapable: true,\n status: 'supported',\n },\n opencode: {\n id: 'opencode',\n label: 'OpenCode (📁 .opencode/)',\n projectDir: '.opencode',\n globalDirSegments: ['.config', 'opencode'],\n agentsSubdir: 'agent',\n detectionMarkers: ['.opencode', 'opencode.json'],\n profile: 'opencode',\n projectionCapable: true,\n status: 'under-development',\n },\n codex: {\n id: 'codex',\n label: 'OpenAI Codex, Copilot, Aider & Zed (📄 ./AGENTS.md)',\n projectDir: '.',\n globalDirSegments: ['.codex'],\n agentsSubdir: undefined,\n detectionMarkers: ['AGENTS.md', '.codex'],\n profile: 'agentsmd',\n projectionCapable: true,\n status: 'under-development',\n },\n};\n\nexport const KNOWN_HOST_IDS = Object.keys(HOST_REGISTRY);\nexport function isKnownHost(id: string): id is keyof typeof HOST_REGISTRY {\n return Object.prototype.hasOwnProperty.call(HOST_REGISTRY, id);\n}\n\n/**\n * Splits a `--target`/`--fanout`-style option value into host ids.\n *\n * On Windows PowerShell, an unquoted `a,b` is parsed as an array literal, and PowerShell\n * flattens that array into a single space-joined argument when invoking a native command —\n * so `--fanout claude,cline` arrives here as the one string `\"claude cline\"` (comma gone,\n * space in its place; verified against the owner's field test, 2026-09-28). Host ids never\n * contain whitespace, so splitting on comma or whitespace is unambiguous and safe.\n */\nexport function splitHostList(value: string): string[] {\n return value.split(/[,\\s]+/).filter(Boolean);\n}\n/** Hosts on the product's supported focus list (Antigravity, Cline, Claude Code). */\nexport const SUPPORTED_HOST_IDS = Object.values(HOST_REGISTRY)\n .filter((h) => h.status === 'supported')\n .map((h) => h.id);\n\n/** Listed in the TUI as 🚧 Under Development: projections still render, but the host is not on the supported focus list and is unavailable in the wizard. */\nexport const UNDER_DEVELOPMENT_HOST_IDS = Object.values(HOST_REGISTRY)\n .filter((h) => h.status === 'under-development')\n .map((h) => h.id);\n\n/** Display-only: announced on the TUI but deliberately absent from HOST_REGISTRY — target formats are unverified, so they are never stubbed (Plan 017 R3). */\nexport const PLANNED_HOSTS: ReadonlyArray<{ id: string; label: string }> = [\n { id: 'kimi', label: 'Kimi / Moonshot' },\n];\n\n/** TUI availability notice: supported focus list, 🚧 Under Development tags, and planned hosts. */\nexport function hostAvailabilityNotice(): string {\n const supported = SUPPORTED_HOST_IDS.map((id) => HOST_REGISTRY[id].label).join(' · ');\n const underDev = UNDER_DEVELOPMENT_HOST_IDS.map((id) => HOST_REGISTRY[id].label).join(' · ');\n const planned = PLANNED_HOSTS.map((h) => h.label).join(' · ');\n return [\n `✅ Supported: ${supported}`,\n `🚧 Under Development (unavailable): ${underDev}`,\n `🗓 Planned: ${planned} (projector on the planning list)`,\n ].join('\\n');\n}\n\nexport function resolveHostProjectDir(host: string, cwd: string): string {\n return path.resolve(cwd, HOST_REGISTRY[host].projectDir);\n}\nexport function resolveHostGlobalDir(host: string, home: string): string {\n return path.join(home, ...HOST_REGISTRY[host].globalDirSegments);\n}\n\n/**\n * The result of turning a user-facing \"which assistants do you use?\" selection into\n * an install plan: which directories get direct installs, and which get translated\n * copies fanned out from the main library (.agents/).\n */\nexport interface InstallTargetPlan {\n /** Direct install targets. Contains 'agents' whenever any translated copy is needed. */\n hosts: AgentHost[];\n /** Projection-capable runtimes that receive translated copies from the main library. */\n fanout: string[];\n /** True when .agents/ was not selected but had to be added as the shared source. */\n addedCanonicalStore: boolean;\n /**\n * Plan 023 B (ADR 0022, D4) — where the machine state lives: `'sidecar'` (the hidden\n * `.claude/.agents-united/` snapshot + lockfile, no `.agents/`) only when Claude is the sole\n * selected host and neither `--canonical-store` nor the plugin lane asks for the store.\n */\n storeShape: 'store' | 'sidecar';\n}\n\n/**\n * Maps a user selection of assistants/IDEs to an install plan (Option B):\n * - `agents` (main library) and `gemini` (legacy Antigravity) install directly.\n * - Every other assistant (Claude Code, Cursor, Cline, OpenCode, Codex) receives a\n * translated copy projected from the main library — never an untranslated direct\n * install, so no runtime ever gets Antigravity-only frontmatter it cannot parse.\n * - When any translated copy is needed, the main library is added automatically.\n */\nexport function planInstallTargets(\n selected: string[],\n opts: { canonicalStore?: boolean; pluginLane?: boolean } = {},\n): InstallTargetPlan {\n const normalized = Array.from(\n new Set(selected.map(s => (typeof s === 'string' ? s.trim().toLowerCase() : '')).filter(Boolean))\n );\n const known = normalized.filter(isKnownHost);\n\n const fanout = known.filter(h => HOST_REGISTRY[h].projectionCapable);\n const hosts = known.filter(h => !HOST_REGISTRY[h].projectionCapable) as AgentHost[];\n\n // ADR 0022 (D4): Claude alone needs no canonical store — its created artifacts are\n // self-contained, and the sidecar keeps the machine state. Every other selection keeps `.agents/`.\n const storeShape: 'store' | 'sidecar' =\n hosts.length === 0 && fanout.length === 1 && fanout[0] === 'claude' && !opts.canonicalStore && !opts.pluginLane\n ? 'sidecar'\n : 'store';\n\n let addedCanonicalStore = false;\n if (fanout.length > 0 && !hosts.includes('agents')) {\n // The `agents` host is the state-dir host in both shapes; only a store shape adds `.agents/`.\n hosts.unshift('agents');\n addedCanonicalStore = storeShape === 'store';\n }\n if (hosts.length === 0 && fanout.length === 0) {\n hosts.push('agents');\n }\n\n return { hosts, fanout, addedCanonicalStore, storeShape };\n}","import YAML from 'yaml';\nimport type { ProjectionProfile } from './hosts.js';\nimport { ClineProjector } from './cline-projector.js';\n\n/**\n * Error raised by {@link HostProjector} when a canonical file cannot be projected:\n * missing frontmatter, invalid YAML, or a serialization failure. Always carries the\n * canonical file name (relative path) and, when known, the underlying cause.\n */\nexport class ProjectionError extends Error {\n public readonly fileName: string;\n public readonly cause?: unknown;\n\n constructor(message: string, fileName: string, cause?: unknown) {\n super(message, { cause });\n this.name = 'ProjectionError';\n this.fileName = fileName;\n this.cause = cause;\n }\n}\n\n/** Result of projecting one canonical asset into a host runtime's dialect. */\nexport interface ProjectionResult {\n /** Full output file: frontmatter + managed marker + verbatim body. */\n content: string;\n /** Dropped tools, degraded orchestrator notices, etc. */\n warnings: string[];\n}\n\n/** A canonical asset destined for the root AGENTS.md bridge index. */\nexport interface IndexableAsset {\n name: string;\n type: 'agent' | 'skill' | 'workflow';\n relPath: string;\n}\n\n/**\n * Antigravity tool name -> host-native tool name. Anything not present here is\n * **unknown**: it is dropped from the output and reported in `warnings` — never kept\n * in its original form and never assigned an invented mapping. The set covers every\n * documented tool in plan 007 §5; unknown tools (e.g. invoke_subagent) are dropped.\n */\nexport const TOOL_NAME_MAP: Record<string, string> = {\n view_file: 'Read',\n replace_file_content: 'Edit',\n write_to_file: 'Write',\n run_command: 'Bash',\n grep_search: 'Grep',\n list_dir: 'Glob',\n read_file: 'Read',\n search_file_content: 'Grep',\n apply_diff: 'Edit',\n web_search: 'WebSearch',\n};\n\n/** Antigravity-only keys that must never be projected into other runtimes. */\nconst ANTIGRAVITY_ONLY_KEYS = [\n 'version',\n 'type',\n 'permissionMode',\n 'commandExecutionPolicy',\n 'mainAgent',\n 'subagent',\n 'hooks',\n 'inheritCustomizations',\n 'rules',\n 'effort',\n] as const;\n\n/** Reused from src/core/doctor.ts:48. */\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]+?)\\r?\\n---/;\n\nexport class HostProjector {\n /**\n * Splits a canonical file into its YAML frontmatter metadata and markdown body.\n * The returned body starts right after the closing `---` delimiter so callers can\n * insert a managed marker as the very first body line.\n */\n public static parseFrontmatter(\n content: string,\n fileName = '<memory>'\n ): { meta: Record<string, unknown>; body: string } {\n const match = content.match(FRONTMATTER_REGEX);\n if (!match) {\n throw new ProjectionError(\n `No YAML frontmatter found in ${fileName}. Expected a leading \"---\" block.`,\n fileName\n );\n }\n let parsed: unknown;\n try {\n parsed = YAML.parse(match[1]);\n } catch (cause) {\n const err =\n cause instanceof Error ? cause : new Error(typeof cause === 'string' ? cause : '');\n throw new ProjectionError(\n `Invalid YAML frontmatter in ${fileName}: ${err.message}`,\n fileName,\n err\n );\n }\n const meta =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n // Strip the single line terminator that ends the closing `---` delimiter so a\n // projected managed marker becomes the true first line of the returned body.\n const body = content.slice(match[0].length).replace(/^\\r?\\n/, '');\n return { meta, body };\n }\n/**\n * Projects a canonical `.agents/` file into the given {@link ProjectionProfile}'s\n * native dialect, stamping it with the managed marker and preserving the body\n * verbatim (line endings normalized to `\\n`).\n */\n public static projectAgent(\n md: string,\n profile: ProjectionProfile,\n canonicalRelPath: string\n ): ProjectionResult {\n const { meta, body } = HostProjector.parseFrontmatter(md, canonicalRelPath);\n const warnings: string[] = [];\n const normalizedBody = body.replace(/\\r\\n/g, '\\n');\n const marker = `<!-- managed-by: agents-united | profile: ${profile} | canonical: ${canonicalRelPath} | do not edit -->`;\n\n // agentsmd: AGENTS.md bridge entry (name -> link text, description -> table cell,\n // body -> link to the canonical path).\n if (profile === 'agentsmd') {\n const name = typeof meta.name === 'string' ? meta.name : '(unnamed)';\n const description =\n typeof meta.description === 'string'\n ? meta.description.replace(/[\\r\\n]+/g, ' ').replace(/\\|/g, '\\\\|')\n : '';\n const link = canonicalRelPath.replace(/\\\\/g, '/');\n const content = [\n `## ${name}`,\n '',\n `| ${name} | ${description} |`,\n '| --- | --- |',\n '',\n `[View source](${link})`,\n '',\n marker,\n '',\n ].join('\\n');\n return { content, warnings };\n }\n\n if (profile === 'cline') {\n // ADR 0013: Cline consumes configured-agent YAML (.cline/agents/<role>.yml),\n // not markdown role copies.\n const content = ClineProjector.renderConfiguredAgent(md, canonicalRelPath);\n return { content, warnings };\n }\n\n // Frontmatter profiles: claude-code, cursor, opencode. Keep name/description;\n // keep model unless `inherit`; translate tools; drop all Antigravity-only keys\n // (see field policy, plan 007 §5 step 3).\n const out: Record<string, unknown> = {};\n out.name = meta.name;\n if (typeof meta.description === 'string') {\n out.description = meta.description;\n }\n if (meta.model !== undefined && meta.model !== 'inherit') {\n out.model = meta.model;\n }\n // Explicitness guard: never let an Antigravity-only key leak into a native profile,\n // even if a future refactor stops building `out` from a clean object map.\n for (const key of ANTIGRAVITY_ONLY_KEYS) {\n delete out[key];\n }\n if (Array.isArray(meta.tools)) {\n const translated: string[] = [];\n for (const raw of meta.tools) {\n if (typeof raw !== 'string') {\n continue;\n }\n const mapped = TOOL_NAME_MAP[raw];\n if (mapped !== undefined) {\n translated.push(mapped);\n } else {\n warnings.push(\n `Dropping unknown tool \"${raw}\" for profile ${profile}: no known name mapping (never kept, never invented).`\n );\n }\n }\n out.tools = translated;\n }\n\n let yamlStr: string;\n try {\n yamlStr = YAML.stringify(out).replace(/\\r\\n/g, '\\n').trimEnd();\n } catch (cause) {\n const err = cause instanceof Error ? cause : new Error(String(cause));\n throw new ProjectionError(\n `Failed to serialize frontmatter for ${canonicalRelPath}: ${err.message}`,\n canonicalRelPath,\n err\n );\n }\n const content = `---\\n${yamlStr}\\n---\\n${marker}\\n${normalizedBody}`;\n return { content, warnings };\n }\n\n /**\n * Returns true when `content` is one of our managed projections. Agent projections\n * carry the marker as the first body line after the frontmatter; the AGENTS.md\n * bridge has no frontmatter, so the whole document is checked. Used to distinguish\n * \"our own deterministic projection\" (safe to regenerate) from foreign user files\n * (never overwritten without --force).\n */\n public static hasManagedMarker(content: string): boolean {\n const match = content.match(FRONTMATTER_REGEX);\n if (match) {\n const rest = content.slice(match[0].length).replace(/^\\r?\\n/, '');\n const firstLine = rest.split(/\\r?\\n/)[0] || '';\n return firstLine.includes('managed-by: agents-united');\n }\n return content.includes('managed-by: agents-united');\n }\n\n /**\n * Builds the root AGENTS.md bridge index, grouping canonical assets by type and\n * linking each to its canonical `.agents/` path. Deterministic for identical input.\n */\n public static buildAgentsMdIndex(\n assets: IndexableAsset[]\n ): string {\n const sections: Array<'agent' | 'skill' | 'workflow'> = ['agent', 'skill', 'workflow'];\n const lines: string[] = [];\n lines.push('# agents-united — Managed Agents Index');\n lines.push('');\n lines.push('<!-- managed-by: agents-united | profile: agentsmd | do not edit -->');\n lines.push('');\n lines.push(\n 'This index links the canonical `.agents/` store for runtimes without a subagent loader. Files under `.claude/`, `.cursor/`, `.cline/`, and `.opencode/` are machine-managed projections (see marker lines).'\n );\n lines.push('');\n for (const type of sections) {\n const heading =\n type === 'agent' ? '## Agents' : type === 'skill' ? '## Skills' : '## Workflows';\n lines.push(heading);\n lines.push('');\n const items = assets\n .filter((a) => a.type === type)\n .map((a) => ({ ...a, relPath: a.relPath.replace(/\\\\/g, '/') }));\n if (items.length === 0) {\n lines.push('_none_');\n lines.push('');\n continue;\n }\n for (const item of items) {\n lines.push(`- [${item.name}](${item.relPath})`);\n }\n lines.push('');\n }\n return lines.join('\\n');\n }\n}","import yaml from 'yaml';\nimport path from 'node:path';\nimport fs from 'fs-extra';\nimport type {\n AgentPluginManifest,\n BundleDefinition,\n ClineTeamManifest,\n InstallScope,\n PlanningLoopMode,\n ProjectionKind,\n ResolvedAssets,\n} from './types.js';\n\nexport interface PlannedClineArtifact {\n kind: ProjectionKind;\n canonical?: string;\n relPath: string; // posix root-relative path\n content?: string;\n sourceFilePath?: string; // for byte-for-byte binary/resource copy\n managedMarker: boolean;\n}\n\nexport class ClineProjector {\n /**\n * Managed marker inserted after YAML frontmatter in every rendered artifact.\n */\n private static marker(canonicalRelPath: string): string {\n const normCanonical = canonicalRelPath.replace(/\\\\/g, '/');\n return `<!-- managed-by: agents-united | profile: cline | canonical: ${normCanonical} | do not edit -->`;\n }\n\n private static runtimeNote = `## Cline runtime note\\n\\nUse the equivalent capabilities available in this Cline session. Canonical tool names describe\\nintent and may differ from Cline's runtime tool names. For delegation, prefer the configured\\nsubagent_* agent tools (projected under .cline/agents/), then session subagents; otherwise\\ncomplete the role in the main session.`;\n\n /**\n * Strip the canonical `subagent-` prefix. Cline prefixes configured-agent tool\n * names with `subagent_` itself, so keeping the prefix would produce names like\n * `subagent_subagent_marketing_growth_strategist`.\n */\n static stripSubagentPrefix(name: string): string {\n return name.trim().replace(/^subagent-/, '');\n }\n\n /**\n * Slugify a workflow display name into a usable slash-command name\n * (e.g. \"Digital Agency Full-Funnel Campaign Orchestration\" -> \"digital-agency-full-funnel-campaign-orchestration\").\n */\n static slugifyWorkflowName(name: string): string {\n return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');\n }\n\n /**\n * Render a Cline Configured Agent definition (.cline/agents/<role>.yml) from\n * canonical agent markdown content. Cline 3.x consumes YAML files with\n * frontmatter (name, description) and treats the body as the agent system prompt.\n */\n static renderConfiguredAgent(canonicalContent: string, canonicalRelPath: string, defaultMaxIterations?: number): string {\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) {\n throw new Error(`Canonical agent ${canonicalRelPath} is missing YAML frontmatter.`);\n }\n\n let parsed: Record<string, unknown> = {};\n try {\n parsed = (yaml.parse(match[1]) as Record<string, unknown>) || {};\n } catch {\n parsed = {};\n }\n\n const baseName = canonicalRelPath.replace(/\\\\/g, '/').split('/').pop() ?? '';\n const rawName = typeof parsed.name === 'string' && parsed.name.trim().length > 0\n ? parsed.name.trim()\n : baseName.replace(/\\.md$/i, '');\n const cleanFrontmatter: Record<string, unknown> = {\n name: this.stripSubagentPrefix(rawName),\n };\n if (typeof parsed.description === 'string' && parsed.description.trim().length > 0) {\n cleanFrontmatter.description = parsed.description.trim();\n }\n // ADR 0014 — canonical frontmatter is the single source of truth; the bundle\n // Consultation Budget `maxIterations` is only a default when frontmatter omits it.\n if (typeof parsed.maxIterations === 'number') {\n cleanFrontmatter.maxIterations = parsed.maxIterations;\n } else if (typeof defaultMaxIterations === 'number') {\n cleanFrontmatter.maxIterations = defaultMaxIterations;\n }\n // Plan 026 Step 4 (ADR 0023 decision 4) — the canonical per-agent skills list projects\n // 1:1 into the Configured Agent's `skills:` field. Verified against cline/cline PR #9502\n // (merged 2026-02-24, shipped by 3.0.65): `SubagentRunner.run()` uses this list only to\n // FILTER `getAvailableSkills()` down to the named subset before it enters\n // `SystemPromptContext` — it scopes discovery, it does not preload full SKILL.md bodies —\n // so this is a `mapped` disposition (registry/translation-ledger.json), not a preload risk.\n if (Array.isArray(parsed.skills)) {\n const skills = parsed.skills.filter((s): s is string => typeof s === 'string' && s.trim().length > 0);\n if (skills.length > 0) {\n cleanFrontmatter.skills = skills;\n }\n }\n\n const frontmatterStr = yaml.stringify(cleanFrontmatter).trim();\n const bodyStr = match[2].trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${this.marker(canonicalRelPath)}\\n\\n${this.runtimeNote}\\n\\n${bodyStr}\\n`;\n }\n\n /**\n * Derive the slash-command slug for a workflow from its frontmatter name,\n * falling back to the canonical filename. Kept separate from the renderer so the\n * projection filename and the frontmatter `name` are guaranteed to match.\n */\n static workflowSlug(canonicalContent: string, canonicalRelPath: string): string {\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n let humanName: string | undefined;\n if (match) {\n try {\n const parsed = (yaml.parse(match[1]) as Record<string, unknown>) || {};\n if (typeof parsed.name === 'string' && parsed.name.trim().length > 0) {\n humanName = parsed.name.trim();\n }\n } catch {\n // fall through to filename fallback\n }\n }\n const baseName = canonicalRelPath.replace(/\\\\/g, '/').split('/').pop() ?? '';\n return this.slugifyWorkflowName(humanName ?? baseName.replace(/\\.md$/i, ''));\n }\n\n /**\n * Render a Cline workflow projection (.cline/workflows/<slug>.md). The frontmatter\n * `name` is slugified so the workflow surfaces as a usable /<slug> command; the\n * human-readable title stays in `description` and the untouched body.\n */\n static renderWorkflowProjection(canonicalContent: string, canonicalRelPath: string): string {\n const slug = this.workflowSlug(canonicalContent, canonicalRelPath);\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n let description: string | undefined;\n if (match) {\n try {\n const parsed = (yaml.parse(match[1]) as Record<string, unknown>) || {};\n if (typeof parsed.description === 'string' && parsed.description.trim().length > 0) {\n description = parsed.description.trim();\n }\n } catch {\n // description stays undefined\n }\n }\n\n const cleanFrontmatter: Record<string, unknown> = { name: slug };\n if (description) cleanFrontmatter.description = description;\n\n const frontmatterStr = yaml.stringify(cleanFrontmatter).trim();\n const bodyStr = match ? match[2].trim() : canonicalContent.trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${this.marker(canonicalRelPath)}\\n\\n${bodyStr}\\n`;\n }\n\n /**\n * Render a Cline SKILL.md preserving frontmatter and placing managed marker after delimiter.\n */\n static renderSkillMd(canonicalContent: string, canonicalRelPath: string): string {\n const normCanonical = canonicalRelPath.replace(/\\\\/g, '/');\n const marker = `<!-- managed-by: agents-united | profile: cline | canonical: ${normCanonical} | do not edit -->`;\n\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) {\n return `${marker}\\n\\n${canonicalContent.trim()}`;\n }\n\n const rawYaml = match[1];\n const rawBody = match[2];\n\n let parsed: Record<string, unknown> = {};\n try {\n parsed = (yaml.parse(rawYaml) as Record<string, unknown>) || {};\n } catch {\n parsed = {};\n }\n\n const frontmatterStr = yaml.stringify(parsed).trim();\n const bodyStr = rawBody.trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${marker}\\n\\n${bodyStr}\\n`;\n }\n\n /**\n * Render Team Manifest YAML matching ClineTeamManifest schema.\n * @param excludeAddons optional addon names to omit from `recommendedAddons`\n * (used to stop advertising bundles already present in the workspace).\n */\n static renderTeamManifest(bundle: BundleDefinition, scope: InstallScope, excludeAddons: string[] = []): string {\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n const coordinatorName = coordinatorFile.replace(/\\.md$/, '');\n const coordinatorCanonical = `agents/${coordinatorFile}`;\n\n const roles = (bundle.agents || []).map((agentFile) => ({\n name: agentFile.replace(/\\.md$/, ''),\n canonicalPath: `agents/${agentFile}`,\n }));\n\n const sortedSkills = [...(bundle.skills || [])].sort();\n const rawWorkflows = bundle.workflows && bundle.workflows.length > 0\n ? bundle.workflows\n : (bundle.skills || []).filter(s => s.startsWith('workflow-'));\n const sortedWorkflows = [...rawWorkflows].sort();\n const recommendedAddons = (bundle.recommendedAddons || []).filter(a => !excludeAddons.includes(a));\n\n const manifest: ClineTeamManifest = {\n schemaVersion: 1,\n bundle: bundle.name,\n scope,\n coordinator: {\n name: coordinatorName,\n canonicalPath: coordinatorCanonical,\n },\n roles,\n skills: sortedSkills,\n workflows: sortedWorkflows,\n recommendedAddons,\n activation: {\n preferred: 'named-team',\n fallbacks: ['adaptive-session', 'single-orchestrator'],\n },\n };\n\n // ADR 0014/0015 — planning-loop bundles declare the loop config and persona map.\n // ADR 0015 defense-in-depth: omit budget/sidekicks from manifest YAML for\n // planner-orchestrator bundles (loader validation should already reject these).\n if (bundle.planningLoop?.enabled) {\n const mode = bundle.planningLoop.mode ?? 'subagent-first';\n manifest.planningLoop = {\n enabled: true,\n mode,\n // Only emit budget/sidekicks for subagent-first bundles\n ...(mode === 'subagent-first' && bundle.planningLoop.budget ? { budget: bundle.planningLoop.budget } : {}),\n ...(mode === 'subagent-first' && bundle.planningLoop.sidekicks ? { sidekicks: bundle.planningLoop.sidekicks } : {}),\n };\n if (bundle.personaAliases && Object.keys(bundle.personaAliases).length > 0) {\n manifest.personas = Object.entries(bundle.personaAliases).map(([persona, role]) => ({ persona, role }));\n }\n }\n\n return yaml.stringify(manifest);\n }\n\n /**\n * Render the coordinator rule file (.agents/plugins/<bundle>/rules/agents-united-<bundle>.md).\n * @param excludeAddons optional addon names to omit from the \"Recommended Addon\n * Policy\" list (used to stop advertising bundles already installed).\n */\n static renderCoordinatorRule(bundle: BundleDefinition, scope: InstallScope, excludeAddons: string[] = []): string {\n const marker = `<!-- managed-by: agents-united | profile: cline | bundle: ${bundle.name} | do not edit -->`;\n const manifestRelPath = scope === 'global'\n ? `~/.agents/plugins/${bundle.name}/agents-united/teams/${bundle.name}.yaml`\n : `.agents/plugins/${bundle.name}/agents-united/teams/${bundle.name}.yaml`;\n\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n const coordinatorName = coordinatorFile.replace(/\\.md$/, '');\n const coordinatorCanonical = `agents/${coordinatorFile}`;\n\n // Plan 016 post-gate fix — the roster must name the host projection as well as the canonical\n // definition. The Cline runtime discovers configured agents at `.cline/agents/<role>.yml` with the\n // `subagent-` prefix stripped (ADR 0013), so a canonical-only line sent the coordinator looking for a\n // file name that does not exist under that namespace. Mirrors the dual-path shape of the\n // \"Installed Workflows & Workflow Skills\" section directly below.\n const specialistLines = (bundle.agents || []).map((agentFile) => {\n const name = agentFile.replace(/\\.md$/, '');\n const projected = this.stripSubagentPrefix(name);\n return `- **${name}**: \\`.cline/agents/${projected}.yml\\` | \\`.agents/agents/${agentFile}\\``;\n });\n\n const rawWorkflows = [\n ...((bundle.workflows || []).map(w => w.replace(/\\.md$/i, ''))),\n ...((bundle.skills || []).filter(s => s.startsWith('workflow-'))),\n ];\n const uniqueWorkflows = Array.from(new Set(rawWorkflows)).sort();\n const workflowSection = uniqueWorkflows.length > 0\n ? `\\n### Installed Workflows & Workflow Skills\\n` +\n `Execute multi-step engineering procedures by consulting the corresponding workflow skill runbook (\\`.agents/skills/<name>/SKILL.md\\`) or triggering its slash command (\\`/<name>\\`):\\n` +\n uniqueWorkflows.map(w => `- **${w}**: \\`.cline/workflows/${w}.md\\` | \\`.agents/skills/${w}/SKILL.md\\``).join('\\n') +\n '\\n'\n : '';\n\n const addons = (bundle.recommendedAddons || []).filter(a => !excludeAddons.includes(a));\n const addonSection = addons.length > 0\n ? `\\n### Recommended Addon Policy\\nWhen user tasks require capabilities from: ${addons.join(', ')}, explain the capability and request user confirmation to install via \\`agents add <addon> -t cline -y\\` before running the installation.`\n : '';\n\n // ADR 0014/0015 — planning-loop bundles replace the soft delegation hint with a\n // mandatory planning policy. Bundles without the flag render byte-identical\n // output to the legacy rule. Mode determines which planning policy is rendered.\n const planning = bundle.planningLoop?.enabled === true ? bundle.planningLoop : undefined;\n const mode: PlanningLoopMode = planning?.mode ?? 'subagent-first';\n const budget = planning?.budget;\n const delegationStep = planning\n ? (mode === 'subagent-first'\n ? '2. **Subagent-First Delegation Policy (ADR 0014)**: execute specialist work through the configured `subagent_*` agent tools (projected under `.cline/agents/`), assigning non-overlapping scopes. Complete specialist work in the main session ONLY if the subagent tools are genuinely absent from this runtime or the task is trivial (single-file read, one-line answer, formatting) — never as a convenience or speed choice.'\n : '2. **Planner-Orchestrator Delegation Policy (ADR 0015)**: execute specialist work through the configured `subagent_*` agent tools (projected under `.cline/agents/`), assigning non-overlapping scopes. Complete specialist work in the main session ONLY if the subagent tools are genuinely absent from this runtime or the task is trivial (single-file read, one-line answer, formatting) — never as a convenience or speed choice.')\n : '2. Delegate specialist tasks using the configured `subagent_*` agent tools (projected under `.cline/agents/`) when available, assigning non-overlapping scopes; fall back to Agent Teams (`team_spawn_teammate`) or session subagents as needed.';\n\n \n \n const planningSection = planning\n ? (mode === 'subagent-first'\n ? '\\n\\n## Subagent-First Planning Dialogue Loop (ADR 0014)' +\n 'Run this loop BEFORE any substantive execution on a non-trivial task. Delegation-first is mandatory, not advisory.\\n\\n' +\n '### Phase 0 — User Alignment\\n' +\n 'If the user\\'s brief is ambiguous, grill it Socratically with the user first: `/grill-me` (strategy / non-code) or `/grill-with-docs` (code & docs; writes ADRs and updates CONTEXT.md).\\n\\n' +\n '### Phase 0.5 — Sidekick Clarification\\n' +\n 'Spawn at most ' + (planning.sidekicks?.max ?? 2) + ' relevant specialists (spawnable `subagent_*` tools) INTO this planning conversation to resolve remaining ambiguity. Sidekicks advise you; you relay their questions to the user.\\n\\n' +\n '### Phase 1 — Specialist Council\\n' +\n 'Have every relevant specialist return a Scope-of-Work Statement (max ' + (budget?.summaryWordCap ?? 150) + ' words): (1) my scope, (2) inputs I need from peers, (3) my deliverable per my own workflows, (4) at most 2 open questions.\\n\\n' +\n '### Phase 2 — Delegation Map\\n' +\n 'Synthesize the council output into a task → specialist map and present it to the user BEFORE execution. Then delegate per the map.\\n\\n' +\n '### Consultation Budget (hard caps)\\n' +\n '- Planning rounds (orchestrator ↔ council): max ' + (budget?.maxPlanningRounds ?? 2) + '\\n' +\n '- Peer exchanges per specialist pair: max ' + (budget?.maxPeerExchangesPerPair ?? 2) + ' directed questions\\n' +\n '- Scope-of-Work statement length: max ' + (budget?.summaryWordCap ?? 150) + ' words\\n' +\n '- Specialist per-invocation iteration cap: maxIterations: ' + (budget?.maxIterations ?? 8) + ' (rendered into .cline/agents/*.yml)'\n : '\\n\\n## Planner-Orchestrator Policy (ADR 0015)' +\n 'Plan solo, delegate execution. This mode replaces the Subagent-First Planning Dialogue Loop for single-discipline domain bundles.\\n\\n' +\n '### Phase 0 — User Alignment (solo)\\n' +\n 'If the user\\'s brief is ambiguous, grill it Socratically yourself: `/grill-me` (strategy / non-code) or `/grill-with-docs` (code & docs). Consult the bundle\\'s skills directly whenever they help you plan — you have the same skill access as your specialists. During planning, specialists are consulted read-only only (the Planning Consultation Phase gate); do not spawn them to produce deliverables.\\n\\n' +\n '### Planning Aid Boundary\\n' +\n 'While planning you may consult skills and reason to give the user PROVISIONAL answers and estimates. A concrete deliverable — data analysis, code, assets, documents — is specialist work: defer it to the delegation map, never produce it yourself during planning.\\n\\n' +\n '### Phase 2 — Delegation Map\\n' +\n 'Compose the task → specialist map from your domain expertise, the skill runbooks and the read-only consultation output, and present it to the user BEFORE execution.\\n\\n' +\n '### Execution\\n' +\n 'Delegate every deliverable to the configured `subagent_*` agent tools (projected under `.cline/agents/`), assigning non-overlapping scopes. Complete specialist work in the main session ONLY if the subagent tools are genuinely absent from this runtime or the task is trivial (single-file read, one-line answer, formatting) — never as a convenience or speed choice.')\n : '';\n\n const personaSection = planning && bundle.personaAliases && Object.keys(bundle.personaAliases).length > 0\n ? `\n\n### Persona → Spawnable Tool Map\n| Persona | Role / Spawnable tool |\n|---|---|\n${Object.entries(bundle.personaAliases).map(([persona, role]) => {\n const target = role.startsWith('subagent-')\n ? `${role} → \\`subagent_${this.stripSubagentPrefix(role).replace(/-/g, '_')}\\``\n : `${role} (you, the coordinator)`;\n return `| ${persona} | ${target} |`;\n}).join('\\n')}`\n : '';\n\n return `# Agents United — ${bundle.name} Coordinator Rule\n${marker}\n\n> Installed bundle: **${bundle.name}** (${scope} scope)\n> Team Manifest: \\`${manifestRelPath}\\`\n> Coordinator role: \\`${coordinatorName}\\` (\\`.agents/${coordinatorCanonical}\\`)\n\n## Activation Protocol\n1. At session start, read the Team Manifest (\\`${manifestRelPath}\\`) and coordinator role prompt (\\`.agents/${coordinatorCanonical}\\`).\n${delegationStep}\n3. For lightweight read-only research, use session subagents.\n4. Only specialist roles declared in the Team Manifest are active in this workspace.\n${planningSection}${personaSection}\n${specialistLines.length > 0 ? `\\n### Installed Specialist Roles\\n${specialistLines.join('\\n')}` : ''}\n${workflowSection}${addonSection}\n`;\n }\n\n /**\n * Plan all compound artifacts for a bundle installation into Cline.\n * @param excludeAddons optional addon names forwarded to the coordinator rule and\n * team manifest renderers so already-installed bundles are not advertised.\n */\n static async planCompoundProjection(\n bundle: BundleDefinition,\n scope: InstallScope,\n resolved: ResolvedAssets,\n registryDir: string,\n excludeAddons: string[] = []\n ): Promise<PlannedClineArtifact[]> {\n const artifacts: PlannedClineArtifact[] = [];\n const baseDir = `.agents/plugins/${bundle.name}`;\n\n // 0. Agent Plugin manifest (.agents/plugins/<bundle-name>/plugin.json)\n // agent-plugins.org v1.0.0. Its presence hard-stops Cline's code-plugin\n // scanner for this directory (isAgentPluginDirectory) and makes the package\n // portable to other Agent Plugins-conforming clients.\n const agentPluginManifest: AgentPluginManifest = {\n $schema: 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',\n name: bundle.name,\n version: bundle.version || '1.0.0',\n description: bundle.description || '',\n };\n artifacts.push({\n kind: 'plugin-manifest',\n relPath: `${baseDir}/plugin.json`.replace(/\\\\/g, '/'),\n content: JSON.stringify(agentPluginManifest, null, 2),\n managedMarker: false,\n });\n\n // 1. Configured agent roles (.cline/agents/<role>.yml) - Cline 3.x natively\n // discovers these and exposes each as a spawnable subagent_<name> tool.\n for (const agentFile of resolved.agents) {\n const canonicalRel = `agents/${agentFile}`;\n const srcPath = path.join(registryDir, 'agents', agentFile);\n if (await fs.pathExists(srcPath)) {\n const content = await fs.readFile(srcPath, 'utf8');\n const rendered = this.renderConfiguredAgent(\n content,\n canonicalRel,\n bundle.planningLoop?.enabled === true ? bundle.planningLoop.budget?.maxIterations : undefined, // ADR 0015: planner-orchestrator has no budget → undefined → key absent from .yml\n );\n const roleName = this.stripSubagentPrefix(agentFile.replace(/\\.md$/i, ''));\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `.cline/agents/${roleName}.yml`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // 2. Skills (.agents/plugins/<bundle-name>/skills/<skill>/**) - kept inside the\n // Agent Plugin package for cross-client portability (ADR 0013, decision 1).\n // Cline discovers the canonical .agents/skills/ copies natively, so no\n // additional Cline-side skill projection is emitted.\n for (const skillName of resolved.skills) {\n const skillSrcDir = path.join(registryDir, 'skills', skillName);\n if (await fs.pathExists(skillSrcDir)) {\n const entries = await fs.readdir(skillSrcDir, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n const entryRel = path.relative(skillSrcDir, path.join(entry.parentPath || skillSrcDir, entry.name)).replace(/\\\\/g, '/');\n const canonicalRel = `skills/${skillName}/${entryRel}`;\n const targetRel = `${baseDir}/skills/${skillName}/${entryRel}`.replace(/\\\\/g, '/');\n const fullSrcPath = path.join(skillSrcDir, entryRel);\n\n if (entry.name === 'SKILL.md') {\n const content = await fs.readFile(fullSrcPath, 'utf8');\n const rendered = this.renderSkillMd(content, canonicalRel);\n artifacts.push({\n kind: 'skill',\n canonical: canonicalRel,\n relPath: targetRel,\n content: rendered,\n managedMarker: true,\n });\n } else {\n // Auxiliary resource: byte-for-byte copy\n artifacts.push({\n kind: 'skill',\n canonical: canonicalRel,\n relPath: targetRel,\n sourceFilePath: fullSrcPath,\n managedMarker: false,\n });\n }\n }\n }\n }\n }\n\n // 3. Workflows (.cline/workflows/<slug>.md) - natively surfaced as /<slug>\n // slash commands by Cline 3.x.\n // ADR 0016: Project workflow skills (name starting with workflow-) into .cline/workflows/\n // retaining the workflow-* prefix so Cline users retain /workflow-* slash commands.\n const workflowSkillNames = resolved.skills.filter(s => s.startsWith('workflow-'));\n for (const skillName of workflowSkillNames) {\n const canonicalRel = `skills/${skillName}/SKILL.md`;\n const skillFilePath = path.join(registryDir, 'skills', skillName, 'SKILL.md');\n if (await fs.pathExists(skillFilePath)) {\n const content = await fs.readFile(skillFilePath, 'utf8');\n const slug = skillName;\n const rendered = this.renderWorkflowProjection(content, canonicalRel);\n artifacts.push({\n kind: 'workflow',\n canonical: canonicalRel,\n relPath: `.cline/workflows/${slug}.md`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // Fallback for any legacy resolved.workflows entries\n for (const workflowFile of resolved.workflows || []) {\n const canonicalRel = `workflows/${workflowFile}`;\n const srcPath = path.join(registryDir, 'workflows', workflowFile);\n if (await fs.pathExists(srcPath)) {\n const content = await fs.readFile(srcPath, 'utf8');\n const slug = this.workflowSlug(content, canonicalRel);\n const rendered = this.renderWorkflowProjection(content, canonicalRel);\n artifacts.push({\n kind: 'workflow',\n canonical: canonicalRel,\n relPath: `.cline/workflows/${slug}.md`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // 4. Coordinator Rule (.cline/rules/agents-united-<bundle>.md) - natively\n // loaded as an always-active rule by Cline 3.x.\n const ruleContent = this.renderCoordinatorRule(bundle, scope, excludeAddons);\n artifacts.push({\n kind: 'rule',\n relPath: `.cline/rules/agents-united-${bundle.name}.md`.replace(/\\\\/g, '/'),\n content: ruleContent,\n managedMarker: true,\n });\n\n // 5. Projected Domain Rules (.cline/rules/<rule-file>)\n // Plan 015 Step 2 / §0/C6d + §0/C7. Cline has no per-agent rule scoping,\n // so `.cline/rules/` is the only lane available: project ONLY the\n // deduplicated, agent-referenced rule set (never the whole registry/rules\n // tree), sorted for byte-stable lockfile hashes and `agents doctor`.\n // Host entrypoint rules belong to their own hosts and are skipped.\n const hostEntrypointRules = new Set(['GEMINI.md', 'AGENTS.md', 'CLAUDE.md', 'CURSOR.md']);\n for (const ruleFile of [...(resolved.rules || [])].sort()) {\n if (hostEntrypointRules.has(ruleFile)) continue;\n const ruleSrcPath = path.join(registryDir, 'rules', ruleFile);\n if (await fs.pathExists(ruleSrcPath)) {\n const ruleFileContent = await fs.readFile(ruleSrcPath, 'utf8');\n // Rule modules carry no YAML frontmatter, so the managed marker is line 1.\n // HostProjector.hasManagedMarker() accepts that (its no-frontmatter path is\n // a plain includes('managed-by: agents-united')).\n artifacts.push({\n kind: 'rule',\n canonical: `rules/${ruleFile}`,\n relPath: `.cline/rules/${ruleFile}`.replace(/\\\\/g, '/'),\n content: `${ClineProjector.marker(`rules/${ruleFile}`)}\\n\\n${ruleFileContent.trim()}\\n`,\n managedMarker: true,\n });\n }\n }\n\n // 6. Team Manifest (.agents/plugins/<bundle-name>/agents-united/teams/<bundle>.yaml)\n const manifestContent = this.renderTeamManifest(bundle, scope, excludeAddons);\n artifacts.push({\n kind: 'team-manifest',\n relPath: `${baseDir}/agents-united/teams/${bundle.name}.yaml`.replace(/\\\\/g, '/'),\n content: manifestContent,\n managedMarker: false,\n });\n\n return artifacts;\n }\n}\n","import yaml from 'yaml';\nimport { managedGuardHooks } from './guard.js';\nimport path from 'node:path';\nimport fs from 'fs-extra';\nimport type {\n BundleDefinition,\n ClaudePluginManifest,\n\n InstallScope,\n LedgerDisposition,\n ProjectionKind,\n ResolvedAssets,\n TranslationLedgerEntry,\n} from './types.js';\nimport type { ClaudeDialect } from './types.js';\nimport { RESIDUE_PATTERNS_BY_HOST } from './residue-patterns.js';\nimport { CLAUDE_FIELD_POLICY, validateProjectionOverlays } from './overlays.js';\n\n/** Result of rendering one canonical asset into the Claude dialect. */\nexport interface ClaudeRenderResult {\n content: string;\n ledger: TranslationLedgerEntry[];\n}\n\n/** A planned Claude projection artifact (workspace-root-relative POSIX path). */\nexport interface PlannedClaudeArtifact {\n kind: ProjectionKind;\n canonical?: string;\n relPath: string;\n content?: string;\n sourceFilePath?: string;\n /** ADR 0018 decision 12 — distribution-only artifact: tracked, but never a `projectedTo` target. */\n distributionOnly?: boolean;\n\n managedMarker: boolean;\n}\n\n/** Canonical frontmatter keys that map 1:1 into a Claude field (no loss, no ledger row). */\nconst INLINE_KEYS = new Set([\n 'name',\n 'description',\n 'model',\n 'permissionMode',\n 'effort',\n 'tools',\n 'maxIterations',\n 'projections',\n]);\n\n/**\n * ADR 0018 decision 9 — every canonical feature that cannot survive verbatim carries exactly one\n * disposition. A drop with no entry here is a hard error, never a silent warning.\n */\nconst FEATURE_LEDGER: Record<string, { disposition: LedgerDisposition; rationale: string }> = {\n version: { disposition: 'mapped', rationale: 'Authoring metadata for the canonical store; no Claude field needed.' },\n type: { disposition: 'mapped', rationale: 'Canonical role discriminator; Claude distinguishes roles by file location.' },\n mainAgent: { disposition: 'mapped', rationale: 'Canonical masthead flag; Claude decides main-thread status at launch (--agent).' },\n subagent: { disposition: 'mapped', rationale: 'Canonical masthead flag; every file under .claude/agents/ is a subagent.' },\n inheritCustomizations: { disposition: 'mapped', rationale: 'Claude loads CLAUDE.md and project memory unless omitClaudeMd is set (flag-gated).' },\n commandExecutionPolicy: { disposition: 'unsupported', rationale: 'Antigravity shell policy has no Claude frontmatter equivalent; Bash permissions cover it.' },\n hooks: { disposition: 'unsupported', rationale: 'Antigravity hook schema (PreInvocation/PostInvocation matchers) differs from Claude hook events; canonical prose hooks are not translated and stay advisory. The one enforced hook is the managed PreToolUse guard every role carries (Plan 022 H5).' },\n rules: { disposition: 'mapped', rationale: 'Agent-referenced rules project into the lean .claude/rules/ lane.' },\n effort: { disposition: 'mapped', rationale: 'Reasoning effort passes through to the Claude effort field.' },\n invoke_subagent: { disposition: 'mapped', rationale: 'Delegation maps to the Claude Agent tool (allowlist on coordinators).' },\n send_message: { disposition: 'approximated', rationale: 'Maps to the Claude SendMessage tool; cross-session reach differs from Antigravity messaging.' },\n manage_task: { disposition: 'approximated', rationale: 'Maps to the Claude task tools (TaskCreate/TaskUpdate), but the live tools reference says they are \"provided by default only on the models listed under Task tool availability, and on other models when you opt in\" — so the grant can resolve to nothing depending on the model.' },\n schedule: { disposition: 'approximated', rationale: 'Maps to Cron tools, but Antigravity reactive liveness timers are event-driven rather than cron-scheduled.' },\n define_subagent: { disposition: 'approximated', rationale: 'Claude agents are pre-defined: runtime subagent definition is unavailable, so the prompt delegates via the Agent tool.' },\n manage_subagents: { disposition: 'approximated', rationale: 'Claude manages subagent lifecycle itself; the roster is static and the prompt delegates via the Agent tool.' },\n ask_question: { disposition: 'approximated', rationale: 'Claude exposes AskUserQuestion only in the main conversation (excluded from subagents by default).' },\n generate_image: { disposition: 'unsupported', rationale: 'Claude Code exposes no image-generation tool; asset creation must happen outside the agent run.' },\n skills: { disposition: 'degraded', rationale: 'Claude subagents discover project skills and can invoke them; the canonical preload list is not injected to avoid paying its token cost on every spawn.' },\n mcpServers: { disposition: 'mapped', rationale: 'Plan 029 A2 — a canonical `mcpServers:` entry projects into the Claude subagent `mcpServers:` field as a server NAME reference (`- name: <server>`), and the matching grant lands in `tools:` (`mcp__<server>`, or pinned read-only tool names for a read-only role). Credentials, `env` blocks and inline server definitions are never projected (Risk R4).' },\n};\n\nconst MARKER_PROFILE = 'claude';\n/**\n * The marker string `HostProjector.hasManagedMarker()` greps for. Kept as one constant because\n * the JSON plugin manifest (which cannot carry the HTML-comment form) must contain exactly this\n * substring to be recognised as ours by both `applyCompoundLane` and `agents doctor`.\n */\nconst MARKER_PREFIX = 'managed-by: agents-united';\n\nconst HOST = 'claude';\nconst ENTRYPOINT_RULES = new Set(['CLAUDE.md', 'CLAUDE.local.md', 'GEMINI.md', 'AGENTS.md', 'CURSOR.md']);\n\n/**\n * ADR 0018 decision 3 — a coordinator is the delegation hub, so its projected tool set is the\n * translated canonical list unioned with this baseline. Specialists keep exactly their declared\n * (translated) tools plus `Agent`, so a read-mostly specialist is never silently granted write tools.\n */\nconst COORDINATOR_BASELINE_TOOLS = ['Read', 'Write', 'Edit', 'Bash', 'Grep', 'Glob'];\n\n/** Plan 022 H3 — tools a `plan` (read-only) role never holds on this host. */\nconst READ_ONLY_EXCLUDED_TOOLS: ReadonlySet<string> = new Set(['Write', 'Edit', 'NotebookEdit', 'Bash']);\n\n/**\n * Plan 029 A2 — the canonical key naming the MCP servers a role may reach. A YAML sequence of\n * `- name: <server>` mapping objects; the renderer emits those names into the Claude frontmatter\n * and the matching grant into `tools:`.\n */\nconst MCP_SERVERS_KEY = 'mcpServers';\n\n/**\n * Plan 029 A2 / Risk R1 (owner decision: Option B) — what a READ-ONLY (`plan`) role receives for\n * each server it declares. A bare `mcp__<server>` grant resolves to EVERY tool that server\n * exposes — write tools included — and `READ_ONLY_EXCLUDED_TOOLS` only strips the built-ins, so a\n * read-only role never takes a server-level grant. It takes these exact read-only tool names\n * instead. A server absent from this table gets NO grant at all (fail closed): the role keeps the\n * `mcpServers:` name reference and the grant is withheld deliberately — a posture, not a\n * translation loss — so nothing is dropped silently.\n */\nconst READ_ONLY_MCP_TOOL_GRANTS: Record<string, readonly string[]> = {\n // Only GitHub tools whose names are read-only verbs (`search_*`, `get_*`, `list_*`, `*_read`).\n github: [\n 'mcp__github__search_code',\n 'mcp__github__get_file_contents',\n 'mcp__github__list_pull_requests',\n 'mcp__github__pull_request_read',\n ],\n // Context7 is documentation lookup only, so its published tools are read-only by construction.\n // Plan 029 Step 3 pin correction: `get-library-docs` is Context7's DEPRECATED tool name; the\n // current surface is `resolve-library-id` + `query-docs` (verified against the live MCP server).\n context7: ['mcp__context7__resolve-library-id', 'mcp__context7__query-docs'],\n};\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/;\n\nconst RUNTIME_NOTE = `## Claude runtime note\n\nDelegation runs through the Agent tool: the coordinator spawns the specialists named in its own tools\nallowlist; specialists hold no Agent tool and never spawn peers (the coordinator relays and wakes them).\nOutside Agent Teams (\\`--teams\\`), specialists cannot message each other by name: only the coordinator holds\ntheir agent IDs, so relay mode is the default and team mode exists only when the brief says so.\nCanonical tool names in this prompt were rewritten to their\nClaude equivalents; a fenced code block may still show the original spelling because code is preserved\nbyte-for-byte. A subagent does not hand results to a peer: its final report is returned to the\nconversation that spawned it, and on Claude Code v2.1.271+ in auto mode the runtime delivers it through the\nSubagentHandback tool.\n\nEnforced guard: a PreToolUse hook in this file's frontmatter blocks \\`git push --force\\`, \\`.env\\` writes and\n\\`vercel --prod\\` (exit 2, with the reason); ask the user to run those steps themselves.\nAll other lifecycle hooks described in this prompt are advisory: this host does not fire them.`;\n\n/** Plan 022 H5 / Plan 023 A0 — the managed PreToolUse guard (single source: guard.ts). */\nconst MANAGED_HOOKS = managedGuardHooks();\n\nexport class ClaudeProjector {\n /** Pure data (Plan 017 lifts this object into a shared HostDialectSpec). */\n public static readonly CLAUDE_DIALECT: ClaudeDialect = {\n id: 'claude',\n nameRegex: /^[a-z0-9]+(-[a-z0-9]+)*$/,\n toolVocabulary: {\n view_file: 'Read',\n read_file: 'Read',\n replace_file_content: 'Edit',\n apply_diff: 'Edit',\n multi_replace_file_content: 'Edit',\n write_to_file: 'Write',\n run_command: 'Bash',\n grep_search: 'Grep',\n search_file_content: 'Grep',\n list_dir: 'Glob',\n find_by_name: 'Glob',\n web_search: 'WebSearch',\n search_web: 'WebSearch',\n read_url_content: 'WebFetch',\n invoke_subagent: 'Agent',\n define_subagent: 'Agent',\n manage_subagents: 'Agent',\n send_message: 'SendMessage',\n manage_task: 'TaskCreate',\n schedule: 'CronCreate',\n ask_question: 'AskUserQuestion',\n // The runtime's own hand-off channel for subagents (Claude Code v2.1.271+, auto mode): it delivers\n // a subagent's final report to whichever conversation receives that subagent's result. It has no\n // Antigravity-dialect equivalent, so the lane grants it to specialists directly (see renderRole);\n // the token exists so a canonical agent could also name it explicitly.\n subagent_handback: 'SubagentHandback',\n },\n bodyToolVocabulary: {\n view_file: 'Read',\n read_file: 'Read',\n write_to_file: 'Write',\n replace_file_content: 'Edit',\n apply_diff: 'Edit',\n multi_replace_file_content: 'Edit',\n run_command: 'Bash',\n grep_search: 'Grep',\n find_by_name: 'Glob',\n list_dir: 'Glob',\n search_web: 'WebSearch',\n read_url_content: 'WebFetch',\n invoke_subagent: 'Agent',\n define_subagent: 'the Agent tool',\n manage_subagents: 'the Agent tool',\n // ADR 0018 decision 8 requires canonical tool names in prose to be rewritten, not just the\n // frontmatter vocabulary: a specialist reading \"reach a peer with `send_message`\" would otherwise\n // look for a tool that does not exist on this host. Whole-word and code-fence-aware like the rest.\n send_message: 'SendMessage',\n manage_task: 'TaskCreate',\n ask_question: 'AskUserQuestion',\n generate_image: 'image generation (unsupported on this host)',\n // `schedule` is deliberately absent: it is an ordinary English word, so rewriting it in prose\n // would corrupt sentences. Its loss is recorded once at frontmatter level instead.\n },\n commandVocabulary: {\n team_command: 'Agent Teams (opt-in: agents start --host claude --teams)',\n deep_planning_command: '/workflow-grill',\n interview_command: '/grill-me',\n },\n permissionModeMap: {\n acceptEdits: 'acceptEdits',\n readOnly: 'plan',\n requestReview: 'default',\n strict: 'default',\n },\n modelMap: { pro: 'sonnet', flash: 'haiku' },\n // ADR 0018 decision 7, amended 2026-09-22 by the product owner. The canonical catalog declares\n // `model: inherit` on all 59 agents, which made `inherit` the de-facto value and left every\n // projection inheriting the *session* model instead of a chosen posture. The intended posture is\n // explicit — coordinators reason on Opus at high effort, specialists run on Sonnet at medium\n // effort — so `inherit` now resolves to a role default rather than being omitted. Both fields are\n // documented subagent frontmatter: `model` accepts sonnet|opus|haiku|fable|<full id>|inherit, and\n // `effort` (low|medium|high|xhigh|max) overrides the session effort level. Caveats recorded rather\n // than coded around: Opus is unavailable on some plans, so a workspace may need a different anchor;\n // and `xhigh`/`max` exist only on newer models. Both are one-constant changes here.\n roleModelDefaults: { coordinator: 'opus', specialist: 'sonnet' },\n roleEffortDefaults: { coordinator: 'high', specialist: 'medium' },\n bodySectionOverrides: [\n {\n // Plan 019 escape hatch (2026-09-25): the old anchor — \"Subagent Delegation & Host\n // Routing\" — was residue (it described OTHER runtimes: Antigravity's language_server.exe\n // limitation and Cline's subagent_* tools) and the G1 purge deleted it. Its Claude-side\n // rendering survives as this per-host overlay, keyed on the neutral \"Delegation\n // Mechanics\" stub in canonical; hosts without an overlay render the stub itself.\n heading: /^#{2,3}\\s*.*Delegation Mechanics/m,\n replacement: [\n '### ⚡ Subagent Delegation & Agent Routing (Claude Code)',\n '',\n '- **Delegation tool**: spawn specialists with the `Agent` tool. Your `tools` allowlist names exactly the specialist types you may call (the projected definitions in `.claude/agents/`, with the `subagent-` prefix stripped); calling any other type fails, so send work only to those names. There are no `TypeName`/`Role`/`Prompt` fields — `Agent` takes the specialist type and one self-contained prompt, so put the role, the scope boundaries and the acceptance criteria inside that prompt.',\n '- **Parallel work**: spawn independent specialists in one turn — each runs in its own context window and returns its result to you (delivered by `SubagentHandback` on Claude Code v2.1.271+ in auto mode). You are the single synthesis and relay point: name who reported what, and never let one specialist wait on another.',\n '- **Your allowlist is the whole domain team, not only what is installed.** A listed type whose definition is not in this workspace yet will fail to spawn: say so, recommend installing it (`agents add <addon>`), and handle that slice yourself if the user declines. Never delegate to a type outside your allowlist.',\n '- **Agent Teams (opt-in, `--teams`)**: the lead can spawn *teammates* instead of subagents and message them directly with `SendMessage`. The scaffold is experimental — one team per session, a fixed lead, no nested teams — so never make it load-bearing.',\n ].join('\\n'),\n },\n ],\n budgets: { skillDescriptionChars: 1536, agentDescriptionTokens: 15000 },\n maxRuleLines: 200,\n };\n\n /** `subagent-backend-architect` -> `backend-architect` (Step 0 proved zero collisions). */\n public static stripSubagentPrefix(name: string): string {\n return name.trim().replace(/^subagent-/, '');\n }\n\n /** Uniform managed-projection marker; always the first line of the projected body. */\n private static marker(canonicalRelPath: string): string {\n const norm = canonicalRelPath.replace(/\\\\/g, '/');\n return `<!-- managed-by: agents-united | profile: ${MARKER_PROFILE} | canonical: ${norm} | do not edit -->`;\n }\n\n /** `generative_ui` -> `generative-ui`: every dialect requires lowercase-hyphen names. */\n public static normalizeSkillName(name: string): string {\n return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');\n }\n\n private static parse(\n canonicalContent: string,\n canonicalRelPath: string\n ): { meta: Record<string, unknown>; body: string } {\n const match = canonicalContent.match(FRONTMATTER_REGEX);\n if (!match) {\n throw new Error(`Cannot project ${canonicalRelPath}: no YAML frontmatter found.`);\n }\n let parsed: unknown;\n try {\n parsed = yaml.parse(match[1]);\n } catch (cause) {\n const err = cause instanceof Error ? cause : new Error(String(cause));\n throw new Error(`Cannot project ${canonicalRelPath}: invalid YAML frontmatter (${err.message}).`);\n }\n const meta =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n return { meta, body: match[2].replace(/^\\r?\\n/, '') };\n }\n\n /**\n * Plan 029 A2 / Risk R4 — the servers a canonical role declares, by NAME only.\n *\n * The canonical dialect is a sequence of `- name: <server>` mapping objects (a projected-style\n * plain string is accepted too). Anything else is a fail-fast error: an inline server definition\n * (`command`, `args`, `env`, `headers`, `url`, …) would put a credential-shaped block into a\n * projected artifact — exactly what Risk R4 forbids — so it never reaches the output and is\n * never silently dropped either (ADR 0018 decision 9).\n */\n private static declaredMcpServers(\n meta: Record<string, unknown>,\n canonicalRelPath: string\n ): string[] {\n const raw = meta[MCP_SERVERS_KEY];\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) {\n throw new Error(\n `Cannot project ${canonicalRelPath}: ${MCP_SERVERS_KEY} must be a sequence of ` +\n '\"- name: <server>\" entries (server names only; an inline server definition is never projected).'\n );\n }\n const names: string[] = [];\n raw.forEach((entry, index) => {\n if (typeof entry === 'string' && entry.trim().length > 0) {\n if (!names.includes(entry.trim())) names.push(entry.trim());\n return;\n }\n if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {\n const record = entry as Record<string, unknown>;\n const keys = Object.keys(record);\n const name = record.name;\n if (typeof name === 'string' && name.trim().length > 0 && keys.every(key => key === 'name')) {\n if (!names.includes(name.trim())) names.push(name.trim());\n return;\n }\n throw new Error(\n `Cannot project ${canonicalRelPath}: ${MCP_SERVERS_KEY} entry #${index + 1} carries ` +\n `[${keys.join(', ')}] — servers are referenced by NAME only, never by an inline server ` +\n 'definition (Risk R4: no credential may reach a projected artifact).'\n );\n }\n throw new Error(\n `Cannot project ${canonicalRelPath}: ${MCP_SERVERS_KEY} entry #${index + 1} is not a server ` +\n 'name reference (expected \"- name: <server>\").'\n );\n });\n return names;\n }\n\n private static ledgerEntry(feature: string): TranslationLedgerEntry | undefined {\n const known = FEATURE_LEDGER[feature];\n if (!known) return undefined;\n return { feature, host: HOST, disposition: known.disposition, rationale: known.rationale };\n }\n\n /** Guard: an unmapped feature must never be dropped without a recorded disposition. */\n private static requireDisposition(feature: string, canonicalRelPath: string): TranslationLedgerEntry {\n const entry = ClaudeProjector.ledgerEntry(feature);\n if (!entry) {\n throw new Error(\n `No translation-ledger disposition recorded for feature \"${feature}\" in ${canonicalRelPath}. ` +\n 'Add it to FEATURE_LEDGER so translation loss is never silent (ADR 0018 decision 9).'\n );\n }\n return entry;\n }\n\n /**\n * Replace one canonical body section, matched by its heading, with a host-native rendering.\n *\n * Deterministic: the section runs from the matched heading to the next heading of the same or a higher\n * level (an `h3` stops at the next `h1`/`h2`), and trailing blank lines and the `---` separator are left\n * with the following section so the document structure is unchanged. A heading that is absent is a no-op.\n */\n private static replaceSection(body: string, heading: RegExp, replacement: string): string {\n const lines = body.split('\\n');\n const start = lines.findIndex(line => heading.test(line));\n if (start < 0) return body;\n\n let end = lines.length;\n for (let i = start + 1; i < lines.length; i += 1) {\n if (/^#{1,2}\\s/.test(lines[i])) {\n end = i;\n break;\n }\n }\n while (end > start + 1 && (lines[end - 1].trim() === '' || lines[end - 1].trim() === '---')) end -= 1;\n\n return [...lines.slice(0, start), ...replacement.split('\\n'), ...lines.slice(end)].join('\\n');\n }\n\n /**\n * Deterministically rewrite canonical tool names in prompt prose (whole-word, case-sensitive,\n * fenced code blocks byte-preserved) and report a disposition for every rewrite that loses fidelity.\n */\n /** Command tokens are ledger citizens (Plan 020 note 7) — rewritten and dispositioned. */\n private static readonly COMMAND_LEDGER: Record<string, { disposition: LedgerDisposition; rationale: string }> = {\n team_command: { disposition: 'mapped', rationale: 'Rewritten to the host team entrypoint (Agent Teams opt-in).' },\n deep_planning_command: { disposition: 'mapped', rationale: 'Rewritten to the host deep-planning command.' },\n interview_command: { disposition: 'mapped', rationale: 'Rewritten to the host interview command.' },\n };\n\n /** Plan 019 safety net: residue-headed sections never survive into a projection body. */\n private static dropResidueSections(body: string): string {\n let out = body;\n for (const pattern of RESIDUE_PATTERNS_BY_HOST.claude) {\n out = out.replace(\n new RegExp(`(^|\\\\n)#{1,6}[^\\\\n]*${pattern.source}[^\\\\n]*\\\\n[\\\\s\\\\S]*?(?=\\\\n#{1,6} |$)`, 'g'),\n '$1'\n );\n }\n return out;\n }\n\n /** Plan 019 safety net: residual residue phrases in prose are neutralized deterministically. */\n private static scrubResiduePhrases(body: string): string {\n return body\n .replace(/Cline & CLI/g, 'other hosts')\n .replace(/language_server(\\.exe)?/g, 'the runtime')\n .replace(/Nested Subagent Delegation/g, 'peer delegation')\n .replace(/Host Routing/g, 'host delegation');\n }\n\n /** Whole-word canonical tokens surviving OUTSIDE code fences after the rewrite pass. */\n private static survivingBodyTokens(body: string): string[] {\n const vocab: Record<string, string> = {\n ...ClaudeProjector.CLAUDE_DIALECT.toolVocabulary,\n ...ClaudeProjector.CLAUDE_DIALECT.commandVocabulary,\n };\n const prose = body\n .split(/(```[\\s\\S]*?```)/g)\n .filter((_, index) => index % 2 === 0)\n .join('\\n');\n return Object.keys(vocab).filter(token =>\n new RegExp(`(^|[^A-Za-z0-9_])${token}(?=[^A-Za-z0-9_]|$)`).test(prose)\n );\n }\n\n public static rewriteBody(body: string): { body: string; ledger: TranslationLedgerEntry[] } {\n const ledger = new Map<string, TranslationLedgerEntry>();\n // Plan 019 residue safety net (canonical is purge-clean since the G1 group): residue\n // sections are dropped and residual phrases neutralized so no synthetic or legacy body\n // can leak foreign-host residue into a projection.\n body = ClaudeProjector.dropResidueSections(body);\n body = ClaudeProjector.scrubResiduePhrases(body);\n // ADR 0018 decision 8: sections that describe another host's routing are re-rendered first, so the\n // vocabulary pass below only ever rewrites host-neutral prose.\n for (const override of ClaudeProjector.CLAUDE_DIALECT.bodySectionOverrides) {\n body = ClaudeProjector.replaceSection(body, override.heading, override.replacement);\n }\n // Note 7: command tokens join the tool tokens in the prose rewrite and carry dispositions.\n const vocab: Record<string, string> = {\n ...ClaudeProjector.CLAUDE_DIALECT.bodyToolVocabulary,\n ...ClaudeProjector.CLAUDE_DIALECT.commandVocabulary,\n };\n const tokens = Object.keys(vocab).sort((a, b) => b.length - a.length);\n const parts = body.split(/(```[\\s\\S]*?```)/g);\n\n const rewritten = parts.map((part, index) => {\n if (index % 2 === 1) return part; // fenced code block, preserved byte-for-byte\n let text = part;\n for (const token of tokens) {\n const re = new RegExp(`(^|[^A-Za-z0-9_])${token}(?=[^A-Za-z0-9_]|$)`, 'g');\n if (!text.match(re)) continue;\n const command = ClaudeProjector.COMMAND_LEDGER[token];\n const entry: TranslationLedgerEntry | undefined = command\n ? { feature: token, host: HOST, disposition: command.disposition, rationale: command.rationale }\n : ClaudeProjector.ledgerEntry(token);\n if (entry) ledger.set(token, entry);\n text = text.replace(re, `$1${vocab[token]}`);\n }\n return text;\n });\n\n return { body: rewritten.join(''), ledger: [...ledger.values()] };\n }\n\n /** Render `.claude/agents/<role>.md` from a canonical agent definition. */\n public static renderRole(\n canonicalContent: string,\n canonicalRelPath: string,\n opts: { allowlist?: string[]; maxTurns?: number } = {}\n ): ClaudeRenderResult {\n const { meta, body } = ClaudeProjector.parse(canonicalContent, canonicalRelPath);\n const ledger = new Map<string, TranslationLedgerEntry>();\n\n // 1. Every canonical key either maps inline or carries a recorded disposition.\n for (const key of Object.keys(meta)) {\n if (INLINE_KEYS.has(key)) continue;\n const entry = ClaudeProjector.requireDisposition(key, canonicalRelPath);\n ledger.set(entry.feature, entry);\n }\n\n const rawName =\n typeof meta.name === 'string' && meta.name.trim().length > 0\n ? meta.name.trim()\n : path.basename(canonicalRelPath).replace(/\\.md$/i, '');\n const out: Record<string, unknown> = { name: ClaudeProjector.stripSubagentPrefix(rawName) };\n\n if (typeof meta.description === 'string' && meta.description.trim().length > 0) {\n out.description = meta.description.trim();\n }\n\n // 2. Delegation first (ADR 0018 decision 3), then the translated vocabulary.\n // Coordinator-ness comes from the canonical role, not only from a caller-supplied allowlist: a\n // bundle-less fanout (`domain:*`, addons) has no bundle definition to derive specialists from, and\n // without this a projected orchestrator silently took the specialist posture (sonnet, bare `Agent`,\n // hand-back tool) — the operator saw `orchestrator-engineering.md` on Sonnet while\n // `orchestrator-digital-agency.md` was on Opus. `type: orchestrator` / `mainAgent: true` is the\n // catalog's own discriminator (9 orchestrators, 50 subagents).\n const isCoordinator = !!(opts.allowlist && opts.allowlist.length > 0)\n || meta.type === 'orchestrator'\n || meta.mainAgent === true;\n const tools: string[] = [];\n if (isCoordinator) {\n tools.push(opts.allowlist && opts.allowlist.length > 0 ? `Agent(${opts.allowlist.join(', ')})` : 'Agent');\n }\n for (const raw of Array.isArray(meta.tools) ? meta.tools : []) {\n if (typeof raw !== 'string') continue;\n const entry = ClaudeProjector.ledgerEntry(raw);\n if (entry) ledger.set(entry.feature, entry);\n const mapped = ClaudeProjector.CLAUDE_DIALECT.toolVocabulary[raw];\n if (!mapped) {\n ClaudeProjector.requireDisposition(raw, canonicalRelPath);\n continue;\n }\n if (!tools.includes(mapped)) tools.push(mapped);\n }\n\n // ADR 0018 decision 3: when the coordinator has an allowlist, `Agent(<specialists>)` IS the\n // delegation grant. Adding a bare `Agent` next to it is contradictory — the docs treat `Agent`\n // without parentheses as \"allow spawning any subagent without restrictions\" — so the allowlist\n // would be silently widened. Keep the allowlist as the single source of the bound.\n if (opts.allowlist && opts.allowlist.length > 0) {\n const withoutBareAgent = tools.filter(t => t !== 'Agent');\n tools.length = 0;\n tools.push(...withoutBareAgent);\n }\n\n // Plan 022 H2 (gate 5): specialists hold NO Agent tool. Inside a subagent definition the\n // runtime ignores an `Agent(type, …)` list, so any Agent entry is an unbounded nested-spawn\n // grant; omitting it is the only bound (Claude Code sub-agents reference, 2026-09-25). A\n // canonical `invoke_subagent`-family token on a specialist is therefore dropped here.\n if (!isCoordinator) {\n const withoutAgent = tools.filter(t => t !== 'Agent' && !t.startsWith('Agent('));\n tools.length = 0;\n tools.push(...withoutAgent);\n }\n\n // 3. Posture: permissionMode, model tier, effort, and the consultation budget.\n if (isCoordinator) {\n for (const base of COORDINATOR_BASELINE_TOOLS) {\n if (!tools.includes(base)) tools.push(base);\n }\n } else if (!tools.includes('SubagentHandback')) {\n // `SubagentHandback` is the runtime's own hand-off channel for subagents — it \"delivers a\n // subagent's final report to whichever conversation receives that subagent's result\" (Claude Code\n // v2.1.271+, auto mode). Granting it makes the documented Tier-1 hand-off explicit instead of\n // implicit; where the runtime does not provide it the entry simply does not resolve, and Claude\n // Code only refuses to launch an agent when NOTHING in its tools list resolves.\n tools.push('SubagentHandback');\n }\n const permission =\n typeof meta.permissionMode === 'string'\n ? ClaudeProjector.CLAUDE_DIALECT.permissionModeMap[meta.permissionMode] ?? 'default'\n : undefined;\n if (permission === 'plan') {\n // Plan 022 H3 (gate 6): a read-only role holds no mutating capability at all — command\n // execution included, since a shell can write files regardless of the permission mode.\n const restricted = tools.filter(t => !READ_ONLY_EXCLUDED_TOOLS.has(t));\n tools.length = 0;\n tools.push(...restricted);\n }\n // Plan 029 A2 — the servers a canonical role declares reach the projection in both halves: the\n // `mcpServers:` name references (the documented \"a name that references a server you already\n // configured\" form) and the matching grant in `tools:`. A name reference alone does not survive\n // an explicit `tools:` allowlist, which is why every declared server also gets its grant — the\n // server-level `mcp__<server>` for a writable role, pinned read-only tool names for a `plan`\n // role (Risk R1, owner Option B). Servers are referenced BY NAME ONLY (Risk R4).\n const declaredServers = ClaudeProjector.declaredMcpServers(meta, canonicalRelPath);\n for (const server of declaredServers) {\n const grants = permission === 'plan' ? READ_ONLY_MCP_TOOL_GRANTS[server] ?? [] : [`mcp__${server}`];\n for (const grant of grants) {\n if (!tools.includes(grant)) tools.push(grant);\n }\n }\n out.tools = tools;\n if (declaredServers.length > 0) {\n out.mcpServers = declaredServers.map(server => ({ name: server }));\n }\n if (permission) out.permissionMode = permission;\n\n // `inherit` is the catalog's marker for \"no opinion\" — all 59 agents declare `model: inherit` — so it\n // resolves to the role posture instead of being dropped: coordinators opus, specialists sonnet\n // (ADR 0018 d7 as amended 2026-09-22). An explicitly declared tier or effort always wins, so per-agent\n // authoring survives (eight specialists declare `effort: high` today and keep it).\n const declaredModel = typeof meta.model === 'string' ? meta.model : undefined;\n const mappedModel = declaredModel && declaredModel !== 'inherit'\n ? ClaudeProjector.CLAUDE_DIALECT.modelMap[declaredModel] ?? declaredModel\n : undefined;\n out.model = mappedModel ?? (isCoordinator\n ? ClaudeProjector.CLAUDE_DIALECT.roleModelDefaults.coordinator\n : ClaudeProjector.CLAUDE_DIALECT.roleModelDefaults.specialist);\n const declaredEffort = typeof meta.effort === 'string' ? meta.effort : undefined;\n out.effort = declaredEffort ?? (isCoordinator\n ? ClaudeProjector.CLAUDE_DIALECT.roleEffortDefaults.coordinator\n : ClaudeProjector.CLAUDE_DIALECT.roleEffortDefaults.specialist);\n if (typeof opts.maxTurns === 'number') out.maxTurns = opts.maxTurns;\n // Plan 022 H5: the managed guard (never the canonical prose hooks — those stay advisory, H7).\n out.hooks = MANAGED_HOOKS;\n\n // 4. Prose is part of the interface. A surviving canonical body token outside code\n // fences without a ledger disposition is a render-time error (decision 4) — never a\n // silent survivor.\n const rewritten = ClaudeProjector.rewriteBody(body);\n for (const entry of rewritten.ledger) ledger.set(entry.feature, entry);\n for (const token of ClaudeProjector.survivingBodyTokens(rewritten.body)) {\n ClaudeProjector.requireDisposition(token, canonicalRelPath);\n }\n\n // Plan 017 decision 3 (render application): declarative overlays win over dialect\n // defaults and canonical-derived values; invalid overlays fail fast (never silent).\n if (meta.projections !== undefined && meta.projections !== null) {\n validateProjectionOverlays(meta.projections, { id: HOST, fields: CLAUDE_FIELD_POLICY });\n const overlay = (meta.projections as Record<string, Record<string, unknown>>)[HOST];\n if (overlay) Object.assign(out, overlay);\n }\n\n const yamlStr = yaml.stringify(out).replace(/\\r\\n/g, '\\n').trimEnd();\n const content = `---\\n${yamlStr}\\n---\\n${ClaudeProjector.marker(canonicalRelPath)}\\n\\n${RUNTIME_NOTE}\\n\\n${rewritten.body.trim()}\\n`;\n return { content, ledger: [...ledger.values()] };\n }\n\n /** Render `.claude/skills/<name>/SKILL.md` from a canonical skill. */\n public static renderSkill(canonicalContent: string, canonicalRelPath: string): ClaudeRenderResult {\n const { meta, body } = ClaudeProjector.parse(canonicalContent, canonicalRelPath);\n const ledger = new Map<string, TranslationLedgerEntry>();\n\n const rawName =\n typeof meta.name === 'string' && meta.name.trim().length > 0\n ? meta.name.trim()\n : path.basename(path.dirname(canonicalRelPath));\n const normalized = ClaudeProjector.normalizeSkillName(rawName);\n if (normalized !== rawName) {\n ledger.set(`skill-name:${rawName}`, {\n feature: `skill-name:${rawName}`,\n host: HOST,\n disposition: 'mapped',\n rationale: `Skill name normalized to the dialect rule (${rawName} -> ${normalized}); body references follow the artifact name.`,\n });\n }\n\n const out: Record<string, unknown> = { name: normalized };\n if (typeof meta.description === 'string' && meta.description.trim().length > 0) {\n out.description = meta.description.trim();\n }\n if (meta['disable-slash-command'] === true || meta.disableSlashCommand === true) {\n out['user-invocable'] = false;\n ledger.set('disable-slash-command', {\n feature: 'disable-slash-command',\n host: HOST,\n disposition: 'mapped',\n rationale:\n 'Hidden from the / palette while staying model-invocable (Claude polarity: user-invocable, never disable-model-invocation).',\n });\n }\n const metadata = meta.metadata;\n if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n const allowed = ['author', 'version', 'icon', 'source', 'license'];\n const kept: Record<string, unknown> = {};\n for (const key of allowed) {\n const value = (metadata as Record<string, unknown>)[key];\n if (value !== undefined) kept[key] = value;\n }\n for (const key of Object.keys(metadata as Record<string, unknown>)) {\n if (allowed.includes(key)) continue;\n ledger.set(`metadata:${key}`, {\n feature: `metadata:${key}`,\n host: HOST,\n disposition: 'mapped',\n rationale: 'Non-standard skill metadata; stripped because the projection carries only the Agent Skills contract.',\n });\n }\n if (Object.keys(kept).length > 0) out.metadata = kept;\n }\n if (typeof meta.license === 'string') out.license = meta.license;\n\n // Any other canonical skill key needs a recorded disposition (never a silent drop).\n const HANDLED_SKILL_KEYS = new Set([\n 'name',\n 'description',\n 'metadata',\n 'license',\n 'disable-slash-command',\n 'disableSlashCommand',\n ]);\n for (const key of Object.keys(meta)) {\n if (HANDLED_SKILL_KEYS.has(key)) continue;\n const entry = ClaudeProjector.requireDisposition(key, canonicalRelPath);\n ledger.set(entry.feature, entry);\n }\n\n let rewrittenBody = body;\n if (normalized !== rawName) {\n const re = new RegExp(`(^|[^A-Za-z0-9_-])${rawName}(?![A-Za-z0-9_-])`, 'gi');\n rewrittenBody = rewrittenBody.replace(re, `$1${normalized}`);\n }\n const rewritten = ClaudeProjector.rewriteBody(rewrittenBody);\n for (const entry of rewritten.ledger) ledger.set(entry.feature, entry);\n\n const yamlStr = yaml.stringify(out).replace(/\\r\\n/g, '\\n').trimEnd();\n const content = `---\\n${yamlStr}\\n---\\n${ClaudeProjector.marker(canonicalRelPath)}\\n\\n${rewritten.body.trim()}\\n`;\n return { content, ledger: [...ledger.values()] };\n }\n\n /**\n * Render `.claude/rules/<rule>.md`. Rules load unconditionally in every Claude session, so this\n * lane is deliberately lean: optional `paths:` scoping plus a hard adherence budget (ADR 0018).\n *\n * The `paths:` block is the ONLY frontmatter field this lane emits, so it is emitted only when a\n * rule is actually scoped. The live doc is explicit — \"Rules without a `paths` field are loaded\n * unconditionally and apply to all files\" — which makes frontmatter optional; an unscoped rule is\n * therefore rendered marker-first with no frontmatter block at all, matching the Cline lane's shape\n * instead of emitting a stray empty `--- {} ---`.\n */\n public static renderRule(\n canonicalContent: string,\n canonicalRelPath: string,\n opts: { paths?: string[] } = {}\n ): ClaudeRenderResult {\n const lineCount = canonicalContent.split(/\\r?\\n/).length;\n if (lineCount > ClaudeProjector.CLAUDE_DIALECT.maxRuleLines) {\n throw new Error(\n `Rule ${canonicalRelPath} has ${lineCount} lines, exceeding the ${ClaudeProjector.CLAUDE_DIALECT.maxRuleLines}-line adherence budget (ADR 0018 decision 5).`\n );\n }\n const frontmatter: Record<string, unknown> = {};\n if (opts.paths && opts.paths.length > 0) frontmatter.paths = opts.paths;\n const head = Object.keys(frontmatter).length > 0\n ? `---\\n${yaml.stringify(frontmatter).replace(/\\r\\n/g, '\\n').trimEnd()}\\n---\\n`\n : '';\n const rewritten = ClaudeProjector.rewriteBody(canonicalContent.trim());\n const content = `${head}${ClaudeProjector.marker(canonicalRelPath)}\\n\\n${rewritten.body}\\n`;\n return { content, ledger: rewritten.ledger };\n }\n\n /**\n * The specialist roster a coordinator may delegate to: the whole **domain** team, not only the slice\n * this bundle declares or what happens to be installed.\n *\n * `software-engineering` declares 4 specialists, but the `engineering` domain has 15 — so an essentials\n * install used to leave the domain lead able to call 4 of its 15 people, with the list growing only when\n * the operator happened to install more *and* re-project. `bundles.json` already groups every bundle under\n * a `domain`, so the roster is the union of that domain's declared agents minus the coordinator itself.\n * The allowlist is then stable (independent of install state) and complete (it never silently hides a\n * teammate). The cost is that a listed type may not be installed yet — the delegation section turns that\n * into an install recommendation rather than a dead end.\n *\n * Sorted for determinism: repeated projections must be byte-identical, because `agents doctor` diffs them.\n */\n private static resolveDomainRoster(\n bundle: BundleDefinition,\n coordinatorFile: string,\n registryDir: string\n ): string[] {\n const names = new Set<string>();\n try {\n const raw = fs.readFileSync(path.join(registryDir, 'bundles.json'), 'utf8');\n const bundles = (JSON.parse(raw).bundles ?? {}) as Record<string, BundleDefinition>;\n for (const candidate of Object.values(bundles)) {\n if (!bundle.domain || candidate.domain !== bundle.domain) continue;\n for (const agentFile of candidate.agents || []) {\n if (agentFile === coordinatorFile) continue;\n names.add(ClaudeProjector.stripSubagentPrefix(agentFile.replace(/\\.md$/i, '')));\n }\n }\n } catch {\n // No registry to read: fall back to the bundle's own declared roster (the caller's).\n }\n return [...names].sort();\n }\n\n /**\n * Plan the full Claude compound projection for one bundle: roles (with a coordinator allowlist of\n * its whole domain team), skills (normalized names plus auxiliary files copied byte-for-byte), and\n * the lean deduplicated rule set. It emits **no** team-manifest duplicate and **no** workflows lane,\n * because Claude workflows are JavaScript orchestration scripts rather than markdown (ADR 0018 d14).\n */\n public static async planCompoundProjection(\n bundle: BundleDefinition,\n scope: InstallScope,\n resolved: ResolvedAssets,\n registryDir: string,\n _excludeAddons?: string[]\n ): Promise<PlannedClaudeArtifact[]> {\n void scope;\n const artifacts: PlannedClaudeArtifact[] = [];\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n // A coordinator delegates to its domain team, not just this bundle's declared slice of it.\n const domainRoster = ClaudeProjector.resolveDomainRoster(bundle, coordinatorFile, registryDir);\n const specialistNames = domainRoster.length > 0\n ? domainRoster\n : (bundle.agents || []).map(f => ClaudeProjector.stripSubagentPrefix(f.replace(/\\.md$/i, '')));\n const maxTurns = bundle.planningLoop?.budget?.maxIterations;\n\n // 1. Roles.\n for (const agentFile of resolved.agents || []) {\n const canonicalRel = `agents/${agentFile}`;\n const src = path.join(registryDir, 'agents', agentFile);\n if (!(await fs.pathExists(src))) continue;\n const content = await fs.readFile(src, 'utf8');\n const isCoordinator = coordinatorFile === agentFile;\n const roleName = ClaudeProjector.stripSubagentPrefix(agentFile.replace(/\\.md$/i, ''));\n const rendered = ClaudeProjector.renderRole(content, canonicalRel, {\n allowlist: isCoordinator ? specialistNames : undefined,\n maxTurns: isCoordinator ? maxTurns : undefined,\n });\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `.claude/agents/${roleName}.md`,\n content: rendered.content,\n managedMarker: true,\n });\n }\n\n // 2. Skills, plus every auxiliary resource copied byte-for-byte.\n for (const skillName of resolved.skills || []) {\n const skillDir = path.join(registryDir, 'skills', skillName);\n const skillFile = path.join(skillDir, 'SKILL.md');\n if (!(await fs.pathExists(skillFile))) continue;\n const canonicalRel = `skills/${skillName}/SKILL.md`;\n const normalized = ClaudeProjector.normalizeSkillName(skillName);\n artifacts.push({\n kind: 'skill',\n canonical: canonicalRel,\n relPath: `.claude/skills/${normalized}/SKILL.md`,\n content: ClaudeProjector.renderSkill(await fs.readFile(skillFile, 'utf8'), canonicalRel).content,\n managedMarker: true,\n });\n // Recursive: `references/`, `scripts/` (and deeper, e.g. `scripts/lib/`) must reach Claude\n // Code too, matching the Cline lane and the canonical `.agents/` store.\n const resourceRels = (await ClaudeProjector.listSkillResources(skillDir))\n .filter(rel => rel !== 'SKILL.md');\n for (const rel of resourceRels) {\n artifacts.push({\n kind: 'skill',\n canonical: `skills/${skillName}/${rel}`,\n relPath: `.claude/skills/${normalized}/${rel}`,\n sourceFilePath: path.join(skillDir, ...rel.split('/')),\n managedMarker: false,\n });\n }\n }\n\n // 3. Rules: deduplicated, agent-referenced only, host entrypoints skipped, budget-guarded.\n for (const ruleFile of [...new Set(resolved.rules || [])].sort()) {\n if (ENTRYPOINT_RULES.has(ruleFile)) continue;\n const src = path.join(registryDir, 'rules', ruleFile);\n if (!(await fs.pathExists(src))) continue;\n const canonicalRel = `rules/${ruleFile}`;\n const content = await fs.readFile(src, 'utf8');\n if (content.split(/\\r?\\n/).length > ClaudeProjector.CLAUDE_DIALECT.maxRuleLines) continue;\n artifacts.push({\n kind: 'rule',\n canonical: canonicalRel,\n relPath: `.claude/rules/${ruleFile}`,\n content: ClaudeProjector.renderRule(content, canonicalRel).content,\n managedMarker: true,\n });\n }\n\n return artifacts;\n }\n\n /**\n * Every file under a skill folder, as sorted POSIX-style paths relative to it\n * (deterministic across platforms, so projection plans and lockfile keys never differ).\n */\n private static async listSkillResources(skillDir: string, prefix = ''): Promise<string[]> {\n const out: string[] = [];\n for (const entry of await fs.readdir(path.join(skillDir, ...prefix.split('/').filter(Boolean)), { withFileTypes: true })) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name;\n if (entry.isDirectory()) out.push(...await ClaudeProjector.listSkillResources(skillDir, rel));\n else if (entry.isFile()) out.push(rel);\n }\n return out.sort((a, b) => a.localeCompare(b));\n }\n\n /** Claude plugin package name rule; every bundle in `registry/bundles.json` satisfies it today. */\n private static readonly PLUGIN_NAME_REGEX = /^[a-z0-9][a-z0-9-]*$/;\n\n /**\n * Render the Claude plugin manifest (`.claude-plugin/plugin.json`).\n *\n * Deterministic: fixed field order, two-space indent, trailing newline, and no data read\n * from the environment (a `package.json` lookup would make the bytes differ between a\n * project and a global install and would trip doctor's recorded-hash drift check).\n */\n private static renderPluginManifest(bundle: BundleDefinition, canonicalRelPath: string): string {\n if (!ClaudeProjector.PLUGIN_NAME_REGEX.test(bundle.name)) {\n throw new Error(\n `Cannot project ${canonicalRelPath}: bundle name \"${bundle.name}\" is not a valid Claude plugin ` +\n `name (must match ^[a-z0-9][a-z0-9-]*$).`\n );\n }\n\n // JSON cannot carry the `<!-- managed-by: agents-united ... -->` comment the markdown\n // renderers use, yet BOTH `InstallEngine.applyCompoundLane` (regeneration of our own\n // artifact) and `agents doctor` (drift/marker integrity) classify an artifact by that\n // marker *string* (`HostProjector.hasManagedMarker`). The manifest is declared\n // `managedMarker: true` — a machine-generated file we own and must be able to\n // regenerate and drift-check — so the marker travels inside `description`, the only\n // free-text field of the seven. Without it the second flagged install would refuse\n // with \"not managed by agents-united\" and doctor would report a false\n // \"user-modified projection\" on every run.\n const markerText = `${MARKER_PREFIX} | profile: ${MARKER_PROFILE} | do not edit`;\n const description = bundle.description\n ? `${bundle.description} [${markerText}]`\n : markerText;\n\n const manifest: ClaudePluginManifest = {\n author: '',\n description,\n homepage: '',\n license: '',\n name: bundle.name,\n repository: '',\n version: bundle.version || '1.0.0',\n };\n\n return JSON.stringify(manifest, null, 2) + '\\n';\n }\n\n /**\n * ADR 0018 decision 12 / Plan 016 decision 13 — the opt-in Claude **plugin lane**.\n *\n * Plans the `claude --plugin-dir` consumable package *inside* the organization package:\n * `.agents/plugins/<bundle>/.claude-plugin/plugin.json` plus an `agents/` subdirectory that\n * mirrors the `.claude/agents/` projection name-for-name and byte-for-byte (same `renderRole`\n * call, same coordinator allowlist, same `maxTurns`).\n *\n * **Distribution-only, never the behavioural source.** Claude has no project-local plugin\n * auto-discovery, plugin agents are namespaced (`plugin:agent`) and a plugin\n * `permissionMode` is ignored — so the `.claude/agents/` projection produced by\n * `planCompoundProjection` stays the single behavioural source. This package exists purely\n * so the same folder can be zipped and consumed elsewhere via `--plugin-dir`.\n *\n * Additive and caller-gated (`InstallOptions.pluginLane`): when the flag is off this method\n * is never called and the install plan is byte-identical to before.\n */\n public static async planPluginLane(\n bundle: BundleDefinition,\n resolved: ResolvedAssets,\n registryDir: string\n ): Promise<PlannedClaudeArtifact[]> {\n const artifacts: PlannedClaudeArtifact[] = [];\n const baseDir = `.agents/plugins/${bundle.name}`;\n\n // 1. Manifest — the discriminator `claude --plugin-dir` reads.\n artifacts.push({\n kind: 'plugin-manifest',\n relPath: `${baseDir}/.claude-plugin/plugin.json`,\n content: ClaudeProjector.renderPluginManifest(bundle, `${baseDir}/.claude-plugin/plugin.json`),\n managedMarker: true,\n distributionOnly: true,\n });\n\n // 2. Roles — mirror of the project projection. Same allowlist/maxTurns treatment as\n // `planCompoundProjection` so the package's `agents/` subdir cannot diverge from\n // `.claude/agents/` (the byte-identity is asserted in tests/claude-plugin-lane.test.ts).\n const coordinatorFile = bundle.orchestrator || `${bundle.name}.md`;\n const domainRoster = ClaudeProjector.resolveDomainRoster(bundle, coordinatorFile, registryDir);\n const specialistNames = domainRoster.length > 0\n ? domainRoster\n : (bundle.agents || []).map(f => ClaudeProjector.stripSubagentPrefix(f.replace(/\\.md$/i, '')));\n const maxTurns = bundle.planningLoop?.budget?.maxIterations;\n\n for (const agentFile of resolved.agents || []) {\n const canonicalRel = `agents/${agentFile}`;\n const src = path.join(registryDir, 'agents', agentFile);\n if (!(await fs.pathExists(src))) continue;\n const isCoordinator = coordinatorFile === agentFile;\n const roleName = ClaudeProjector.stripSubagentPrefix(agentFile.replace(/\\.md$/i, ''));\n const rendered = ClaudeProjector.renderRole(await fs.readFile(src, 'utf8'), canonicalRel, {\n allowlist: isCoordinator ? specialistNames : undefined,\n maxTurns: isCoordinator ? maxTurns : undefined,\n });\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `${baseDir}/agents/${roleName}.md`,\n content: rendered.content,\n managedMarker: true,\n distributionOnly: true,\n });\n }\n\n return artifacts;\n }\n\n}\n\n\n\n","/**\n * Plan 022 H5 / Plan 023 A0 — the managed PreToolUse guard, single-sourced for every lane that\n * wires it (role frontmatter today; the plain-session settings entry in Plan 023 A1–A2).\n *\n * Verified against the Claude Code references: frontmatter hooks fire for spawned subagents and\n * for `--agent` main sessions; a command hook exiting 2 blocks the call and its stderr is shown as\n * the reason. EXEC FORM (Plan 023 A0): `command` + `args` is spawned directly with no shell. The\n * earlier shell form (`node -e '<js>'`) runs under PowerShell on Windows without Git Bash, whose\n * native-argument quoting can mangle the script and let the guarded command through (fail open).\n * The script blocks `git push --force`/`-f` (not `--force-with-lease`), `vercel --prod`, and\n * `.env*` writes (not `.env.example`) via Write/Edit/NotebookEdit or a shell redirect.\n *\n * Testing this by hand? Asking a session hypothetically tests the model, not the hook — see\n * `docs/guard-testing.md` (Plan 024 S5) for a model-proof test protocol.\n */\nexport const GUARD_SCRIPT = String.raw`let s=\"\";process.stdin.on(\"data\",c=>s+=c).on(\"end\",()=>{let i={};try{i=JSON.parse(s)}catch(e){}const t=i.tool_input||{},c=String(t.command||\"\"),f=String(t.file_path||\"\").replace(/\\\\/g,\"/\");let r=\"\";if(/\\bgit\\b[^;&|]*\\bpush\\b[^;&|]*(--force(?!-with-lease)\\b|(^|\\s)-f\\b)/.test(c))r=\"git push --force\";else if(/\\bvercel\\b[^;&|]*--prod\\b/.test(c))r=\"vercel --prod\";else if(/(^|\\/)\\.env(\\.(?!example$)[^\\/]+)?$/.test(f)||/>\\s*(\\S*\\/)?\\.env(\\.(?!example\\b)\\S+)?(\\s|$)/.test(c))r=\"a .env write\";if(r){process.stderr.write(\"Blocked by agents-united guard: \"+r+\" requires explicit human approval outside the agent session.\\n\");process.exit(2)}})`;\n\n/** The exec-form handler: `node -e <script>`, no shell on any OS. */\nexport function guardHandler(): { type: 'command'; command: string; args: string[] } {\n return { type: 'command', command: 'node', args: ['-e', GUARD_SCRIPT] };\n}\n\n/** The PreToolUse groups every guarded surface carries. */\nexport function managedGuardHooks(): { PreToolUse: Array<{ matcher: string; hooks: ReturnType<typeof guardHandler>[] }> } {\n return {\n PreToolUse: [\n { matcher: 'Bash', hooks: [guardHandler()] },\n { matcher: 'Write|Edit|NotebookEdit', hooks: [guardHandler()] },\n ],\n };\n}\n","/**\n * Plan 019 Step 4 — host-keyed forbidden-pattern lists (acceptance gate 4 extension).\n * Lives in a leaf module so both the body lint (dialects) and the renderer's scrub safety\n * net (claude-projector) consume ONE list without an import cycle. The list must grow with\n * every new host section (Plan 019 maintenance note).\n */\nexport const RESIDUE_PATTERNS_BY_HOST: Record<string, readonly RegExp[]> = {\n claude: [/Nested Subagent Delegation/, /Host Routing/, /language_server/, /Cline & CLI/],\n};\n\n/**\n * Plan 025 Step 1/6 — specialist-anatomy body lint.\n * Code exemplars belong in skill `references/**`, not in `registry/agents/*.md` bodies\n * (Plan 025 Objective 4). This constant and the two helpers below are the single seam the\n * anatomy test (`tests/specialist-anatomy.test.ts`) and any future CI check share, so the\n * threshold and the parsing rules never drift between the two. Calibrated on\n * `subagent-ml-platform-engineer.md` (0 fenced blocks) and the shared comms sections'\n * short illustrative snippets (<= 6 lines) per Plan 025 risk R5.\n */\nexport const AGENT_BODY_FENCE_LINE_THRESHOLD = 15;\n\n/**\n * Fence info-strings exempted from the threshold: these carry the mandatory Output Format\n * Requirements / report-shape template (an illustrative report skeleton, not runnable code),\n * which is unchanged anatomy (Plan 025 Objective 1) and legitimately runs longer than a\n * code exemplar.\n */\nconst EXEMPT_FENCE_LANGS = new Set(['', 'markdown', 'md', 'text', 'plain']);\n\nexport interface OversizedFencedBlock {\n /** 1-based line number of the opening fence. */\n readonly line: number;\n /** Number of content lines strictly between the opening and closing fence. */\n readonly contentLines: number;\n /** The fence's info string, e.g. \"typescript\" or \"bash\" (may be empty). */\n readonly lang: string;\n}\n\n/**\n * Scans a `registry/agents/*.md` body for fenced code blocks whose content exceeds\n * `AGENT_BODY_FENCE_LINE_THRESHOLD` lines. Returns one entry per offending block.\n */\nexport function findOversizedFencedBlocks(body: string): OversizedFencedBlock[] {\n const lines = body.split('\\n');\n const violations: OversizedFencedBlock[] = [];\n let openLine: number | null = null;\n let openLang = '';\n let contentLines = 0;\n for (let i = 0; i < lines.length; i++) {\n const fenceMatch = /^```(.*)$/.exec(lines[i]);\n if (fenceMatch) {\n if (openLine === null) {\n openLine = i + 1;\n openLang = fenceMatch[1].trim();\n contentLines = 0;\n } else {\n if (\n contentLines > AGENT_BODY_FENCE_LINE_THRESHOLD &&\n !EXEMPT_FENCE_LANGS.has(openLang.toLowerCase())\n ) {\n violations.push({ line: openLine, contentLines, lang: openLang });\n }\n openLine = null;\n openLang = '';\n contentLines = 0;\n }\n continue;\n }\n if (openLine !== null) contentLines++;\n }\n return violations;\n}\n\nexport interface SkillConsultationMapRow {\n readonly situation: string;\n readonly skill: string;\n readonly loadWhen: string;\n readonly providedBy: string;\n}\n\n/**\n * Parses the `## Skill Consultation Map` table (Situation | Skill | Load when | Provided by)\n * out of an agent body, if present. The skill cell is expected to name exactly one skill,\n * inline-coded (e.g. `` `supabase-backend-architecture` ``).\n */\nexport function parseSkillConsultationMap(body: string): SkillConsultationMapRow[] {\n const sectionMatch = /^## .*Skill Consultation Map.*$/m.exec(body);\n if (!sectionMatch) return [];\n const rest = body.slice(sectionMatch.index + sectionMatch[0].length);\n const nextHeading = /^## /m.exec(rest);\n const section = nextHeading ? rest.slice(0, nextHeading.index) : rest;\n const rows: SkillConsultationMapRow[] = [];\n for (const line of section.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed.startsWith('|')) continue;\n const cells = trimmed\n .split('|')\n .slice(1, -1)\n .map(c => c.trim());\n if (cells.length < 4) continue;\n if (/^:?-+:?$/.test(cells[1])) continue; // separator row\n if (/^situation$/i.test(cells[0])) continue; // header row\n const skillMatch = /`([a-z0-9-]+)`/.exec(cells[1]);\n if (!skillMatch) continue;\n rows.push({ situation: cells[0], skill: skillMatch[1], loadWhen: cells[2], providedBy: cells[3] });\n }\n return rows;\n}","/**\n * Plan 017 decision 3 declarative overlays — shared validation (leaf module; consumed by\n * the catalog validator in dialects and by renderRole's overlay application without an\n * import cycle). Rule: overlay hosts must be the spec's own host; overlay fields must be\n * keep/map fields; enum-ish values must sit in the host vocabulary. Fail-fast throws.\n */\nexport const OVERLAY_FIELD_VOCAB: Record<string, readonly string[]> = {\n permissionMode: ['default', 'acceptEdits', 'bypassPermissions', 'plan', 'delegate'],\n model: ['opus', 'sonnet', 'haiku', 'inherit'],\n effort: ['low', 'medium', 'high', 'inherit'],\n};\n\n/**\n * The Claude field policy (keep/map/drop) — ONE map shared by `HOST_DIALECTS.claude.fields`\n * (catalog validation) and renderRole's overlay application (render validation).\n */\nexport const CLAUDE_FIELD_POLICY: Record<string, 'keep' | 'map' | 'drop'> = {\n name: 'keep',\n description: 'keep',\n model: 'map',\n tools: 'map',\n permissionMode: 'map',\n effort: 'map',\n skills: 'map',\n projections: 'map',\n version: 'drop',\n type: 'drop',\n commandExecutionPolicy: 'drop',\n mainAgent: 'drop',\n subagent: 'drop',\n hooks: 'drop',\n mcpServers: 'drop',\n rules: 'drop',\n inheritCustomizations: 'drop',\n};\n\ninterface OverlaySpecLike {\n id: string;\n fields: Record<string, 'keep' | 'map' | 'drop'>;\n}\n\nexport function validateProjectionOverlays(projections: unknown, spec: OverlaySpecLike): void {\n if (projections === undefined || projections === null) return;\n if (typeof projections !== 'object' || Array.isArray(projections)) {\n throw new Error('Projection overlay validation failed: projections must be an object.');\n }\n for (const [host, overlay] of Object.entries(projections as Record<string, unknown>)) {\n if (host !== spec.id) {\n throw new Error(`Projection overlay validation failed: unknown overlay host \"${host}\".`);\n }\n if (overlay === null || typeof overlay !== 'object' || Array.isArray(overlay)) {\n throw new Error(`Projection overlay validation failed: overlay for \"${host}\" must be an object.`);\n }\n for (const [field, value] of Object.entries(overlay as Record<string, unknown>)) {\n const policy = spec.fields[field];\n if (policy === undefined) {\n throw new Error(`Projection overlay validation failed: unknown overlay field \"${field}\".`);\n }\n if (policy === 'drop') {\n throw new Error(\n `Projection overlay validation failed: \"${field}\" is unsupported on host \"${host}\" and must never be introduced by an overlay.`,\n );\n }\n const vocab = OVERLAY_FIELD_VOCAB[field];\n if (vocab && (typeof value !== 'string' || !vocab.includes(value))) {\n throw new Error(\n `Projection overlay validation failed: invalid value \"${String(value)}\" for \"${field}\" (allowed: ${vocab.join(', ')}).`,\n );\n }\n }\n }\n}","/**\n * Plan 023 Workstream B (ADR 0022, owner decisions D3–D4) — the STATE DIR abstraction.\n *\n * The whole install state machine (installer, doctor, updater, uninstaller, inventory, launchers)\n * is keyed on one directory holding both the canonical copies and the lockfile\n * `agents-united.json`, with lockfile `files` keys relative to that directory and `projections`\n * keys relative to the workspace root. Two shapes exist:\n *\n * - store (`<root>/.agents/`) — the canonical store, as before;\n * - sidecar (`<root>/.claude/.agents-united/`) — a hidden, machine-owned snapshot + lockfile for\n * a store-less Claude-only install (ADR 0022). Claude Code never loads from this path.\n *\n * Only state-dir DISCOVERY and WORKSPACE-ROOT derivation differ between them (B0 inventory:\n * every root derivation was `dirname(stateDir)`, which `workspaceRootOf` generalizes).\n */\nimport os from 'node:os';\nimport path from 'node:path';\nimport fs from 'fs-extra';\nimport type { InstallScope } from './types.js';\n\n/** The store-less sidecar, relative to the workspace root (POSIX form). */\nexport const SIDECAR_DIR = '.claude/.agents-united';\nconst STORE_DIR = '.agents';\nconst LOCKFILE = 'agents-united.json';\n\nexport type StoreShape = 'store' | 'sidecar';\n\n/** True when `stateDir` is a sidecar (`…/.claude/.agents-united`). */\nexport function isSidecarDir(stateDir: string): boolean {\n const resolved = path.resolve(stateDir);\n return path.basename(resolved) === '.agents-united' && path.basename(path.dirname(resolved)) === '.claude';\n}\n\n/** The workspace (or, for global installs, home) root that projections are relative to. */\nexport function workspaceRootOf(stateDir: string): string {\n const resolved = path.resolve(stateDir);\n return isSidecarDir(resolved) ? path.dirname(path.dirname(resolved)) : path.dirname(resolved);\n}\n\n/** The state dir of a given shape under a root. */\nexport function stateDirFor(root: string, shape: StoreShape): string {\n return shape === 'sidecar' ? path.join(root, ...SIDECAR_DIR.split('/')) : path.join(root, STORE_DIR);\n}\n\n/**\n * Discover the state dir. Order: explicit override → an existing store (`.agents/` lockfile) → an\n * existing sidecar lockfile → the default for `preferShape` (store unless a caller asks for the\n * sidecar shape). An existing store always wins, so a workspace that has both (a half-finished\n * upgrade move) resolves to the store and the next install completes the move.\n */\nexport function resolveStateDir(\n scope: InstallScope = 'project',\n overrideDir?: string,\n opts: { cwd?: string; home?: string; preferShape?: StoreShape } = {},\n): string {\n if (overrideDir) return path.resolve(overrideDir);\n const root = scope === 'global' ? opts.home ?? os.homedir() : opts.cwd ?? process.cwd();\n const store = stateDirFor(root, 'store');\n if (fs.existsSync(path.join(store, LOCKFILE))) return store;\n const sidecar = stateDirFor(root, 'sidecar');\n if (fs.existsSync(path.join(sidecar, LOCKFILE))) return sidecar;\n return opts.preferShape === 'sidecar' ? sidecar : store;\n}\n","/**\n * Plan 023 Workstream A (owner decisions D1–D2, 2026-09-26) — the plain-session guard.\n *\n * The Plan 022 guard lives in role frontmatter, so it fires only while an agents-united role\n * runs. A plain `claude` session in the same repo is covered only by a settings-level hook.\n * Hook entries MERGE across settings levels (Claude Code hooks reference), so this module adds\n * our two PreToolUse groups to a settings file beside whatever the user already has.\n *\n * This is the first write agents-united makes into a user-owned file, so it is deliberately\n * conservative:\n * - the file is parsed as strict JSON; anything else (JSONC comments, trailing commas, a\n * non-object root) is NEVER rewritten — the caller reports `skipped-invalid`;\n * - every other key and hook entry is preserved in order, and the file's own indent, EOL and\n * trailing-newline style are reused, so removing our groups restores the user's bytes;\n * - ownership is recognized by the guard's marker text inside an exec-form `node -e` handler;\n * the CURRENT guard is recognized by exact handler equality (`guardHandlerHash`).\n */\nimport os from 'node:os';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { guardHandler, managedGuardHooks } from './guard.js';\n\nexport type SessionGuardVariant = 'project' | 'local' | 'user';\nexport type MergeStatus = 'created' | 'merged' | 'unchanged' | 'modified' | 'skipped-invalid';\nexport type RemoveStatus = 'removed' | 'deleted-file' | 'absent' | 'skipped-invalid';\nexport type InspectStatus = 'wired' | 'missing' | 'modified' | 'skipped-invalid' | 'absent';\n\ninterface Handler { type?: string; command?: string; args?: unknown[] }\ninterface Group { matcher?: string; hooks?: Handler[] }\ntype Settings = Record<string, unknown> & { hooks?: Record<string, unknown> & { PreToolUse?: Group[] } };\n\n/** Text every version of the guard script carries (ownership marker for older/edited copies). */\nconst GUARD_MARKER = 'Blocked by agents-united guard';\n\n/** Workspace-relative settings file for each variant (`user` resolves against the home dir). */\nexport const SESSION_GUARD_FILES: Record<SessionGuardVariant, string> = {\n project: '.claude/settings.json',\n local: '.claude/settings.local.json',\n user: '.claude/settings.json',\n};\n\n/** Absolute settings path for a variant; `user` always means the home directory's settings. */\nexport function resolveSessionGuardFile(variant: SessionGuardVariant, workspaceRoot: string): string {\n const base = variant === 'user' ? os.homedir() : workspaceRoot;\n return path.join(base, ...SESSION_GUARD_FILES[variant].split('/'));\n}\n\n/** Variant a recorded lockfile path stands for (inverse of resolveSessionGuardFile). */\nexport function variantOfRecordedFile(file: string): SessionGuardVariant {\n if (path.isAbsolute(file)) return 'user';\n return file.endsWith('settings.local.json') ? 'local' : 'project';\n}\n\n/** Stable hash of the current exec-form handler — recorded in the lockfile as ownership proof. */\nexport function guardHandlerHash(): string {\n return crypto.createHash('sha256').update(JSON.stringify(guardHandler())).digest('hex').slice(0, 16);\n}\n\n/** The snippet a user pastes by hand when their settings file cannot be rewritten safely. */\nexport function sessionGuardSnippet(): string {\n return JSON.stringify({ hooks: managedGuardHooks() }, null, 2);\n}\n\nconst isOursAnyVersion = (handler: Handler): boolean =>\n handler.command === 'node' &&\n Array.isArray(handler.args) &&\n handler.args[0] === '-e' &&\n typeof handler.args[1] === 'string' &&\n (handler.args[1] as string).includes(GUARD_MARKER);\n\nconst isCurrentGuard = (handler: Handler): boolean =>\n JSON.stringify({ type: handler.type, command: handler.command, args: handler.args }) === JSON.stringify(guardHandler());\n\nconst groupIsOurs = (group: Group): boolean => Array.isArray(group.hooks) && group.hooks.some(isOursAnyVersion);\n\ninterface Parsed { settings: Settings; indent: string | number; eol: string; trailingNewline: boolean }\n\nasync function parse(file: string): Promise<Parsed | 'absent' | 'invalid'> {\n if (!(await fs.pathExists(file))) return 'absent';\n const text = await fs.readFile(file, 'utf8');\n let value: unknown;\n try {\n value = JSON.parse(text.replace(/^/, ''));\n } catch {\n return 'invalid';\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return 'invalid';\n const hooks = (value as Settings).hooks;\n if (hooks !== undefined && (hooks === null || typeof hooks !== 'object' || Array.isArray(hooks))) return 'invalid';\n if (hooks?.PreToolUse !== undefined && !Array.isArray(hooks.PreToolUse)) return 'invalid';\n const indentMatch = text.match(/\\n([ \\t]+)\"/);\n return {\n settings: value as Settings,\n indent: indentMatch ? indentMatch[1] : 2,\n eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n',\n trailingNewline: /\\r?\\n$/.test(text),\n };\n}\n\nasync function write(file: string, parsed: Omit<Parsed, 'settings'>, settings: Settings): Promise<void> {\n let text = JSON.stringify(settings, null, parsed.indent);\n if (parsed.eol === '\\r\\n') text = text.replace(/\\n/g, '\\r\\n');\n if (parsed.trailingNewline) text += parsed.eol;\n await fs.ensureDir(path.dirname(file));\n await fs.writeFile(file, text, 'utf8');\n}\n\n/**\n * Add the guard's two PreToolUse groups. A group whose guard handler was hand-edited is left\n * alone (`modified` — never auto-repaired); an older guard version recorded by `replaceHash`\n * is replaced by the current one.\n */\nexport async function mergeSessionGuard(\n file: string,\n opts: { replaceHash?: string } = {},\n): Promise<{ status: MergeStatus; handlerHash: string }> {\n const handlerHash = guardHandlerHash();\n const parsed = await parse(file);\n if (parsed === 'invalid') return { status: 'skipped-invalid', handlerHash };\n\n const created = parsed === 'absent';\n const base = created ? { indent: 2, eol: '\\n', trailingNewline: true } : parsed;\n const settings: Settings = created ? {} : parsed.settings;\n const hooks = (settings.hooks ??= {});\n let pre: Group[] = (hooks.PreToolUse ??= []);\n\n if (opts.replaceHash && opts.replaceHash !== handlerHash) {\n // Our previous version: drop it so the current handler takes its place.\n pre = hooks.PreToolUse = pre.filter(group => !(groupIsOurs(group) && !group.hooks!.some(isCurrentGuard)));\n }\n\n let changed = false;\n let modified = false;\n for (const wanted of managedGuardHooks().PreToolUse) {\n const sameMatcher = pre.filter(group => group.matcher === wanted.matcher && groupIsOurs(group));\n if (sameMatcher.some(group => group.hooks!.some(isCurrentGuard))) continue;\n if (sameMatcher.length > 0) {\n modified = true;\n continue;\n }\n pre.push(JSON.parse(JSON.stringify(wanted)) as Group);\n changed = true;\n }\n\n if (!changed) return { status: modified ? 'modified' : 'unchanged', handlerHash };\n await write(file, base, settings);\n return { status: created ? 'created' : 'merged', handlerHash };\n}\n\n/**\n * Remove every agents-united guard group (any version). Empty containers our removal left behind\n * are pruned; the file itself is deleted only when agents-united created it and nothing remains.\n */\nexport async function removeSessionGuard(file: string, opts: { createdFile: boolean }): Promise<RemoveStatus> {\n const parsed = await parse(file);\n if (parsed === 'absent') return 'absent';\n if (parsed === 'invalid') return 'skipped-invalid';\n const { settings } = parsed;\n const pre = settings.hooks?.PreToolUse;\n if (!pre || !pre.some(groupIsOurs)) return 'absent';\n\n const kept = pre.filter(group => !groupIsOurs(group));\n if (kept.length > 0) {\n settings.hooks!.PreToolUse = kept;\n } else {\n delete settings.hooks!.PreToolUse;\n if (Object.keys(settings.hooks!).length === 0) delete settings.hooks;\n }\n\n if (opts.createdFile && Object.keys(settings).length === 0) {\n await fs.remove(file);\n return 'deleted-file';\n }\n await write(file, parsed, settings);\n return 'removed';\n}\n\n/** Doctor view: is the current guard wired in this file? */\nexport async function inspectSessionGuard(file: string): Promise<InspectStatus> {\n const parsed = await parse(file);\n if (parsed === 'absent' || parsed === 'invalid') return parsed === 'absent' ? 'absent' : 'skipped-invalid';\n const pre = parsed.settings.hooks?.PreToolUse ?? [];\n let allCurrent = true;\n let anyOurs = false;\n for (const wanted of managedGuardHooks().PreToolUse) {\n const ours = pre.filter(group => group.matcher === wanted.matcher && groupIsOurs(group));\n if (ours.length > 0) anyOurs = true;\n if (!ours.some(group => group.hooks!.some(isCurrentGuard))) allCurrent = false;\n }\n if (allCurrent) return 'wired';\n return anyOurs ? 'modified' : 'missing';\n}\n","/**\n * Plan 024 Step S4 (owner decisions E2/E4, 2026-09-27) — the opt-in command-permission preset.\n *\n * Field finding: outside auto mode, a background specialist cannot stop to ask for command\n * approval, so `npm test` / `npx tsc` get refused and a specialist can write code but never prove\n * it runs. This module pre-approves a small, fixed set of commands — never a wildcard, never\n * implied by `-y`, and never written to the shared, committed settings file.\n *\n * Security posture (owner asked whether this is a risk — yes, mitigated by design):\n * - opt-in only;\n * - written ONLY to the per-user `.claude/settings.local.json`, never `.claude/settings.json`,\n * regardless of which session-guard variant (Plan 023) is also active;\n * - `git commit`, `git push`, `rm`, `curl`/`wget`, and any deploy/publish command are excluded\n * from every tier, unconditionally (`NEVER_PRESET`, also unit-tested against both tiers);\n * - two tiers: `verify` (default) is fixed read/test commands only; `build` (must be requested\n * explicitly) additionally allows `npm install` / `npm run` / `npm test`, which execute code\n * the agent itself can edit (package scripts) — never on by default;\n * - the managed guard (Plan 022/023) still runs before every allowed command;\n * - remove-only-ours uninstall, exactly like the session guard (Plan 023) — ownership is the\n * exact set of entries this merge added, recorded by the caller (installer → lockfile).\n *\n * Host-neutral design: tiers are plain command prefixes, independent of any host's settings\n * syntax. `claudeAllowEntries` is the only renderer today (`Bash(<cmd> *)` in `permissions.allow`);\n * a host without a verified renderer is reported \"not supported yet\" by the installer rather than\n * guessing that host's file format.\n */\nimport path from 'node:path';\nimport fs from 'fs-extra';\n\nexport type PermissionTier = 'verify' | 'build';\nexport type MergeStatus = 'created' | 'merged' | 'unchanged' | 'skipped-invalid';\nexport type RemoveStatus = 'removed' | 'deleted-file' | 'absent' | 'skipped-invalid';\n\n/** Read-only / fixed-output commands: no side effect a reviewer would need to approve. */\nconst VERIFY_COMMANDS: readonly string[] = [\n 'git status',\n 'git diff',\n 'git log',\n 'npx tsc --noEmit',\n 'npx vitest run',\n 'npx eslint',\n];\n\n/** Adds commands that execute project-defined code (package.json scripts, installs). */\nconst BUILD_COMMANDS: readonly string[] = [...VERIFY_COMMANDS, 'npm install', 'npm run', 'npm test'];\n\nexport const PERMISSION_TIER_COMMANDS: Record<PermissionTier, readonly string[]> = {\n verify: VERIFY_COMMANDS,\n build: BUILD_COMMANDS,\n};\n\n/** Defense in depth: neither tier may ever contain these, and this list is itself unit-tested. */\nexport const NEVER_PRESET: readonly RegExp[] = [\n /\\bgit\\s+push\\b/,\n /\\bgit\\s+commit\\b/,\n /(^|\\s)rm(\\s|$)/,\n /\\bcurl\\b/,\n /\\bwget\\b/,\n /\\bvercel\\b[^,]*--prod\\b/,\n /\\bnpm\\s+publish\\b/,\n];\n\n/** Render a tier as Claude `permissions.allow` entries: `Bash(<cmd> *)`. */\nexport function claudeAllowEntries(tier: PermissionTier): string[] {\n return PERMISSION_TIER_COMMANDS[tier].map(cmd => `Bash(${cmd} *)`);\n}\n\n/** Hosts with a verified permission-preset renderer. Any other host is reported unsupported. */\nexport const SUPPORTED_PERMISSION_PRESET_HOSTS: readonly string[] = ['claude'];\n\ninterface Settings extends Record<string, unknown> {\n permissions?: { allow?: unknown[] } & Record<string, unknown>;\n}\ninterface Parsed { settings: Settings; indent: string | number; eol: string; trailingNewline: boolean }\n\nasync function parse(file: string): Promise<Parsed | 'absent' | 'invalid'> {\n if (!(await fs.pathExists(file))) return 'absent';\n const text = await fs.readFile(file, 'utf8');\n let value: unknown;\n try {\n value = JSON.parse(text.replace(/^/, ''));\n } catch {\n return 'invalid';\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return 'invalid';\n const permissions = (value as Settings).permissions;\n if (permissions !== undefined && (permissions === null || typeof permissions !== 'object' || Array.isArray(permissions))) return 'invalid';\n if (permissions?.allow !== undefined && !Array.isArray(permissions.allow)) return 'invalid';\n const indentMatch = text.match(/\\n([ \\t]+)\"/);\n return {\n settings: value as Settings,\n indent: indentMatch ? indentMatch[1] : 2,\n eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n',\n trailingNewline: /\\r?\\n$/.test(text),\n };\n}\n\nasync function write(file: string, parsed: Omit<Parsed, 'settings'>, settings: Settings): Promise<void> {\n let text = JSON.stringify(settings, null, parsed.indent);\n if (parsed.eol === '\\r\\n') text = text.replace(/\\n/g, '\\r\\n');\n if (parsed.trailingNewline) text += parsed.eol;\n await fs.ensureDir(path.dirname(file));\n await fs.writeFile(file, text, 'utf8');\n}\n\n/** Add every entry the tier requires that isn't already present. Never removes an existing entry. */\nexport async function mergePermissionPreset(\n file: string,\n tier: PermissionTier,\n): Promise<{ status: MergeStatus; entries: string[] }> {\n const wanted = claudeAllowEntries(tier);\n const parsed = await parse(file);\n if (parsed === 'invalid') return { status: 'skipped-invalid', entries: [] };\n\n const created = parsed === 'absent';\n const base = created ? { indent: 2, eol: '\\n', trailingNewline: true } : parsed;\n const settings: Settings = created ? {} : parsed.settings;\n const permissions = (settings.permissions ??= {});\n const allow: unknown[] = (permissions.allow ??= []);\n\n const added: string[] = [];\n for (const entry of wanted) {\n if (!allow.includes(entry)) {\n allow.push(entry);\n added.push(entry);\n }\n }\n\n if (added.length === 0) return { status: 'unchanged', entries: wanted };\n await write(file, base, settings);\n return { status: created ? 'created' : 'merged', entries: wanted };\n}\n\n/**\n * Remove exactly the recorded entries (never entries the caller didn't add). Empty containers\n * left behind are pruned; the file is deleted only when the caller created it and nothing remains.\n */\nexport async function removePermissionPreset(\n file: string,\n entries: string[],\n opts: { createdFile: boolean },\n): Promise<RemoveStatus> {\n const parsed = await parse(file);\n if (parsed === 'absent') return 'absent';\n if (parsed === 'invalid') return 'skipped-invalid';\n const { settings } = parsed;\n const allow = settings.permissions?.allow;\n if (!Array.isArray(allow)) return 'absent';\n\n const owned = new Set(entries);\n const kept = allow.filter(e => !(typeof e === 'string' && owned.has(e)));\n if (kept.length > 0) {\n settings.permissions!.allow = kept;\n } else {\n delete settings.permissions!.allow;\n if (Object.keys(settings.permissions!).length === 0) delete settings.permissions;\n }\n\n if (opts.createdFile && Object.keys(settings).length === 0) {\n await fs.remove(file);\n return 'deleted-file';\n }\n await write(file, parsed, settings);\n return 'removed';\n}\n","export type InstallScope = 'project' | 'global';\n\n/**\n * Effective owners of a tracked asset (`AssetFileMeta` or a projection entry) at READ time.\n *\n * The type documents `owners` as \"Absent ⇒ [bundle]\", but legacy records store the installing bundle in\n * `bundle` and write `owners: []`. `??` alone does not fall back for those — `[]` is not nullish — so an\n * empty `owners` array read as \"owned by nobody\": the asset vanished from removal and became permanent\n * residue no `agents remove` could reach. Treat an empty `owners` as absent and fall back to `bundle`.\n *\n * READ-side only. At WRITE time an installer must seed from `existing?.owners` verbatim: `bundle` is who\n * *deployed* a record first, not who *declared* it, so an addon that merely deploys an inherited asset\n * must not be resurrected as its owner (the ownership contract is the Declared Asset Set — see A6 of the\n * lifecycle conformance suite).\n */\nexport function assetOwners(rec: { owners?: string[]; bundle?: string } | undefined | null): string[] {\n if (!rec) return [];\n const declared = rec.owners ?? [];\n if (declared.length > 0) return declared;\n return rec.bundle ? [rec.bundle] : [];\n}\n\n/**\n * Union an owner into a record's effective owners. Never replaces: shared assets are refcounted, so a\n * second bundle installing the same file must add itself alongside the existing owners, not overwrite\n * them (an overwrite silently drops the first bundle's claim and its removal then deletes or strands a\n * file another bundle still needs).\n */\nexport function mergeAssetOwners(\n rec: { owners?: string[]; bundle?: string } | undefined | null,\n owner: string | undefined\n): string[] {\n const owners = assetOwners(rec);\n if (!owner) return owners;\n return owners.includes(owner) ? owners : [...owners, owner];\n}\nexport type InstallMethod = 'symlink' | 'copy';\nexport type AgentHost = 'agents' | 'gemini' | 'claude' | 'cursor' | 'cline' | 'opencode' | 'codex';\n\n// Backward compatibility alias\nexport type Scope = InstallScope;\n\nexport type BundleTier = 'domain' | 'organization';\nexport type BundleStatus = 'stable' | 'experimental' | 'under-construction' | 'needs-audit' | 'deprecated';\nexport type ExecutionMode = 'operational' | 'limited-operational' | 'brainstorming';\n\nexport interface RequiredMcp {\n name: string;\n purpose?: string;\n optionalForBrainstorming?: boolean;\n}\n\nexport interface BundlePrerequisites {\n requiredMcps?: RequiredMcp[];\n requiredPackages?: string[];\n requiredEnvVars?: string[];\n}\n\nexport interface BundleModes {\n operational?: string;\n brainstorming?: string;\n}\n\nexport interface PrerequisiteItemCheck {\n type: 'mcp' | 'package' | 'env';\n name: string;\n purpose?: string;\n satisfied: boolean;\n status: 'ok' | 'missing' | 'partial';\n details?: string;\n optionalForBrainstorming?: boolean;\n detectedInHosts?: string[];\n missingInHosts?: string[];\n}\n\nexport interface PrerequisiteEvaluation {\n bundleName: string;\n tier: BundleTier;\n hasPrerequisites: boolean;\n allSatisfied: boolean;\n operationalPossible: boolean;\n items: PrerequisiteItemCheck[];\n modes?: BundleModes;\n}\n\n/** ADR 0014 — declarative caps bounding all inter-agent planning dialogue. */\nexport interface ConsultationBudget {\n maxPlanningRounds: number;\n maxPeerExchangesPerPair: number;\n summaryWordCap: number;\n maxIterations: number;\n}\n\n/** ADR 0014/0015 — declarative planning-loop posture. Mode absent ⇒ 'subagent-first' (backward compat). */\nexport type PlanningLoopMode = 'subagent-first' | 'planner-orchestrator';\n\nexport interface PlanningLoopConfig {\n enabled: boolean;\n mode?: PlanningLoopMode;\n budget?: ConsultationBudget;\n sidekicks?: { max: number };\n}\n\nexport interface BundleDefinition {\n name: string;\n version?: string;\n description: string;\n category?: string;\n domain?: string;\n tier?: BundleTier;\n status?: BundleStatus;\n parentBundle?: string;\n recommendedAddons?: string[];\n aliases?: string[];\n orchestrator?: string;\n agents?: string[];\n /** @deprecated ADR 0016: Workflows are unified into `skills`. Preserved for backward compatibility with legacy manifests. */\n workflows?: string[];\n skills?: string[];\n prerequisites?: BundlePrerequisites;\n modes?: BundleModes;\n /** ADR 0014 — opt-in Subagent-First Planning Dialogue Loop (digital-agency first). */\n planningLoop?: PlanningLoopConfig;\n /** ADR 0014 — AstrolabsAI persona → canonical roster role (`.md` stripped) map. */\n personaAliases?: Record<string, string>;\n /**\n * Plan 015 §0/C6d — optional bundle-level rule bindings. Forward-compatible:\n * no bundle in `registry/bundles.json` declares this today (agent frontmatter\n * `rules:` is the single source of truth). Adding it here keeps\n * `RegistryResolver.resolve()` ready for a future catalog-level declaration\n * without another schema change.\n */\n rules?: string[];\n}\n\nexport interface BundlesManifest {\n $schema?: string;\n version: number;\n bundles: Record<string, BundleDefinition>;\n}\n\nexport interface LockfileAsset {\n hash: string;\n bundle?: string;\n /** Every bundle whose Declared Asset Set contains this file. Absent ⇒ [bundle]. */\n owners?: string[];\n method?: InstallMethod;\n installedAt: string;\n /** Workspace-root-relative paths (forward slashes) of translated copies fanned out\n * into other host runtimes (e.g. '.claude/agents/x.md', 'AGENTS.md'). Optional so\n * pre-existing lockfiles without projections remain valid. */\n projectedTo?: string[];\n}\n\nexport type ProjectionKind = 'role' | 'skill' | 'rule' | 'team-manifest' | 'workflow' | 'bridge' | 'plugin-manifest';\n\nexport interface LockfileProjection {\n host: string;\n kind: ProjectionKind;\n canonical?: string;\n owners: string[];\n hash: string;\n installedAt: string;\n managedMarker: boolean;\n}\n\n/**\n * ADR 0018 — the structural shape every compound-lane projector emits\n * (`ClineProjector` / `ClaudeProjector`). The installer's compound lane is\n * host-parameterised against this shape, so Cline and Claude share one\n * implementation instead of a copy-paste fork.\n */\nexport interface PlannedProjectionArtifact {\n kind: ProjectionKind;\n canonical?: string;\n relPath: string;\n content?: string;\n sourceFilePath?: string;\n managedMarker: boolean;\n /**\n * ADR 0018 decision 12 — a **distribution-only** artifact (the opt-in Claude plugin lane).\n * It is deployed and tracked in `lockfile.projections`, but it is never a projection\n * *target*: no `projectedTo` pointer is recorded for it, because its namespace\n * (`.agents/plugins/<bundle>/`) belongs to the **cline** reconcile pass and a `claude`\n * pointer recorded there would be dropped on the next Cline install.\n */\n distributionOnly?: boolean;\n\n}\n\nexport interface ClineTeamManifest {\n schemaVersion: 1;\n bundle: string;\n scope: InstallScope;\n coordinator: { name: string; canonicalPath: string };\n roles: Array<{ name: string; canonicalPath: string }>;\n skills: string[];\n /** @deprecated ADR 0016: Workflows are unified into `skills`. Preserved for backward compatibility. */\n workflows?: string[];\n recommendedAddons: string[];\n activation: {\n preferred: 'named-team';\n fallbacks: Array<'adaptive-session' | 'single-orchestrator'>;\n };\n /** ADR 0014 — present when the bundle opts into the Planning Dialogue Loop. */\n planningLoop?: PlanningLoopConfig;\n /** ADR 0014 — persona → role pairs rendered from `BundleDefinition.personaAliases`. */\n personas?: Array<{ persona: string; role: string }>;\n}\n\nexport type ResolvedClineCommand =\n | { executable: string; prefixArgs: string[]; source: 'env-binary' }\n | { executable: string; prefixArgs: string[]; source: 'node-wrapper' }\n | { executable: string; prefixArgs: string[]; source: 'path-executable' };\n\nexport type ClineActivationStrategy =\n | 'named-team'\n | 'adaptive-session'\n | 'single-orchestrator';\n\nexport interface ClineCapabilityReport {\n installed: boolean;\n version?: string;\n command?: ResolvedClineCommand;\n namedTeams: boolean;\n rolePresetConsumer: 'detected' | 'not-detected' | 'unknown';\n diagnostics: string[];\n}\n\nexport type ResolvedClaudeCommand = {\n executable: string;\n prefixArgs: string[];\n source: 'env-binary' | 'node-wrapper' | 'path-executable';\n};\n\n/**\n * ADR 0018 decision 11 / Plan 016 decision 12 — the read-only Claude Code probe result.\n * `pluginSupport` and `agentTeamsExperimental` are derived from `--help` text only; both\n * default to `false` when help output is unavailable, so an unverifiable capability is\n * never reported as supported.\n */\nexport interface ClaudeCapabilityReport {\n installed: boolean;\n version?: string;\n command?: ResolvedClaudeCommand;\n pluginSupport: boolean;\n agentTeamsExperimental: boolean;\n /**\n * Whether the probed runtime provides `SubagentHandback` — the subagent hand-off tool the live tools\n * reference dates at Claude Code v2.1.271+ (and only in auto mode). Derived from `--version`, so it\n * reports the version floor rather than attempting to detect the permission mode.\n */\n subagentHandback: boolean;\n diagnostics: string[];\n}\n\n/**\n * Plan 029 B6 — the resolved `agy` (Antigravity CLI) invocation. Mirrors `ResolvedClaudeCommand`,\n * minus the npm node-wrapper branch: `agy` ships as a native binary plus `.cmd`/`.bat` shims, so a\n * PATH hit is always either the binary itself or the shell shim routed through `cmd.exe`.\n */\nexport type ResolvedAgyCommand = {\n executable: string;\n prefixArgs: string[];\n source: 'env-binary' | 'path-executable';\n};\n\n/**\n * Plan 029 B6 — the read-only Antigravity CLI capability report.\n *\n * `installed` is a pure \"the binary answered `--version` with exit 0\" signal (mirroring\n * `ClaudeCapabilityReport`), so an unverifiable runtime is never reported as capable. The three\n * feature flags are derived from `agy --help` text only. `meetsVersionFloor` is reported as data:\n * it names the version on which the `--agent` / `--prompt-interactive` surface was verified live\n * and is deliberately never a launch gate.\n */\nexport interface AntigravityCapabilityReport {\n installed: boolean;\n version?: string;\n command?: ResolvedAgyCommand;\n /** `--agent <name>` (agent for the current CLI session) is advertised by `agy --help`. */\n agentFlag: boolean;\n /** `-i, --prompt-interactive` is advertised — i.e. an opening prompt CAN be passed. */\n promptInteractive: boolean;\n /** Values advertised for `--mode` (verified live: `accept-edits`, `plan`). */\n modes: string[];\n /** Whether the reported version is at or above the live-verified floor. Informational only. */\n meetsVersionFloor: boolean;\n diagnostics: string[];\n}\n\nexport interface ProcessRunnerResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport type ProcessRunner = (\n executable: string,\n args: string[],\n options?: { cwd?: string; env?: Record<string, string>; timeoutMs?: number }\n) => Promise<ProcessRunnerResult>;\n\nexport interface LockfileManifest {\n $schema: string;\n version: number;\n scope?: InstallScope;\n method?: InstallMethod;\n hosts?: AgentHost[];\n /** Runtime ids this install was fanned out to (e.g. ['cline']). Persisted so that\n * `update` / re-install regenerate projections without the user re-passing --fanout. */\n fanout?: string[];\n installed: {\n bundles: string[];\n agents: string[];\n skills: string[];\n /** @deprecated ADR 0016: Workflows are unified into `skills`. Preserved for backward compatibility with existing lockfiles. */\n workflows?: string[];\n };\n bundleVersions?: Record<string, string>;\n bundleModes?: Record<string, ExecutionMode>;\n files: Record<string, LockfileAsset>;\n /** File-level projection ownership map (keyed by workspace-root-relative POSIX path). */\n projections?: Record<string, LockfileProjection>;\n /**\n * Plan 016 / ADR 0018 decision 12 — the recorded opt-in for the Claude plugin lane.\n *\n * Persisted for the same reason `fanout` is: `agents update` re-runs the installer without the\n * user re-passing `--plugin`, so without this field every update would prune the opted-in\n * `.agents/plugins/<bundle>/.claude-plugin/**` package as a superseded projection. Absent ⇒ the\n * lane was never opted into.\n */\n pluginLane?: boolean;\n /**\n * Plan 023 A (owner D1–D2) — the recorded plain-session guard decision. `{ off: true }` is a\n * remembered \"no\"; otherwise the settings file (workspace-relative, or absolute for `user`)\n * holding our managed PreToolUse groups, the handler hash that proves ownership, and whether\n * agents-united created the file (only then may uninstall delete it). Absent ⇒ never decided.\n */\n sessionGuard?: SessionGuardRecord;\n /**\n * Plan 023 B (ADR 0022, D3) — `'sidecar'` when this lockfile lives in the store-less sidecar\n * `.claude/.agents-united/`. Absent on a store-backed install (the lockfile shape is unchanged).\n */\n storeShape?: 'sidecar';\n /**\n * Plan 024 S4 (owner E2/E4) — the recorded opt-in command-permission preset. `{ off: true }` is\n * a remembered \"no\"; otherwise the tier, the settings file it was written to (always\n * `.claude/settings.local.json`, workspace-relative), the exact entries this install added\n * (removal is limited to these), and whether agents-united created the file. Absent ⇒ never\n * decided.\n */\n permissionPreset?: PermissionPresetRecord;\n}\n\nexport type PermissionPresetRecord =\n | { off: true }\n | { tier: 'verify' | 'build'; file: string; entries: string[]; createdFile: boolean };\n\nexport type SessionGuardRecord =\n | { off: true }\n | { file: string; handlerHash: string; createdFile: boolean };\n\nexport type VersionDriftStatus = 'up-to-date' | 'outdated' | 'modified';\n\nexport interface InstalledPackageRecord {\n id: string; // unique identifier, e.g. \"software-engineering@project:agents\"\n name: string;\n type: 'bundle' | 'agent' | 'skill' | 'workflow';\n scope: InstallScope;\n host: AgentHost;\n targetDir: string;\n displayLocation: string; // e.g. \"./.agents\" or \"~/.agents\"\n installedVersion: string;\n upstreamVersion: string;\n driftStatus: VersionDriftStatus;\n method?: InstallMethod;\n fileCount: number;\n title?: string;\n description?: string;\n fanout?: string[];\n projections?: string[];\n}\n\nexport interface ScannedLocationSummary {\n scope: InstallScope;\n targetDir: string;\n displayLocation: string;\n packageCount: number;\n fanout: string[];\n}\n\nexport interface PackageInventory {\n records: InstalledPackageRecord[];\n bundles: InstalledPackageRecord[];\n standaloneItems: InstalledPackageRecord[];\n targetDirs: string[];\n scannedScopes?: InstallScope[];\n scannedLocations?: ScannedLocationSummary[];\n}\n\nexport interface InventoryOptions {\n scope?: InstallScope;\n global?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n targetDir?: string;\n cwd?: string;\n}\n\nexport interface UpdateOptions {\n scope?: InstallScope;\n global?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n targetDir?: string;\n force?: boolean;\n dryRun?: boolean;\n yes?: boolean;\n cwd?: string;\n /** Fan the canonical store out into these runtimes during the update re-install\n * (e.g. to add Cline projections to a bundle originally installed without fanout). */\n fanout?: string[];\n}\n\nexport interface UpdateCheckItem {\n record: InstalledPackageRecord;\n hasUpdate: boolean;\n installedVersion: string;\n upstreamVersion: string;\n reason?: string;\n}\n\nexport interface UpdateCheckReport {\n items: UpdateCheckItem[];\n outdatedCount: number;\n upToDateCount: number;\n totalCount: number;\n scannedScopes?: InstallScope[];\n scannedLocations?: ScannedLocationSummary[];\n}\n\nexport interface UpdateResult {\n updated: InstalledPackageRecord[];\n skipped: Array<{ record: InstalledPackageRecord; reason: string }>;\n targetDirs: string[];\n dryRun: boolean;\n projections: ProjectionInfo[];\n}\n\n\nexport interface InstallOptions {\n scope?: InstallScope;\n global?: boolean;\n method?: InstallMethod;\n symlink?: boolean;\n copy?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n targetDir?: string;\n /** Host ids to project the canonical `.agents/` store into (validated against\n * HOST_REGISTRY; only `projectionCapable` hosts are honored). */\n fanout?: string[];\n /** Execution mode for organization bundles with prerequisites */\n mode?: ExecutionMode;\n /** Allow installation even if prerequisites are missing */\n allowMissingPrereqs?: boolean;\n /** Allow installation of bundles marked as under-construction */\n allowUnderConstruction?: boolean;\n /**\n * ADR 0018 decision 12 / Plan 016 decision 13 — opt-in **Claude plugin lane**: also emit the\n * distribution-only package (`.agents/plugins/<bundle>/.claude-plugin/plugin.json` + `agents/`)\n * for `claude --plugin-dir`. Claude lane only; the plan is byte-identical to today when absent.\n */\n pluginLane?: boolean;\n /**\n * Plan 023 A — guard plain Claude sessions too: `project` (.claude/settings.json), `local`\n * (.claude/settings.local.json), `user` (~/.claude/settings.json, explicit only), or `false`\n * (remembered \"no\"). Omitted ⇒ inherit the lockfile decision. Claude lane only.\n */\n sessionGuard?: 'project' | 'local' | 'user' | false;\n /**\n * Plan 024 S4 (owner E2/E4) — opt-in command-permission preset: `verify` (fixed read/test\n * commands only) or `build` (adds npm install/run/test — must be requested explicitly). Written\n * ONLY to `.claude/settings.local.json`, never the shared `.claude/settings.json`, and never for\n * a global install. `false` records a remembered \"no\". Omitted ⇒ inherit the lockfile decision\n * (absent decision ⇒ off). A host with no verified renderer yet (anything but Claude today)\n * reports \"not supported\" instead of writing a guessed file.\n */\n permissionPreset?: 'verify' | 'build' | false;\n /**\n * Plan 023 B (ADR 0022, D4) — where the machine state lives when no `targetDir` is given:\n * `'sidecar'` (store-less Claude-only install) or `'store'` (`.agents/`). Decided by\n * `planInstallTargets`; an existing store always wins, and a store-requiring install moves an\n * existing sidecar into `.agents/`. Omitted ⇒ discover (existing store > existing sidecar > store).\n */\n storeShape?: 'store' | 'sidecar';\n}\n\nexport interface ProjectionInfo {\n host: string;\n path: string;\n kind?: ProjectionKind;\n warnings: string[];\n}\n\nexport interface UninstallOptions {\n scope?: InstallScope;\n global?: boolean;\n hosts?: AgentHost[];\n target?: string | string[];\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n targetDir?: string;\n}\n\nexport interface ResolvedAssets {\n targetBundle?: string;\n agents: string[];\n skills: string[];\n workflows: string[];\n rules: string[];\n}\n\nexport interface SearchOptions {\n domain?: string;\n type?: 'bundle' | 'agent' | 'skill' | 'workflow';\n}\n\nexport interface SearchResults {\n bundles: BundleDefinition[];\n agents: string[];\n skills: string[];\n workflows: string[];\n}\n\nexport type ModelTier = 'inherit' | 'pro' | 'flash';\nexport type ReasoningEffort = 'low' | 'medium' | 'high';\nexport type PermissionMode = 'acceptEdits' | 'requestReview' | 'strict' | 'readOnly';\nexport type CommandExecutionPolicy = 'auto' | 'ask' | 'never';\n\nexport interface AgentHook {\n matcher: string;\n action: string;\n}\n\nexport interface AgentFrontmatter {\n name: string;\n version?: string;\n type?: 'orchestrator' | 'subagent';\n description?: string;\n model?: ModelTier;\n effort?: ReasoningEffort;\n permissionMode?: PermissionMode;\n commandExecutionPolicy?: CommandExecutionPolicy;\n mainAgent?: boolean;\n subagent?: boolean;\n inheritCustomizations?: boolean;\n rules?: string[];\n tools?: string[];\n hooks?: Record<string, AgentHook[]>;\n}\n\nexport interface SkillMetadata {\n author?: string;\n version?: string;\n icon?: string;\n source?: string;\n license?: string;\n}\n\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n 'disable-slash-command'?: boolean;\n disableSlashCommand?: boolean;\n metadata?: SkillMetadata;\n}\n\n/**\n * agent-plugins.org v1.0.0 Agent Plugin manifest (`plugin.json`) written at the root\n * of `.agents/plugins/<bundle>/`. Its presence is the discriminator Cline uses to\n * hard-stop code-plugin scanning of the directory (see `isAgentPluginDirectory` in\n * Cline's `@cline/shared/storage`), and it makes the package portable to other\n * Agent Plugins-conforming clients.\n */\nexport interface AgentPluginManifest {\n $schema: string;\n name: string;\n version: string;\n description: string;\n}\n\n/** ADR 0018 — how one canonical feature is treated when projected into a host dialect. */\nexport type LedgerDisposition = 'mapped' | 'approximated' | 'degraded' | 'unsupported';\n\n/** ADR 0018 decision 9 — a recorded disposition; a drop without one is a hard error. */\nexport interface TranslationLedgerEntry {\n feature: string;\n host: string;\n disposition: LedgerDisposition;\n rationale: string;\n}\n/**\n * Plan 016 decision 13 / ADR 0018 decision 12 — the Anthropic Claude Code plugin manifest\n * (`.claude-plugin/plugin.json`), consumed via `claude --plugin-dir`. The field set is the\n * documented seven; `author`/`homepage`/`repository`/`license` are emitted as empty strings\n * because `BundleDefinition` (and `registry/bundles.json`) declares no such metadata — the\n * keys stay present for schema completeness rather than being invented, and the manifest\n * stays deterministic across project and global installs.\n */\nexport interface ClaudePluginManifest {\n author: string;\n description: string;\n homepage: string;\n license: string;\n name: string;\n repository: string;\n version: string;\n}\n\n\n\n/**\n * ADR 0018 — the pure-data description of the Claude Code dialect that the Claude lane renders\n * against. Plan 017 (ADR 0019) lifts this shape into the shared `HostDialectSpec` so additional\n * hosts are added as data rather than as hand-wired translators.\n */\nexport interface ClaudeDialect {\n id: 'claude';\n nameRegex: RegExp;\n /** Canonical frontmatter tool token -> Claude tool name. */\n toolVocabulary: Record<string, string>;\n /** Canonical tool token -> Claude phrase used when rewriting prompt prose. */\n bodyToolVocabulary: Record<string, string>;\n /** Canonical command tokens -> host renderings (Plan 020 note 7 command bindings). */\n commandVocabulary: Record<string, string>;\n /** Canonical permissionMode -> Claude permissionMode. */\n permissionModeMap: Record<string, string>;\n /** Canonical model tier -> Claude model. */\n modelMap: Record<string, string>;\n /**\n * Model applied when the canonical declares `inherit` (ADR 0018 decision 7 as amended 2026-09-22):\n * coordinators and specialists get an explicit posture instead of inheriting the session model.\n */\n roleModelDefaults: { coordinator: string; specialist: string };\n /** Effort applied when the canonical does not declare one (coordinator vs specialist posture). */\n roleEffortDefaults: { coordinator: string; specialist: string };\n /**\n * Canonical body sections replaced wholesale with a host-native rendering (ADR 0018 decision 8).\n *\n * Tool-name rewriting alone cannot rescue a section that describes *another host's* routing (Antigravity's\n * `language_server.exe` limitation, Cline's `subagent_*` tools): the words rewrite but the meaning does\n * not. Each entry replaces the matched heading's whole section with prose the target host can act on.\n * This is a rendering, not a feature drop, so it carries no ledger disposition.\n */\n bodySectionOverrides: Array<{ heading: RegExp; replacement: string }>;\n budgets: { skillDescriptionChars: number; agentDescriptionTokens: number };\n maxRuleLines: number;\n}\n\n/**\n * ADR 0021 decision 9 — Translation Ledger dispositions survive as delta classifications;\n * a Declared Delta is an audited host-specific deviation ABOVE the Contract Floor.\n */\nexport type DeltaDisposition = LedgerDisposition;\nexport type DeclaredDelta = TranslationLedgerEntry;\n\n/**\n * Plan 021 (ADR 0021) — the tool-free definition of what an agent IS: identity, mission,\n * scope boundaries, structured output contract, safety rules, and tool-neutral behavioural\n * invariants. Authored in `registry/core/*.core.md`; contains zero host tool names,\n * command names, or host mechanics (decision 1).\n */\nexport interface SemanticCore {\n identity: string;\n mission: string;\n scope_boundaries: string;\n output_contract: string;\n safety: string;\n invariants: string[];\n}\n\n/** Plan 021 gate 4 — conformance input: what the realization binds, adds, and declares. */\nexport interface ValidateDeclaredDeltasInput {\n realization: { boundInvariants: string[]; aboveFloorScope: string[] };\n core: SemanticCore;\n deltas: DeclaredDelta[];\n}\n\n/** ADR 0021 decision 2 — an invariant BOUND to host mechanics, never translated. */\nexport interface InvariantBinding {\n /** Tool-neutral behavioural law as authored in the Semantic Core invariants. */\n invariant: string;\n /** The concrete host-native mechanic this law is bound to on this host. */\n binding: string;\n}\n\n/**\n * ADR 0021 decision 9 — `HostDialectSpec` evolves into the per-host Binding Table schema:\n * the Plan 017 codex fields survive (they are the vocabulary surface) and the realization\n * gains `capabilityProfile`, `invariantBindings`, and a `deltaRegistry` reference. One spec\n * per host; host churn is a one-host data PR.\n */\nexport interface HostDialectSpec {\n id: string;\n fields: Record<string, 'keep' | 'map' | 'drop'>;\n toolVocabulary: Record<string, string>;\n bodyToolVocabulary: Record<string, string>;\n commandVocabulary: Record<string, string>;\n features: Record<string, boolean | string>;\n budgets: { skillDescriptionChars: number; agentDescriptionTokens: number };\n nameRules: { pattern: string; subagentPrefixPolicy: string };\n launcher: { flags: string[]; notes: string };\n markerProfile: string;\n /** ADR 0021 additions — the Binding Table proper. */\n capabilityProfile: string;\n invariantBindings: InvariantBinding[];\n deltaRegistry: string;\n}\n\n/** Plan 021 Step 4 — the per-role binding view consumed by the Claude Creation Engine. */\nexport interface ClaudeCreationBindingTable {\n host: string;\n /** The native role name (e.g. `backend-architect`); optional so fixtures stay minimal. */\n roleName?: string;\n /** `invariant` (HostDialectSpec shape) or `feature` (legacy codex shape) identify the law. */\n invariantBindings?: Array<{ invariant?: string; feature?: string; binding: string }>;\n /** `rendering` (Binding Table shape) or `native` (legacy shape) give the host command. */\n commandBindings?: Array<{ command: string; rendering?: string; native?: string; rationale?: string }>;\n commandVocabulary?: Record<string, string>;\n deltas?: DeclaredDelta[];\n /**\n * Plan 022 H2/H3 — the role's own least-privilege allowlist (Realization Layer). Absent ⇒ the\n * profile's whole surface (fixtures only); every entry must exist in the profile.\n */\n tools?: string[];\n /** Plan 022 H3 — native permission mode (e.g. `plan` for read-only roles). */\n permissionMode?: string;\n}\n\n/** Plan 021 Step 4 — the versioned tool-surface snapshot the creation engine targets. */\nexport interface ClaudeCreationProfile {\n host: string;\n version: string;\n tools?: string[];\n}\n\n\n\n","import path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { AgentHostAdapter } from './adapter.js';\nimport { isKnownHost } from './hosts.js';\nimport { HostProjector } from './projector.js';\nimport { ClineProjector } from './cline-projector.js';\nimport { removeSessionGuard } from './session-guard.js';\nimport { removePermissionPreset } from './permission-preset.js';\nimport { isSidecarDir, resolveStateDir, workspaceRootOf } from './state-dir.js';\nimport type { UninstallOptions, LockfileManifest, InstallScope, AgentHost, BundleDefinition } from './types.js';\nimport { assetOwners } from './types.js';\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]+?)\\r?\\n---/;\n\nexport class UninstallEngine {\n private registry: RegistryResolver;\n\n constructor(registry?: RegistryResolver) {\n this.registry = registry || new RegistryResolver();\n }\n\n private async calculateHash(filePath: string): Promise<string> {\n const buffer = await fs.readFile(filePath);\n return 'sha256:' + crypto.createHash('sha256').update(buffer).digest('hex');\n }\n\n /**\n * Determines whether a projected file still carries our managed marker. Agent\n * projections have YAML frontmatter with the marker as the first body line; the\n * AGENTS.md bridge (agentsmd profile) is a plain markdown index with no\n * frontmatter, so the marker is checked against the whole content.\n */\n private async isManagedProjection(absPath: string, isAgentsMd: boolean, recordedHash?: string): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n if (HostProjector.hasManagedMarker(content)) return true;\n // ADR 0017 amendment (Gate 7, 2026-09-25): markerless sidecar artifacts (LICENSE.txt,\n // references/**) cannot carry the marker — they are managed iff their bytes still hash\n // to the value recorded at install time.\n if (recordedHash) {\n const bytes = await fs.readFile(absPath);\n return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` === recordedHash;\n }\n return false;\n }\n\n /**\n * Removes empty projection dirs left behind after deleting a projected file\n * (e.g. `.claude/agents/` and then `.claude/`). Only ever removes empty dirs.\n */\n private async removeEmptyProjectionDirs(workspaceRoot: string, projPath: string): Promise<void> {\n let dir = path.dirname(path.join(workspaceRoot, projPath));\n while (dir !== workspaceRoot && dir.startsWith(workspaceRoot)) {\n try {\n const entries = await fs.readdir(dir);\n if (entries.length > 0) break;\n await fs.rmdir(dir);\n } catch {\n break;\n }\n dir = path.dirname(dir);\n }\n }\n\n /**\n * Removes every recorded projection for a canonical asset, guarding against\n * clobbering user-modified files. Mirrors the hash-conflict error pattern.\n */\n private async removeProjections(\n workspaceRoot: string,\n projectedTo: string[],\n force?: boolean,\n projectionHashes?: Record<string, { hash?: string }>,\n ): Promise<void> {\n for (const projPath of projectedTo) {\n const absProjection = path.join(workspaceRoot, projPath);\n if (!await fs.pathExists(absProjection)) {\n continue;\n }\n\n const isAgentsMd = projPath === 'AGENTS.md';\n const managed = await this.isManagedProjection(absProjection, isAgentsMd, projectionHashes?.[projPath]?.hash);\n if (!managed && !force) {\n throw new Error(\n `Projection ${projPath} has user modifications. Use --force to remove.`\n );\n }\n\n await this.safeRemoveProjection(absProjection);\n await this.removeEmptyProjectionDirs(workspaceRoot, projPath);\n }\n }\n\n private async safeRemoveProjection(absPath: string): Promise<void> {\n try {\n const lstat = await fs.lstat(absPath);\n if (lstat.isSymbolicLink()) {\n await fs.unlink(absPath);\n return;\n }\n } catch {\n // not a symlink\n }\n await fs.remove(absPath);\n }\n\n /**\n * Installed-addon freshness (plan 003): after a child bundle (one with a\n * `parentBundle`) is removed, re-render the parent's coordinator rule + team\n * manifest excluding every remaining installed bundle in the lockfile, so the\n * removed addon returns to the parent's recommendedAddons. Presentation-free:\n * the two projection files carry the managed marker trustees inside (rule) and\n * are overwritten directly via fs-extra. If a parent artifact does not exist in\n * the workspace (parent not installed as its own bundle), it is skipped.\n */\n private async refreshParentCoordination(\n bundleName: string,\n workspaceRoot: string,\n lockfile: LockfileManifest,\n scope: InstallScope\n ): Promise<void> {\n const bundleDef: BundleDefinition | null = await this.registry.getBundle(bundleName);\n if (!bundleDef?.parentBundle) return;\n const parentDef = await this.registry.getBundle(bundleDef.parentBundle);\n if (!parentDef) return;\n const parentResolved = await this.registry.resolve(parentDef.name).catch(() => null);\n if (!parentResolved) return;\n\n const registryDir = this.registry.getRegistryDir();\n const projection = await ClineProjector.planCompoundProjection(\n parentDef,\n scope,\n parentResolved,\n registryDir,\n lockfile.installed.bundles\n );\n\n for (const artifact of projection) {\n if (artifact.kind !== 'rule' && artifact.kind !== 'team-manifest') continue;\n if (artifact.content === undefined) continue;\n const dest = path.join(workspaceRoot, artifact.relPath);\n if (!await fs.pathExists(dest)) continue; // parent not installed as its own bundle\n await fs.writeFile(dest, artifact.content, 'utf8');\n const hash = await this.calculateHash(dest);\n if (lockfile.projections?.[artifact.relPath]) {\n lockfile.projections[artifact.relPath].hash = hash;\n }\n }\n }\n\n private parseHosts(options: UninstallOptions): AgentHost[] {\n if (options.hosts && options.hosts.length > 0) return options.hosts;\n if (options.target) {\n const raw = Array.isArray(options.target) ? options.target.join(',') : options.target;\n const parsed = raw.split(',').map(s => s.trim().toLowerCase()) as AgentHost[];\n const valid = parsed.filter(isKnownHost);\n if (valid.length > 0) return valid;\n }\n return ['agents'];\n }\n\n private parseScope(options: UninstallOptions): InstallScope {\n if (options.global) return 'global';\n return options.scope || 'project';\n }\n\n private async safeRemove(targetDir: string, relPath: string): Promise<void> {\n const fullPath = path.join(targetDir, relPath);\n\n // If relPath is inside skills, check if skill directory itself is a symlink/junction\n if (relPath.startsWith('skills' + path.sep) || relPath.startsWith('skills/')) {\n const parts = relPath.split(/[/\\\\]/);\n if (parts.length >= 2) {\n const skillDir = path.join(targetDir, parts[0], parts[1]);\n try {\n const lstat = await fs.lstat(skillDir);\n if (lstat.isSymbolicLink()) {\n await fs.unlink(skillDir);\n return;\n }\n } catch {\n // not a symlink directory\n }\n }\n }\n\n try {\n const lstat = await fs.lstat(fullPath);\n if (lstat.isSymbolicLink()) {\n await fs.unlink(fullPath);\n return;\n }\n } catch {\n // not a symlink\n }\n\n await fs.remove(fullPath);\n }\n\n public async uninstall(identifier: string, options: UninstallOptions = {}): Promise<{ removed: string[]; kept: string[]; staleRecords: string[]; retainedOwners: string[]; targetDirs: string[]; dryRun: boolean }> {\n const scope = this.parseScope(options);\n const hosts = this.parseHosts(options);\n\n // Plan 023 B (ADR 0022) — the `agents` host's directory is the discovered state dir: the\n // `.agents/` store or the store-less `.claude/.agents-united/` sidecar.\n const targetDirs: string[] = hosts.map(h => h === 'agents'\n ? resolveStateDir(scope, options.targetDir)\n : AgentHostAdapter.resolveHostDir(scope, h, options.targetDir));\n const resolved = await this.registry.resolve(identifier).catch(() => null);\n\n const totalRemoved: string[] = [];\n const totalKept: string[] = [];\n const totalStale: string[] = [];\n const retainedOwners = new Set<string>();\n\n for (const targetDir of targetDirs) {\n const subPaths = AgentHostAdapter.getSubPaths(targetDir);\n\n if (!await fs.pathExists(subPaths.lockfile)) {\n continue;\n }\n\n const lockfile: LockfileManifest = await fs.readJson(subPaths.lockfile);\n const removedFiles: string[] = [];\n const keptFiles: string[] = [];\n const staleRecords: string[] = [];\n // Projection ownership is the UNION of its own refcount and its canonical record's owners\n // (legacy `bundle` fallback included). Deriving it only at stamping time made the sharing\n // guarantee order-dependent: a projection created BEFORE a second bundle co-owned its\n // canonical stayed single-owner, and removing that bundle deleted the projection out from\n // under the other owner (reported both ways round). Unioning here makes \"a shared canonical's\n // projections are shared\" true regardless of install order. Bundle-scoped lanes\n // (`.agents/plugins/<bundle>/`) are per-bundle distribution copies: the canonical's other\n // owners do not keep them alive.\n const projectionOwners = (projRelPath: string, proj: { owners?: string[]; canonical?: string }): string[] => {\n const own = proj.owners ?? [];\n if (projRelPath.startsWith('.agents/plugins/')) return own;\n const canonical = proj.canonical ?? '';\n const rec = lockfile.files[canonical] ?? lockfile.files[canonical.replace(/^\\.agents\\//, '')];\n return Array.from(new Set([...own, ...assetOwners(rec)]));\n };\n\n /**\n * Universal Coverage Rule (ADR 0019). An artifact is deletable only when no surviving\n * installed identifier covers its source. A surviving identifier covers:\n * - a canonical asset, when what it DECLARES contains that asset (a domain declares its\n * whole expansion; a bundle declares its own bundles.json fields — never an inherited\n * parent's extras, per the A6 Declared-Asset-Set contract); and\n * - a bundle-derived artifact (`.agents/plugins/<b>/…` — team manifest, plugin.json,\n * skill mirrors), when what it declares contains every asset `<b>` declares.\n * Owner refcounts alone answered \"does anyone still name this?\" — coverage answers \"does\n * anyone still need this?\", which is what the operator means by \"don't break my domain\".\n */\n const survivingCoverage = async (\n source: { asset?: string; declaringBundle?: string },\n removedId: string\n ): Promise<string[]> => {\n const survivors = lockfile.installed.bundles.filter(b => b !== removedId);\n const covering: string[] = [];\n for (const id of survivors) {\n try {\n // DECLARATION semantics, not resolution: a survivor covers exactly what it declares.\n // A real bundle declares its own bundles.json fields only (ADR 0006/A6 — an addon\n // must NOT keep the parent's undeclared surface alive); a domain pseudo-bundle's\n // declaration IS its expansion (the union of its members), which is what makes\n // `domain:engineering` cover everything `software-engineering` declares.\n const def = await this.registry.getBundle(id);\n const have = new Set<string>([]);\n if (def) {\n if (def.orchestrator) have.add(`agents/${def.orchestrator}`);\n (def.agents || []).forEach(a => have.add(`agents/${a}`));\n (def.skills || []).forEach(s => have.add(`skills/${s}/SKILL.md`));\n (def.workflows || []).forEach(w => have.add(`workflows/${w}`));\n (def.rules || []).forEach(rl => have.add(`rules/${rl}`));\n } else {\n const r = await this.registry.resolve(id);\n r.agents.forEach(f => have.add(`agents/${f}`));\n r.skills.forEach(s => have.add(`skills/${s}/SKILL.md`));\n (r.workflows || []).forEach(w => have.add(`workflows/${w}`));\n (r.rules || []).forEach(rl => have.add(`rules/${rl}`));\n }\n if (source.asset) {\n if (have.has(source.asset)) covering.push(id);\n } else if (source.declaringBundle) {\n const def = await this.registry.getBundle(source.declaringBundle);\n if (!def) continue;\n const want = new Set<string>([]);\n if (def.orchestrator) want.add(`agents/${def.orchestrator}`);\n (def.agents || []).forEach(a => want.add(`agents/${a}`));\n (def.skills || []).forEach(s => want.add(`skills/${s}/SKILL.md`));\n (def.workflows || []).forEach(w => want.add(`workflows/${w}`));\n (def.rules || []).forEach(rl => want.add(`rules/${rl}`));\n if (want.size > 0 && [...want].every(k => have.has(k))) covering.push(id);\n }\n } catch {\n // A survivor that no longer resolves cannot cover anything.\n }\n }\n return covering;\n };\n\n // Bundle removal mode. Triggered by a roster entry OR by owned assets: a lockfile that lost\n // its `installed.bundles` entry (older partial removals, pre-fix rosters) still has records\n // naming this owner, and those must be reachable — otherwise `agents remove` reports\n // \"No installed assets found\" for assets that are visibly right there in the lockfile.\n if (resolved && resolved.targetBundle) {\n const bundleName = resolved.targetBundle;\n const ownsSomething =\n Object.values(lockfile.files).some(m => assetOwners(m).includes(bundleName)) ||\n Object.values(lockfile.projections || {}).some(p => (p.owners ?? []).includes(bundleName));\n if (lockfile.installed.bundles.includes(bundleName) || ownsSomething) {\n if (!options.dryRun) {\n const workspaceRoot = workspaceRootOf(targetDir);\n\n // Transactional validation BEFORE any write: if this bundle owns zero file\n // records and zero projections, reject without mutating the lockfile.\n const ownedFiles = Object.entries(lockfile.files)\n .filter(([, m]) => assetOwners(m).includes(bundleName));\n const ownedProjections = lockfile.projections\n ? Object.entries(lockfile.projections).filter(([p, v]) => projectionOwners(p, v).includes(bundleName)).length\n : 0;\n if (ownedFiles.length === 0 && ownedProjections === 0) {\n throw new Error(`No installed assets found matching \"${bundleName}\".`);\n }\n\n // Clean up compound projections using owner refcounting\n if (lockfile.projections) {\n for (const [projRelPath, proj] of Object.entries(lockfile.projections)) {\n const owners = projectionOwners(projRelPath, proj);\n if (owners.includes(bundleName)) {\n proj.owners = owners.filter(o => o !== bundleName);\n if (proj.owners.length === 0) {\n // Universal Coverage Rule (ADR 0019) — bundle-DERIVED coordination artifacts:\n // everything under `.agents/plugins/<b>/` (team manifest, plugin.json, skill\n // mirrors) and the bundle's own coordinator rule. Each bundle's package is its\n // OWN (A6: an addon shares skills but ships its own mirror, so it does not keep\n // the parent's package alive); what keeps these alive is a survivor that\n // DECLARES A SUPERSET of the bundle — a domain that contains it. That is\n // exactly the reported case: `remove software-engineering` under a standing\n // `domain:engineering` must delete nothing.\n const declaringMatch = /^\\.agents\\/plugins\\/([^/]+)\\//.exec(projRelPath);\n const derivedCoordination = Boolean(declaringMatch)\n || proj.kind === 'rule' || proj.kind === 'team-manifest' || proj.kind === 'plugin-manifest';\n const covering = derivedCoordination\n ? await survivingCoverage({ declaringBundle: declaringMatch ? declaringMatch[1] : bundleName }, bundleName)\n : [];\n if (covering.length > 0) {\n proj.owners = covering;\n keptFiles.push(projRelPath);\n covering.forEach(o => retainedOwners.add(o));\n continue;\n }\n const absProjection = path.join(workspaceRoot, projRelPath);\n // Capture existence BEFORE deleting: the accounting below must distinguish a\n // file that really left the disk from a ghost record that never had one.\n const existedOnDisk = await fs.pathExists(absProjection);\n if (existedOnDisk) {\n if (proj.managedMarker) {\n const managed = await this.isManagedProjection(absProjection, projRelPath === 'AGENTS.md');\n if (!managed && !options.force) {\n throw new Error(`Projection ${projRelPath} has user modifications. Use --force to remove.`);\n }\n } else {\n const currentHash = await this.calculateHash(absProjection).catch(() => null);\n if (currentHash && currentHash !== proj.hash && !options.force) {\n throw new Error(`Projection ${projRelPath} has user modifications. Use --force to remove.`);\n }\n }\n await this.safeRemoveProjection(absProjection);\n await this.removeEmptyProjectionDirs(workspaceRoot, projRelPath);\n }\n delete lockfile.projections[projRelPath];\n // Honest accounting: only a path whose FILE existed counts as \"deleted\". A\n // record without a file (ghost bookkeeping from older partial removals) is\n // stale-record cleanup — reporting it as a deleted file told operators that\n // content vanished when nothing on disk changed.\n if (existedOnDisk) {\n removedFiles.push(projRelPath);\n } else {\n staleRecords.push(projRelPath);\n }\n // Drop the pointer from its canonical record too: a surviving canonical that\n // still lists this path sends `agents doctor` hunting for a projection that is\n // deliberately gone (\"Missing projection …\" storm). The fallback lane spells\n // canonicals `.agents/<sub>/<file>`, the files map `<sub>/<file>` — try both.\n const canonicalKey = (proj.canonical ?? '').replace(/^\\.agents\\//, '');\n for (const key of new Set([proj.canonical ?? '', canonicalKey])) {\n const rec = key ? lockfile.files[key] : undefined;\n if (rec?.projectedTo) {\n rec.projectedTo = rec.projectedTo.filter(p => p !== projRelPath);\n if (rec.projectedTo.length === 0) delete rec.projectedTo;\n }\n }\n } else {\n // Survives for its remaining owners: report it as kept, not removed.\n keptFiles.push(projRelPath);\n proj.owners.forEach(o => retainedOwners.add(o));\n }\n }\n }\n }\n\n for (const [relPath, assetMeta] of Object.entries(lockfile.files)) {\n const recordOwners = assetOwners(assetMeta);\n if (!recordOwners.includes(bundleName)) continue;\n\n const newOwners = recordOwners.filter(o => o !== bundleName);\n if (newOwners.length === 0) {\n // Last owner removed: drop the recorded projections, then the canonical file.\n if (assetMeta.projectedTo && assetMeta.projectedTo.length > 0) {\n await this.removeProjections(workspaceRoot, assetMeta.projectedTo, options.force, lockfile.projections);\n }\n\n const fullPath = path.join(targetDir, relPath);\n if (await fs.pathExists(fullPath) || await fs.pathExists(fullPath).catch(() => false)) {\n if (!options.force && assetMeta.method !== 'symlink') {\n const currentHash = await this.calculateHash(fullPath).catch(() => null);\n if (currentHash && currentHash !== assetMeta.hash) {\n throw new Error(`File ${relPath} has user modifications. Use --force to remove.`);\n }\n }\n\n await this.safeRemove(targetDir, relPath);\n removedFiles.push(relPath);\n }\n\n delete lockfile.files[relPath];\n } else {\n // A surviving bundle still owns this file: keep it on disk, shrink owners.\n lockfile.files[relPath] = { ...assetMeta, owners: newOwners };\n keptFiles.push(relPath);\n newOwners.forEach(o => retainedOwners.add(o));\n }\n }\n\n // Prune the managed subdirectories once empty — a removal that leaves `.agents/agents/`\n // behind as an empty shell reads as residue to the operator even though nothing in it is\n // tracked anymore. Projections already do this via removeEmptyProjectionDirs.\n for (const dir of [subPaths.agentsDir, subPaths.skillsDir, subPaths.workflowsDir, subPaths.rulesDir]) {\n if (await fs.pathExists(dir)) {\n const entries = await fs.readdir(dir).catch(() => [] as string[]);\n if (entries.length === 0) {\n await fs.remove(dir);\n }\n }\n }\n\n lockfile.installed.bundles = lockfile.installed.bundles.filter(b => b !== bundleName);\n if (lockfile.bundleVersions) {\n delete lockfile.bundleVersions[bundleName];\n }\n // Survival set: only entries still declared by a surviving bundle stay on the\n // roster (declared asset sets, not the removed bundle's resolved superset).\n const surviving = lockfile.installed.bundles.filter(b => b !== bundleName);\n const survival = new Set<string>();\n for (const b of surviving) {\n const bdef = await this.registry.getBundle(b);\n if (!bdef) {\n // Unbundled survivor (`domain:*` pseudo-entry or unknown identifier): it has no\n // declaration to read, so what it still owns in the lockfile IS its roster.\n for (const [relPath, meta] of Object.entries(lockfile.files)) {\n if (assetOwners(meta).includes(b)) survival.add(relPath);\n }\n continue;\n }\n if (bdef.orchestrator) survival.add(`agents/${bdef.orchestrator}`);\n (bdef.agents || []).forEach(a => survival.add(`agents/${a}`));\n (bdef.skills || []).forEach(s => survival.add(`skills/${s}/SKILL.md`));\n (bdef.workflows || []).forEach(w => survival.add(`workflows/${w}`));\n }\n lockfile.installed.agents = lockfile.installed.agents.filter(a => survival.has(`agents/${a}`));\n lockfile.installed.skills = lockfile.installed.skills.filter(s => survival.has(`skills/${s}/SKILL.md`));\n if (lockfile.installed.workflows) {\n lockfile.installed.workflows = lockfile.installed.workflows.filter(w => survival.has(`workflows/${w}`));\n }\n\n // Installed-addon freshness (plan 003): a removed child bundle restores\n // its addon into the parent's recommendedAddons via a re-render here.\n await this.refreshParentCoordination(bundleName, workspaceRoot, lockfile, scope);\n\n // Plan 023 A — the plain-session guard serves the whole workspace, so it goes with the\n // LAST bundle: only our PreToolUse groups are removed, and the settings file is deleted\n // only when agents-united created it and nothing of the user's remains.\n const guard = lockfile.sessionGuard;\n if (lockfile.installed.bundles.length === 0 && guard && !('off' in guard)) {\n const guardFile = path.isAbsolute(guard.file) ? guard.file : path.join(workspaceRoot, guard.file);\n const outcome = await removeSessionGuard(guardFile, { createdFile: guard.createdFile });\n if (outcome === 'removed' || outcome === 'deleted-file') removedFiles.push(guard.file);\n delete lockfile.sessionGuard;\n }\n\n // Plan 024 S4 — the command-permission preset is workspace-wide too: remove only the\n // entries this install recorded, and delete the file only if agents-united created it.\n const preset = lockfile.permissionPreset;\n if (lockfile.installed.bundles.length === 0 && preset && !('off' in preset)) {\n const presetFile = path.isAbsolute(preset.file) ? preset.file : path.join(workspaceRoot, preset.file);\n const outcome = await removePermissionPreset(presetFile, preset.entries, { createdFile: preset.createdFile });\n if (outcome === 'removed' || outcome === 'deleted-file') removedFiles.push(preset.file);\n delete lockfile.permissionPreset;\n }\n\n await fs.writeJson(subPaths.lockfile, lockfile, { spaces: 2 });\n\n // Plan 023 B (ADR 0022) — the store-less sidecar is pure machine state: once the last\n // bundle is gone it is deleted outright, and an emptied `.claude/` goes with it (the\n // store-backed `.agents/` keeps its historical behavior: the lockfile stays).\n if (isSidecarDir(targetDir) && lockfile.installed.bundles.length === 0) {\n await fs.remove(targetDir);\n const claudeDir = path.dirname(targetDir);\n if ((await fs.readdir(claudeDir).catch(() => ['keep'])).length === 0) await fs.remove(claudeDir);\n }\n } else {\n // Dry run: report the same refcount outcome the real pass would produce, without\n // mutating anything — \"would remove 84\" when every asset is co-owned is a lie.\n for (const [relPath, m] of Object.entries(lockfile.files)) {\n const owners = assetOwners(m);\n if (!owners.includes(bundleName)) continue;\n const remaining = owners.filter(o => o !== bundleName);\n (remaining.length === 0 ? removedFiles : keptFiles).push(relPath);\n remaining.forEach(o => retainedOwners.add(o));\n }\n for (const [projRelPath, proj] of Object.entries(lockfile.projections || {})) {\n const owners = projectionOwners(projRelPath, proj);\n if (!owners.includes(bundleName)) continue;\n const remaining = owners.filter(o => o !== bundleName);\n (remaining.length === 0 ? removedFiles : keptFiles).push(projRelPath);\n remaining.forEach(o => retainedOwners.add(o));\n }\n }\n }\n } else {\n // Item removal mode\n const itemTargetRelPaths = Object.keys(lockfile.files).filter(p => p.includes(identifier));\n\n if (!options.dryRun) {\n for (const relPath of itemTargetRelPaths) {\n const fullPath = path.join(targetDir, relPath);\n if (await fs.pathExists(fullPath) || await fs.pathExists(fullPath).catch(() => false)) {\n if (!options.force && lockfile.files[relPath]?.method !== 'symlink') {\n const currentHash = await this.calculateHash(fullPath).catch(() => null);\n const assetMeta = lockfile.files[relPath];\n if (currentHash && assetMeta && currentHash !== assetMeta.hash) {\n throw new Error(`File ${relPath} has user modifications. Use --force to remove.`);\n }\n }\n await this.safeRemove(targetDir, relPath);\n removedFiles.push(relPath);\n }\n delete lockfile.files[relPath];\n }\n\n await fs.writeJson(subPaths.lockfile, lockfile, { spaces: 2 });\n } else {\n removedFiles.push(...itemTargetRelPaths);\n }\n }\n\n totalRemoved.push(...removedFiles);\n totalKept.push(...keptFiles);\n totalStale.push(...staleRecords);\n }\n\n // \"Nothing deleted\" is not \"nothing found\": a removal whose assets are all co-owned legitimately\n // deletes nothing and keeps every record for the remaining owners. Only a removal that matched\n // no records at all is an error.\n if (totalRemoved.length === 0 && totalKept.length === 0 && totalStale.length === 0 && !options.dryRun) {\n throw new Error(`No installed assets found matching \"${identifier}\".`);\n }\n\n return {\n removed: totalRemoved,\n kept: totalKept,\n staleRecords: totalStale,\n retainedOwners: [...retainedOwners].sort(),\n targetDirs,\n dryRun: options.dryRun || false,\n };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { RegistryResolver } from './registry.js';\nimport { AgentHostAdapter } from './adapter.js';\nimport { KNOWN_HOST_IDS } from './hosts.js';\nimport { resolveStateDir } from './state-dir.js';\nimport type {\n InventoryOptions,\n PackageInventory,\n InstalledPackageRecord,\n LockfileManifest,\n InstallScope,\n AgentHost,\n VersionDriftStatus,\n ScannedLocationSummary,\n} from './types.js';\n\nexport class InventoryScanner {\n private registry: RegistryResolver;\n\n constructor(registry?: RegistryResolver) {\n this.registry = registry || new RegistryResolver();\n }\n\n public static formatDisplayLocation(scope: InstallScope, host: AgentHost, targetDir: string, fanout?: string[]): string {\n const home = os.homedir();\n const cwd = process.cwd();\n\n let prettyPath = targetDir;\n if (targetDir.startsWith(cwd)) {\n const rel = path.relative(cwd, targetDir);\n prettyPath = rel ? `./${rel.replace(/\\\\/g, '/')}` : '.';\n } else if (targetDir.startsWith(home)) {\n const rel = path.relative(home, targetDir);\n prettyPath = `~/${rel.replace(/\\\\/g, '/')}`;\n }\n\n const fanoutSuffix = fanout && fanout.length > 0 ? ` + ${fanout.join(', ')}` : '';\n return `[${scope}: ${prettyPath}${fanoutSuffix}]`;\n }\n\n private parseHosts(options: InventoryOptions): AgentHost[] {\n if (options.hosts && options.hosts.length > 0) return options.hosts;\n if (options.target) {\n const raw = Array.isArray(options.target) ? options.target.join(',') : options.target;\n const parsed = raw.split(',').map(s => s.trim().toLowerCase()) as AgentHost[];\n const valid = parsed.filter(h => KNOWN_HOST_IDS.includes(h));\n if (valid.length > 0) return valid as AgentHost[];\n }\n return [...KNOWN_HOST_IDS] as AgentHost[];\n }\n\n public async scan(options: InventoryOptions = {}): Promise<PackageInventory> {\n const cwd = options.cwd || process.cwd();\n const hosts = this.parseHosts(options);\n\n const scopes: InstallScope[] = [];\n if (options.global || options.scope === 'global') {\n scopes.push('global');\n } else if (options.scope === 'project') {\n scopes.push('project');\n } else {\n scopes.push('project', 'global');\n }\n\n const candidateDirs: Array<{ dir: string; scope: InstallScope; host: AgentHost }> = [];\n\n if (options.targetDir) {\n candidateDirs.push({\n dir: path.resolve(options.targetDir),\n scope: options.scope || 'project',\n host: hosts[0] || 'agents',\n });\n } else {\n for (const scope of scopes) {\n for (const host of hosts) {\n // Plan 023 B (ADR 0022) — the `agents` host's directory is the discovered state dir (the\n // `.agents/` store or the store-less `.claude/.agents-united/` sidecar), so a sidecar\n // install is listed under host `agents` and `update` re-installs into it.\n const dir = host === 'agents'\n ? resolveStateDir(scope, undefined, { cwd })\n : AgentHostAdapter.resolveHostDir(scope, host);\n candidateDirs.push({ dir, scope, host });\n }\n }\n }\n\n const allRecords: InstalledPackageRecord[] = [];\n const bundleRecords: InstalledPackageRecord[] = [];\n const standaloneRecords: InstalledPackageRecord[] = [];\n const scannedTargetDirs: Set<string> = new Set();\n const scannedLocationsMap = new Map<string, ScannedLocationSummary>();\n\n const home = os.homedir();\n for (const scope of scopes) {\n const canonicalDir = resolveStateDir(scope, options.targetDir, { cwd });\n let displayLoc = canonicalDir;\n if (canonicalDir.startsWith(cwd)) {\n const rel = path.relative(cwd, canonicalDir);\n displayLoc = rel ? `./${rel.replace(/\\\\/g, '/')}` : '.';\n } else if (canonicalDir.startsWith(home)) {\n const rel = path.relative(home, canonicalDir);\n displayLoc = `~/${rel.replace(/\\\\/g, '/')}`;\n }\n scannedLocationsMap.set(`${scope}:${canonicalDir}`, {\n scope,\n targetDir: canonicalDir,\n displayLocation: displayLoc,\n packageCount: 0,\n fanout: [],\n });\n }\n\n for (const item of candidateDirs) {\n const lockfilePath = path.join(item.dir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n continue;\n }\n\n scannedTargetDirs.add(item.dir);\n let lockfile: LockfileManifest;\n try {\n lockfile = await fs.readJson(lockfilePath);\n } catch {\n continue;\n }\n\n const lockfileFanout = lockfile.fanout || [];\n const displayLocation = InventoryScanner.formatDisplayLocation(item.scope, item.host, item.dir, lockfileFanout);\n\n const locKey = `${item.scope}:${item.dir}`;\n const locSummary = scannedLocationsMap.get(locKey) || {\n scope: item.scope,\n targetDir: item.dir,\n displayLocation: InventoryScanner.formatDisplayLocation(item.scope, item.host, item.dir),\n packageCount: 0,\n fanout: [],\n };\n for (const f of lockfileFanout) {\n if (!locSummary.fanout.includes(f)) {\n locSummary.fanout.push(f);\n }\n }\n scannedLocationsMap.set(locKey, locSummary);\n\n // Track all skills/agents/workflows mapped to installed bundles\n const bundleOwnedSkills = new Set<string>();\n const bundleOwnedAgents = new Set<string>();\n const bundleOwnedWorkflows = new Set<string>();\n\n // 1. Process Installed Bundles\n const installedBundleNames = lockfile.installed?.bundles || [];\n for (const bundleName of installedBundleNames) {\n const bundleDef = await this.registry.getBundle(bundleName).catch(() => null);\n const resolvedBundle = await this.registry.resolve(bundleName).catch(() => null);\n const installedVersion = lockfile.bundleVersions?.[bundleName] || '1.0.0';\n const upstreamVersion = bundleDef?.version || '1.0.0';\n\n let driftStatus: VersionDriftStatus = 'up-to-date';\n if (installedVersion !== upstreamVersion) {\n driftStatus = 'outdated';\n }\n\n // Count associated files\n let fileCount = 0;\n if (lockfile.files) {\n fileCount = Object.values(lockfile.files).filter(f => f.bundle === bundleName).length;\n }\n\n if (resolvedBundle) {\n resolvedBundle.skills?.forEach(s => bundleOwnedSkills.add(s));\n resolvedBundle.agents?.forEach(a => {\n bundleOwnedAgents.add(a);\n bundleOwnedAgents.add(a.replace(/\\.md$/, ''));\n });\n resolvedBundle.workflows?.forEach(w => {\n bundleOwnedWorkflows.add(w);\n bundleOwnedWorkflows.add(w.replace(/\\.md$/, ''));\n });\n }\n if (bundleDef) {\n if (bundleDef.orchestrator) {\n bundleOwnedAgents.add(bundleDef.orchestrator);\n bundleOwnedAgents.add(bundleDef.orchestrator.replace(/\\.md$/, ''));\n }\n bundleDef.skills?.forEach(s => bundleOwnedSkills.add(s));\n bundleDef.agents?.forEach(a => {\n bundleOwnedAgents.add(a);\n bundleOwnedAgents.add(a.replace(/\\.md$/, ''));\n });\n bundleDef.workflows?.forEach(w => {\n bundleOwnedWorkflows.add(w);\n bundleOwnedWorkflows.add(w.replace(/\\.md$/, ''));\n });\n }\n\n locSummary.packageCount++;\n\n const record: InstalledPackageRecord = {\n id: `${bundleName}@${item.scope}:${item.host}`,\n name: bundleName,\n type: 'bundle',\n scope: item.scope,\n host: item.host,\n targetDir: item.dir,\n displayLocation,\n installedVersion,\n upstreamVersion,\n driftStatus,\n method: lockfile.method || 'symlink',\n fileCount,\n title: bundleDef?.name || bundleName,\n description: bundleDef?.description,\n fanout: lockfileFanout,\n projections: lockfileFanout,\n };\n\n allRecords.push(record);\n bundleRecords.push(record);\n }\n\n // 2. Process Standalone Skills\n const installedSkills = lockfile.installed?.skills || [];\n for (const skillName of installedSkills) {\n if (bundleOwnedSkills.has(skillName)) continue;\n\n locSummary.packageCount++;\n\n const record: InstalledPackageRecord = {\n id: `skill:${skillName}@${item.scope}:${item.host}`,\n name: skillName,\n type: 'skill',\n scope: item.scope,\n host: item.host,\n targetDir: item.dir,\n displayLocation,\n installedVersion: '1.0.0',\n upstreamVersion: '1.0.0',\n driftStatus: 'up-to-date',\n method: lockfile.method || 'symlink',\n fileCount: 1,\n title: skillName,\n description: `Standalone skill (${skillName})`,\n fanout: lockfileFanout,\n projections: lockfileFanout,\n };\n\n allRecords.push(record);\n standaloneRecords.push(record);\n }\n\n // 3. Process Standalone Agents\n const installedAgents = lockfile.installed?.agents || [];\n for (const agentFile of installedAgents) {\n if (bundleOwnedAgents.has(agentFile)) continue;\n const agentName = agentFile.replace(/\\.md$/, '');\n\n locSummary.packageCount++;\n\n const record: InstalledPackageRecord = {\n id: `agent:${agentName}@${item.scope}:${item.host}`,\n name: agentName,\n type: 'agent',\n scope: item.scope,\n host: item.host,\n targetDir: item.dir,\n displayLocation,\n installedVersion: '1.0.0',\n upstreamVersion: '1.0.0',\n driftStatus: 'up-to-date',\n method: lockfile.method || 'symlink',\n fileCount: 1,\n title: agentName,\n description: `Standalone agent (${agentFile})`,\n fanout: lockfileFanout,\n projections: lockfileFanout,\n };\n\n allRecords.push(record);\n standaloneRecords.push(record);\n }\n }\n\n return {\n records: allRecords,\n bundles: bundleRecords,\n standaloneItems: standaloneRecords,\n targetDirs: Array.from(scannedTargetDirs),\n scannedScopes: scopes,\n scannedLocations: Array.from(scannedLocationsMap.values()),\n };\n }\n}\n\n","import path from 'node:path';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { workspaceRootOf } from './state-dir.js';\nimport { RegistryResolver } from './registry.js';\nimport { InventoryScanner } from './inventory.js';\nimport { InstallEngine } from './installer.js';\nimport { HostProjector } from './projector.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport type {\n UpdateOptions,\n UpdateCheckReport,\n UpdateCheckItem,\n UpdateResult,\n InstalledPackageRecord,\n LockfileManifest,\n InventoryOptions,\n ProjectionInfo,\n} from './types.js';\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]+?)\\r?\\n---/;\n\nexport class UpdateEngine {\n private registry: RegistryResolver;\n private scanner: InventoryScanner;\n private installer: InstallEngine;\n\n constructor(registry?: RegistryResolver, scanner?: InventoryScanner, installer?: InstallEngine) {\n this.registry = registry || new RegistryResolver();\n this.scanner = scanner || new InventoryScanner(this.registry);\n this.installer = installer || new InstallEngine(this.registry);\n }\n\n private deduplicateProjections(projections: ProjectionInfo[]): ProjectionInfo[] {\n const seen = new Set<string>();\n const deduplicated: ProjectionInfo[] = [];\n for (const p of projections) {\n const key = `${p.host}:${p.path}`;\n if (!seen.has(key)) {\n seen.add(key);\n deduplicated.push(p);\n }\n }\n return deduplicated;\n }\n\n private async calculateHash(filePath: string): Promise<string> {\n const buffer = await fs.readFile(filePath);\n return 'sha256:' + crypto.createHash('sha256').update(buffer).digest('hex');\n }\n\n /**\n * Determines whether a projected file still carries our managed marker (plan 007\n * M5). Agent projections place the marker as the first body line after frontmatter;\n * the AGENTS.md bridge has no frontmatter so it is checked over the whole content.\n */\n private async isManagedProjection(absPath: string, isAgentsMd: boolean, recordedHash?: string): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n if (HostProjector.hasManagedMarker(content)) return true;\n // ADR 0017 amendment (Gate 7, 2026-09-25): markerless sidecar artifacts (LICENSE.txt,\n // references/**) cannot carry the marker — they are managed iff their bytes still hash\n // to the value recorded at install time.\n if (recordedHash) {\n const bytes = await fs.readFile(absPath);\n return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` === recordedHash;\n }\n return false;\n }\n\n /**\n * Returns the first user-modified projection path belonging to a record, or '' when\n * every recorded projection still carries the managed marker.\n */\n private async staleProjection(record: InstalledPackageRecord, lockfile: LockfileManifest): Promise<string> {\n const workspaceRoot = workspaceRootOf(record.targetDir);\n for (const assetMeta of Object.values(lockfile.files)) {\n if (assetMeta.bundle !== record.name) continue;\n if (!assetMeta.projectedTo || assetMeta.projectedTo.length === 0) continue;\n for (const projPath of assetMeta.projectedTo) {\n const absProjection = path.join(workspaceRoot, projPath);\n if (await fs.pathExists(absProjection)) {\n const managed = await this.isManagedProjection(absProjection, projPath === 'AGENTS.md', lockfile.projections?.[projPath]?.hash);\n if (!managed) {\n return projPath;\n }\n }\n }\n }\n return '';\n }\n\n /** Plan 016 Step 4 — the canonical asset whose dialect name changed (ADR 0016 pattern). */\n private static readonly LEGACY_GENERATIVE_UI_CANONICAL = 'skills/generative_ui/SKILL.md';\n private static readonly LEGACY_GENERATIVE_UI_PATH = /(^|\\/)generative_ui\\/SKILL\\.md$/;\n\n /** Removes empty projection dirs left behind by the migration (never a non-empty one). */\n private async removeEmptyProjectionDirs(workspaceRoot: string, projPath: string): Promise<void> {\n let dir = path.dirname(path.join(workspaceRoot, projPath));\n while (dir !== workspaceRoot && dir.startsWith(workspaceRoot)) {\n try {\n const entries = await fs.readdir(dir);\n if (entries.length > 0) break;\n await fs.rmdir(dir);\n } catch {\n break;\n }\n dir = path.dirname(dir);\n }\n }\n\n /** Drops one projected path from every canonical file record (host-agnostic). */\n private dropProjectedTo(lockfile: LockfileManifest, projectedRelPath: string): void {\n const normProj = projectedRelPath.replace(/\\\\/g, '/');\n for (const asset of Object.values(lockfile.files)) {\n if (!asset.projectedTo || asset.projectedTo.length === 0) continue;\n const kept = asset.projectedTo.filter(p => p !== normProj);\n if (kept.length === asset.projectedTo.length) continue;\n if (kept.length === 0) {\n delete asset.projectedTo;\n } else {\n asset.projectedTo = kept;\n }\n }\n }\n\n /**\n * Plan 016 Step 4 — silent, bounded, idempotent migration of the `generative_ui`\n * projection rename (ADR 0016 pattern).\n *\n * `registry/skills/generative_ui/` is deliberately NOT renamed: the underscore is\n * invalid in every host dialect, so the projectors normalize the name at projection\n * time (`generative_ui` -> `generative-ui`; ADR 0018 decision 2 — normalization is\n * projection-level). Projections recorded before that change therefore still point at\n * `.claude/skills/generative_ui/SKILL.md` and/or the Cline plugin copy\n * `.agents/plugins/<bundle>/skills/generative_ui/SKILL.md`, which the current renderers\n * no longer produce.\n *\n * Runs before each record's re-install so the freshly rendered normalized path is\n * registered by the normal install path. Guarantees: (a) a file that lacks the managed\n * marker is never deleted (its lockfile entries are left untouched too, so the\n * migration never lies about a file it did not remove); (b) a second run is a no-op\n * because the entries are gone; (c) it is host-agnostic, so it covers `.claude/**` and\n * the Cline plugin lane alike, and it never touches the canonical registry store.\n */\n private async migrateLegacyGenerativeUiProjections(\n workspaceRoot: string,\n lockfile: LockfileManifest\n ): Promise<string[]> {\n const projections = lockfile.projections;\n if (!projections) return [];\n\n const normalized = ClaudeProjector.normalizeSkillName('generative_ui');\n const removed: string[] = [];\n\n for (const [projRelPath, proj] of Object.entries(projections)) {\n const posixPath = projRelPath.replace(/\\\\/g, '/');\n const isLegacy = proj.canonical === UpdateEngine.LEGACY_GENERATIVE_UI_CANONICAL\n || UpdateEngine.LEGACY_GENERATIVE_UI_PATH.test(posixPath);\n if (!isLegacy) continue;\n // Already the normalized path (a re-projection landed first): nothing to migrate.\n if (posixPath.includes(`/${normalized}/`)) continue;\n\n const absProjection = path.join(workspaceRoot, projRelPath);\n if (await fs.pathExists(absProjection)) {\n const managed = await this.isManagedProjection(absProjection, posixPath === 'AGENTS.md');\n if (!managed) continue; // (a) never clobber a foreign or user-modified file\n await fs.remove(absProjection);\n await this.removeEmptyProjectionDirs(workspaceRoot, projRelPath);\n }\n\n delete projections[projRelPath];\n this.dropProjectedTo(lockfile, projRelPath);\n removed.push(projRelPath);\n }\n\n return removed;\n }\n\n public async checkUpdates(options: InventoryOptions = {}): Promise<UpdateCheckReport> {\n const inventory = await this.scanner.scan(options);\n const items: UpdateCheckItem[] = [];\n\n for (const record of inventory.records) {\n const hasUpdate = record.driftStatus === 'outdated' || record.installedVersion !== record.upstreamVersion;\n items.push({\n record,\n hasUpdate,\n installedVersion: record.installedVersion,\n upstreamVersion: record.upstreamVersion,\n reason: hasUpdate\n ? `Upstream version (${record.upstreamVersion}) is newer than installed version (${record.installedVersion})`\n : undefined,\n });\n }\n\n const outdatedCount = items.filter(i => i.hasUpdate).length;\n const upToDateCount = items.filter(i => !i.hasUpdate).length;\n\n return {\n items,\n outdatedCount,\n upToDateCount,\n totalCount: items.length,\n scannedScopes: inventory.scannedScopes,\n scannedLocations: inventory.scannedLocations,\n };\n }\n\n public async update(\n targets: string | string[] | '__all__',\n options: UpdateOptions = {}\n ): Promise<UpdateResult> {\n const inventory = await this.scanner.scan({\n scope: options.scope,\n global: options.global,\n hosts: options.hosts,\n target: options.target,\n targetDir: options.targetDir,\n cwd: options.cwd,\n });\n\n const isAll = targets === '__all__' || targets === '*' || (Array.isArray(targets) && targets.includes('__all__'));\n const targetList = Array.isArray(targets) ? targets : [targets];\n\n const recordsToUpdate: InstalledPackageRecord[] = inventory.records.filter(r => {\n if (isAll) return true;\n return targetList.includes(r.name) || targetList.includes(r.id);\n });\n\n if (recordsToUpdate.length === 0) {\n return {\n updated: [],\n skipped: [],\n targetDirs: inventory.targetDirs,\n dryRun: options.dryRun || false,\n projections: [],\n };\n }\n\n if (options.dryRun) {\n const dryProjections: ProjectionInfo[] = [];\n for (const record of recordsToUpdate) {\n const lockfilePath = path.join(record.targetDir, 'agents-united.json');\n if (await fs.pathExists(lockfilePath)) {\n const dryResult = await this.installer.install(record.name, {\n scope: record.scope,\n method: record.method,\n hosts: [record.host],\n targetDir: record.targetDir,\n fanout: options.fanout,\n dryRun: true,\n });\n if (dryResult.projections) {\n dryProjections.push(...dryResult.projections);\n }\n }\n }\n return {\n updated: recordsToUpdate,\n skipped: [],\n targetDirs: inventory.targetDirs,\n dryRun: true,\n projections: this.deduplicateProjections(dryProjections),\n };\n }\n\n\n const updated: InstalledPackageRecord[] = [];\n const skipped: Array<{ record: InstalledPackageRecord; reason: string }> = [];\n const collectedProjections: ProjectionInfo[] = [];\n\n for (const record of recordsToUpdate) {\n const lockfilePath = path.join(record.targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n continue;\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n\n // Check for user modifications in copy mode\n if (record.method === 'copy' && !options.force && lockfile.files) {\n let hasConflict = false;\n let conflictRelPath = '';\n\n for (const [relPath, assetMeta] of Object.entries(lockfile.files)) {\n if (assetMeta.bundle === record.name || relPath.includes(record.name)) {\n const fullPath = path.join(record.targetDir, relPath);\n if (await fs.pathExists(fullPath)) {\n const currentHash = await this.calculateHash(fullPath).catch(() => null);\n if (currentHash && currentHash !== assetMeta.hash) {\n hasConflict = true;\n conflictRelPath = relPath;\n break;\n }\n }\n }\n }\n\n if (hasConflict) {\n skipped.push({\n record,\n reason: `User modifications detected in ${conflictRelPath}. Use --force to overwrite.`,\n });\n continue;\n }\n }\n\n // Projection-aware guard (plan 007 M5): a stale projection whose managed\n // marker was manually removed counts as user-modified and is never clobbered\n // without --force — it lands in `skipped`.\n if (!options.force && lockfile.files) {\n const stale = await this.staleProjection(record, lockfile);\n if (stale) {\n skipped.push({\n record,\n reason: `User modifications detected in projection ${stale}. Use --force to overwrite.`,\n });\n continue;\n }\n }\n\n // Plan 016 Step 4 (ADR 0016 pattern) — silent migration of the legacy\n // `generative_ui` projection path before re-installation registers the\n // normalized one. Deliberately implemented on UpdateEngine rather than\n // InstallEngine: it is an update-path reconciliation (`agents update` is the\n // documented remediation for it) and it leaves fresh installs untouched, since\n // a fresh install can never have recorded the legacy path.\n const migratedGenerativeUi = await this.migrateLegacyGenerativeUiProjections(\n workspaceRootOf(record.targetDir),\n lockfile\n );\n if (migratedGenerativeUi.length > 0) {\n await fs.writeJson(lockfilePath, lockfile, { spaces: 2 });\n }\n\n // Re-install with upstream version. Fan-out flows from --fanout if given,\n // otherwise the installer inherits the fanout recorded in the lockfile.\n const installResult = await this.installer.install(record.name, {\n scope: record.scope,\n method: record.method,\n hosts: [record.host],\n targetDir: record.targetDir,\n fanout: options.fanout,\n force: true, // force overwrite since we passed collision check above\n });\n\n if (installResult.projections) {\n collectedProjections.push(...installResult.projections);\n }\n\n // Synchronize bundleVersion in lockfile\n if (await fs.pathExists(lockfilePath)) {\n const updatedLockfile: LockfileManifest = await fs.readJson(lockfilePath);\n updatedLockfile.bundleVersions = updatedLockfile.bundleVersions || {};\n updatedLockfile.bundleVersions[record.name] = record.upstreamVersion;\n await fs.writeJson(lockfilePath, updatedLockfile, { spaces: 2 });\n if (updatedLockfile.fanout) {\n record.fanout = updatedLockfile.fanout;\n record.projections = updatedLockfile.fanout;\n record.displayLocation = InventoryScanner.formatDisplayLocation(\n record.scope,\n record.host,\n record.targetDir,\n updatedLockfile.fanout\n );\n }\n }\n\n record.installedVersion = record.upstreamVersion;\n record.driftStatus = 'up-to-date';\n updated.push(record);\n }\n\n return {\n updated,\n skipped,\n targetDirs: inventory.targetDirs,\n dryRun: false,\n projections: this.deduplicateProjections(collectedProjections),\n };\n\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport crypto from 'node:crypto';\nimport YAML from 'yaml';\nimport { AgentHostAdapter } from './adapter.js';\nimport { HostProjector } from './projector.js';\nimport { ClaudeCapabilityProbe } from './claude-capabilities.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport { ClineCapabilityProbe } from './cline-capabilities.js';\nimport { ClineProjector } from './cline-projector.js';\nimport { RegistryResolver, loadTranslationLedger } from './registry.js';\nimport { McpLocationRegistry } from './mcp-locations.js';\nimport { assetOwners } from './types.js';\nimport { inspectSessionGuard, sessionGuardSnippet } from './session-guard.js';\nimport { isSidecarDir, resolveStateDir, workspaceRootOf } from './state-dir.js';\nimport type {\n ClaudeCapabilityReport,\n ClineCapabilityReport,\n LockfileManifest,\n TranslationLedgerEntry,\n} from './types.js';\n\nexport interface HealthReport {\n valid: boolean;\n targetDir: string;\n isInitialized: boolean;\n issues: string[];\n warnings: string[];\n agentsCount: number;\n skillsCount: number;\n workflowsCount: number;\n clineCapability?: ClineCapabilityReport;\n claudeCapability?: ClaudeCapabilityReport;\n /** Plan 023 A — plain-session guard state; absent when no decision was ever recorded. */\n sessionGuard?: 'wired' | 'missing' | 'modified' | 'skipped-invalid' | 'off';\n /** Plan 024 S4 — command-permission preset state; absent when no decision was ever recorded. */\n permissionPreset?: 'wired' | 'missing' | 'skipped-invalid' | 'off';\n /**\n * Plan 026 Objective 3 — the Declared-Delta Registry entries (`registry/\n * translation-ledger.json`) for `host` that are `degraded` or `unsupported`: what does\n * not carry over to this host, in the user's own vocabulary. Present only when `host`\n * was recognized (a known Declared-Delta Registry host); absent for an unknown/omitted\n * host so the CLI never guesses.\n */\n declaredDeltas?: TranslationLedgerEntry[];\n}\n\n/** Hosts the Declared-Delta Registry (Plan 026) carries entries for. */\nconst DECLARED_DELTA_HOSTS = new Set(['claude', 'antigravity', 'cline']);\n\n/** The only hosts that own a content-derived compound lane: Cline (ADR 0013), Claude (ADR 0018). */\ntype CompoundLaneHost = 'cline' | 'claude';\n\n/**\n * Plan 029 A3 — the hosts whose MCP configuration surface `agents doctor --host <h>` audits.\n * `agents` is deliberately absent: the canonical store configures no MCP servers itself.\n */\nconst MCP_AUDIT_HOSTS: ReadonlySet<string> = new Set(['claude', 'antigravity', 'cline']);\n\n/**\n * Plan 029 A3 — the McpLocationRegistry host key each audited host's config is discovered under.\n * Antigravity reads the Gemini config surface (`~/.gemini/config/mcp_config.json`, ADR 0009), which\n * the registry files under the `gemini` host key.\n */\nconst MCP_LOCATION_HOST: Record<string, string> = {\n claude: 'claude',\n antigravity: 'gemini',\n cline: 'cline',\n};\n\n/**\n * Plan 029 A3 — the host's own command for registering a server, PRINTED for the user to run.\n * `agents doctor` never executes it, never installs a server and never writes an MCP config file.\n */\nfunction mcpAddCommand(host: string, server: string, workspaceRoot: string): string {\n if (host === 'antigravity') {\n return `Add it with: agy mcp add ${server} -- <command> [args...]`;\n }\n if (host === 'cline') {\n const settingsPath = McpLocationRegistry.getPrimaryWritePath('cline', workspaceRoot);\n return `Add it with the interactive wizard: cline mcp install|add <name> (or cline config mcp for the current list); settings live in ${settingsPath}.`;\n }\n return `Add it with: claude mcp add ${server} -- <command> [args...]`;\n}\n\n/** A projection that now serves the same canonical at a different path. */\ninterface SupersedingProjection {\n relPath: string;\n host: string;\n owners: string[];\n}\n\nexport class DoctorEngine {\n private static async isManagedProjection(absPath: string, isAgentsMd: boolean, recordedHash?: string): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n if (HostProjector.hasManagedMarker(content)) return true;\n // ADR 0017 amendment (Gate 7, 2026-09-25): markerless sidecar artifacts (LICENSE.txt,\n // references/**) cannot carry the marker — they are managed iff their bytes still hash\n // to the value recorded at install time.\n if (recordedHash) {\n const bytes = await fs.readFile(absPath);\n return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` === recordedHash;\n }\n return false;\n }\n\n private static isCompoundLaneHost(host: string | undefined): host is CompoundLaneHost {\n return host === 'cline' || host === 'claude';\n }\n\n /**\n * Plan 015 §5.9 item 3 / ADR 0018 decision 2 — find the projection that now serves\n * `canonical` at a *different* path and actually exists on disk. A hit turns an absent\n * recorded path into self-healing staleness (`Stale projection … (superseded by …)`)\n * instead of a user-deletion report.\n *\n * Covers every rename the lockfile can still carry: the ADR 0016 workflow slug rename\n * (`.cline/workflows/implement-feature-or-fix.md` → `…/workflow-implement.md`) and the\n * ADR 0018 prefix strip (`.claude/agents/subagent-<role>.md` → `.claude/agents/<role>.md`).\n */\n private static async findSupersedingProjection(\n projPath: string,\n canonical: string | undefined,\n manifest: LockfileManifest,\n workspaceRoot: string\n ): Promise<SupersedingProjection | null> {\n if (!canonical) return null;\n for (const [projRelPath, proj] of Object.entries(manifest.projections ?? {})) {\n if (projRelPath === projPath) continue;\n if (proj.canonical !== canonical) continue;\n if (!await fs.pathExists(path.join(workspaceRoot, projRelPath))) continue;\n return { relPath: projRelPath, host: proj.host, owners: proj.owners ?? [] };\n }\n return null;\n }\n\n /**\n * ADR 0017 — re-render the compound projections owned by the installed bundles so\n * doctor can compare what is on disk with what the current renderer produces.\n *\n * Returns projection path -> acceptable content variants **for `host` only**, or `null`\n * when the registry is unavailable (the freshness check is then skipped rather than\n * guessed).\n *\n * ADR 0018 decision 11 — the renderer is dispatched by the *recorded projection's* host.\n * Cline entries are diffed against `ClineProjector` output and Claude entries against\n * `ClaudeProjector` output; nothing else is comparable, and the Cline path is unchanged\n * because it renders exactly what it rendered before.\n *\n * Two variants are produced per path on purpose: the coordinator rule and team manifest\n * legitimately render either with or without the installed-bundle addon exclusions\n * (installer primary path vs parent-bundle refresh path). Matching *either* means the\n * projection is fresh, which keeps the check false-positive free while still catching\n * content that matches neither.\n */\n private static async renderProjectionVariants(\n owners: Set<string>,\n installedBundles: string[],\n host: CompoundLaneHost\n ): Promise<Map<string, string[]> | null> {\n if (owners.size === 0) return null;\n\n let resolver: RegistryResolver;\n try {\n resolver = new RegistryResolver();\n await resolver.loadBundles();\n } catch {\n return null;\n }\n\n const registryDir = resolver.getRegistryDir();\n const variants = new Map<string, string[]>();\n\n for (const owner of owners) {\n try {\n const bundleDef = await resolver.getBundle(owner);\n if (!bundleDef) continue; // 'domain:*' pseudo-entries and retired bundles\n\n const resolved = await resolver.resolve(bundleDef.name);\n for (const excludeAddons of [undefined, installedBundles]) {\n const artifacts = host === 'cline'\n ? await ClineProjector.planCompoundProjection(\n bundleDef,\n 'project',\n resolved,\n registryDir,\n excludeAddons\n )\n : await ClaudeProjector.planCompoundProjection(\n bundleDef,\n 'project',\n resolved,\n registryDir,\n excludeAddons\n );\n\n for (const artifact of artifacts) {\n if (artifact.content === undefined) continue;\n const list = variants.get(artifact.relPath) ?? [];\n if (!list.includes(artifact.content)) list.push(artifact.content);\n variants.set(artifact.relPath, list);\n }\n }\n } catch {\n continue; // degrade gracefully — never emit a speculative warning\n }\n }\n\n return variants;\n }\n\n /**\n * Plan 029 A3 — the servers the INSTALLED roles declare, read from each state-dir agent's\n * `mcpServers:` frontmatter. Names only: a credential, an `env` block or an inline server\n * definition never reaches this set (Risk R4).\n */\n private static async declaredMcpServers(agentsDir: string): Promise<string[]> {\n const names = new Set<string>();\n if (!(await fs.pathExists(agentsDir))) return [];\n for (const file of (await fs.readdir(agentsDir)).filter(f => f.endsWith('.md'))) {\n const content = await fs.readFile(path.join(agentsDir, file), 'utf8').catch(() => null);\n if (content === null) continue;\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (!match) continue;\n let meta: { mcpServers?: unknown } | undefined;\n try {\n meta = YAML.parse(match[1]) ?? undefined;\n } catch {\n continue; // a malformed frontmatter is reported by the frontmatter check, never guessed at\n }\n const entries = Array.isArray(meta?.mcpServers) ? (meta?.mcpServers as unknown[]) : [];\n for (const entry of entries) {\n const name =\n typeof entry === 'string' ? entry : (entry as { name?: unknown } | null)?.name;\n if (typeof name === 'string' && name.trim().length > 0) names.add(name.trim());\n }\n }\n return [...names].sort();\n }\n\n /**\n * Plan 029 A3 — warn for every server an installed role declares that this host has NOT\n * configured, printing that host's own add command. STRICTLY READ-ONLY: doctor reads the MCP\n * location registry, never installs a server and never writes a config file (the printed command\n * belongs to the user, and is never executed here).\n */\n private static async auditMcpServers(\n host: string,\n workspaceRoot: string,\n agentsDir: string,\n warnings: string[]\n ): Promise<string[]> {\n const declared = await DoctorEngine.declaredMcpServers(agentsDir);\n if (declared.length === 0) return [];\n\n const discovered = await McpLocationRegistry.discoverForHosts(\n [MCP_LOCATION_HOST[host]],\n workspaceRoot\n );\n const configured = new Set<string>();\n for (const location of discovered) {\n for (const server of Object.keys(location.servers ?? {})) configured.add(server.toLowerCase());\n }\n\n const unconfigured = declared.filter(server => !configured.has(server.toLowerCase()));\n for (const server of unconfigured) {\n warnings.push(\n `MCP server \"${server}\" is declared by the installed roles but not configured for ` +\n `--host ${host}. ${mcpAddCommand(host, server, workspaceRoot)}`\n );\n }\n return unconfigured;\n }\n\n public static async runDoctor(targetDir?: string, host?: string): Promise<HealthReport> {\n // Plan 023 B — the state dir: the `.agents/` store or the store-less `.claude/.agents-united/` sidecar.\n const root = resolveStateDir('project', targetDir);\n const subPaths = AgentHostAdapter.getSubPaths(root);\n\n const issues: string[] = [];\n const warnings: string[] = [];\n\n let agentsCount = 0;\n let skillsCount = 0;\n let workflowsCount = 0;\n let manifest: LockfileManifest | undefined;\n let clineCapability: ClineCapabilityReport | undefined;\n let claudeCapability: ClaudeCapabilityReport | undefined;\n let isInitialized = false;\n\n const lockfileExists = await fs.pathExists(subPaths.lockfile);\n const agentsDirExists = await fs.pathExists(subPaths.agentsDir);\n\n // Check Lockfile\n if (lockfileExists) {\n try {\n const parsed: LockfileManifest = await fs.readJson(subPaths.lockfile);\n manifest = parsed;\n agentsCount = parsed.installed?.agents?.length || 0;\n skillsCount = parsed.installed?.skills?.length || 0;\n // ADR 0016 unified workflows into skills: `installed.workflows` is a\n // deprecated legacy field that stays empty on modern installs, so reading it\n // made the report show \"Installed Workflows: 0\" even when workflow skills\n // were installed and projected. Count workflow skills (plus any legacy\n // entries) so the number reflects reality. Note this is a SUBSET of\n // `skillsCount`, not a partition — the CLI labels it \"Workflow Skills\".\n const legacyWorkflows = parsed.installed?.workflows?.length || 0;\n const workflowSkillCount = (parsed.installed?.skills || [])\n .filter(s => String(s).startsWith('workflow-')).length;\n workflowsCount = legacyWorkflows + workflowSkillCount;\n isInitialized = true;\n } catch (err: any) {\n issues.push(`Corrupt lockfile at ${subPaths.lockfile}: ${err.message}`);\n }\n } else if (agentsDirExists) {\n warnings.push(`No lockfile found at ${subPaths.lockfile}, but agent files were detected in ${subPaths.agentsDir}. Run 'agents update' to sync.`);\n }\n\n // Validate Agents YAML Frontmatter\n if (await fs.pathExists(subPaths.agentsDir)) {\n const agentFiles = await fs.readdir(subPaths.agentsDir);\n for (const file of agentFiles) {\n if (file.endsWith('.md')) {\n const content = await fs.readFile(path.join(subPaths.agentsDir, file), 'utf8');\n const frontmatterMatch = content.match(/^---\\r?\\n([\\s\\S]+?)\\r?\\n---/);\n if (!frontmatterMatch) {\n warnings.push(`Agent ${file} is missing YAML frontmatter.`);\n } else {\n try {\n const meta = YAML.parse(frontmatterMatch[1]);\n if (!meta.name) issues.push(`Agent ${file} missing 'name' in frontmatter.`);\n if (!meta.description) warnings.push(`Agent ${file} missing 'description'.`);\n if (!meta.model) warnings.push(`Agent ${file} missing 'model' definition.`);\n } catch (err: any) {\n issues.push(`Invalid YAML in agent ${file}: ${err.message}`);\n }\n }\n }\n }\n }\n\n // Check for unmigrated legacy workflows (ADR 0016)\n if (await fs.pathExists(subPaths.workflowsDir)) {\n const remainingWorkflowFiles = (await fs.readdir(subPaths.workflowsDir)).filter(f => f.endsWith('.md'));\n if (remainingWorkflowFiles.length > 0) {\n warnings.push(`Detected ${remainingWorkflowFiles.length} legacy workflows in ${subPaths.workflowsDir}. Run 'agents update' to automatically migrate them to modern skills.`);\n }\n }\n\n // Projection checks: verify each recorded `projectedTo` and `projections` path\n if (manifest) {\n const workspaceRoot = workspaceRootOf(root);\n\n // ADR 0017 decision 2 — exactly one warning per projection path. The presence, marker\n // and content passes below all inspect the same recorded paths (one path is routinely\n // present in both `files[canonical].projectedTo` and `projections`), so the first\n // cause found for a path wins and every later pass stays silent for it instead of\n // double-reporting the same defect under two names.\n const warnedProjectionPaths = new Set<string>();\n const pushProjectionWarning = (projPath: string, message: string): void => {\n if (warnedProjectionPaths.has(projPath)) return;\n warnedProjectionPaths.add(projPath);\n warnings.push(message);\n };\n\n // 1. Check legacy/compatible projectedTo\n for (const [relPath, assetMeta] of Object.entries(manifest.files)) {\n const projectedTo = assetMeta.projectedTo;\n if (!projectedTo || projectedTo.length === 0) continue;\n for (const projPath of projectedTo) {\n const absProjection = path.join(workspaceRoot, projPath);\n if (!await fs.pathExists(absProjection)) {\n // Plan 015 §5.9 item 3 — distinguish a RENAMED/superseded projection\n // (the same canonical is served by a newer path, so `agents update\n // --fanout` self-heals it) from one the user DELETED (which must keep\n // the \"Missing projection\" advice).\n const superseding = await this.findSupersedingProjection(projPath, relPath, manifest, workspaceRoot);\n\n if (superseding) {\n const owner = superseding.owners[0];\n pushProjectionWarning(\n projPath,\n `Stale projection ${projPath} for canonical ${relPath} (superseded by ${superseding.relPath}).` +\n (owner ? ` Run: agents update ${owner} --fanout ${superseding.host} to reconcile.` : '')\n );\n } else {\n pushProjectionWarning(\n projPath,\n `Missing projection ${projPath} for canonical ${relPath}. Re-run: agents add ... --fanout`\n );\n }\n continue;\n }\n const managed = await this.isManagedProjection(absProjection, projPath === 'AGENTS.md', manifest.projections?.[projPath]?.hash);\n if (!managed) {\n pushProjectionWarning(projPath, `user-modified projection ${projPath}`);\n }\n }\n }\n\n // 2. Check compound projections (ADR 0013 Cline lane, ADR 0018 Claude lane).\n // Same stale-vs-missing classification as §1: a recorded path whose canonical is\n // now served by a different, existing path is a rename this CLI can self-heal —\n // e.g. `.claude/agents/subagent-<role>.md` after the ADR 0018 decision 2 prefix\n // strip — and must never be reported as a missing file, nor under Cline's name.\n if (manifest.projections) {\n for (const [projRelPath, proj] of Object.entries(manifest.projections)) {\n const absPath = path.join(workspaceRoot, projRelPath);\n if (!await fs.pathExists(absPath)) {\n const superseding = await this.findSupersedingProjection(projRelPath, proj.canonical, manifest, workspaceRoot);\n if (superseding) {\n const owner = superseding.owners[0];\n pushProjectionWarning(\n projRelPath,\n `Stale projection ${projRelPath} for canonical ${proj.canonical} (superseded by ${superseding.relPath}).` +\n (owner ? ` Run: agents update ${owner} --fanout ${superseding.host} to reconcile.` : '')\n );\n } else {\n pushProjectionWarning(\n projRelPath,\n `Missing ${proj.host} projection ${projRelPath} (owners: ${proj.owners.join(', ')}).`\n );\n }\n continue;\n }\n if (proj.managedMarker) {\n const managed = await this.isManagedProjection(absPath, projRelPath === 'AGENTS.md', proj.hash);\n if (!managed) {\n pushProjectionWarning(projRelPath, `user-modified projection ${projRelPath}`);\n }\n }\n }\n }\n\n // 2b. ADR 0017 — renderer-backed freshness. Presence and marker integrity cannot\n // reveal a projection rendered from an older bundle definition (the on-disk\n // hash still matches what was recorded), so the only reliable check is to\n // re-render with the current registry and diff. Exactly one warning is raised\n // per path, attributed to the actual cause.\n //\n // ADR 0018 decision 11 — variants are rendered PER HOST and a recorded\n // projection is only ever diffed against its own host's renderer. Comparing a\n // `.claude/**` entry against Cline variants (or vice versa) is meaningless: it\n // made the Claude freshness check inert and risked reporting every Cline entry\n // as outdated purely because Claude variants existed.\n if (manifest.projections && manifest.installed) {\n const ownersByHost = new Map<CompoundLaneHost, Set<string>>();\n for (const proj of Object.values(manifest.projections)) {\n if (!DoctorEngine.isCompoundLaneHost(proj.host)) continue;\n const owners = ownersByHost.get(proj.host) ?? new Set<string>();\n for (const owner of proj.owners) owners.add(owner);\n ownersByHost.set(proj.host, owners);\n }\n\n const variantsByHost = new Map<CompoundLaneHost, Map<string, string[]>>();\n for (const [projHost, owners] of ownersByHost) {\n const variants = await this.renderProjectionVariants(owners, manifest.installed.bundles ?? [], projHost);\n if (variants) variantsByHost.set(projHost, variants);\n }\n\n if (variantsByHost.size > 0) {\n for (const [projRelPath, proj] of Object.entries(manifest.projections)) {\n const projHost = proj.host;\n if (!DoctorEngine.isCompoundLaneHost(projHost)) continue;\n const expectedVariants = variantsByHost.get(projHost);\n if (!expectedVariants) continue; // registry unavailable for this host — never guess\n const absPath = path.join(workspaceRoot, projRelPath);\n if (!await fs.pathExists(absPath)) continue; // missing/stale reported above\n if (!proj.managedMarker) continue; // unmanaged artifacts are not ours\n const content = await fs.readFile(absPath, 'utf8');\n if (!HostProjector.hasManagedMarker(content)) continue; // user-modified reported above\n\n // Content drift — edited after installation, marker left intact.\n if (proj.hash) {\n const diskHash = `sha256:${crypto.createHash('sha256').update(await fs.readFile(absPath)).digest('hex')}`;\n if (diskHash !== proj.hash) {\n const owner = proj.owners[0];\n pushProjectionWarning(\n projRelPath,\n `Content drift ${projRelPath} — edited after installation (recorded ${proj.hash.slice(0, 16)}…, on disk ${diskHash.slice(0, 16)}…).` +\n (owner ? ` Run: agents update ${owner} --fanout ${proj.host} to restore it.` : '')\n );\n continue;\n }\n }\n\n // Stale render — hash matches what was deployed, but the current renderer\n // would produce something different.\n const variants = expectedVariants.get(projRelPath);\n if (!variants || variants.length === 0) continue;\n const onDisk = content.replace(/\\r\\n/g, '\\n');\n if (!variants.some(variant => variant.replace(/\\r\\n/g, '\\n') === onDisk)) {\n const owner = proj.owners[0];\n pushProjectionWarning(\n projRelPath,\n `Outdated projection ${projRelPath} (content differs from the current render).` +\n (owner ? ` Run: agents update ${owner} --fanout ${proj.host} to refresh it.` : '')\n );\n }\n }\n }\n }\n\n // 3. Ownership cross-validation\n const installedBundles = manifest.installed?.bundles ?? [];\n const fileOwnersOf = (rec: { owners?: string[]; bundle?: string }): string[] =>\n assetOwners(rec);\n\n // 3a. Projection owned by a bundle absent from installed.bundles\n if (manifest.projections) {\n for (const [projRelPath, proj] of Object.entries(manifest.projections)) {\n for (const owner of proj.owners) {\n if (!installedBundles.includes(owner)) {\n warnings.push(`Projection ${projRelPath} is owned by bundle \"${owner}\" which is not in installed.bundles.`);\n }\n }\n }\n }\n // 3b. File-record owner absent from installed.bundles\n for (const [relPath, rec] of Object.entries(manifest.files)) {\n for (const owner of fileOwnersOf(rec)) {\n if (!installedBundles.includes(owner)) {\n warnings.push(`File record ${relPath} is owned by bundle \"${owner}\" which is not in installed.bundles.`);\n }\n }\n }\n // 3c. Installed bundle with zero owned file records\n for (const bundleName of installedBundles) {\n const fileCount = Object.values(manifest.files)\n .filter(m => fileOwnersOf(m).includes(bundleName)).length;\n if (fileCount === 0) {\n warnings.push(`Installed bundle \"${bundleName}\" owns zero file records.`);\n }\n }\n }\n\n // Plan 023 B (ADR 0022) — the store-less sidecar is a machine-owned snapshot, so any byte\n // change to a recorded file is drift (the `.agents/` store stays user-editable, unchecked).\n if (manifest && isSidecarDir(root)) {\n for (const [relPath, meta] of Object.entries(manifest.files)) {\n const abs = path.join(root, relPath);\n if (!meta.hash || !await fs.pathExists(abs)) continue;\n const diskHash = `sha256:${crypto.createHash('sha256').update(await fs.readFile(abs)).digest('hex')}`;\n if (diskHash !== meta.hash) {\n warnings.push(`Sidecar snapshot modified: ${relPath} — .claude/.agents-united/ is machine-owned. Run 'agents update --force' to restore it.`);\n }\n }\n }\n\n // Plan 023 A — plain-session guard. Reported whenever a decision is recorded; repairs are\n // never automatic (a hand-edited guard or an unparseable settings file is the user's call).\n let sessionGuard: HealthReport['sessionGuard'];\n const guardRecord = manifest?.sessionGuard;\n if (guardRecord) {\n if ('off' in guardRecord) {\n sessionGuard = 'off';\n } else {\n const guardFile = path.isAbsolute(guardRecord.file)\n ? guardRecord.file\n : path.join(workspaceRootOf(root), guardRecord.file);\n const state = await inspectSessionGuard(guardFile);\n sessionGuard = state === 'absent' ? 'missing' : state;\n if (state === 'missing' || state === 'absent') {\n warnings.push(`Session guard missing from ${guardRecord.file}: plain Claude sessions are unguarded. Run 'agents update' to restore it.`);\n } else if (state === 'modified') {\n warnings.push(`Session guard in ${guardRecord.file} was edited by hand; agents-united leaves it as-is.`);\n } else if (state === 'skipped-invalid') {\n warnings.push(`Session guard not wired: ${guardRecord.file} is not valid JSON (comments or trailing commas?), so agents-united left it untouched. Paste this into it by hand:\\n${sessionGuardSnippet()}`);\n }\n }\n }\n\n // Plan 024 S4 — command-permission preset. Reported whenever a decision is recorded; a user\n // who removed an entry by hand is left alone (never auto-repaired).\n let permissionPreset: HealthReport['permissionPreset'];\n const presetRecord = manifest?.permissionPreset;\n if (presetRecord) {\n if ('off' in presetRecord) {\n permissionPreset = 'off';\n } else {\n const presetFile = path.isAbsolute(presetRecord.file)\n ? presetRecord.file\n : path.join(workspaceRootOf(root), presetRecord.file);\n if (!await fs.pathExists(presetFile)) {\n permissionPreset = 'missing';\n warnings.push(`Permission preset missing: ${presetRecord.file} not found. Run 'agents update' to restore it.`);\n } else {\n const text = await fs.readFile(presetFile, 'utf8').catch(() => null);\n let parsed: { permissions?: { allow?: unknown[] } } | null = null;\n try {\n parsed = text === null ? null : JSON.parse(text);\n } catch {\n parsed = null;\n }\n if (parsed === null) {\n permissionPreset = 'skipped-invalid';\n warnings.push(`Permission preset not wired: ${presetRecord.file} is not valid JSON (comments or trailing commas?), so agents-united left it untouched.`);\n } else {\n const allow = parsed.permissions?.allow ?? [];\n const stillPresent = presetRecord.entries.every(e => allow.includes(e));\n permissionPreset = stillPresent ? 'wired' : 'missing';\n if (!stillPresent) {\n warnings.push(`Permission preset partially removed from ${presetRecord.file}. Run 'agents update' to restore it, or --no-permission-preset to drop it for good.`);\n }\n }\n }\n }\n }\n\n // Plan 026 Objective 3 — surface the Declared-Delta Registry's degraded/unsupported\n // features for a recognized host, independent of which host-specific probe (if any)\n // also runs below. An unrecognized/omitted host yields no section (never guessed).\n let declaredDeltas: TranslationLedgerEntry[] | undefined;\n if (host && DECLARED_DELTA_HOSTS.has(host)) {\n // The ledger lives beside the package's own `registry/`, not the CWD (this runs from\n // an arbitrary workspace directory via the installed CLI) — resolve it the same way\n // RegistryResolver does, module-relative with a CWD fallback.\n const ledger = loadTranslationLedger(new RegistryResolver().getRegistryDir());\n declaredDeltas = ledger.filter(\n e => e.host === host && (e.disposition === 'degraded' || e.disposition === 'unsupported')\n );\n }\n\n // Plan 029 A3 — MCP access audit (read-only). Every server an installed role declares that\n // this host has not configured is reported with the host's own add command; doctor never\n // installs a server and never writes an MCP config file.\n if (host && MCP_AUDIT_HOSTS.has(host)) {\n await DoctorEngine.auditMcpServers(host, workspaceRootOf(root), subPaths.agentsDir, warnings);\n }\n\n // Host-specific checks (e.g. --host cline, --host claude)\n if (host === 'cline') {\n const probe = new ClineCapabilityProbe();\n clineCapability = await probe.probe();\n if (!clineCapability.installed) {\n warnings.push('Cline executable was not detected on PATH or via CLINE_BIN_PATH.');\n }\n } else if (host === 'claude') {\n // ADR 0018 decision 11 / Plan 016 decision 12 — read-only probe: `--version` and\n // `--help` only, never `claude agents --json` (daemon) and never headless `-p`.\n const probe = new ClaudeCapabilityProbe();\n claudeCapability = await probe.probe();\n if (!claudeCapability.installed) {\n warnings.push('Claude Code executable was not detected on PATH or via CLAUDE_BIN_PATH.');\n }\n }\n\n return {\n valid: issues.length === 0,\n targetDir: root,\n isInitialized,\n issues,\n warnings,\n agentsCount,\n skillsCount,\n workflowsCount,\n permissionPreset,\n clineCapability,\n claudeCapability,\n sessionGuard,\n declaredDeltas,\n };\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport { defaultProcessRunner } from './cline-capabilities.js';\nimport type {\n ClaudeCapabilityReport,\n ProcessRunner,\n ResolvedClaudeCommand,\n} from './types.js';\n\nexport interface ClaudeProbeResolverOptions {\n resolveExecutable?: () => ResolvedClaudeCommand | null;\n}\n\n/**\n * ADR 0018 decision 11 / Plan 016 decision 12 — side-effect-free Claude Code capability probe.\n *\n * The probe runs **exactly two** commands, in this order and no others:\n * 1. `<exe> [...prefixArgs, '--version']`\n * 2. `<exe> [...prefixArgs, '--help']`\n *\n * Two documented non-goals (ADR 0018 decision 11, restated as Plan 016 decision 12) are\n * deliberately never invoked:\n * - `claude agents --json` — it can start the supervisor daemon (a mutating side effect).\n * - headless `-p` runs — they cost tokens (a billed side effect).\n * `--help` text is the only source of truth for capability flags, so the probe stays free of\n * both side effects; anything it cannot verify is reported as unsupported with a diagnostic.\n *\n * The process primitive is the shared `defaultProcessRunner` (argv arrays, `shell: false`,\n * hard timeout, never throws) that the Cline probe uses, so the Windows `.cmd`/`.bat`\n * `cmd.exe` bridge added by ADR 0013 §5 applies identically here.\n */\n/**\n * The live tools reference dates `SubagentHandback` at Claude Code v2.1.271 or later, and provides it\n * only in auto mode. Only `--version` is readable here, so this reports the version floor.\n */\nconst SUBAGENT_HANDBACK_MIN = { major: 2, minor: 1, patch: 271 } as const;\n\nfunction supportsSubagentHandback(version: string | undefined): boolean {\n if (!version) return false;\n const match = version.match(/(\\d+)\\.(\\d+)\\.(\\d+)/);\n if (!match) return false;\n const [major, minor, patch] = [Number(match[1]), Number(match[2]), Number(match[3])];\n if (major !== SUBAGENT_HANDBACK_MIN.major) return major > SUBAGENT_HANDBACK_MIN.major;\n if (minor !== SUBAGENT_HANDBACK_MIN.minor) return minor > SUBAGENT_HANDBACK_MIN.minor;\n return patch >= SUBAGENT_HANDBACK_MIN.patch;\n}\n\nexport class ClaudeCapabilityProbe {\n private runner: ProcessRunner;\n private customResolver?: () => ResolvedClaudeCommand | null;\n\n constructor(runner?: ProcessRunner, options?: ClaudeProbeResolverOptions) {\n this.runner = runner || defaultProcessRunner;\n this.customResolver = options?.resolveExecutable;\n }\n\n /**\n * Safe executable resolution across POSIX and Windows layouts.\n */\n public resolveExecutable(): ResolvedClaudeCommand | null {\n if (this.customResolver) {\n return this.customResolver();\n }\n\n // 1. Explicit CLAUDE_BIN_PATH\n const envBin = process.env.CLAUDE_BIN_PATH;\n if (envBin && path.isAbsolute(envBin) && fs.existsSync(envBin)) {\n return {\n executable: envBin,\n prefixArgs: [],\n source: 'env-binary',\n };\n }\n\n // 2. PATH scanning\n const pathEnv = process.env.PATH || '';\n const pathSeparator = process.platform === 'win32' ? ';' : ':';\n const dirs = pathEnv.split(pathSeparator).filter(Boolean);\n\n if (process.platform === 'win32') {\n const exeNames = ['claude.cmd', 'claude.bat', 'claude.exe', 'claude'];\n for (const dir of dirs) {\n for (const exeName of exeNames) {\n const fullPath = path.join(dir, exeName);\n if (fs.existsSync(fullPath)) {\n // Check adjacent Node wrapper in npm / nvm / volta structure\n const adjacentWrapper1 = path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js');\n const adjacentWrapper2 = path.join(dir, 'node_modules', 'claude', 'bin', 'claude');\n\n if (fs.existsSync(adjacentWrapper1)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper1],\n source: 'node-wrapper',\n };\n }\n if (fs.existsSync(adjacentWrapper2)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper2],\n source: 'node-wrapper',\n };\n }\n\n // Windows hardening (ADR 0013 §5): Node >= 18.20 / 20.12 / 24 rejects\n // spawning .cmd/.bat shims with shell:false (EINVAL), so bridge through\n // cmd.exe while keeping the argv array shell-safe.\n const ext = path.extname(fullPath).toLowerCase();\n if (ext === '.cmd' || ext === '.bat') {\n return {\n executable: 'cmd.exe',\n prefixArgs: ['/c', fullPath],\n source: 'path-executable',\n };\n }\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n } else {\n for (const dir of dirs) {\n const fullPath = path.join(dir, 'claude');\n if (fs.existsSync(fullPath)) {\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n\n return null;\n }\n\n /**\n * Run the read-only capability probe against local Claude Code. Never throws: an absent\n * executable, a non-zero exit and a runner error are all reported as data.\n */\n public async probe(): Promise<ClaudeCapabilityReport> {\n const cmd = this.resolveExecutable();\n const diagnostics: string[] = [];\n\n if (!cmd) {\n diagnostics.push('Claude Code executable not found on PATH or via CLAUDE_BIN_PATH.');\n return {\n installed: false,\n pluginSupport: false,\n agentTeamsExperimental: false,\n subagentHandback: false,\n diagnostics,\n };\n }\n\n // 1. Version check — `--version` only (ADR 0018 decision 11).\n let version: string | undefined;\n let subagentHandback = false;\n try {\n const verRes = await this.runner(cmd.executable, [...cmd.prefixArgs, '--version'], {\n timeoutMs: 5000,\n });\n\n if (verRes.exitCode === 0) {\n version = verRes.stdout.trim().split('\\n')[0]?.trim();\n subagentHandback = supportsSubagentHandback(version);\n } else {\n diagnostics.push(`Claude Code version check failed (exit code ${verRes.exitCode}): ${verRes.stderr.trim()}`);\n return {\n installed: false,\n command: cmd,\n pluginSupport: false,\n agentTeamsExperimental: false,\n subagentHandback: false,\n diagnostics,\n };\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Error executing Claude Code version check: ${msg}`);\n return {\n installed: false,\n command: cmd,\n pluginSupport: false,\n agentTeamsExperimental: false,\n subagentHandback: false,\n diagnostics,\n };\n }\n\n // 2. Flag surface — `--help` text only. No `claude agents --json` (it can start the\n // supervisor daemon) and no headless `-p` run (it costs tokens) — see the class JSDoc.\n let pluginSupport = false;\n let agentTeamsExperimental = false;\n try {\n const helpRes = await this.runner(cmd.executable, [...cmd.prefixArgs, '--help'], {\n timeoutMs: 5000,\n });\n\n if (helpRes.exitCode === 0) {\n const help = helpRes.stdout;\n pluginSupport = help.includes('--plugin-dir');\n agentTeamsExperimental =\n /agent teams/i.test(help) || help.includes('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS');\n } else {\n diagnostics.push(\n `Claude Code help probe returned non-zero (exit code ${helpRes.exitCode}); plugin and agent-team support could not be verified.`\n );\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Claude Code help probe failed: ${msg}`);\n }\n\n return {\n installed: true,\n version,\n command: cmd,\n pluginSupport,\n agentTeamsExperimental,\n subagentHandback,\n diagnostics,\n };\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport { execFile } from 'node:child_process';\nimport type {\n ClineCapabilityReport,\n ProcessRunner,\n ProcessRunnerResult,\n ResolvedClineCommand,\n} from './types.js';\n\nexport interface ClineProbeResolverOptions {\n resolveExecutable?: () => ResolvedClineCommand | null;\n}\n\nexport const defaultProcessRunner: ProcessRunner = (\n executable: string,\n args: string[],\n options?: { cwd?: string; env?: Record<string, string>; timeoutMs?: number }\n): Promise<ProcessRunnerResult> => {\n return new Promise((resolve) => {\n const timeout = options?.timeoutMs ?? 5000;\n try {\n execFile(\n executable,\n args,\n {\n cwd: options?.cwd,\n env: options?.env ? { ...process.env, ...options.env } : process.env,\n timeout,\n shell: false,\n },\n (error, stdout, stderr) => {\n if (error) {\n const exitCode = typeof error.code === 'number' ? error.code : 1;\n resolve({\n exitCode,\n stdout: (stdout || '').toString(),\n stderr: (stderr || error.message || '').toString(),\n });\n } else {\n resolve({\n exitCode: 0,\n stdout: (stdout || '').toString(),\n stderr: (stderr || '').toString(),\n });\n }\n }\n );\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n resolve({\n exitCode: 1,\n stdout: '',\n stderr: msg,\n });\n }\n });\n};\n\nexport class ClineCapabilityProbe {\n private runner: ProcessRunner;\n private customResolver?: () => ResolvedClineCommand | null;\n\n constructor(runner?: ProcessRunner, options?: ClineProbeResolverOptions) {\n this.runner = runner || defaultProcessRunner;\n this.customResolver = options?.resolveExecutable;\n }\n\n /**\n * Safe executable resolution across POSIX and Windows layouts.\n */\n public resolveExecutable(): ResolvedClineCommand | null {\n if (this.customResolver) {\n return this.customResolver();\n }\n\n // 1. Explicit CLINE_BIN_PATH\n const envBin = process.env.CLINE_BIN_PATH;\n if (envBin && path.isAbsolute(envBin) && fs.existsSync(envBin)) {\n return {\n executable: envBin,\n prefixArgs: [],\n source: 'env-binary',\n };\n }\n\n // 2. PATH scanning\n const pathEnv = process.env.PATH || '';\n const pathSeparator = process.platform === 'win32' ? ';' : ':';\n const dirs = pathEnv.split(pathSeparator).filter(Boolean);\n\n if (process.platform === 'win32') {\n const exeNames = ['cline.cmd', 'cline.bat', 'cline.exe', 'cline'];\n for (const dir of dirs) {\n for (const exeName of exeNames) {\n const fullPath = path.join(dir, exeName);\n if (fs.existsSync(fullPath)) {\n // Check adjacent Node wrapper in npm / nvm / volta structure\n const adjacentWrapper1 = path.join(dir, 'node_modules', 'cline', 'bin', 'cline');\n const adjacentWrapper2 = path.join(dir, 'node_modules', '@cline', 'cline', 'bin', 'cline');\n\n if (fs.existsSync(adjacentWrapper1)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper1],\n source: 'node-wrapper',\n };\n }\n if (fs.existsSync(adjacentWrapper2)) {\n return {\n executable: process.execPath,\n prefixArgs: [adjacentWrapper2],\n source: 'node-wrapper',\n };\n }\n\n // Windows hardening (ADR 0013 §5): Node >= 18.20 / 20.12 / 24 rejects\n // spawning .cmd/.bat shims with shell:false (EINVAL), so bridge through\n // cmd.exe while keeping the argv array shell-safe.\n const ext = path.extname(fullPath).toLowerCase();\n if (ext === '.cmd' || ext === '.bat') {\n return {\n executable: 'cmd.exe',\n prefixArgs: ['/c', fullPath],\n source: 'path-executable',\n };\n }\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n } else {\n for (const dir of dirs) {\n const fullPath = path.join(dir, 'cline');\n if (fs.existsSync(fullPath)) {\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n\n return null;\n }\n\n /**\n * Run read-only capability probe against local Cline.\n */\n public async probe(): Promise<ClineCapabilityReport> {\n const cmd = this.resolveExecutable();\n const diagnostics: string[] = [];\n\n if (!cmd) {\n diagnostics.push('Cline executable not found on PATH or via CLINE_BIN_PATH.');\n return {\n installed: false,\n namedTeams: false,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n\n // 1. Version check\n let version: string | undefined;\n try {\n const verRes = await this.runner(cmd.executable, [...cmd.prefixArgs, 'version'], {\n timeoutMs: 5000,\n });\n\n if (verRes.exitCode === 0) {\n version = verRes.stdout.trim().split('\\n')[0]?.trim();\n } else {\n diagnostics.push(`Cline version check failed (exit code ${verRes.exitCode}): ${verRes.stderr.trim()}`);\n return {\n installed: false,\n command: cmd,\n namedTeams: false,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Error executing Cline version check: ${msg}`);\n return {\n installed: false,\n command: cmd,\n namedTeams: false,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n\n // 2. Named team parser probe\n let namedTeams = false;\n try {\n const probeRes = await this.runner(\n cmd.executable,\n [...cmd.prefixArgs, '--team-name', 'agents-united-capability-probe', 'version'],\n { timeoutMs: 5000 }\n );\n\n if (probeRes.exitCode === 0) {\n namedTeams = true;\n } else {\n diagnostics.push(`Named teams probe returned non-zero (exit code ${probeRes.exitCode}). Falling back to adaptive session.`);\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Named teams probe failed: ${msg}`);\n }\n\n return {\n installed: true,\n version,\n command: cmd,\n namedTeams,\n rolePresetConsumer: 'unknown',\n diagnostics,\n };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport type { AgentHost } from './types.js';\n\nexport type McpClientCategory = 'cli' | 'extension' | 'desktop' | 'workspace';\n\n/**\n * Plan 029 A4 — the home directory `~` resolves against. `USERPROFILE`/`HOME` deliberately win\n * over `os.homedir()`: a caller (the doctor suites) can then sandbox discovery so the fixture\n * config — never the developer's real `~/.claude.json` — decides what counts as configured.\n */\nfunction resolveHomeDir(): string {\n return process.env.USERPROFILE || process.env.HOME || os.homedir();\n}\n\n/** Plan 029 A3/A4 — the AppData root `%APPDATA%` resolves against, honouring an env override. */\nfunction resolveAppDataDir(homeDir: string): string {\n return (\n process.env.APPDATA ||\n (process.platform === 'darwin'\n ? path.join(homeDir, 'Library', 'Application Support')\n : path.join(homeDir, '.config'))\n );\n}\n\n/** True for a plain name → definition map (never an array or a scalar). */\nfunction isServerMap(value: unknown): value is Record<string, any> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport interface McpLocationDescriptor {\n id: string;\n host: AgentHost | 'gemini' | 'cline' | 'claude' | 'cursor' | 'opencode' | 'windsurf' | 'zed' | 'custom';\n category: McpClientCategory;\n label: string;\n resolvePath: (cwd: string, homeDir: string, appData: string) => string;\n isPrimary?: boolean;\n /**\n * Plan 029 A4 — an optional scope-aware reader for a file that carries more than one scope.\n * Claude Code keeps the user-scope `mcpServers` map AND the local-scope\n * `projects.<abs-path>.mcpServers` map in the same `~/.claude.json`, so the default\n * \"`mcpServers` at the top level\" reader would miss the local scope entirely.\n */\n selectServers?: (config: any, cwd: string) => Record<string, any> | undefined;\n}\n\nexport interface DiscoveredMcpConfig {\n id: string;\n host: string;\n category: McpClientCategory;\n label: string;\n path: string;\n exists: boolean;\n serverCount: number;\n servers?: Record<string, any>;\n isPrimary?: boolean;\n}\n\nexport class McpLocationRegistry {\n /**\n * Declarative catalog of known MCP configuration files across AI tools, CLIs, extensions, and workspaces.\n */\n public static readonly LOCATIONS: McpLocationDescriptor[] = [\n // --- Google Antigravity & Gemini ---\n {\n id: 'antigravity-global',\n host: 'gemini',\n category: 'cli',\n label: 'Google Antigravity & Gemini Global Config',\n resolvePath: (_, home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),\n isPrimary: true,\n },\n {\n id: 'antigravity-system',\n host: 'gemini',\n category: 'desktop',\n label: 'Google Antigravity System Config',\n resolvePath: (_, home) => path.join(home, '.gemini', 'antigravity', 'mcp_config.json'),\n },\n {\n id: 'antigravity-workspace',\n host: 'gemini',\n category: 'workspace',\n label: 'Google Antigravity Local Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.gemini', 'config', 'mcp_config.json'),\n },\n {\n id: 'gemini-appdata',\n host: 'gemini',\n category: 'cli',\n label: 'Google Gemini AppData Config',\n resolvePath: (_, __, appData) => path.join(appData, 'gemini', 'config', 'mcp_config.json'),\n },\n\n // --- Cline CLI & VS Code Extension ---\n {\n id: 'cline-cli-settings',\n host: 'cline',\n category: 'cli',\n label: 'Cline CLI MCP Settings',\n resolvePath: (_, home) => path.join(home, '.cline', 'data', 'settings', 'cline_mcp_settings.json'),\n isPrimary: true,\n },\n {\n id: 'cline-extension-settings',\n host: 'cline',\n category: 'extension',\n label: 'Cline VS Code Extension Global Settings',\n resolvePath: (_, __, appData) => path.join(appData, 'Code', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-insiders-extension-settings',\n host: 'cline',\n category: 'extension',\n label: 'Cline VS Code Insiders Extension Settings',\n resolvePath: (_, __, appData) => path.join(appData, 'Code - Insiders', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-legacy-settings',\n host: 'cline',\n category: 'cli',\n label: 'Cline Home Legacy Settings',\n resolvePath: (_, home) => path.join(home, '.cline', 'settings', 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-home-flat',\n host: 'cline',\n category: 'cli',\n label: 'Cline Home Flat Settings',\n resolvePath: (_, home) => path.join(home, 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-workspace-flat',\n host: 'cline',\n category: 'workspace',\n label: 'Cline Workspace Settings',\n resolvePath: (cwd) => path.join(cwd, 'cline_mcp_settings.json'),\n },\n {\n id: 'cline-workspace-dot',\n host: 'cline',\n category: 'workspace',\n label: 'Cline Workspace .cline/mcp.json',\n resolvePath: (cwd) => path.join(cwd, '.cline', 'mcp.json'),\n },\n\n // --- Roo Code Extension ---\n {\n id: 'roo-code-extension-settings',\n host: 'cline',\n category: 'extension',\n label: 'Roo Code VS Code Extension Settings',\n resolvePath: (_, __, appData) => path.join(appData, 'Code', 'User', 'globalStorage', 'rooveterinaryinc.roo-cline', 'settings', 'cline_mcp_settings.json'),\n },\n\n // --- Cursor IDE / CLI ---\n {\n id: 'cursor-workspace',\n host: 'cursor',\n category: 'workspace',\n label: 'Cursor Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.cursor', 'mcp.json'),\n isPrimary: true,\n },\n {\n id: 'cursor-global',\n host: 'cursor',\n category: 'desktop',\n label: 'Cursor Global User Config',\n resolvePath: (_, home) => path.join(home, '.cursor', 'mcp.json'),\n },\n\n // --- Claude Code CLI & Claude Desktop ---\n // Plan 029 A4 — Claude Code's documented MCP config paths. The project scope is `.mcp.json` at\n // the repo root; the user scope (`mcpServers`) and the local scope\n // (`projects.<abs-path>.mcpServers`) both live in `~/.claude.json`. Claude *Desktop* keeps its\n // own separate file, which is why that entry is untouched.\n // (Replaced here: `.claude/mcp.json`, `<cwd>/claude.json` and `~/claude.json` — none of them is\n // a Claude Code MCP config, and `~/claude.json` was a mis-spelling of `~/.claude.json`.)\n {\n id: 'claude-project',\n host: 'claude',\n category: 'workspace',\n label: 'Claude Code Project Config (.mcp.json)',\n resolvePath: (cwd) => path.join(cwd, '.mcp.json'),\n isPrimary: true,\n },\n {\n id: 'claude-user-local',\n host: 'claude',\n category: 'cli',\n label: 'Claude Code User & Local Config (~/.claude.json)',\n resolvePath: (_, home) => path.join(home, '.claude.json'),\n // One file, two scopes: `mcpServers` is the user scope, `projects.<abs-path>.mcpServers` is\n // the local scope. A workspace can reach both, so discovery reports the union (a local entry\n // wins on a name collision). The project key is tried in its raw, resolved and forward-slash\n // spellings because Claude Code writes the absolute project path as the key.\n selectServers: (config, cwd) => {\n const user = isServerMap(config?.mcpServers) ? config.mcpServers : {};\n const projects = isServerMap(config?.projects) ? config.projects : {};\n const resolved = path.resolve(cwd);\n let local: Record<string, any> = {};\n for (const key of [cwd, resolved, resolved.split(path.sep).join('/')]) {\n const entry = projects[key];\n if (isServerMap(entry?.mcpServers)) {\n local = entry.mcpServers;\n break;\n }\n }\n const merged = { ...user, ...local };\n return Object.keys(merged).length > 0 ? merged : undefined;\n },\n },\n {\n id: 'claude-desktop-global',\n host: 'claude',\n category: 'desktop',\n label: 'Claude Desktop Global Config',\n resolvePath: (_, __, appData) => path.join(appData, 'Claude', 'claude_desktop_config.json'),\n },\n\n // --- Windsurf IDE ---\n {\n id: 'windsurf-global',\n host: 'windsurf',\n category: 'desktop',\n label: 'Windsurf Global Config',\n resolvePath: (_, home) => path.join(home, '.codeium', 'windsurf', 'mcp_config.json'),\n isPrimary: true,\n },\n {\n id: 'windsurf-appdata',\n host: 'windsurf',\n category: 'desktop',\n label: 'Windsurf AppData Config',\n resolvePath: (_, __, appData) => path.join(appData, 'Windsurf', 'mcp_config.json'),\n },\n\n // --- OpenCode & Codex ---\n {\n id: 'opencode-workspace',\n host: 'opencode',\n category: 'workspace',\n label: 'OpenCode Workspace Config',\n resolvePath: (cwd) => path.join(cwd, '.opencode', 'mcp.json'),\n isPrimary: true,\n },\n {\n id: 'opencode-global',\n host: 'opencode',\n category: 'cli',\n label: 'OpenCode Global Config',\n resolvePath: (_, home) => path.join(home, '.config', 'opencode', 'mcp.json'),\n },\n ];\n\n /**\n * Discovers all MCP configuration files across the filesystem, inspecting existence and parsing server definitions.\n */\n public static async discoverAll(cwd: string = process.cwd()): Promise<DiscoveredMcpConfig[]> {\n const homeDir = resolveHomeDir();\n const appData = resolveAppDataDir(homeDir);\n\n const results: DiscoveredMcpConfig[] = [];\n const seenPaths = new Set<string>();\n\n for (const desc of McpLocationRegistry.LOCATIONS) {\n const resolved = path.normalize(desc.resolvePath(cwd, homeDir, appData));\n const key = resolved.toLowerCase();\n if (seenPaths.has(key)) continue;\n seenPaths.add(key);\n\n const exists = await fs.pathExists(resolved);\n let serverCount = 0;\n let servers: Record<string, any> | undefined;\n\n if (exists) {\n try {\n const config = await fs.readJson(resolved);\n // Plan 029 A4 — a descriptor may own a scope-aware reader (Claude's `~/.claude.json`\n // holds the user scope and the local `projects.<abs-path>` scope in one file).\n const rawServers = desc.selectServers\n ? desc.selectServers(config, cwd)\n : config?.mcpServers || config?.servers || config;\n if (rawServers && typeof rawServers === 'object') {\n servers = rawServers;\n serverCount = Object.keys(rawServers).length;\n }\n } catch {}\n }\n\n results.push({\n id: desc.id,\n host: desc.host,\n category: desc.category,\n label: desc.label,\n path: resolved,\n exists,\n serverCount,\n servers,\n isPrimary: desc.isPrimary,\n });\n }\n\n return results;\n }\n\n /**\n * Returns discovered locations filtered for specific host(s).\n */\n public static async discoverForHosts(hosts: (AgentHost | string)[], cwd: string = process.cwd()): Promise<DiscoveredMcpConfig[]> {\n const all = await McpLocationRegistry.discoverAll(cwd);\n const hostSet = new Set(hosts.map(h => (h === 'agents' ? 'gemini' : h)));\n return all.filter(loc => hostSet.has(loc.host));\n }\n\n /**\n * Resolves the primary target write path for a given host runtime.\n */\n public static getPrimaryWritePath(host: AgentHost | string, cwd: string = process.cwd()): string {\n const homeDir = resolveHomeDir();\n const appData = resolveAppDataDir(homeDir);\n\n const targetHost = host === 'agents' ? 'gemini' : host;\n const desc = McpLocationRegistry.LOCATIONS.find(l => l.host === targetHost && l.isPrimary);\n if (desc) {\n return path.normalize(desc.resolvePath(cwd, homeDir, appData));\n }\n return path.normalize(path.join(cwd, '.cursor', 'mcp.json'));\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport crypto from 'node:crypto';\nimport fs from 'fs-extra';\nimport { AgentHostAdapter } from './adapter.js';\nimport { ClineCapabilityProbe, defaultProcessRunner } from './cline-capabilities.js';\nimport type {\n ClineActivationStrategy,\n ClineCapabilityReport,\n InstallScope,\n LockfileManifest,\n ProcessRunner,\n} from './types.js';\n\nexport interface ClineActivationPlan {\n bundleName: string;\n scope: InstallScope;\n workspace: string;\n teamName: string;\n strategy: ClineActivationStrategy;\n executable: string;\n argv: string[];\n bootstrapPrompt: string;\n}\n\nexport interface PlanActivationOptions {\n bundleName: string;\n workspace: string;\n scope: InstallScope;\n report: ClineCapabilityReport;\n prompt?: string;\n teamName?: string;\n allowAddons?: boolean;\n headless?: boolean;\n /** Optional coordinator agent filename (e.g. \"orchestrator-universal.md\"). Resolved from the bundle definition by the caller; defaults to orchestrator-engineering.md for backward compatibility. */\n orchestrator?: string;\n}\n\nexport interface ResolveInstallationOptions {\n scope?: InstallScope;\n global?: boolean;\n cwd?: string;\n}\n\nexport class ClineLauncher {\n private probe: ClineCapabilityProbe;\n private runner: ProcessRunner;\n\n constructor(probe?: ClineCapabilityProbe, runner?: ProcessRunner) {\n this.probe = probe || new ClineCapabilityProbe();\n this.runner = runner || defaultProcessRunner;\n }\n\n /**\n * Generate stable team name: au-<bundle>-<first-8-sha256-of-workspace>\n */\n public static generateTeamName(bundleName: string, workspace: string): string {\n const sanitizedBundle = bundleName.replace(/[^A-Za-z0-9_-]/g, '-');\n const hash = crypto.createHash('sha256').update(path.resolve(workspace)).digest('hex').slice(0, 8);\n const prefix = `au-${sanitizedBundle}`;\n const maxPrefixLen = 64 - 9; // 64 - (1 for hyphen + 8 for hash)\n const truncatedPrefix = prefix.slice(0, maxPrefixLen);\n return `${truncatedPrefix}-${hash}`;\n }\n\n /**\n * Validate custom team names against safe identifier requirements.\n */\n public static validateTeamName(name: string): boolean {\n return /^[A-Za-z0-9_-]{1,64}$/.test(name);\n }\n\n /**\n * Resolve an installed bundle for Cline activation.\n */\n public async resolveInstallation(\n bundleName: string,\n options: ResolveInstallationOptions = {}\n ): Promise<{ scope: InstallScope; workspace: string; lockfile: LockfileManifest; manifestPath: string }> {\n const cwd = options.cwd || process.cwd();\n const isGlobal = !!options.global;\n\n let targetDir: string;\n let scope: InstallScope;\n let workspace: string;\n\n if (isGlobal) {\n targetDir = AgentHostAdapter.resolveHostDir('global', 'agents');\n scope = 'global';\n workspace = os.homedir();\n } else {\n workspace = cwd;\n targetDir = path.join(cwd, '.agents');\n scope = 'project';\n }\n\n const lockfilePath = path.join(targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n if (!isGlobal) {\n // Check if global installation exists as fallback\n const globalTarget = AgentHostAdapter.resolveHostDir('global', 'agents');\n const globalLockfile = path.join(globalTarget, 'agents-united.json');\n if (await fs.pathExists(globalLockfile)) {\n const gLock: LockfileManifest = await fs.readJson(globalLockfile);\n if (gLock.installed?.bundles?.includes(bundleName)) {\n return this.resolveInstallation(bundleName, { ...options, global: true });\n }\n }\n }\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n if (!lockfile.installed?.bundles?.includes(bundleName)) {\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n // Check Cline fanout and Team Manifest presence\n const hasClineFanout = (lockfile.fanout || []).includes('cline');\n const manifestRel = `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n const manifestPath = path.join(workspace, manifestRel);\n\n if (!hasClineFanout || !await fs.pathExists(manifestPath)) {\n throw new Error(\n `Bundle '${bundleName}' is not projected to Cline. Run 'agents update ${bundleName} --fanout cline' first.`\n );\n }\n\n return {\n scope,\n workspace,\n lockfile,\n manifestPath,\n };\n }\n\n /**\n * Plan activation strategy, argv, and bootstrap prompt without launching process.\n */\n public planActivation(options: PlanActivationOptions): ClineActivationPlan {\n const {\n bundleName,\n workspace,\n scope,\n report,\n prompt,\n teamName: customTeamName,\n allowAddons,\n headless,\n orchestrator,\n } = options;\n\n const command = report.command || {\n executable: 'cline',\n prefixArgs: [],\n source: 'path-executable' as const,\n };\n\n let teamName = ClineLauncher.generateTeamName(bundleName, workspace);\n if (customTeamName) {\n if (!ClineLauncher.validateTeamName(customTeamName)) {\n throw new Error(\n `Invalid team name \"${customTeamName}\". Must match [A-Za-z0-9_-] and be at most 64 characters.`\n );\n }\n teamName = customTeamName;\n }\n\n const strategy: ClineActivationStrategy = report.namedTeams ? 'named-team' : 'adaptive-session';\n\n const manifestRel = scope === 'global'\n ? `~/.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`\n : `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n // Coordinator role = the bundle's declared orchestrator when available; fall back to\n // orchestrator-engineering.md only to preserve pre-existing platform-manifest behavior.\n const coordinatorFile = (orchestrator || 'orchestrator-engineering.md').replace(/\\.md$/, '');\n const coordinatorCanonical = `.agents/agents/${coordinatorFile}.md`;\n\n const addonPolicyText = allowAddons\n ? 'Addon auto-installation is pre-authorized for this session.'\n : `Before installing any recommended addon, explain the requirement to the user and request explicit confirmation to run: agents add <addon> -t cline ${scope === 'global' ? '-g ' : ''}-y.`;\n\n const deploymentNoteText = `Deployment note: this bundle is already projected natively for this workspace (skills, rules, workflows, and configured subagent roles) - no \"cline plugin install\" step is needed.`;\n\n const taskText = prompt && prompt.trim().length > 0\n ? `User task: ${prompt.trim()}`\n : 'Please introduce your coordinator role to the user and ask for their first task.';\n\n const bootstrapPrompt = [\n `You are coordinating the \"${bundleName}\" team in Agents United.`,\n `Read the Team Manifest at \"${manifestRel}\" and your coordinator role definition at \"${coordinatorCanonical}\" before acting.`,\n `Use specialist roles only when necessary.`,\n addonPolicyText,\n deploymentNoteText,\n taskText,\n ].join('\\n\\n');\n\n const argv: string[] = [...command.prefixArgs];\n if (strategy === 'named-team') {\n argv.push('--team-name', teamName);\n }\n argv.push('--cwd', workspace);\n if (!headless) {\n argv.push('-i');\n }\n argv.push(bootstrapPrompt);\n\n return {\n bundleName,\n scope,\n workspace,\n teamName,\n strategy,\n executable: command.executable,\n argv,\n bootstrapPrompt,\n };\n }\n\n /**\n * Launch Cline session using argument array.\n */\n public async launch(plan: ClineActivationPlan): Promise<void> {\n const { spawn } = await import('node:child_process');\n const child = spawn(plan.executable, plan.argv, {\n cwd: plan.workspace,\n stdio: 'inherit',\n shell: false,\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('error', reject);\n child.on('exit', (code) => {\n if (code === 0 || code === null) {\n resolve();\n } else {\n resolve(); // return cleanly on process exit\n }\n });\n });\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { ClaudeCapabilityProbe } from './claude-capabilities.js';\nimport { ClaudeProjector } from './claude-projector.js';\nimport { defaultProcessRunner } from './cline-capabilities.js';\nimport { resolveStateDir } from './state-dir.js';\nimport type {\n ClaudeCapabilityReport,\n InstallScope,\n LockfileManifest,\n ProcessRunner,\n} from './types.js';\n\n/** Default coordinator when the caller could not resolve the bundle's own `orchestrator` field. */\nconst DEFAULT_COORDINATOR = 'orchestrator-engineering.md';\n\nexport interface ClaudeActivationPlan {\n bundleName: string;\n scope: InstallScope;\n workspace: string;\n executable: string;\n argv: string[];\n bootstrapPrompt: string;\n env: Record<string, string>;\n}\n\nexport interface PlanClaudeActivationOptions {\n bundleName: string;\n workspace: string;\n scope: InstallScope;\n report: ClaudeCapabilityReport;\n prompt?: string;\n /** Optional coordinator agent filename (e.g. \"orchestrator-universal.md\"). Resolved from the bundle\n * definition by the caller; defaults to orchestrator-engineering.md for backward compatibility. */\n orchestrator?: string;\n /** `--bg`: run the session in the background. */\n background?: boolean;\n /** Pre-authorize recommended addon installs for this session (mirrors `ClineLauncher`). */\n allowAddons?: boolean;\n /** Experimental agent-teams scaffold — ephemeral env + prompt instruction only (Plan 016 decision 14). */\n teams?: boolean;\n /** Plugin root for `--plugin-dir` (Step 7 emits the manifest inside it). */\n pluginDir?: string;\n /**\n * Whether the single host-neutral team manifest exists on disk for this workspace.\n *\n * ADR 0018 decision 6 keeps exactly one manifest under the organization package (never a\n * `.claude/` duplicate), and it is written by the Cline half of the compound lane. A claude-only\n * fanout therefore has none, so the caller passes `false` and the bootstrap prompt points at the\n * projected `.claude/agents/` roster instead of a dangling path. Omitted ⇒ the established\n * manifest instruction is used.\n */\n manifestAvailable?: boolean;\n}\n\nexport interface ResolveClaudeInstallationOptions {\n scope?: InstallScope;\n global?: boolean;\n cwd?: string;\n}\n\n/**\n * ADR 0018 / Plan 016 decision 12 — the Claude Code activation lane, mirroring `ClineLauncher` in shape\n * (same constructor seam, same resolve/plan/launch split, same argv-array discipline with `shell: false`).\n *\n * Two hard boundaries carried by this file:\n * 1. The launcher only ever *describes* a session. It writes no file under `.claude/**`, never touches\n * `CLAUDE.md` / `CLAUDE.local.md` / `.claude/settings.json` / `.claude/workflows/**`, and the teams\n * scaffold persists nothing anywhere (no `~/.claude/teams/`, no settings key).\n * 2. Every value is one argv element. `--agent` and its value are pushed separately, the workspace is a\n * single `--add-dir` argument, and the bootstrap prompt is a single final *positional* argument (the\n * only opening-prompt mechanism Claude Code offers — there is intentionally no\n * `--prompt-interactive` flag on this host), so no prompt text is ever word-split, shell-expanded\n * or joined into a command string.\n */\nexport class ClaudeLauncher {\n private probe: ClaudeCapabilityProbe;\n private runner: ProcessRunner;\n\n constructor(probe?: ClaudeCapabilityProbe, runner?: ProcessRunner) {\n this.probe = probe || new ClaudeCapabilityProbe();\n this.runner = runner || defaultProcessRunner;\n }\n\n /**\n * The `--agent` value must equal the projected coordinator definition's basename without `.md`.\n *\n * A projected coordinator keeps its full `orchestrator-<x>` name in `.claude/agents/`: coordinators are\n * never `subagent-<x>` files, so the prefix stripping that applies to every specialist role is a no-op\n * here. We still route through the projector's own helper so the launcher and the renderer can never\n * diverge if a bundle ever declares a differently-prefixed orchestrator.\n */\n public static resolveCoordinatorName(orchestrator?: string): string {\n const file = (orchestrator && orchestrator.trim().length > 0 ? orchestrator.trim() : DEFAULT_COORDINATOR)\n .replace(/\\.md$/i, '');\n return ClaudeProjector.stripSubagentPrefix(path.basename(file));\n }\n\n /**\n * Resolve an installed bundle for Claude Code activation. Mirrors `ClineLauncher.resolveInstallation`:\n * same global→project fallback, same `.agents/agents-united.json` lockfile path, same error text.\n */\n public async resolveInstallation(\n bundleName: string,\n options: ResolveClaudeInstallationOptions = {}\n ): Promise<{ scope: InstallScope; workspace: string; lockfile: LockfileManifest; manifestPath: string }> {\n const cwd = options.cwd || process.cwd();\n const isGlobal = !!options.global;\n\n let targetDir: string;\n let scope: InstallScope;\n let workspace: string;\n\n // Plan 023 B (ADR 0022) — the state dir is the `.agents/` store or the store-less sidecar.\n if (isGlobal) {\n targetDir = resolveStateDir('global');\n scope = 'global';\n workspace = os.homedir();\n } else {\n workspace = cwd;\n targetDir = resolveStateDir('project', undefined, { cwd });\n scope = 'project';\n }\n\n const lockfilePath = path.join(targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n if (!isGlobal) {\n // Check if global installation exists as fallback\n const globalTarget = resolveStateDir('global');\n const globalLockfile = path.join(globalTarget, 'agents-united.json');\n if (await fs.pathExists(globalLockfile)) {\n const gLock: LockfileManifest = await fs.readJson(globalLockfile);\n if (gLock.installed?.bundles?.includes(bundleName)) {\n return this.resolveInstallation(bundleName, { ...options, global: true });\n }\n }\n }\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n if (!lockfile.installed?.bundles?.includes(bundleName)) {\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n // Host gate. The Cline lane requires both the recorded fanout and the projected artifact. The Claude\n // lane is satisfied by either signal: the host-neutral Team Manifest under `.agents/plugins/<bundle>/`\n // is the artifact the bootstrap prompt actually reads, and it is emitted by the compound lane, while\n // `fanout: ['claude']` is the recorded host signal. Requiring both would make\n // `agents start --host claude --dry-run` fail in a workspace whose install predates the Claude lane,\n // which is exactly the case the dry-run exists to preview. A workspace with neither signal is not\n // projected at all and gets the same actionable remedy the Cline lane prints.\n const hasClaudeFanout = (lockfile.fanout || []).includes('claude');\n const manifestRel = `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n const manifestPath = path.join(workspace, manifestRel);\n\n if (!hasClaudeFanout && !await fs.pathExists(manifestPath)) {\n throw new Error(\n `Bundle '${bundleName}' is not projected to Claude. Run 'agents update ${bundleName} --fanout claude' first.`\n );\n }\n\n return {\n scope,\n workspace,\n lockfile,\n manifestPath,\n };\n }\n\n /**\n * Plan the argv, bootstrap prompt and ephemeral environment for a Claude Code session. Pure: no process\n * is spawned and nothing is written to disk, so `--dry-run` can call it safely.\n */\n public planActivation(options: PlanClaudeActivationOptions): ClaudeActivationPlan {\n const {\n bundleName,\n workspace,\n scope,\n report,\n prompt,\n orchestrator,\n allowAddons,\n background,\n teams,\n pluginDir,\n manifestAvailable,\n } = options;\n\n const command = report.command || {\n executable: 'claude',\n prefixArgs: [],\n source: 'path-executable' as const,\n };\n\n const coordinatorName = ClaudeLauncher.resolveCoordinatorName(orchestrator);\n const homePrefix = scope === 'global' ? '~/' : '';\n const manifestRel = `${homePrefix}.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n // The projected coordinator definition. Read-only reference: this launcher never writes under\n // `.claude/**` — the projection engine owns that namespace.\n const coordinatorRel = `${homePrefix}.claude/agents/${coordinatorName}.md`;\n\n const addonPolicyText = allowAddons\n ? 'Addon auto-installation is pre-authorized for this session.'\n : `Before installing any recommended addon, explain the requirement to the user and request explicit confirmation to run: agents add <addon> -t claude ${scope === 'global' ? '-g ' : ''}-y.`;\n\n const deploymentNoteText =\n `Deployment note: this bundle is already projected natively for this workspace - roles in \"${homePrefix}.claude/agents/\", ` +\n `skills in \"${homePrefix}.claude/skills/\" and rules in \"${homePrefix}.claude/rules/\". The single source of truth stays the ` +\n `canonical store under \"${homePrefix}.agents/\" (ADR 0018): read the projections, edit the canonical files, never the copies.`;\n\n // Ordinary Claude sessions delegate by description; a `--agent` session runs this coordinator's own\n // projected definition on the main thread, which is the only way the real `Agent(...)` allowlist\n // (specialist type names) is enforced.\n const delegationNoteText =\n `Delegation on this host works by description: in an ordinary Claude Code session you name a specialist and Claude ` +\n `picks the matching definition from \"${homePrefix}.claude/agents/\". This session was started with \\`claude --agent ${coordinatorName}\\`, ` +\n `so your own projected coordinator definition runs on the main thread and the real \\`Agent(...)\\` allowlist in its ` +\n `frontmatter is what bounds the specialists you may delegate to - send work only to those exact agent type names.`;\n\n const taskText = prompt && prompt.trim().length > 0\n ? `User task: ${prompt.trim()}`\n : 'Please introduce your coordinator role to the user and ask for their first task.';\n\n // ADR 0018 decision 6 keeps ONE host-neutral team manifest, emitted under the organization\n // package and never duplicated into `.claude/`. That package is written by the Cline half of\n // the compound lane, so a claude-only fanout legitimately has no manifest on disk: pointing a\n // coordinator at a path that does not exist would make its first instruction fail. When the\n // caller reports the manifest is absent, the prompt falls back to the roster Claude actually\n // discovers — the projected agent definitions in `.claude/agents/`.\n const manifestInstruction = manifestAvailable === false\n ? `Read your coordinator role definition at \"${coordinatorRel}\" before acting. Specialist roles are ` +\n `discoverable by name and description from the projected definitions in \"${homePrefix}.claude/agents/\" ` +\n `(the host-neutral team manifest is not present in this workspace yet - it is written by a ` +\n `\\`--fanout cline\\` install).`\n : `Read the Team Manifest at \"${manifestRel}\" and your coordinator role definition at \"${coordinatorRel}\" before acting.`;\n\n const bootstrapLines = [\n `You are coordinating the \"${bundleName}\" team in Agents United.`,\n manifestInstruction,\n delegationNoteText,\n 'Use specialist roles only when necessary.',\n addonPolicyText,\n deploymentNoteText,\n taskText,\n ];\n\n if (teams === true) {\n // ADR 0018 decision 13 / Plan 016 decision 14 — the teams scaffold is experimental, minimal and never\n // load-bearing. This instruction text deliberately never names the opt-in environment variable: the\n // variable is injected into the spawned process environment only and must not appear in argv, so it can\n // never leak into a prompt, a shell echo or a transcript.\n bootstrapLines.push(\n `Agent teams are enabled for this session as an EXPERIMENTAL scaffold: spawn teammates from the projected agent ` +\n `types by name - the names you see in \"${homePrefix}.claude/agents/\" (specialists are projected with their ` +\n `\"subagent-\" prefix stripped, e.g. \\`backend-architect\\`). The scaffold is deliberately minimal: exactly one team per ` +\n `session, you are the fixed lead, there is no nested teams and no session resumption, and nothing about it is ` +\n `persisted to disk. Never make it load-bearing - if a teammate cannot be spawned, continue with ordinary delegated ` +\n `subagents using the Agent tool.`\n );\n }\n\n const bootstrapPrompt = bootstrapLines.join('\\n\\n');\n\n // ADR 0018 decision 13 / Plan 016 decision 14: the opt-in is injected EPHEMERALLY into the spawned\n // process environment only. It is never written to `.claude/settings.json`, never recorded in a lockfile\n // or any other workspace file, nothing is written under `~/.claude/teams/`, and the variable name must\n // never appear in argv. `env` is otherwise empty - the launcher merges it over `process.env` at spawn.\n const env: Record<string, string> = {};\n if (teams === true) {\n env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = '1';\n }\n\n const argv: string[] = [...command.prefixArgs];\n // `--agent` names the projected coordinator definition. The projected file in `.claude/agents/` keeps its\n // full `orchestrator-<x>` name - the `subagent-` prefix stripping that applies to every specialist role is\n // a no-op for coordinators - so this value MUST equal the projected file basename without `.md`.\n argv.push('--agent');\n argv.push(coordinatorName);\n argv.push('--add-dir');\n argv.push(workspace);\n if (background === true) {\n argv.push('--bg');\n }\n if (pluginDir) {\n argv.push('--plugin-dir');\n argv.push(pluginDir);\n }\n argv.push(bootstrapPrompt);\n\n return {\n bundleName,\n scope,\n workspace,\n executable: command.executable,\n argv,\n bootstrapPrompt,\n env,\n };\n }\n\n /**\n * Launch the Claude Code session from the argv array. Mirrors `ClineLauncher.launch`: `shell: false`\n * (never `shell: true`), `stdio: 'inherit'`, and the plan's ephemeral env merged over `process.env`.\n */\n public async launch(plan: ClaudeActivationPlan): Promise<void> {\n const { spawn } = await import('node:child_process');\n const child = spawn(plan.executable, plan.argv, {\n cwd: plan.workspace,\n stdio: 'inherit',\n shell: false,\n env: { ...process.env, ...plan.env },\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('error', reject);\n child.on('exit', (code) => {\n if (code === 0 || code === null) {\n resolve();\n } else {\n resolve(); // return cleanly on process exit\n }\n });\n });\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { AntigravityCapabilityProbe } from './antigravity-capabilities.js';\nimport { defaultProcessRunner } from './cline-capabilities.js';\nimport { resolveStateDir } from './state-dir.js';\nimport type {\n AntigravityCapabilityReport,\n InstallScope,\n LockfileManifest,\n ProcessRunner,\n} from './types.js';\n\n/** Default coordinator when the caller could not resolve the bundle's own `orchestrator` field. */\nconst DEFAULT_COORDINATOR = 'orchestrator-engineering.md';\n\nexport interface AntigravityActivationPlan {\n bundleName: string;\n scope: InstallScope;\n workspace: string;\n executable: string;\n argv: string[];\n bootstrapPrompt: string;\n env: Record<string, string>;\n}\n\nexport interface PlanAntigravityActivationOptions {\n bundleName: string;\n workspace: string;\n scope: InstallScope;\n report: AntigravityCapabilityReport;\n /** The opening prompt, passed as one `--prompt-interactive` argument. Omitted ⇒ no opening prompt. */\n prompt?: string;\n /** Optional coordinator agent filename (e.g. \"orchestrator-universal.md\"). Resolved from the bundle\n * definition by the caller; defaults to orchestrator-engineering.md for backward compatibility. */\n orchestrator?: string;\n}\n\nexport interface ResolveAntigravityInstallationOptions {\n scope?: InstallScope;\n global?: boolean;\n cwd?: string;\n}\n\n/**\n * Plan 029 B6 / Objective 6 — the Antigravity activation lane, mirroring `ClaudeLauncher` in shape\n * (same constructor seam, same resolve/plan/launch split, same argv-array discipline with\n * `shell: false`).\n *\n * Two hard boundaries carried by this file:\n * 1. The launcher only ever *describes* a session. It writes no file, and the canonical\n * `.agents/**` tree it points at is installed by the `agents` host, never by this lane.\n * 2. Every value is one argv element. `--agent` and its value are pushed separately, and the\n * opening prompt is a single `--prompt-interactive` argument, so no prompt text is ever\n * word-split, shell-expanded or joined into a command string.\n *\n * The verified-live invocation (agy 1.2.12) is:\n * `agy --agent <bundle orchestrator> --prompt-interactive \"<opening prompt>\"`\n * `--print` / `-p` / `--prompt` are non-interactive and are deliberately never emitted.\n */\nexport class AntigravityLauncher {\n private probe: AntigravityCapabilityProbe;\n private runner: ProcessRunner;\n\n constructor(probe?: AntigravityCapabilityProbe, runner?: ProcessRunner) {\n this.probe = probe || new AntigravityCapabilityProbe();\n this.runner = runner || defaultProcessRunner;\n }\n\n /**\n * The `--agent` value must equal the canonical coordinator definition's basename without `.md`.\n *\n * Mirrors `ClaudeLauncher.resolveCoordinatorName` (same strip of a leading `subagent-` prefix and\n * the `.md` suffix) without importing the Claude lane: on Antigravity the canonical file under\n * `.agents/agents/` is installed verbatim, so its basename *is* the agent name.\n */\n public static resolveCoordinatorName(orchestrator?: string): string {\n const file = (orchestrator && orchestrator.trim().length > 0 ? orchestrator.trim() : DEFAULT_COORDINATOR)\n .replace(/\\.md$/i, '');\n return path.basename(file).replace(/^subagent-/, '');\n }\n\n /**\n * Resolve an installed bundle for Antigravity activation. Mirrors\n * `ClaudeLauncher.resolveInstallation`: same state-dir discovery (`.agents/` store or the\n * store-less sidecar), same global→project fallback, same error text.\n *\n * No host gate is applied here on purpose. The `agents` host IS the canonical store, so a bundle\n * present in this lockfile is by definition projected to the Antigravity lane; requiring a\n * separate fanout signal would make `agents start --host antigravity` fail on exactly the install\n * it is meant to launch. Whether the canonical coordinator file exists is checked by the caller\n * before anything is spawned.\n */\n public async resolveInstallation(\n bundleName: string,\n options: ResolveAntigravityInstallationOptions = {}\n ): Promise<{ scope: InstallScope; workspace: string; lockfile: LockfileManifest; manifestPath: string }> {\n const cwd = options.cwd || process.cwd();\n const isGlobal = !!options.global;\n\n let targetDir: string;\n let scope: InstallScope;\n let workspace: string;\n\n // Plan 023 B (ADR 0022) — the state dir is the `.agents/` store or the store-less sidecar.\n if (isGlobal) {\n targetDir = resolveStateDir('global');\n scope = 'global';\n workspace = os.homedir();\n } else {\n workspace = cwd;\n targetDir = resolveStateDir('project', undefined, { cwd });\n scope = 'project';\n }\n\n const lockfilePath = path.join(targetDir, 'agents-united.json');\n if (!await fs.pathExists(lockfilePath)) {\n if (!isGlobal) {\n // Check if global installation exists as fallback\n const globalTarget = resolveStateDir('global');\n const globalLockfile = path.join(globalTarget, 'agents-united.json');\n if (await fs.pathExists(globalLockfile)) {\n const gLock: LockfileManifest = await fs.readJson(globalLockfile);\n if (gLock.installed?.bundles?.includes(bundleName)) {\n return this.resolveInstallation(bundleName, { ...options, global: true });\n }\n }\n }\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n const lockfile: LockfileManifest = await fs.readJson(lockfilePath);\n if (!lockfile.installed?.bundles?.includes(bundleName)) {\n throw new Error(`Bundle '${bundleName}' is not installed in ${scope} scope.`);\n }\n\n const manifestRel = `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n\n return {\n scope,\n workspace,\n lockfile,\n manifestPath: path.join(workspace, manifestRel),\n };\n }\n\n /**\n * Plan the argv and bootstrap prompt for an Antigravity session. Pure: no process is spawned and\n * nothing is written to disk, so `--dry-run` can call it safely.\n */\n public planActivation(options: PlanAntigravityActivationOptions): AntigravityActivationPlan {\n const { bundleName, workspace, scope, report, prompt, orchestrator } = options;\n\n const command = report.command || {\n executable: 'agy',\n prefixArgs: [],\n source: 'path-executable' as const,\n };\n\n // Coordinator role = the bundle's declared orchestrator when available; falls back to\n // orchestrator-engineering.md only to preserve pre-existing behaviour. `.agents/agents/<name>.md`\n // is the canonical file installed by the `agents` host, so it is also the desktop-route target.\n const coordinatorName = AntigravityLauncher.resolveCoordinatorName(orchestrator);\n const coordinatorCanonical = `.agents/agents/${coordinatorName}.md`;\n\n const manifestRel = scope === 'global'\n ? `~/.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`\n : `.agents/plugins/${bundleName}/agents-united/teams/${bundleName}.yaml`;\n\n const taskText = prompt && prompt.trim().length > 0\n ? `User task: ${prompt.trim()}`\n : 'Please introduce your coordinator role to the user and ask for their first task.';\n\n const bootstrapPrompt = [\n `You are coordinating the \"${bundleName}\" team in Agents United.`,\n `Read the Team Manifest at \"${manifestRel}\" and your coordinator role definition at \"${coordinatorCanonical}\" before acting.`,\n `Delegate specialist work with the invoke_subagent tool; register a specialist with define_subagent only when it is not already reachable by name, and pass the canonical role body verbatim rather than a summary.`,\n `Use specialist roles only when necessary.`,\n `Before installing any recommended addon, explain the requirement to the user and request explicit confirmation to run: agents add <addon> -t agents -y.`,\n taskText,\n ].join('\\n\\n');\n\n const env: Record<string, string> = {};\n\n const argv: string[] = [...command.prefixArgs];\n // `--agent` names the canonical coordinator definition under `.agents/agents/`.\n argv.push('--agent');\n argv.push(coordinatorName);\n // An opening prompt CAN be passed on this CLI (verified live: `-i, --prompt-interactive`). The\n // flag is emitted whenever a prompt exists rather than gated on the probe's help-derived flag:\n // help text can be unavailable while the flag itself is still present, and silently dropping the\n // user's task would be worse than an explicit failure. The caller reports an unverified flag.\n if (prompt && prompt.trim().length > 0) {\n argv.push('--prompt-interactive');\n argv.push(prompt);\n }\n\n return {\n bundleName,\n scope,\n workspace,\n executable: command.executable,\n argv,\n bootstrapPrompt,\n env,\n };\n }\n\n /**\n * Launch the Antigravity session from the argv array. Mirrors `ClaudeLauncher.launch`: no shell is\n * ever used to interpret the command (`shell: false` on the spawn options below), `stdio: 'inherit'`,\n * and the plan's ephemeral env merged over `process.env`.\n */\n public async launch(plan: AntigravityActivationPlan): Promise<void> {\n const { spawn } = await import('node:child_process');\n const child = spawn(plan.executable, plan.argv, {\n cwd: plan.workspace,\n stdio: 'inherit',\n shell: false,\n env: { ...process.env, ...plan.env },\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('error', reject);\n child.on('exit', () => {\n resolve(); // return cleanly on process exit\n });\n });\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport { defaultProcessRunner } from './cline-capabilities.js';\nimport type {\n AntigravityCapabilityReport,\n ProcessRunner,\n ResolvedAgyCommand,\n} from './types.js';\n\nexport interface AntigravityProbeResolverOptions {\n resolveExecutable?: () => ResolvedAgyCommand | null;\n}\n\n/**\n * Plan 029 B6 / Objective 6 — side-effect-free Antigravity CLI (`agy`) capability probe.\n *\n * Mirrors `ClaudeCapabilityProbe` structurally (same constructor seam, same never-throws contract,\n * same argv-array discipline through the shared `defaultProcessRunner`). The probe runs **exactly\n * two** commands, in this order and no others:\n *\n * 1. `<exe> [...prefixArgs, '--version']`\n * 2. `<exe> [...prefixArgs, '--help']`\n *\n * Deliberate non-goals, restated because they are the whole point of the design:\n * - no `agy --agent ... --prompt-interactive ...` run — that opens an interactive session and can\n * mutate the workspace;\n * - no `agy --print` / `-p` headless turn — that costs tokens (and is explicitly not a\n * conformance target of Plan 029);\n * - no `agy mcp list` — the MCP surface belongs to `agents doctor`, not to a probe.\n * `--help` text is the only source of truth for the flag surface, so an unverifiable capability is\n * reported as unsupported with a diagnostic rather than assumed.\n *\n * Executable resolution order: an absolute, existing `AGY_BIN_PATH` wins, then a PATH scan\n * (`agy.exe` / `agy.cmd` / `agy.bat` / `agy` on Windows, `agy` on POSIX). A `.cmd`/`.bat` hit is\n * bridged through `cmd.exe` exactly like the Cline/Claude probes (ADR 0013 §5): Node >= 18.20 /\n * 20.12 / 24 rejects spawning shell shims with `shell: false` (EINVAL). There is deliberately **no**\n * hard-coded install-location fallback — a machine-specific path would make the probe's answer\n * depend on whose machine it runs on; `AGY_BIN_PATH` is the documented escape hatch for an `agy`\n * that is not on PATH.\n */\n\n/**\n * The live-verified floor: `agy 1.2.12` (Windows, probed 2026-09-28) is the release on which\n * `--agent <name>`, `-i, --prompt-interactive` and `--mode <accept-edits|plan>` were confirmed.\n * Reported as data, never as a gate — the probe's `installed` flag stays a pure `--version` signal.\n */\nconst AGY_MIN_VERSION = { major: 1, minor: 2, patch: 12 } as const;\n\nfunction meetsVersionFloor(version: string | undefined): boolean {\n if (!version) return false;\n const match = version.match(/(\\d+)\\.(\\d+)\\.(\\d+)/);\n if (!match) return false;\n const [major, minor, patch] = [Number(match[1]), Number(match[2]), Number(match[3])];\n if (major !== AGY_MIN_VERSION.major) return major > AGY_MIN_VERSION.major;\n if (minor !== AGY_MIN_VERSION.minor) return minor > AGY_MIN_VERSION.minor;\n return patch >= AGY_MIN_VERSION.patch;\n}\n\n/** Values advertised after the `--mode <mode>` placeholder (e.g. `accept-edits, plan`). */\nfunction parseModeValues(help: string): string[] {\n const line = help.split('\\n').find(candidate => /--mode\\b/.test(candidate));\n if (!line) return [];\n const afterPlaceholder = line.includes('>') ? line.slice(line.indexOf('>') + 1) : line;\n return Array.from(\n new Set(\n afterPlaceholder\n .split(',')\n .map(value => value.trim())\n .filter(value => /^[a-z][a-z-]*$/.test(value))\n )\n );\n}\n\n\nexport class AntigravityCapabilityProbe {\n private runner: ProcessRunner;\n private customResolver?: () => ResolvedAgyCommand | null;\n\n constructor(runner?: ProcessRunner, options?: AntigravityProbeResolverOptions) {\n this.runner = runner || defaultProcessRunner;\n this.customResolver = options?.resolveExecutable;\n }\n\n /**\n * Safe executable resolution across POSIX and Windows layouts.\n */\n public resolveExecutable(): ResolvedAgyCommand | null {\n if (this.customResolver) {\n return this.customResolver();\n }\n\n // 1. Explicit AGY_BIN_PATH (mirrors CLAUDE_BIN_PATH: absolute + existing wins).\n const envBin = process.env.AGY_BIN_PATH;\n if (envBin && path.isAbsolute(envBin) && fs.existsSync(envBin)) {\n return {\n executable: envBin,\n prefixArgs: [],\n source: 'env-binary',\n };\n }\n\n // 2. PATH scanning\n const pathEnv = process.env.PATH || '';\n const pathSeparator = process.platform === 'win32' ? ';' : ':';\n const dirs = pathEnv.split(pathSeparator).filter(Boolean);\n\n if (process.platform === 'win32') {\n const exeNames = ['agy.exe', 'agy.cmd', 'agy.bat', 'agy'];\n for (const dir of dirs) {\n for (const exeName of exeNames) {\n const fullPath = path.join(dir, exeName);\n if (!fs.existsSync(fullPath)) continue;\n\n // Windows hardening (ADR 0013 §5): route .cmd/.bat shims through cmd.exe while keeping\n // the argv array shell-safe.\n const ext = path.extname(fullPath).toLowerCase();\n if (ext === '.cmd' || ext === '.bat') {\n return {\n executable: 'cmd.exe',\n prefixArgs: ['/c', fullPath],\n source: 'path-executable',\n };\n }\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n } else {\n for (const dir of dirs) {\n const fullPath = path.join(dir, 'agy');\n if (fs.existsSync(fullPath)) {\n return {\n executable: fullPath,\n prefixArgs: [],\n source: 'path-executable',\n };\n }\n }\n }\n\n return null;\n }\n\n\n /**\n * Run the read-only capability probe against the local Antigravity CLI. Never throws: an absent\n * executable, a non-zero exit and a runner error are all reported as data.\n */\n public async probe(): Promise<AntigravityCapabilityReport> {\n const cmd = this.resolveExecutable();\n const diagnostics: string[] = [];\n\n if (!cmd) {\n diagnostics.push('Antigravity CLI (agy) not found on PATH or via AGY_BIN_PATH.');\n return {\n installed: false,\n agentFlag: false,\n promptInteractive: false,\n modes: [],\n meetsVersionFloor: false,\n diagnostics,\n };\n }\n\n // 1. Version check — `--version` only.\n let version: string | undefined;\n try {\n const verRes = await this.runner(cmd.executable, [...cmd.prefixArgs, '--version'], {\n timeoutMs: 5000,\n });\n\n if (verRes.exitCode === 0) {\n version = verRes.stdout.trim().split('\\n')[0]?.trim();\n } else {\n diagnostics.push(\n `Antigravity CLI version check failed (exit code ${verRes.exitCode}): ${verRes.stderr.trim()}`\n );\n return {\n installed: false,\n command: cmd,\n agentFlag: false,\n promptInteractive: false,\n modes: [],\n meetsVersionFloor: false,\n diagnostics,\n };\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Error executing Antigravity CLI version check: ${msg}`);\n return {\n installed: false,\n command: cmd,\n agentFlag: false,\n promptInteractive: false,\n modes: [],\n meetsVersionFloor: false,\n diagnostics,\n };\n }\n\n // 2. Flag surface — `--help` text only. No session, no headless turn, no MCP listing.\n let agentFlag = false;\n let promptInteractive = false;\n let modes: string[] = [];\n try {\n const helpRes = await this.runner(cmd.executable, [...cmd.prefixArgs, '--help'], {\n timeoutMs: 5000,\n });\n\n if (helpRes.exitCode === 0) {\n const help = helpRes.stdout;\n agentFlag = help.includes('--agent');\n promptInteractive = help.includes('--prompt-interactive');\n modes = parseModeValues(help);\n } else {\n diagnostics.push(\n `Antigravity CLI help probe returned non-zero (exit code ${helpRes.exitCode}); the --agent / --prompt-interactive / --mode surface could not be verified.`\n );\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n diagnostics.push(`Antigravity CLI help probe failed: ${msg}`);\n }\n\n return {\n installed: true,\n version,\n command: cmd,\n agentFlag,\n promptInteractive,\n modes,\n meetsVersionFloor: meetsVersionFloor(version),\n diagnostics,\n };\n }\n}\n","import path from 'node:path';\nimport os from 'node:os';\nimport fs from 'fs-extra';\nimport { McpLocationRegistry, type DiscoveredMcpConfig } from './mcp-locations.js';\nimport type {\n BundleDefinition,\n PrerequisiteEvaluation,\n PrerequisiteItemCheck,\n BundlePrerequisites,\n AgentHost,\n} from './types.js';\n\nexport interface PrerequisiteCheckOptions {\n cwd?: string;\n env?: Record<string, string | undefined>;\n targetHosts?: (AgentHost | string)[];\n}\n\nexport interface DiscoveredConfigFile {\n host: 'gemini' | 'cursor' | 'cline' | 'claude' | 'opencode' | 'custom' | string;\n label: string;\n path: string;\n exists: boolean;\n serverCount?: number;\n}\n\nexport interface McpCheckResult {\n configured: boolean;\n host?: string;\n location?: string;\n disabled?: boolean;\n serverKey?: string;\n foundInConfigs: Array<{ id: string; host: string; label: string; path: string; disabled?: boolean; serverKey: string }>;\n missingInConfigs: Array<{ id: string; host: string; label: string; path: string }>;\n}\n\nexport class PrerequisiteChecker {\n /**\n * Discovers all candidate and existing MCP configuration files across AI hosts\n */\n public static async discoverHostConfigFiles(cwd: string = process.cwd()): Promise<DiscoveredConfigFile[]> {\n const discovered = await McpLocationRegistry.discoverAll(cwd);\n return discovered.map(d => ({\n host: d.host,\n label: d.label,\n path: d.path,\n exists: d.exists,\n serverCount: d.serverCount,\n }));\n }\n\n /**\n * Helper that checks if a configured MCP server key or its configuration payload matches the target MCP name\n */\n public static matchesMcpServer(targetMcpName: string, serverKey: string, serverConfig: any = {}): boolean {\n const targetNorm = targetMcpName.toLowerCase().replace(/[^a-z0-9]/g, '');\n const keyNorm = serverKey.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n // 1. Direct or Substring Key Match (e.g. \"github-mcp-server\" -> \"github\", \"StitchMCP\" -> \"stitch\")\n if (keyNorm === targetNorm) return true;\n if (keyNorm.includes(targetNorm)) return true;\n if (targetNorm.includes(keyNorm)) return true;\n\n // Stripping common prefixes / suffixes: mcp, server, mcpserver, domain prefixes\n const strippedKey = keyNorm\n .replace(/^githubcom/g, '')\n .replace(/^mcp/g, '')\n .replace(/mcp$/g, '')\n .replace(/^server/g, '')\n .replace(/server$/g, '');\n if (strippedKey === targetNorm || (strippedKey.length > 2 && targetNorm.includes(strippedKey)) || (targetNorm.length > 2 && strippedKey.includes(targetNorm))) {\n return true;\n }\n\n // 2. Executable / Package Signature Match (in command or args)\n const cmd = String(serverConfig?.command || '').toLowerCase();\n const args = Array.isArray(serverConfig?.args)\n ? serverConfig.args.map((a: any) => String(a).toLowerCase()).join(' ')\n : '';\n const fullExec = `${cmd} ${args}`;\n\n if (targetMcpName === 'github') {\n if (fullExec.includes('github') || fullExec.includes('ghcr.io/github')) return true;\n }\n if (targetMcpName === 'playwright') {\n if (fullExec.includes('playwright')) return true;\n }\n if (targetMcpName === 'markitdown') {\n if (fullExec.includes('markitdown')) return true;\n }\n if (targetMcpName === 'chrome-devtools-mcp' || targetMcpName === 'chrome-devtools') {\n if (fullExec.includes('chrome-devtools')) return true;\n }\n if (targetMcpName === 'stitch') {\n if (fullExec.includes('stitch') || fullExec.includes('stitch.googleapis.com')) return true;\n }\n if (targetMcpName === 'figma') {\n if (fullExec.includes('figma')) return true;\n }\n if (targetMcpName === 'firecrawl') {\n if (fullExec.includes('firecrawl')) return true;\n }\n if (targetMcpName === 'context7') {\n if (fullExec.includes('context7')) return true;\n }\n if (targetMcpName === 'supabase') {\n if (fullExec.includes('supabase')) return true;\n }\n\n // 3. Endpoint / URL Signature Match (in url or serverUrl)\n const url = String(serverConfig?.url || serverConfig?.serverUrl || '').toLowerCase();\n if (url.includes(targetNorm)) return true;\n if (targetMcpName === 'stitch' && url.includes('stitch.googleapis.com')) return true;\n if (targetMcpName === 'context7' && url.includes('context7.com')) return true;\n if (targetMcpName === 'firecrawl' && url.includes('firecrawl.dev')) return true;\n if (targetMcpName === 'supabase' && url.includes('supabase.com')) return true;\n\n return false;\n }\n\n /**\n * Discovers whether an MCP server is configured across supported host runtimes\n * (Antigravity/Gemini, Cursor, Cline, Claude Code, etc.)\n */\n public static async isMcpConfigured(\n mcpName: string,\n cwd: string = process.cwd()\n ): Promise<McpCheckResult> {\n const discovered = await McpLocationRegistry.discoverAll(cwd);\n const foundInConfigs: McpCheckResult['foundInConfigs'] = [];\n const missingInConfigs: McpCheckResult['missingInConfigs'] = [];\n\n // 1. Check all discovered configuration files\n for (const file of discovered) {\n if (!file.exists) {\n missingInConfigs.push({\n id: file.id,\n host: file.host,\n label: file.label,\n path: file.path,\n });\n continue;\n }\n\n let matched = false;\n if (file.servers && typeof file.servers === 'object') {\n for (const [key, serverDef] of Object.entries(file.servers)) {\n if (PrerequisiteChecker.matchesMcpServer(mcpName, key, serverDef)) {\n const isDisabled = (serverDef as any)?.disabled === true;\n foundInConfigs.push({\n id: file.id,\n host: file.host,\n label: file.label,\n path: file.path,\n disabled: isDisabled,\n serverKey: key,\n });\n matched = true;\n break;\n }\n }\n }\n\n if (!matched) {\n missingInConfigs.push({\n id: file.id,\n host: file.host,\n label: file.label,\n path: file.path,\n });\n }\n }\n\n // 2. Also check directory-based MCP definitions (e.g. Antigravity folder ~/.gemini/antigravity/mcp/<serverName>)\n const homeDir = os.homedir();\n const dirCandidates = [\n path.join(cwd, '.gemini', 'antigravity', 'mcp'),\n path.join(homeDir, '.gemini', 'antigravity', 'mcp'),\n ];\n for (const dir of dirCandidates) {\n if (await fs.pathExists(dir)) {\n const entries = await fs.readdir(dir).catch(() => []);\n for (const entry of entries) {\n if (PrerequisiteChecker.matchesMcpServer(mcpName, entry, {})) {\n foundInConfigs.push({\n id: 'antigravity-dir',\n host: 'gemini',\n label: 'Google Antigravity MCP Directory',\n path: path.join(dir, entry),\n disabled: false,\n serverKey: entry,\n });\n break;\n }\n }\n }\n }\n\n const isConfigured = foundInConfigs.length > 0;\n const firstFound = foundInConfigs[0];\n\n return {\n configured: isConfigured,\n host: firstFound?.host,\n location: firstFound?.path,\n disabled: firstFound?.disabled,\n serverKey: firstFound?.serverKey,\n foundInConfigs,\n missingInConfigs,\n };\n }\n\n /**\n * Checks if an npm package is installed in node_modules or declared in package.json\n */\n public static async isPackageInstalled(\n pkgName: string,\n cwd: string = process.cwd()\n ): Promise<{ installed: boolean; location?: string }> {\n // 1. Direct node_modules check\n const modulePath = path.join(cwd, 'node_modules', ...pkgName.split('/'));\n if (await fs.pathExists(modulePath)) {\n return { installed: true, location: modulePath };\n }\n\n // 2. package.json dependencies check\n const pkgJsonPath = path.join(cwd, 'package.json');\n if (await fs.pathExists(pkgJsonPath)) {\n try {\n const pkg = await fs.readJson(pkgJsonPath);\n const deps = {\n ...pkg.dependencies,\n ...pkg.devDependencies,\n ...pkg.peerDependencies,\n };\n if (deps[pkgName]) {\n return { installed: true, location: pkgJsonPath };\n }\n } catch {\n // Ignore malformed package.json\n }\n }\n\n return { installed: false };\n }\n\n /**\n * Checks if an environment variable is defined in process.env or local .env files\n */\n public static async isEnvVarSet(\n varName: string,\n cwd: string = process.cwd(),\n customEnv?: Record<string, string | undefined>\n ): Promise<{ set: boolean; source?: string }> {\n const envSource = customEnv || process.env;\n if (envSource[varName] && envSource[varName]?.trim() !== '') {\n return { set: true, source: 'process.env' };\n }\n\n // Check local .env and .env.local in cwd\n const envFiles = [\n path.join(cwd, '.env.local'),\n path.join(cwd, '.env'),\n ];\n\n for (const envFile of envFiles) {\n if (await fs.pathExists(envFile)) {\n try {\n const content = await fs.readFile(envFile, 'utf8');\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith('#') || !trimmed.includes('=')) continue;\n const [k, ...v] = trimmed.split('=');\n if (k.trim() === varName && v.join('=').trim() !== '') {\n return { set: true, source: path.basename(envFile) };\n }\n }\n } catch {\n // Ignore read errors\n }\n }\n }\n\n return { set: false };\n }\n\n /**\n * Evaluates all prerequisites declared on a bundle, supporting target host scoping and multi-host partial breakdowns\n */\n public async evaluate(\n bundle: BundleDefinition,\n options: PrerequisiteCheckOptions = {}\n ): Promise<PrerequisiteEvaluation> {\n const cwd = options.cwd || process.cwd();\n const env = options.env || process.env;\n const tier = bundle.tier || 'domain';\n const prereqs: BundlePrerequisites = bundle.prerequisites || {};\n\n const targetHosts = options.targetHosts || ['agents'];\n const targetHostKeys = new Set(targetHosts.map(h => (h === 'agents' ? 'gemini' : h)));\n\n const items: PrerequisiteItemCheck[] = [];\n\n // 1. Evaluate Required MCPs\n if (prereqs.requiredMcps && prereqs.requiredMcps.length > 0) {\n for (const mcp of prereqs.requiredMcps) {\n const check = await PrerequisiteChecker.isMcpConfigured(mcp.name, cwd);\n\n // Discovered configs filtered by target host(s)\n const relevantFound = check.foundInConfigs.filter(c => targetHostKeys.has(c.host));\n const hostCleanNames: Record<string, string> = {\n gemini: 'Google Antigravity',\n agents: 'Google Antigravity',\n cline: 'Cline',\n cursor: 'Cursor',\n claude: 'Claude Code',\n opencode: 'OpenCode',\n windsurf: 'Windsurf',\n };\n\n const detectedHostLabels = Array.from(new Set(relevantFound.map(c => hostCleanNames[c.host] || c.host)));\n const detectedHostKeys = new Set(relevantFound.map(c => c.host));\n const missingHostKeys = Array.from(targetHostKeys).filter(h => !detectedHostKeys.has(h));\n const missingHostLabels = missingHostKeys.map(h => hostCleanNames[h] || h);\n\n let satisfied = false;\n let status: 'ok' | 'missing' | 'partial' = 'missing';\n let details = 'Not found in host MCP configuration';\n\n if (relevantFound.length > 0 && missingHostKeys.length === 0) {\n satisfied = true;\n status = 'ok';\n details = `Configured in ${detectedHostLabels.join(', ')}`;\n } else if (relevantFound.length > 0 && missingHostKeys.length > 0) {\n satisfied = false;\n status = 'partial';\n details = `Detected in ${detectedHostLabels.join(', ')}; Missing in ${missingHostLabels.join(', ')}`;\n } else if (check.foundInConfigs.length > 0 && relevantFound.length === 0) {\n const otherLabels = Array.from(new Set(check.foundInConfigs.map(c => hostCleanNames[c.host] || c.host)));\n satisfied = false;\n status = 'partial';\n details = `Detected in ${otherLabels.join(', ')}; Missing in target (${Array.from(targetHostKeys).map(h => hostCleanNames[h] || h).join(', ')})`;\n }\n\n items.push({\n type: 'mcp',\n name: mcp.name,\n purpose: mcp.purpose,\n satisfied,\n status,\n details,\n optionalForBrainstorming: mcp.optionalForBrainstorming ?? true,\n detectedInHosts: detectedHostLabels,\n missingInHosts: missingHostLabels,\n });\n }\n }\n\n // 2. Evaluate Required Packages\n if (prereqs.requiredPackages && prereqs.requiredPackages.length > 0) {\n for (const pkg of prereqs.requiredPackages) {\n const check = await PrerequisiteChecker.isPackageInstalled(pkg, cwd);\n items.push({\n type: 'package',\n name: pkg,\n satisfied: check.installed,\n status: check.installed ? 'ok' : 'missing',\n details: check.installed ? 'Installed in workspace' : 'Not found in node_modules or package.json',\n optionalForBrainstorming: false,\n });\n }\n }\n\n // 3. Evaluate Required Environment Variables\n if (prereqs.requiredEnvVars && prereqs.requiredEnvVars.length > 0) {\n for (const envVar of prereqs.requiredEnvVars) {\n const check = await PrerequisiteChecker.isEnvVarSet(envVar, cwd, env);\n items.push({\n type: 'env',\n name: envVar,\n satisfied: check.set,\n status: check.set ? 'ok' : 'missing',\n details: check.set ? `Defined in ${check.source}` : 'Environment variable not set',\n optionalForBrainstorming: true,\n });\n }\n }\n\n const hasPrerequisites = items.length > 0;\n const allSatisfied = items.length === 0 || items.every(i => i.satisfied);\n const operationalPossible = allSatisfied;\n\n return {\n bundleName: bundle.name,\n tier,\n hasPrerequisites,\n allSatisfied,\n operationalPossible,\n items,\n modes: bundle.modes,\n };\n }\n\n /**\n * Returns canonical command and environment definitions for known MCP servers\n */\n public static getMcpDefinition(\n mcpName: string,\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): { command: string; args: string[]; env?: Record<string, string> } {\n const norm = mcpName.trim().toLowerCase();\n switch (norm) {\n case 'github':\n return {\n command: 'npx',\n args: ['-y', '@modelcontextprotocol/server-github'],\n ...(mode === 'operational' && (envVars.GITHUB_PERSONAL_ACCESS_TOKEN || process.env.GITHUB_PERSONAL_ACCESS_TOKEN)\n ? { env: { GITHUB_PERSONAL_ACCESS_TOKEN: envVars.GITHUB_PERSONAL_ACCESS_TOKEN || process.env.GITHUB_PERSONAL_ACCESS_TOKEN || '' } }\n : {}),\n };\n case 'firecrawl':\n return {\n command: 'npx',\n args: ['-y', 'firecrawl-mcp'],\n ...(mode === 'operational' && (envVars.FIRECRAWL_API_KEY || process.env.FIRECRAWL_API_KEY)\n ? { env: { FIRECRAWL_API_KEY: envVars.FIRECRAWL_API_KEY || process.env.FIRECRAWL_API_KEY || '' } }\n : mode === 'limited-operational' && envVars.FIRECRAWL_API_URL\n ? { env: { FIRECRAWL_API_URL: envVars.FIRECRAWL_API_URL } }\n : {}),\n };\n case 'context7':\n return {\n command: 'npx',\n args: ['-y', '@upstash/context7-mcp'],\n ...(mode === 'operational' && envVars.UPSTASH_REDIS_REST_URL && envVars.UPSTASH_REDIS_REST_TOKEN\n ? { env: { UPSTASH_REDIS_REST_URL: envVars.UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN: envVars.UPSTASH_REDIS_REST_TOKEN } }\n : {}),\n };\n case 'playwright':\n return {\n command: 'npx',\n args: ['-y', '@executeautomation/playwright-mcp-server'],\n };\n case 'markitdown':\n return {\n command: 'uvx',\n args: ['markitdown-mcp'],\n };\n case 'chrome-devtools-mcp':\n case 'chrome-devtools':\n return {\n command: 'npx',\n args: ['-y', 'chrome-devtools-mcp'],\n };\n case 'stitch':\n return {\n command: 'npx',\n args: ['-y', 'mcp-remote', 'https://stitch.googleapis.com/mcp'],\n ...(mode === 'operational' && (envVars.STITCH_API_KEY || process.env.STITCH_API_KEY)\n ? { env: { STITCH_API_KEY: envVars.STITCH_API_KEY || process.env.STITCH_API_KEY || '' } }\n : {}),\n };\n case 'figma':\n return {\n command: 'npx',\n args: ['-y', 'ai-figma-mcp'],\n ...(mode === 'operational' && (envVars.FIGMA_ACCESS_TOKEN || process.env.FIGMA_ACCESS_TOKEN)\n ? { env: { FIGMA_ACCESS_TOKEN: envVars.FIGMA_ACCESS_TOKEN || process.env.FIGMA_ACCESS_TOKEN || '' } }\n : {}),\n };\n default:\n return {\n command: 'npx',\n args: ['-y', norm],\n };\n }\n }\n\n /**\n * Generates client-specific MCP configuration objects for Cursor, Cline, Claude, or Antigravity\n */\n public static generateClientConfig(\n client: 'cursor' | 'cline' | 'claude' | 'antigravity',\n mcpNames: string[],\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): Record<string, any> {\n const servers: Record<string, any> = {};\n\n for (const name of mcpNames) {\n const def = PrerequisiteChecker.getMcpDefinition(name, mode, envVars);\n if (client === 'cline') {\n servers[name] = {\n ...def,\n disabled: false,\n autoApprove: [],\n };\n } else {\n servers[name] = def;\n }\n }\n\n return { mcpServers: servers };\n }\n\n /**\n * Attempts to automatically provision a missing MCP server using the native CLI.\n */\n public static async provisionMcpServer(\n mcpName: string,\n options: { cwd?: string; env?: Record<string, string | undefined> } = {}\n ): Promise<{ success: boolean; output?: string }> {\n try {\n const { execSync } = await import('node:child_process');\n const cmd = `npx @antigravity/cli mcp add ${mcpName} --type stdio`;\n const output = execSync(cmd, { \n cwd: options.cwd || process.cwd(), \n env: options.env || process.env,\n encoding: 'utf8' \n });\n return { success: true, output };\n } catch (err: any) {\n return { success: false, output: err.message || String(err) };\n }\n }\n\n /**\n * Automatically configures missing MCP servers into a specific MCP JSON configuration file,\n * activating disabled servers and appending missing definitions.\n */\n public static async autoConfigureConfigFile(\n targetFilePath: string,\n mcpNames: string[],\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): Promise<{ success: boolean; targetFile: string; addedServers: string[]; enabledServers: string[] }> {\n await fs.ensureDir(path.dirname(targetFilePath));\n let existingConfig: any = {};\n if (await fs.pathExists(targetFilePath)) {\n try {\n existingConfig = await fs.readJson(targetFilePath);\n } catch {\n existingConfig = {};\n }\n }\n\n const isServersProp = Boolean(existingConfig.servers && !existingConfig.mcpServers);\n const existingServers = (isServersProp ? existingConfig.servers : existingConfig.mcpServers) || {};\n const addedServers: string[] = [];\n const enabledServers: string[] = [];\n\n for (const mcp of mcpNames) {\n let foundKey: string | null = null;\n for (const [key, serverDef] of Object.entries(existingServers)) {\n if (PrerequisiteChecker.matchesMcpServer(mcp, key, serverDef)) {\n foundKey = key;\n if ((serverDef as any)?.disabled === true) {\n (existingServers[key] as any).disabled = false;\n enabledServers.push(key);\n }\n break;\n }\n }\n\n if (!foundKey) {\n const def = PrerequisiteChecker.getMcpDefinition(mcp, mode, envVars);\n existingServers[mcp] = def;\n addedServers.push(mcp);\n }\n }\n\n if (isServersProp) {\n existingConfig.servers = existingServers;\n } else {\n existingConfig.mcpServers = existingServers;\n }\n\n await fs.writeJson(targetFilePath, existingConfig, { spaces: 2 });\n return {\n success: true,\n targetFile: targetFilePath,\n addedServers,\n enabledServers,\n };\n }\n\n /**\n * Automatically configures missing MCP servers into a specific AI host's configuration file.\n */\n public static async autoConfigureHost(\n host: string,\n mcpNames: string[],\n cwd: string = process.cwd(),\n mode: 'operational' | 'limited-operational' = 'operational',\n envVars: Record<string, string | undefined> = {}\n ): Promise<{ configured: boolean; targetFile: string; addedServers: string[] }> {\n const targetFile = McpLocationRegistry.getPrimaryWritePath(host as AgentHost, cwd);\n const res = await PrerequisiteChecker.autoConfigureConfigFile(targetFile, mcpNames, mode, envVars);\n return {\n configured: res.success,\n targetFile: res.targetFile,\n addedServers: [...res.addedServers, ...res.enabledServers],\n };\n }\n\n /**\n * Automatically installs missing NPM packages into the workspace.\n */\n public static async autoInstallPackages(\n packages: string[],\n cwd: string = process.cwd()\n ): Promise<{ success: boolean; output: string }> {\n try {\n const { execSync } = await import('node:child_process');\n const cmd = `npm install -D ${packages.join(' ')}`;\n const output = execSync(cmd, { cwd, encoding: 'utf8' });\n return { success: true, output };\n } catch (err: any) {\n return { success: false, output: err.message || String(err) };\n }\n }\n}\n"],"mappings":";;;AAAA,SAAS,WAAW;AACpB,OAAO,QAAQ;AACf,SAAS,OAAO,OAAO,SAAS,MAAM,KAAK,QAAQ,aAAa,SAAS,YAAY;AACrF,OAAOA,UAAQ;AACf,OAAOC,YAAU;;;ACJjB,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAG9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,KAAK,QAAQ,UAAU;AAElC,IAAM,mBAAN,MAAM,kBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,OAAwB,iBAAiB,CAAC,WAAW;AAAA,EA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AAI,uBAAuB,OAAO,mBAAmB,QAAQ,IAAI;AAAA,IAC5R,qBAAqB,eAAe,KAAK,IAAI,CAAC;AAAA,IAC9C,SAAS,KAAK,KAAK,MAAM;AAAA,IACzB,GAAG,KAAK,KAAK,IAAI,CAAC,KAAK,UAAU,MAAM,KAAK,KAAK,IAAI,QAAQ,UAAU,KAAK,CAAC,EAAE;AAAA,EACjF,EAAE,KAAK,IAAI;AACb;AAEA,IAAI,KAAK;AACT,IAAI,QAAQ,OAAO;AAEnB,IAAI,MAAM;","names":["fs","path","path","crypto","fs","path","path","path","yaml","path","fs","content","yaml","path","fs","FRONTMATTER_REGEX","yaml","text","path","fs","os","path","fs","os","path","fs","os","path","fs","text","path","fs","parse","fs","text","write","path","YAML","registry","fs","crypto","path","YAML","projections","relPath","path","crypto","fs","registry","fs","crypto","path","def","path","os","fs","registry","os","path","fs","path","crypto","fs","registry","scanner","installer","fs","crypto","path","path","fs","crypto","YAML","path","fs","path","fs","path","fs","path","os","fs","fs","crypto","path","YAML","text","path","os","crypto","fs","crypto","path","os","fs","path","os","fs","path","os","fs","path","os","fs","path","fs","path","fs","DEFAULT_COORDINATOR","path","os","fs","path","os","fs","os","path","fs","fs","path","text","s","targetBundleDef","lines","action"]}
|