agents-united 0.5.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/LICENSE +21 -0
- package/README.md +673 -0
- package/dist/cli.d.ts +5 -0
- package/dist/cli.js +4789 -0
- package/dist/cli.js.map +1 -0
- package/package.json +77 -0
- package/registry/agents/orchestrator-business.md +188 -0
- package/registry/agents/orchestrator-design.md +168 -0
- package/registry/agents/orchestrator-engineering.md +183 -0
- package/registry/agents/orchestrator-marketing.md +228 -0
- package/registry/agents/orchestrator-research.md +196 -0
- package/registry/agents/orchestrator-security.md +190 -0
- package/registry/agents/orchestrator-system-architecture.md +171 -0
- package/registry/agents/orchestrator-universal.md +168 -0
- package/registry/agents/subagent-accessibility-lead.md +47 -0
- package/registry/agents/subagent-ai-model-architect.md +97 -0
- package/registry/agents/subagent-android-architect.md +47 -0
- package/registry/agents/subagent-appsec-penetration-tester.md +189 -0
- package/registry/agents/subagent-backend-architect.md +360 -0
- package/registry/agents/subagent-business-panel-experts.md +126 -0
- package/registry/agents/subagent-cloud-infrastructure-architect.md +126 -0
- package/registry/agents/subagent-cloud-security-architect.md +221 -0
- package/registry/agents/subagent-code-reviewer.md +193 -0
- package/registry/agents/subagent-compliance-grc-specialist.md +147 -0
- package/registry/agents/subagent-cross-platform-specialist.md +47 -0
- package/registry/agents/subagent-data-engineer.md +46 -0
- package/registry/agents/subagent-database-administrator.md +141 -0
- package/registry/agents/subagent-deep-research.md +94 -0
- package/registry/agents/subagent-design-ops-lead.md +121 -0
- package/registry/agents/subagent-design-researcher.md +133 -0
- package/registry/agents/subagent-design-systems-architect.md +134 -0
- package/registry/agents/subagent-designer-toolkit-expert.md +363 -0
- package/registry/agents/subagent-devops-engineer.md +423 -0
- package/registry/agents/subagent-distributed-systems-architect.md +47 -0
- package/registry/agents/subagent-e2e-tester.md +60 -0
- package/registry/agents/subagent-financial-analyst.md +119 -0
- package/registry/agents/subagent-finops-cost-engineer.md +98 -0
- package/registry/agents/subagent-frontend-architect.md +368 -0
- package/registry/agents/subagent-interaction-designer.md +302 -0
- package/registry/agents/subagent-ios-architect.md +46 -0
- package/registry/agents/subagent-legal-contract-analyst.md +108 -0
- package/registry/agents/subagent-lifecycle-email-specialist.md +46 -0
- package/registry/agents/subagent-literature-patent-analyst.md +78 -0
- package/registry/agents/subagent-market-intelligence-analyst.md +110 -0
- package/registry/agents/subagent-marketing-campaign-specialist.md +80 -0
- package/registry/agents/subagent-marketing-content-strategist.md +184 -0
- package/registry/agents/subagent-marketing-conversion-specialist.md +79 -0
- package/registry/agents/subagent-marketing-creative-designer.md +93 -0
- package/registry/agents/subagent-marketing-growth-strategist.md +137 -0
- package/registry/agents/subagent-ml-platform-engineer.md +95 -0
- package/registry/agents/subagent-operations-strategist.md +85 -0
- package/registry/agents/subagent-paid-acquisition-specialist.md +47 -0
- package/registry/agents/subagent-plg-strategist.md +46 -0
- package/registry/agents/subagent-prototype-tester.md +140 -0
- package/registry/agents/subagent-qa-automation-lead.md +63 -0
- package/registry/agents/subagent-repo-index.md +180 -0
- package/registry/agents/subagent-security-engineer.md +134 -0
- package/registry/agents/subagent-seo-specialist.md +46 -0
- package/registry/agents/subagent-socratic-mentor.md +105 -0
- package/registry/agents/subagent-statistical-analyst.md +132 -0
- package/registry/agents/subagent-sysops-sre-lead.md +84 -0
- package/registry/agents/subagent-system-architect.md +122 -0
- package/registry/agents/subagent-ui-designer.md +149 -0
- package/registry/agents/subagent-ux-strategist.md +88 -0
- package/registry/bundles.json +1386 -0
- package/registry/rules/AGENTS.md +41 -0
- package/registry/rules/CLAUDE.md +12 -0
- package/registry/rules/CURSOR.md +12 -0
- package/registry/rules/GEMINI.md +41 -0
- package/registry/rules/clean-code-and-architecture.md +25 -0
- package/registry/rules/domain-modeling-and-adr.md +27 -0
- package/registry/rules/git-guardrails.md +19 -0
- package/registry/rules/multi-agent-coordination.md +33 -0
- package/registry/rules/quality-aesthetics-accessibility.md +29 -0
- package/registry/rules/skill-attribution.md +27 -0
- package/registry/rules/test-driven-development.md +41 -0
- package/registry/skills/ab-test-setup/SKILL.md +150 -0
- package/registry/skills/accessibility-audit/SKILL.md +150 -0
- package/registry/skills/ad-attribution-modeling/SKILL.md +206 -0
- package/registry/skills/ad-creative-design/SKILL.md +27 -0
- package/registry/skills/ai-prototype-refactoring/SKILL.md +29 -0
- package/registry/skills/architecture-design/SKILL.md +141 -0
- package/registry/skills/azure-infrastructure-bicep/SKILL.md +28 -0
- package/registry/skills/backend-api-design/SKILL.md +151 -0
- package/registry/skills/chaos-engineering/SKILL.md +41 -0
- package/registry/skills/churn-prevention-playbook/SKILL.md +181 -0
- package/registry/skills/ci-cd-pipeline-automation/SKILL.md +40 -0
- package/registry/skills/clickable-prototype-spec/SKILL.md +150 -0
- package/registry/skills/code-refactoring/SKILL.md +135 -0
- package/registry/skills/component-library-management/SKILL.md +150 -0
- package/registry/skills/component-playground-setup/SKILL.md +150 -0
- package/registry/skills/content-calendar-strategy/SKILL.md +150 -0
- package/registry/skills/conversion-funnel-optimization/SKILL.md +150 -0
- package/registry/skills/copywriting-frameworks/SKILL.md +150 -0
- package/registry/skills/database-design/SKILL.md +135 -0
- package/registry/skills/dependency-management/SKILL.md +142 -0
- package/registry/skills/design-handoff-spec/SKILL.md +150 -0
- package/registry/skills/design-ops-workflow/SKILL.md +150 -0
- package/registry/skills/design-system-governance/SKILL.md +150 -0
- package/registry/skills/design-system-tokens/SKILL.md +150 -0
- package/registry/skills/design-tokens-management/SKILL.md +150 -0
- package/registry/skills/design-version-control/SKILL.md +150 -0
- package/registry/skills/diagnosing-bugs/SKILL.md +45 -0
- package/registry/skills/docker-deployment/SKILL.md +144 -0
- package/registry/skills/domain-modeling/SKILL.md +52 -0
- package/registry/skills/email-drip-sequences/SKILL.md +181 -0
- package/registry/skills/email-marketing-automation/SKILL.md +150 -0
- package/registry/skills/finishing-a-development-branch/SKILL.md +132 -0
- package/registry/skills/frontend-component-design/SKILL.md +153 -0
- package/registry/skills/git-guardrails/SKILL.md +41 -0
- package/registry/skills/google-ads-optimization/SKILL.md +27 -0
- package/registry/skills/graphql-schema-design/SKILL.md +146 -0
- package/registry/skills/grill-me/SKILL.md +57 -0
- package/registry/skills/grill-with-docs/SKILL.md +84 -0
- package/registry/skills/growth-experiment-design/SKILL.md +150 -0
- package/registry/skills/handoff/SKILL.md +44 -0
- package/registry/skills/hf-model-evaluation/SKILL.md +84 -0
- package/registry/skills/interaction-pattern-library/SKILL.md +150 -0
- package/registry/skills/interactive-prototype-builder/SKILL.md +157 -0
- package/registry/skills/local-llm-inference/SKILL.md +77 -0
- package/registry/skills/maestro-mobile-testing/SKILL.md +40 -0
- package/registry/skills/marketing-creative-design/SKILL.md +186 -0
- package/registry/skills/mcp-setup/SKILL.md +370 -0
- package/registry/skills/meta-ad-creative-testing/SKILL.md +26 -0
- package/registry/skills/micro-interaction-design/SKILL.md +150 -0
- package/registry/skills/microservices-architecture/SKILL.md +141 -0
- package/registry/skills/mobile-android-design/SKILL.md +40 -0
- package/registry/skills/mobile-first-design/SKILL.md +150 -0
- package/registry/skills/mobile-ios-design/SKILL.md +40 -0
- package/registry/skills/mobile-platform-offline-validate/SKILL.md +41 -0
- package/registry/skills/modal-serverless-python/SKILL.md +81 -0
- package/registry/skills/onboarding-cro/SKILL.md +185 -0
- package/registry/skills/paid-acquisition-ppc/SKILL.md +171 -0
- package/registry/skills/performance-optimization/SKILL.md +141 -0
- package/registry/skills/playwright-best-practices/SKILL.md +39 -0
- package/registry/skills/product-launch-playbook/SKILL.md +150 -0
- package/registry/skills/programmatic-seo/SKILL.md +213 -0
- package/registry/skills/rag-vector-pipeline/SKILL.md +84 -0
- package/registry/skills/react-best-practices/SKILL.md +40 -0
- package/registry/skills/receiving-code-review/SKILL.md +130 -0
- package/registry/skills/replicate-model-inference/SKILL.md +76 -0
- package/registry/skills/requesting-code-review/SKILL.md +137 -0
- package/registry/skills/responsive-design-audit/SKILL.md +150 -0
- package/registry/skills/runpod-gpu-orchestration/SKILL.md +85 -0
- package/registry/skills/schema-markup-strategy/SKILL.md +194 -0
- package/registry/skills/security-audit/SKILL.md +139 -0
- package/registry/skills/seo-audit/SKILL.md +150 -0
- package/registry/skills/signup-flow-cro/SKILL.md +150 -0
- package/registry/skills/social-media-campaign/SKILL.md +150 -0
- package/registry/skills/state-driven-ui-animation/SKILL.md +150 -0
- package/registry/skills/subagent-driven-development/SKILL.md +135 -0
- package/registry/skills/supabase-backend-architecture/SKILL.md +28 -0
- package/registry/skills/systematic-debugging/SKILL.md +138 -0
- package/registry/skills/technical-documentation/SKILL.md +136 -0
- package/registry/skills/technical-seo-audit/SKILL.md +27 -0
- package/registry/skills/telemetry-monitoring/SKILL.md +40 -0
- package/registry/skills/test-driven-development/SKILL.md +135 -0
- package/registry/skills/to-spec/SKILL.md +48 -0
- package/registry/skills/to-tickets/SKILL.md +47 -0
- package/registry/skills/turso-distributed-sqlite/SKILL.md +27 -0
- package/registry/skills/ui-component-spec/SKILL.md +150 -0
- package/registry/skills/usability-testing-protocol/SKILL.md +150 -0
- package/registry/skills/user-flow-mapping/SKILL.md +150 -0
- package/registry/skills/user-journey-mapping/SKILL.md +150 -0
- package/registry/skills/vector-database-design/SKILL.md +84 -0
- package/registry/skills/vercel-deploy-best-practices/SKILL.md +28 -0
- package/registry/skills/viral-referral-loops/SKILL.md +209 -0
- package/registry/workflows/workflow-agency-ad-creative-sprint.md +50 -0
- package/registry/workflows/workflow-agency-brand-design-system.md +50 -0
- package/registry/workflows/workflow-agency-client-pitch-proposal.md +50 -0
- package/registry/workflows/workflow-agency-cro-funnel-teardown.md +50 -0
- package/registry/workflows/workflow-agency-full-campaign.md +58 -0
- package/registry/workflows/workflow-agency-seo-content-engine.md +50 -0
- package/registry/workflows/workflow-analyze.md +60 -0
- package/registry/workflows/workflow-api-contract-design.md +48 -0
- package/registry/workflows/workflow-app-store-release.md +48 -0
- package/registry/workflows/workflow-brainstorm.md +60 -0
- package/registry/workflows/workflow-build.md +60 -0
- package/registry/workflows/workflow-business-panel.md +60 -0
- package/registry/workflows/workflow-cleanup.md +60 -0
- package/registry/workflows/workflow-deploy-staging.md +49 -0
- package/registry/workflows/workflow-design-code.md +60 -0
- package/registry/workflows/workflow-design-ops--handoff.md +60 -0
- package/registry/workflows/workflow-design-ops--plan-sprint.md +60 -0
- package/registry/workflows/workflow-design-ops--setup-workflow.md +60 -0
- package/registry/workflows/workflow-design-orchestrate.md +60 -0
- package/registry/workflows/workflow-design-systems--audit-system.md +60 -0
- package/registry/workflows/workflow-design-systems--create-component.md +60 -0
- package/registry/workflows/workflow-design-systems--tokenize.md +60 -0
- package/registry/workflows/workflow-diagnose.md +45 -0
- package/registry/workflows/workflow-e2e-testing.md +49 -0
- package/registry/workflows/workflow-email-drip-sequence.md +65 -0
- package/registry/workflows/workflow-estimate.md +60 -0
- package/registry/workflows/workflow-explain.md +60 -0
- package/registry/workflows/workflow-frontend-audit.md +49 -0
- package/registry/workflows/workflow-git.md +60 -0
- package/registry/workflows/workflow-grill.md +51 -0
- package/registry/workflows/workflow-implement.md +61 -0
- package/registry/workflows/workflow-incident-triage.md +49 -0
- package/registry/workflows/workflow-interaction-design--design-interaction.md +60 -0
- package/registry/workflows/workflow-interaction-design--error-flow.md +60 -0
- package/registry/workflows/workflow-interaction-design--map-states.md +60 -0
- package/registry/workflows/workflow-marketing-audit.md +60 -0
- package/registry/workflows/workflow-marketing-campaign-builder.md +60 -0
- package/registry/workflows/workflow-marketing-content-pipeline.md +60 -0
- package/registry/workflows/workflow-marketing-growth-experiment.md +60 -0
- package/registry/workflows/workflow-marketing-launch.md +60 -0
- package/registry/workflows/workflow-marketing-panel.md +60 -0
- package/registry/workflows/workflow-ml-eval.md +51 -0
- package/registry/workflows/workflow-mobile-build.md +49 -0
- package/registry/workflows/workflow-onboarding-funnel-cro.md +65 -0
- package/registry/workflows/workflow-paid-acquisition-campaign.md +65 -0
- package/registry/workflows/workflow-paid-campaign-launch.md +47 -0
- package/registry/workflows/workflow-plan.md +60 -0
- package/registry/workflows/workflow-prototyping-testing--evaluate.md +60 -0
- package/registry/workflows/workflow-prototyping-testing--experiment.md +60 -0
- package/registry/workflows/workflow-prototyping-testing--prototype-plan.md +60 -0
- package/registry/workflows/workflow-prototyping-testing--test-plan.md +60 -0
- package/registry/workflows/workflow-rag-pipeline-deploy.md +53 -0
- package/registry/workflows/workflow-recommend.md +60 -0
- package/registry/workflows/workflow-research.md +60 -0
- package/registry/workflows/workflow-review.md +60 -0
- package/registry/workflows/workflow-seo-audit-pipeline.md +47 -0
- package/registry/workflows/workflow-seo-content-pipeline.md +65 -0
- package/registry/workflows/workflow-serverless-gpu-deploy.md +52 -0
- package/registry/workflows/workflow-spec-panel.md +60 -0
- package/registry/workflows/workflow-spec.md +44 -0
- package/registry/workflows/workflow-test.md +60 -0
- package/registry/workflows/workflow-troubleshoot.md +60 -0
- package/registry/workflows/workflow-ui-design--color-palette.md +60 -0
- package/registry/workflows/workflow-ui-design--design-screen.md +60 -0
- package/registry/workflows/workflow-ui-design--responsive-audit.md +60 -0
- package/registry/workflows/workflow-ui-design--type-system.md +60 -0
- package/registry/workflows/workflow-ux-strategy--benchmark.md +60 -0
- package/registry/workflows/workflow-ux-strategy--frame-problem.md +60 -0
- package/registry/workflows/workflow-ux-strategy--strategize.md +60 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +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/uninstaller.ts","../src/core/inventory.ts","../src/core/updater.ts","../src/core/doctor.ts","../src/core/cline-capabilities.ts","../src/core/cline-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, 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 { PrerequisiteChecker } from './core/prerequisites.js';\nimport { McpLocationRegistry } from './core/mcp-locations.js';\nimport { isKnownHost, HOST_REGISTRY, KNOWN_HOST_IDS, planInstallTargets } from './core/hosts.js';\nimport type { InstallScope, InstallMethod, AgentHost, BundleDefinition, InstalledPackageRecord, ProjectionInfo, ExecutionMode } 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\nfunction 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) lines.push(pc.yellow(` ⚠ ${w}`));\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 (TBA soon)',\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 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, cursor, cline, opencode, codex')\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 }\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 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: 'cursor',\n label: HOST_REGISTRY.cursor.label,\n hint: detectedHosts.includes('cursor') ? 'found in this project' : 'orchestrator & subagent personas for Cursor IDE',\n },\n {\n value: 'cline',\n label: HOST_REGISTRY.cline.label,\n hint: detectedHosts.includes('cline') ? 'found in this project' : 'roles, skills, coordinator rules & team manifests for Cline',\n },\n {\n value: 'opencode',\n label: HOST_REGISTRY.opencode.label,\n hint: detectedHosts.includes('opencode') ? 'found in this project' : 'orchestrator & subagent personas for OpenCode',\n },\n {\n value: 'codex',\n label: HOST_REGISTRY.codex.label,\n hint: detectedHosts.includes('codex') ? 'found in this project' : 'root index linking orchestrators, subagents & skills for Codex, Copilot, Aider & Zed',\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 : ['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 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 `Bundle: ${result.installed.targetBundle || 'Single Item'}\\n` +\n `Scope: ${scope}\\n` +\n `Method: ${result.method}\\n` +\n `Targets: ${hosts.join(', ')}\\n` +\n `Agents: ${result.installed.agents.join(', ') || 'None'}\\n` +\n `Skills: ${result.installed.skills.join(', ') || 'None'}\\n` +\n `Target Directories: ${result.targetDirs.join('\\n ')}` +\n (result.projections.length > 0 ? `\\n\\nProjections:\\n${renderProjections(result.projections)}` : ''),\n 'Installation Success'\n );\n\n const hasClineProjection = result.projections.some(p => p.host === 'cline');\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 if (!options.dryRun && hosts.includes('agents') && result.projections.length === 0) {\n note(\n pc.yellow(\n `Tip: only Antigravity reads the main library (.agents/) directly.\\n` +\n `To use this bundle in Cline, Claude Code & others: agents update ${identifier} --fanout cline,claude`\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 your runtime tools\\n' +\n 'and guide configuration of live browser automation, design tokens, or cloud APIs on demand.'\n ),\n 'Adaptive Tooling'\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(`[DRY RUN] Would remove ${result.removed.length} assets from ${result.targetDirs.join(', ')}`));\n return;\n }\n\n outro(pc.green(`✔ Successfully removed ${result.removed.length} files matching \"${identifier}\"`));\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 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 statusMessage =\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 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 synced to other assistants yet (only Antigravity reads .agents/).\\n` +\n `To add Cline & friends: agents update ${unprojected[0]} --fanout cline,claude`\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\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, 90 skills, and 63 workflows.')}`);\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('90 modular skills & runbooks')}`);\n lines.push(`├── 🔄 Workflows: ${pc.magenta('63 guided multi-step workflows')}`);\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 // Skills\n if (bundle.skills && bundle.skills.length > 0) {\n lines.push(`├── ⚡ Skills (${bundle.skills.length}):`);\n if (bundle.skills.length <= 5) {\n lines.push(`│ └── ${pc.yellow(bundle.skills.join(', '))}`);\n } else {\n lines.push(`│ ├── ${pc.yellow(bundle.skills.slice(0, 5).join(', '))}`);\n lines.push(`│ └── ${pc.dim(`(+${bundle.skills.length - 5} more: ${bundle.skills.slice(5).join(', ')})`)}`);\n }\n } else {\n lines.push(`├── ⚡ Skills: ${pc.dim('Inherited from base bundle')}`);\n }\n\n // Workflows\n if (bundle.workflows && bundle.workflows.length > 0) {\n const wfNames = bundle.workflows.map(w => w.replace(/^workflow-/, '').replace(/\\.md$/, ''));\n lines.push(`├── 🔄 Workflows (${bundle.workflows.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 {\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\n if (b.skills && b.skills.length > 0) {\n const displaySkills =\n b.skills.length > 3 ? `${b.skills.slice(0, 3).join(', ')} (+${b.skills.length - 3} more)` : b.skills.join(', ');\n console.log(`${subIndent}├── ⚡ Skills: ${pc.yellow(displaySkills)}`);\n }\n\n // Workflows\n if (b.workflows && b.workflows.length > 0) {\n const wfNames = b.workflows.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 {\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 if (b.skills && b.skills.length > 0) {\n const displaySkills =\n b.skills.length > 3 ? `${b.skills.slice(0, 3).join(', ')} (+${b.skills.length - 3} more)` : b.skills.join(', ');\n console.log(`${subIndent}├── ⚡ Skills: ${pc.yellow(displaySkills)}`);\n }\n\n if (b.workflows && b.workflows.length > 0) {\n const wfNames = b.workflows.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 note(\n `Bundle: ${result.installed.targetBundle || bundle.name}\\n` +\n `Scope: project\\n` +\n `Method: ${result.method}\\n` +\n `Targets: ${installHosts.join(', ')}\\n` +\n `Agents: ${result.installed.agents.join(', ') || 'None'}\\n` +\n `Skills: ${result.installed.skills.join(', ') || 'None'}\\n` +\n `Target Directories: ${result.targetDirs.join('\\n ')}` +\n (result.projections.length > 0 ? `\\n\\nProjections:\\n${renderProjections(result.projections)}` : ''),\n 'Installation Success'\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 18 bundles and 8 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)')\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('--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 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 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 `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 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)')\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 console.log(` 👉 ${pc.bold('agents list')} Browse all 23 bundles and 8 departments\\n`);\n\n if (report.clineCapability) {\n console.log(pc.bold(pc.cyan('Cline Runtime & Compound Projection 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.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 Workflows: ${pc.bold(report.workflowsCount.toString())}\\n`);\n\n if (report.clineCapability) {\n console.log(pc.bold(pc.cyan('Cline Runtime & Compound Projection 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(` Role Definitions: ${report.agentsCount} prepared (activation via \"agents start\")\\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\ncli.help();\ncli.version('1.0.0');\n\ncli.parse();\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport { fileURLToPath } from 'node:url';\nimport type { BundlesManifest, BundleDefinition, ResolvedAssets, SearchOptions, SearchResults } from './types.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport class RegistryResolver {\n private registryDir: string;\n private bundlesManifest: BundlesManifest | null = null;\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 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\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 }\n\n return {\n targetBundle: `domain:${domainName}`,\n agents: Array.from(agents),\n skills: Array.from(skills),\n workflows: Array.from(workflows),\n rules: ['GEMINI.md'],\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 = ['GEMINI.md'];\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 }\n }\n\n if (bundle.orchestrator) agents.add(bundle.orchestrator);\n if (bundle.agents) bundle.agents.forEach(a => agents.add(a));\n\n return {\n targetBundle: bundle.name,\n agents: Array.from(agents),\n skills: Array.from(skills),\n workflows: Array.from(workflows),\n rules,\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 skillPath = path.join(this.registryDir, 'skills', identifier);\n if (await fs.pathExists(skillPath)) {\n return {\n agents: [],\n skills: [identifier],\n workflows: [],\n rules: [],\n };\n }\n\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') {\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 const workflowsDir = path.join(this.registryDir, 'workflows');\n let matchedWorkflows: string[] = [];\n if (!options?.type || options.type === 'workflow') {\n if (await fs.pathExists(workflowsDir)) {\n const files = await fs.readdir(workflowsDir);\n matchedWorkflows = files.filter(f => f.endsWith('.md')).filter(f => {\n if (!q) return true;\n return f.toLowerCase().includes(q);\n });\n }\n }\n\n return {\n bundles: matchedBundles,\n agents: matchedAgents,\n skills: matchedSkills,\n workflows: matchedWorkflows,\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, HOST_REGISTRY, resolveHostProjectDir } from './hosts.js';\nimport { HostProjector } from './projector.js';\nimport { ClineProjector } from './cline-projector.js';\nimport type { IndexableAsset } from './projector.js';\nimport type { InstallOptions, LockfileManifest, ResolvedAssets, InstallScope, InstallMethod, AgentHost, ProjectionInfo } 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 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 * 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 ): 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') {\n const bundleDef = resolved.targetBundle ? await this.registry.getBundle(resolved.targetBundle) : undefined;\n if (bundleDef) {\n const artifacts = await ClineProjector.planCompoundProjection(bundleDef, scope, resolved, registryDir);\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 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') {\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 const artifacts = await ClineProjector.planCompoundProjection(bundleDef, scope, resolved, registryDir);\n const newPaths = new Set(artifacts.map(a => a.relPath));\n\n // Clean up legacy or obsolete projections previously owned by this bundle\n if (lockfile.projections) {\n for (const [projRelPath, proj] of Object.entries(lockfile.projections)) {\n if (proj.host === 'cline' && !newPaths.has(projRelPath) && proj.owners.includes(bundleDef.name)) {\n proj.owners = proj.owners.filter(o => o !== bundleDef.name);\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 // Clean up any legacy .cline/ projectedTo entries in lockfile.files\n if (lockfile.files) {\n for (const [canonKey, fileMeta] of Object.entries(lockfile.files)) {\n if (fileMeta.projectedTo) {\n const staleClinePaths = fileMeta.projectedTo.filter(p => p.startsWith('.cline/'));\n for (const stalePath of staleClinePaths) {\n const absPath = path.join(root, stalePath);\n if (await fs.pathExists(absPath)) {\n await fs.remove(absPath);\n await this.removeEmptyProjectionDirs(root, stalePath);\n }\n this.removeProjectedTo(lockfile, canonKey, stalePath);\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) && !options.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 bundleName = bundleDef.name;\n const declares = artifact.kind === 'rule' || artifact.kind === 'team-manifest'\n || artifact.kind === 'plugin-manifest'\n || (artifact.canonical ? declared.has(artifact.canonical) : false);\n const priorOwners = existingProj?.owners ?? [];\n const owners = declares\n ? Array.from(new Set([...priorOwners, bundleName]))\n : priorOwners;\n\n lockfile.projections[artifact.relPath] = {\n host: 'cline',\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 if (artifact.canonical) {\n this.recordProjectedTo(lockfile, artifact.canonical, artifact.relPath);\n }\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 (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 const res = HostProjector.projectAgent(content, HOST_REGISTRY[host].profile, canonicalRel);\n const dest = path.join(base, subdir, agentFile);\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 const projPath = this.toPosix(path.relative(root, dest));\n projections.push({ host, path: projPath, kind: 'role', warnings: res.warnings });\n this.recordProjectedTo(lockfile, this.lockRel('agents', agentFile), projPath);\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 const projections = hasCanonicalAgents\n ? await this.buildProjections(fanoutHosts, resolved, registryDir, scope, options.targetDir)\n : [];\n return { installed: resolved, targetDirs, dryRun: true, method, projections };\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 await fs.ensureDir(subPaths.workflowsDir);\n await fs.ensureDir(subPaths.rulesDir);\n\n const lockfile = await this.readLockfile(subPaths.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 if (resolved.targetBundle) {\n const bundleDef = await this.registry.getBundle(resolved.targetBundle);\n if (bundleDef) {\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\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 ?? (existing?.bundle ? [existing.bundle] : []);\n const declaresAsset = declared.has(`agents/${agentFile}`);\n const owners = resolved.targetBundle && declaresAsset\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 ?? (existing?.bundle ? [existing.bundle] : []);\n const declaresAsset = declared.has(`skills/${skillName}/SKILL.md`);\n const owners = resolved.targetBundle && declaresAsset\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 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 ?? (existing?.bundle ? [existing.bundle] : []);\n const declaresAsset = declared.has(`workflows/${workflowFile}`);\n const owners = resolved.targetBundle && declaresAsset\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.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 ?? (existing?.bundle ? [existing.bundle] : []);\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 declaresAsset = true;\n const owners = resolved.targetBundle && declaresAsset\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 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}\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 },\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 },\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 },\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 },\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 },\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 },\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 },\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}\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 const content = ClineProjector.renderRole(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 BundleDefinition,\n ClinePluginManifest,\n ClineTeamManifest,\n InstallScope,\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 * Render a Cline role definition from canonical agent markdown content.\n */\n static renderRole(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 const preamble = `## 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 Agent Teams when\\navailable, then session subagents; otherwise complete the role in the main session.`;\n\n const match = canonicalContent.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) {\n return `${marker}\\n\\n${preamble}\\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 // Keep only name and description (and optional providerId, modelId, cwd, maxIterations if present)\n const cleanFrontmatter: Record<string, unknown> = {};\n if (parsed.name) cleanFrontmatter.name = parsed.name;\n if (parsed.description) cleanFrontmatter.description = parsed.description;\n if (parsed.providerId) cleanFrontmatter.providerId = parsed.providerId;\n if (parsed.modelId) cleanFrontmatter.modelId = parsed.modelId;\n if (parsed.cwd) cleanFrontmatter.cwd = parsed.cwd;\n if (parsed.maxIterations) cleanFrontmatter.maxIterations = parsed.maxIterations;\n\n const frontmatterStr = yaml.stringify(cleanFrontmatter).trim();\n const bodyStr = rawBody.trim();\n\n return `---\\n${frontmatterStr}\\n---\\n${marker}\\n\\n${preamble}\\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 sortedWorkflows = [...(bundle.workflows || [])].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 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 const specialistLines = (bundle.agents || []).map((agentFile) => {\n const name = agentFile.replace(/\\.md$/, '');\n return `- **${name}**: \\`.agents/agents/${agentFile}\\``;\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 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}\\`).\n2. Delegate specialist tasks using **Agent Teams** (\\`team_spawn_teammate\\`, \\`team_delegate_task\\`) when available, assigning non-overlapping scopes.\n3. For lightweight read-only research, use session subagents.\n4. Only specialist roles declared in the Team Manifest are active in this workspace.\n${specialistLines.length > 0 ? `\\n### Installed Specialist Roles\\n${specialistLines.join('\\n')}` : ''}\n${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. Plugin manifest (.agents/plugins/<bundle-name>/package.json)\n const pluginManifest: ClinePluginManifest = {\n name: `agents-united-${bundle.name}`,\n version: '1.0.0',\n description: bundle.description || '',\n cline: {\n plugins: [\n {\n capabilities: ['skills', 'tools', 'workflows'],\n skills: ['./skills'],\n },\n ],\n },\n };\n artifacts.push({\n kind: 'plugin-manifest',\n relPath: `${baseDir}/package.json`.replace(/\\\\/g, '/'),\n content: JSON.stringify(pluginManifest, null, 2),\n managedMarker: false,\n });\n\n // 1. Role definitions (.agents/plugins/<bundle-name>/agents/*.md)\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.renderRole(content, canonicalRel);\n artifacts.push({\n kind: 'role',\n canonical: canonicalRel,\n relPath: `${baseDir}/agents/${agentFile}`.replace(/\\\\/g, '/'),\n content: rendered,\n managedMarker: true,\n });\n }\n }\n\n // 2. Skills (.agents/plugins/<bundle-name>/skills/<skill>/**)\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. Coordinator Rule (.agents/plugins/<bundle-name>/rules/agents-united-<bundle>.md)\n const ruleContent = this.renderCoordinatorRule(bundle, scope, excludeAddons);\n artifacts.push({\n kind: 'rule',\n relPath: `${baseDir}/rules/agents-united-${bundle.name}.md`.replace(/\\\\/g, '/'),\n content: ruleContent,\n managedMarker: true,\n });\n\n // 4. 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 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';\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): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n return HostProjector.hasManagedMarker(content);\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(workspaceRoot: string, projectedTo: string[], force?: boolean): 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);\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[]; 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\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\n // Bundle removal mode\n if (resolved && resolved.targetBundle) {\n const bundleName = resolved.targetBundle;\n if (lockfile.installed.bundles.includes(bundleName)) {\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]) => (m.owners ?? (m.bundle ? [m.bundle] : [])).includes(bundleName));\n const ownedProjections = lockfile.projections\n ? Object.values(lockfile.projections).filter(p => p.owners.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 if (proj.owners.includes(bundleName)) {\n proj.owners = proj.owners.filter(o => o !== bundleName);\n if (proj.owners.length === 0) {\n const absProjection = path.join(workspaceRoot, projRelPath);\n if (await fs.pathExists(absProjection)) {\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 }\n }\n }\n }\n\n for (const [relPath, assetMeta] of Object.entries(lockfile.files)) {\n const assetOwners = assetMeta.owners ?? (assetMeta.bundle ? [assetMeta.bundle] : []);\n if (!assetOwners.includes(bundleName)) continue;\n\n const newOwners = assetOwners.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);\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 }\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) continue;\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 lockfile.installed.workflows = lockfile.installed.workflows.filter(w => survival.has(`workflows/${w}`));\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 removedFiles.push(...resolved.agents, ...resolved.skills, ...resolved.workflows);\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 }\n\n if (totalRemoved.length === 0 && !options.dryRun) {\n throw new Error(`No installed assets found matching \"${identifier}\".`);\n }\n\n return { removed: totalRemoved, targetDirs, dryRun: options.dryRun || false };\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} 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): 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 return `[${scope}: ${prettyPath}]`;\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\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 displayLocation = InventoryScanner.formatDisplayLocation(item.scope, item.host, item.dir);\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 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 };\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 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 };\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 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 };\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 };\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 type {\n UpdateOptions,\n UpdateCheckReport,\n UpdateCheckItem,\n UpdateResult,\n InstalledPackageRecord,\n LockfileManifest,\n InventoryOptions,\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 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): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n return HostProjector.hasManagedMarker(content);\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');\n if (!managed) {\n return projPath;\n }\n }\n }\n }\n return '';\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 };\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 };\n }\n\n if (options.dryRun) {\n return {\n updated: recordsToUpdate,\n skipped: [],\n targetDirs: inventory.targetDirs,\n dryRun: true,\n };\n }\n\n const updated: InstalledPackageRecord[] = [];\n const skipped: Array<{ record: InstalledPackageRecord; reason: string }> = [];\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 // Re-install with upstream version. Fan-out flows from --fanout if given,\n // otherwise the installer inherits the fanout recorded in the lockfile.\n 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 // 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 }\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 };\n }\n}\n","import path from 'node:path';\nimport fs from 'fs-extra';\nimport YAML from 'yaml';\nimport { AgentHostAdapter } from './adapter.js';\nimport { HostProjector } from './projector.js';\nimport { ClineCapabilityProbe } from './cline-capabilities.js';\nimport type { ClineCapabilityReport, LockfileManifest } 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}\n\nexport class DoctorEngine {\n private static async isManagedProjection(absPath: string, isAgentsMd: boolean): Promise<boolean> {\n const content = await fs.readFile(absPath, 'utf8');\n if (isAgentsMd) {\n return content.includes('managed-by: agents-united');\n }\n return HostProjector.hasManagedMarker(content);\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 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 workflowsCount = parsed.installed?.workflows?.length || 0;\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 // Projection checks: verify each recorded `projectedTo` and `projections` path\n if (manifest) {\n const workspaceRoot = path.resolve(path.dirname(root));\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 warnings.push(\n `Missing projection ${projPath} for canonical ${relPath}. Re-run: agents add ... --fanout`\n );\n continue;\n }\n const managed = await this.isManagedProjection(absProjection, projPath === 'AGENTS.md');\n if (!managed) {\n warnings.push(`user-modified projection ${projPath}`);\n }\n }\n }\n\n // 2. Check compound projections\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 warnings.push(`Missing compound projection ${projRelPath} (owners: ${proj.owners.join(', ')}).`);\n continue;\n }\n if (proj.managedMarker) {\n const managed = await this.isManagedProjection(absPath, projRelPath === 'AGENTS.md');\n if (!managed) {\n warnings.push(`user-modified projection ${projRelPath}`);\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 rec.owners ?? (rec.bundle ? [rec.bundle] : []);\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)\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 }\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 };\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 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 pluginInstallText = `Before proceeding, ensure you have installed this bundle's plugin by running: cline plugin install .agents/plugins/${bundleName}`;\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 pluginInstallText,\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 { 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,QAAQ,aAAa,SAAS,YAAY;AAChF,OAAOA,UAAQ;AACf,OAAOC,YAAU;;;ACJjB,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAG9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,KAAK,QAAQ,UAAU;AAElC,IAAM,mBAAN,MAAuB;AAAA,EACpB;AAAA,EACA,kBAA0C;AAAA,EAElD,YAAY,mBAA4B;AACtC,QAAI,mBAAmB;AACrB,WAAK,cAAc,KAAK,QAAQ,iBAAiB;AAAA,IACnD,OAAO;AAEL,YAAM,iBAAiB;AAAA,QACrB,KAAK,QAAQ,WAAW,aAAa;AAAA,QACrC,KAAK,QAAQ,WAAW,gBAAgB;AAAA,QACxC,KAAK,QAAQ,QAAQ,IAAI,GAAG,UAAU;AAAA,MACxC;AAEA,YAAM,QAAQ,eAAe,KAAK,OAAK,GAAG,WAAW,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,OAAK,QAAQ,IAAI,YAAO,CAAC,EAAE,CAAC;AACpD,YAAQ,IAAI;AAAA,EACd;AAEA,MAAI,OAAO,SAAS,OAAO,OAAO,WAAW,GAAG;AAC9C,UAAM,GAAG,MAAM,kEAA6D,CAAC;AAAA,EAC/E,OAAO;AACL,UAAM,GAAG,IAAI,wDAAmD,CAAC;AACjE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,IAAI,KAAK;AACT,IAAI,QAAQ,OAAO;AAEnB,IAAI,MAAM;","names":["fs","path","path","fs","path","path","path","path","fs","content","registry","fs","path","projections","relPath","path","crypto","fs","registry","fs","crypto","path","path","os","fs","registry","os","path","fs","path","crypto","fs","registry","scanner","installer","fs","crypto","path","path","fs","YAML","path","fs","fs","path","YAML","path","os","crypto","fs","crypto","path","os","fs","path","os","fs","path","os","fs","os","path","fs","fs","path","s","targetBundleDef","lines","action"]}
|