-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathinstall.py
More file actions
2124 lines (1876 loc) · 98.3 KB
/
install.py
File metadata and controls
2124 lines (1876 loc) · 98.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""APM install command and dependency installation engine."""
import builtins
import sys
from pathlib import Path
from typing import List
import click
from ..constants import (
APM_LOCK_FILENAME,
APM_MODULES_DIR,
APM_YML_FILENAME,
GITHUB_DIR,
CLAUDE_DIR,
SKILL_MD_FILENAME,
InstallMode,
)
from ..drift import build_download_ref, detect_orphans, detect_ref_change
from ..models.results import InstallResult
from ..core.command_logger import InstallLogger, _ValidationOutcome
from ..utils.console import _rich_echo, _rich_error, _rich_info, _rich_success
from ..utils.diagnostics import DiagnosticCollector
from ..utils.github_host import default_host, is_valid_fqdn
from ..utils.path_security import safe_rmtree
from ._helpers import (
_create_minimal_apm_yml,
_get_default_config,
_rich_blank_line,
_update_gitignore_for_apm_modules,
)
# CRITICAL: Shadow Python builtins that share names with Click commands
set = builtins.set
list = builtins.list
dict = builtins.dict
from ..core.auth import AuthResolver
# APM Dependencies (conditional import for graceful degradation)
APM_DEPS_AVAILABLE = False
_APM_IMPORT_ERROR = None
try:
from ..deps.apm_resolver import APMDependencyResolver
from ..deps.github_downloader import GitHubPackageDownloader
from ..deps.lockfile import LockFile, get_lockfile_path, migrate_lockfile_if_needed
from ..integration import AgentIntegrator, PromptIntegrator
from ..integration.mcp_integrator import MCPIntegrator
from ..models.apm_package import APMPackage, DependencyReference
APM_DEPS_AVAILABLE = True
except ImportError as e:
_APM_IMPORT_ERROR = str(e)
# ---------------------------------------------------------------------------
# Validation helpers
# ---------------------------------------------------------------------------
def _validate_and_add_packages_to_apm_yml(packages, dry_run=False, dev=False, logger=None, auth_resolver=None):
"""Validate packages exist and can be accessed, then add to apm.yml dependencies section.
Implements normalize-on-write: any input form (HTTPS URL, SSH URL, FQDN, shorthand)
is canonicalized before storage. Default host (github.com) is stripped;
non-default hosts are preserved. Duplicates are detected by identity.
Args:
packages: Package specifiers to validate and add.
dry_run: If True, only show what would be added.
dev: If True, write to devDependencies instead of dependencies.
logger: InstallLogger for structured output.
auth_resolver: Shared auth resolver for caching credentials.
Returns:
Tuple of (validated_packages list, _ValidationOutcome).
"""
import subprocess
import tempfile
from pathlib import Path
import yaml
apm_yml_path = Path(APM_YML_FILENAME)
# Read current apm.yml
try:
with open(apm_yml_path, "r") as f:
data = yaml.safe_load(f) or {}
except Exception as e:
if logger:
logger.error(f"Failed to read {APM_YML_FILENAME}: {e}")
else:
_rich_error(f"Failed to read {APM_YML_FILENAME}: {e}")
sys.exit(1)
# Ensure dependencies structure exists
dep_section = "devDependencies" if dev else "dependencies"
if dep_section not in data:
data[dep_section] = {}
if "apm" not in data[dep_section]:
data[dep_section]["apm"] = []
current_deps = data[dep_section]["apm"] or []
validated_packages = []
# Build identity set from existing deps for duplicate detection
existing_identities = builtins.set()
for dep_entry in current_deps:
try:
if isinstance(dep_entry, str):
ref = DependencyReference.parse(dep_entry)
elif isinstance(dep_entry, builtins.dict):
ref = DependencyReference.parse_from_dict(dep_entry)
else:
continue
existing_identities.add(ref.get_identity())
except (ValueError, TypeError, AttributeError, KeyError):
continue
# First, validate all packages
valid_outcomes = [] # (canonical, already_present) tuples
invalid_outcomes = [] # (package, reason) tuples
if logger:
logger.validation_start(len(packages))
for package in packages:
# Validate package format (should be owner/repo, a git URL, or a local path)
if "/" not in package and not DependencyReference.is_local_path(package):
reason = "invalid format -- use 'owner/repo'"
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
continue
# Canonicalize input
try:
dep_ref = DependencyReference.parse(package)
canonical = dep_ref.to_canonical()
identity = dep_ref.get_identity()
except ValueError as e:
reason = str(e)
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
continue
# Check if package is already in dependencies (by identity)
already_in_deps = identity in existing_identities
# Validate package exists and is accessible
verbose = bool(logger and logger.verbose)
if _validate_package_exists(package, verbose=verbose, auth_resolver=auth_resolver):
valid_outcomes.append((canonical, already_in_deps))
if logger:
logger.validation_pass(canonical, already_present=already_in_deps)
if not already_in_deps:
validated_packages.append(canonical)
existing_identities.add(identity) # prevent duplicates within batch
else:
reason = "not accessible or doesn't exist"
if not verbose:
reason += " -- run with --verbose for auth details"
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
outcome = _ValidationOutcome(valid=valid_outcomes, invalid=invalid_outcomes)
# Let the logger emit a summary and decide whether to continue
if logger:
should_continue = logger.validation_summary(outcome)
if not should_continue:
return [], outcome
if not validated_packages:
if dry_run:
if logger:
logger.progress("No new packages to add")
# If all packages already exist in apm.yml, that's OK - we'll reinstall them
return [], outcome
if dry_run:
if logger:
logger.progress(
f"Dry run: Would add {len(validated_packages)} package(s) to apm.yml"
)
for pkg in validated_packages:
logger.verbose_detail(f" + {pkg}")
return validated_packages, outcome
# Add validated packages to dependencies (already canonical)
dep_label = "devDependencies" if dev else "apm.yml"
for package in validated_packages:
current_deps.append(package)
if logger:
logger.verbose_detail(f"Added {package} to {dep_label}")
# Update dependencies
data[dep_section]["apm"] = current_deps
# Write back to apm.yml
try:
with open(apm_yml_path, "w") as f:
yaml.safe_dump(data, f, default_flow_style=False, sort_keys=False)
if logger:
logger.success(f"Updated {APM_YML_FILENAME} with {len(validated_packages)} new package(s)")
except Exception as e:
if logger:
logger.error(f"Failed to write {APM_YML_FILENAME}: {e}")
else:
_rich_error(f"Failed to write {APM_YML_FILENAME}: {e}")
sys.exit(1)
return validated_packages, outcome
def _validate_package_exists(package, verbose=False, auth_resolver=None):
"""Validate that a package exists and is accessible on GitHub, Azure DevOps, or locally."""
import os
import subprocess
import tempfile
from apm_cli.core.auth import AuthResolver
verbose_log = (lambda msg: _rich_echo(f" {msg}", color="dim")) if verbose else None
# Use provided resolver or create new one if not in a CLI session context
if auth_resolver is None:
auth_resolver = AuthResolver()
try:
# Parse the package to check if it's a virtual package or ADO
from apm_cli.models.apm_package import DependencyReference
from apm_cli.deps.github_downloader import GitHubPackageDownloader
dep_ref = DependencyReference.parse(package)
# For local packages, validate directory exists and has valid package content
if dep_ref.is_local and dep_ref.local_path:
local = Path(dep_ref.local_path).expanduser()
if not local.is_absolute():
local = Path.cwd() / local
local = local.resolve()
if not local.is_dir():
return False
# Must contain apm.yml, SKILL.md, or plugin.json
if (local / "apm.yml").exists() or (local / "SKILL.md").exists():
return True
from apm_cli.utils.helpers import find_plugin_json
return find_plugin_json(local) is not None
# For virtual packages, use the downloader's validation method
if dep_ref.is_virtual:
ctx = auth_resolver.resolve_for_dep(dep_ref)
host = dep_ref.host or default_host()
org = dep_ref.repo_url.split('/')[0] if dep_ref.repo_url and '/' in dep_ref.repo_url else None
if verbose_log:
verbose_log(f"Auth resolved: host={host}, org={org}, source={ctx.source}, type={ctx.token_type}")
virtual_downloader = GitHubPackageDownloader(auth_resolver=auth_resolver)
result = virtual_downloader.validate_virtual_package_exists(dep_ref)
if not result and verbose_log:
try:
err_ctx = auth_resolver.build_error_context(host, f"accessing {package}", org=org)
for line in err_ctx.splitlines():
verbose_log(line)
except Exception:
pass
return result
# For Azure DevOps or GitHub Enterprise (non-github.com hosts),
# use the downloader which handles authentication properly
if dep_ref.is_azure_devops() or (dep_ref.host and dep_ref.host != "github.com"):
from apm_cli.utils.github_host import is_github_hostname, is_azure_devops_hostname
ado_downloader = GitHubPackageDownloader(auth_resolver=auth_resolver)
# Set the host
if dep_ref.host:
ado_downloader.github_host = dep_ref.host
# Build authenticated URL using downloader's auth
package_url = ado_downloader._build_repo_url(
dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref
)
# For generic hosts (not GitHub, not ADO), relax the env so native
# credential helpers (SSH keys, macOS Keychain, etc.) can work.
# This mirrors _clone_with_fallback() which does the same relaxation.
is_generic = not is_github_hostname(dep_ref.host) and not is_azure_devops_hostname(dep_ref.host)
if is_generic:
validate_env = {k: v for k, v in ado_downloader.git_env.items()
if k not in ('GIT_ASKPASS', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM')}
validate_env['GIT_TERMINAL_PROMPT'] = '0'
else:
validate_env = {**os.environ, **ado_downloader.git_env}
if verbose_log:
verbose_log(f"Trying git ls-remote for {dep_ref.host}")
cmd = ["git", "ls-remote", "--heads", "--exit-code", package_url]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30,
env=validate_env,
)
if verbose_log:
if result.returncode == 0:
verbose_log(f"git ls-remote rc=0 for {package}")
else:
# Sanitize stderr to avoid leaking tokens
stderr_snippet = (result.stderr or "").strip()[:200]
for env_var in ("GIT_ASKPASS", "GIT_CONFIG_GLOBAL"):
stderr_snippet = stderr_snippet.replace(
validate_env.get(env_var, ""), "***"
)
verbose_log(f"git ls-remote rc={result.returncode}: {stderr_snippet}")
return result.returncode == 0
# For GitHub.com, use AuthResolver with unauth-first fallback
host = dep_ref.host or default_host()
org = dep_ref.repo_url.split('/')[0] if dep_ref.repo_url and '/' in dep_ref.repo_url else None
host_info = auth_resolver.classify_host(host)
if verbose_log:
ctx = auth_resolver.resolve(host, org=org)
verbose_log(f"Auth resolved: host={host}, org={org}, source={ctx.source}, type={ctx.token_type}")
def _check_repo(token, git_env):
"""Check repo accessibility via GitHub API (or git ls-remote for non-GitHub)."""
import urllib.request
import urllib.error
api_base = host_info.api_base
api_url = f"{api_base}/repos/{dep_ref.repo_url}"
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "apm-cli",
}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(api_url, headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=15)
if verbose_log:
verbose_log(f"API {api_url} -> {resp.status}")
return True
except urllib.error.HTTPError as e:
if verbose_log:
verbose_log(f"API {api_url} -> {e.code} {e.reason}")
if e.code == 404 and token:
# 404 with token could mean no access — raise to trigger fallback
raise RuntimeError(f"API returned {e.code}")
raise RuntimeError(f"API returned {e.code}: {e.reason}")
except Exception as e:
if verbose_log:
verbose_log(f"API request failed: {e}")
raise
try:
return auth_resolver.try_with_fallback(
host, _check_repo,
org=org,
unauth_first=True,
verbose_callback=verbose_log,
)
except Exception:
if verbose_log:
try:
ctx = auth_resolver.build_error_context(host, f"accessing {package}", org=org)
for line in ctx.splitlines():
verbose_log(line)
except Exception:
pass
return False
except Exception:
# If parsing fails, assume it's a regular GitHub package
host = default_host()
org = package.split('/')[0] if '/' in package else None
repo_path = package # owner/repo format
def _check_repo_fallback(token, git_env):
import urllib.request
import urllib.error
host_info = auth_resolver.classify_host(host)
api_url = f"{host_info.api_base}/repos/{repo_path}"
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "apm-cli",
}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(api_url, headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=15)
return True
except urllib.error.HTTPError as e:
if verbose_log:
verbose_log(f"API fallback -> {e.code} {e.reason}")
raise RuntimeError(f"API returned {e.code}")
except Exception as e:
if verbose_log:
verbose_log(f"API fallback failed: {e}")
raise
try:
return auth_resolver.try_with_fallback(
host, _check_repo_fallback,
org=org,
unauth_first=True,
verbose_callback=verbose_log,
)
except Exception:
if verbose_log:
try:
ctx = auth_resolver.build_error_context(host, f"accessing {package}", org=org)
for line in ctx.splitlines():
verbose_log(line)
except Exception:
pass
return False
# ---------------------------------------------------------------------------
# Install command
# ---------------------------------------------------------------------------
@click.command(
help="Install APM and MCP dependencies (auto-creates apm.yml when installing packages)"
)
@click.argument("packages", nargs=-1)
@click.option("--runtime", help="Target specific runtime only (copilot, codex, vscode)")
@click.option("--exclude", help="Exclude specific runtime from installation")
@click.option(
"--only",
type=click.Choice(["apm", "mcp"]),
help="Install only specific dependency type",
)
@click.option(
"--update", is_flag=True, help="Update dependencies to latest Git references"
)
@click.option(
"--dry-run", is_flag=True, help="Show what would be installed without installing"
)
@click.option("--force", is_flag=True, help="Overwrite locally-authored files on collision and deploy despite critical security findings")
@click.option("--verbose", "-v", is_flag=True, help="Show detailed installation information")
@click.option(
"--trust-transitive-mcp",
is_flag=True,
help="Trust self-defined MCP servers from transitive packages (skip re-declaration requirement)",
)
@click.option(
"--parallel-downloads",
type=int,
default=4,
show_default=True,
help="Max concurrent package downloads (0 to disable parallelism)",
)
@click.option(
"--dev",
is_flag=True,
default=False,
help="Install as development dependency (devDependencies)",
)
@click.pass_context
def install(ctx, packages, runtime, exclude, only, update, dry_run, force, verbose, trust_transitive_mcp, parallel_downloads, dev):
"""Install APM and MCP dependencies from apm.yml (like npm install).
This command automatically detects AI runtimes from your apm.yml scripts and installs
MCP servers for all detected and available runtimes. It also installs APM package
dependencies from GitHub repositories.
The --only flag filters by dependency type (apm or mcp). Internally converted
to an InstallMode enum for type-safe dispatch.
Examples:
apm install # Install existing deps from apm.yml
apm install org/pkg1 # Add package to apm.yml and install
apm install org/pkg1 org/pkg2 # Add multiple packages and install
apm install --exclude codex # Install for all except Codex CLI
apm install --only=apm # Install only APM dependencies
apm install --only=mcp # Install only MCP dependencies
apm install --update # Update dependencies to latest Git refs
apm install --dry-run # Show what would be installed
"""
try:
# Create structured logger for install output
is_partial = bool(packages)
logger = InstallLogger(verbose=verbose, dry_run=dry_run, partial=is_partial)
# Create shared auth resolver for all downloads in this CLI invocation
# to ensure credentials are cached and reused (prevents duplicate auth popups)
auth_resolver = AuthResolver()
# Check if apm.yml exists
apm_yml_exists = Path(APM_YML_FILENAME).exists()
# Auto-bootstrap: create minimal apm.yml when packages specified but no apm.yml
if not apm_yml_exists and packages:
# Get current directory name as project name
project_name = Path.cwd().name
config = _get_default_config(project_name)
_create_minimal_apm_yml(config)
logger.success(f"Created {APM_YML_FILENAME}")
# Error when NO apm.yml AND NO packages
if not apm_yml_exists and not packages:
logger.error(f"No {APM_YML_FILENAME} found")
logger.progress("Run 'apm init' to create one, or:")
logger.progress(" apm install <org/repo> to auto-create + install")
sys.exit(1)
# If packages are specified, validate and add them to apm.yml first
if packages:
validated_packages, outcome = _validate_and_add_packages_to_apm_yml(
packages, dry_run, dev=dev, logger=logger, auth_resolver=auth_resolver,
)
# Short-circuit: all packages failed validation — nothing to install
if outcome.all_failed:
return
# Note: Empty validated_packages is OK if packages are already in apm.yml
# We'll proceed with installation from apm.yml to ensure everything is synced
logger.resolution_start(
to_install_count=len(validated_packages) if packages else 0,
lockfile_count=0, # Refined later inside _install_apm_dependencies
)
# Parse apm.yml to get both APM and MCP dependencies
try:
apm_package = APMPackage.from_apm_yml(Path(APM_YML_FILENAME))
except Exception as e:
logger.error(f"Failed to parse {APM_YML_FILENAME}: {e}")
sys.exit(1)
logger.verbose_detail(
f"Parsed {APM_YML_FILENAME}: {len(apm_package.get_apm_dependencies())} APM deps, "
f"{len(apm_package.get_mcp_dependencies())} MCP deps"
+ (f", {len(apm_package.get_dev_apm_dependencies())} dev deps"
if apm_package.get_dev_apm_dependencies() else "")
)
# Get APM and MCP dependencies
apm_deps = apm_package.get_apm_dependencies()
dev_apm_deps = apm_package.get_dev_apm_dependencies()
has_any_apm_deps = bool(apm_deps) or bool(dev_apm_deps)
mcp_deps = apm_package.get_mcp_dependencies()
# Convert --only string to InstallMode enum
if only is None:
install_mode = InstallMode.ALL
else:
install_mode = InstallMode(only)
# Determine what to install based on install mode
should_install_apm = install_mode != InstallMode.MCP
should_install_mcp = install_mode != InstallMode.APM
# Show what will be installed if dry run
if dry_run:
logger.progress("Dry run mode - showing what would be installed:")
if should_install_apm and apm_deps:
logger.progress(f"APM dependencies ({len(apm_deps)}):")
for dep in apm_deps:
action = "update" if update else "install"
logger.progress(
f" - {dep.repo_url}#{dep.reference or 'main'} -> {action}"
)
if should_install_mcp and mcp_deps:
logger.progress(f"MCP dependencies ({len(mcp_deps)}):")
for dep in mcp_deps:
logger.progress(f" - {dep}")
if not apm_deps and not dev_apm_deps and not mcp_deps:
logger.progress("No dependencies found in apm.yml")
logger.success("Dry run complete - no changes made")
return
# Install APM dependencies first (if requested)
apm_count = 0
prompt_count = 0
agent_count = 0
# Migrate legacy apm.lock → apm.lock.yaml if needed (one-time, transparent)
migrate_lockfile_if_needed(Path.cwd())
# Capture old MCP servers and configs from lockfile BEFORE
# _install_apm_dependencies regenerates it (which drops the fields).
# We always read this — even when --only=apm — so we can restore the
# field after the lockfile is regenerated by the APM install step.
old_mcp_servers: builtins.set = builtins.set()
old_mcp_configs: builtins.dict = {}
_lock_path = get_lockfile_path(Path.cwd())
_existing_lock = LockFile.read(_lock_path)
if _existing_lock:
old_mcp_servers = builtins.set(_existing_lock.mcp_servers)
old_mcp_configs = builtins.dict(_existing_lock.mcp_configs)
apm_diagnostics = None
if should_install_apm and has_any_apm_deps:
if not APM_DEPS_AVAILABLE:
logger.error("APM dependency system not available")
logger.progress(f"Import error: {_APM_IMPORT_ERROR}")
sys.exit(1)
try:
# If specific packages were requested, only install those
# Otherwise install all from apm.yml
only_pkgs = builtins.list(packages) if packages else None
install_result = _install_apm_dependencies(
apm_package, update, verbose, only_pkgs, force=force,
parallel_downloads=parallel_downloads,
logger=logger,
auth_resolver=auth_resolver,
)
apm_count = install_result.installed_count
prompt_count = install_result.prompts_integrated
agent_count = install_result.agents_integrated
apm_diagnostics = install_result.diagnostics
except Exception as e:
logger.error(f"Failed to install APM dependencies: {e}")
if not verbose:
logger.progress("Run with --verbose for detailed diagnostics")
sys.exit(1)
elif should_install_apm and not has_any_apm_deps:
logger.verbose_detail("No APM dependencies found in apm.yml")
# When --update is used, package files on disk may have changed.
# Clear the parse cache so transitive MCP collection reads fresh data.
if update:
from apm_cli.models.apm_package import clear_apm_yml_cache
clear_apm_yml_cache()
# Collect transitive MCP dependencies from resolved APM packages
apm_modules_path = Path.cwd() / APM_MODULES_DIR
if should_install_mcp and apm_modules_path.exists():
lock_path = get_lockfile_path(Path.cwd())
transitive_mcp = MCPIntegrator.collect_transitive(
apm_modules_path, lock_path, trust_transitive_mcp,
diagnostics=apm_diagnostics,
)
if transitive_mcp:
logger.verbose_detail(f"Collected {len(transitive_mcp)} transitive MCP dependency(ies)")
mcp_deps = MCPIntegrator.deduplicate(mcp_deps + transitive_mcp)
# Continue with MCP installation (existing logic)
mcp_count = 0
new_mcp_servers: builtins.set = builtins.set()
if should_install_mcp and mcp_deps:
mcp_count = MCPIntegrator.install(
mcp_deps, runtime, exclude, verbose,
stored_mcp_configs=old_mcp_configs,
diagnostics=apm_diagnostics,
)
new_mcp_servers = MCPIntegrator.get_server_names(mcp_deps)
new_mcp_configs = MCPIntegrator.get_server_configs(mcp_deps)
# Remove stale MCP servers that are no longer needed
stale_servers = old_mcp_servers - new_mcp_servers
if stale_servers:
MCPIntegrator.remove_stale(stale_servers, runtime, exclude)
# Persist the new MCP server set and configs in the lockfile
MCPIntegrator.update_lockfile(new_mcp_servers, mcp_configs=new_mcp_configs)
elif should_install_mcp and not mcp_deps:
# No MCP deps at all — remove any old APM-managed servers
if old_mcp_servers:
MCPIntegrator.remove_stale(old_mcp_servers, runtime, exclude)
MCPIntegrator.update_lockfile(builtins.set(), mcp_configs={})
logger.verbose_detail("No MCP dependencies found in apm.yml")
elif not should_install_mcp and old_mcp_servers:
# --only=apm: APM install regenerated the lockfile and dropped
# mcp_servers. Restore the previous set so it is not lost.
MCPIntegrator.update_lockfile(old_mcp_servers, mcp_configs=old_mcp_configs)
# Show diagnostics and final install summary
if apm_diagnostics and apm_diagnostics.has_diagnostics:
apm_diagnostics.render_summary()
else:
_rich_blank_line()
error_count = 0
if apm_diagnostics:
try:
error_count = int(apm_diagnostics.error_count)
except (TypeError, ValueError):
error_count = 0
logger.install_summary(apm_count=apm_count, mcp_count=mcp_count, errors=error_count)
# Hard-fail when critical security findings blocked any package.
# Consistent with apm unpack which also hard-fails on critical.
# Use --force to override.
if not force and apm_diagnostics and apm_diagnostics.has_critical_security:
sys.exit(1)
except Exception as e:
logger.error(f"Error installing dependencies: {e}")
if not verbose:
logger.progress("Run with --verbose for detailed diagnostics")
sys.exit(1)
# ---------------------------------------------------------------------------
# Install engine
# ---------------------------------------------------------------------------
def _pre_deploy_security_scan(
install_path: Path,
diagnostics: DiagnosticCollector,
package_name: str = "",
force: bool = False,
logger=None,
) -> bool:
"""Scan package source files for hidden characters BEFORE deployment.
Delegates to :class:`SecurityGate` for the scan->classify->decide pipeline.
Inline CLI feedback (error/info lines) is kept here because it is
install-specific formatting.
Returns:
True if deployment should proceed, False to block.
"""
from ..security.gate import BLOCK_POLICY, SecurityGate
verdict = SecurityGate.scan_files(
install_path, policy=BLOCK_POLICY, force=force
)
if not verdict.has_findings:
return True
# Record into diagnostics (consistent messaging via gate)
SecurityGate.report(verdict, diagnostics, package=package_name, force=force)
if verdict.should_block:
if logger:
logger.error(
f" Blocked: {package_name or 'package'} contains "
f"critical hidden character(s)"
)
logger.progress(f" └─ Inspect source: {install_path}")
logger.progress(" └─ Use --force to deploy anyway")
return False
return True
def _integrate_package_primitives(
package_info,
project_root,
*,
integrate_vscode,
integrate_claude,
integrate_opencode=False,
prompt_integrator,
agent_integrator,
skill_integrator,
instruction_integrator,
command_integrator,
hook_integrator,
force,
managed_files,
diagnostics,
package_name="",
logger=None,
):
"""Run the full integration pipeline for a single package.
Returns a dict with integration counters and the list of deployed file paths.
"""
result = {
"prompts": 0,
"agents": 0,
"skills": 0,
"sub_skills": 0,
"instructions": 0,
"commands": 0,
"hooks": 0,
"links_resolved": 0,
"deployed_files": [],
}
deployed = result["deployed_files"]
if not (integrate_vscode or integrate_claude or integrate_opencode):
return result
def _log_integration(msg):
if logger:
logger.tree_item(msg)
# --- prompts ---
prompt_result = prompt_integrator.integrate_package_prompts(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if prompt_result.files_integrated > 0:
result["prompts"] += prompt_result.files_integrated
_log_integration(f" └─ {prompt_result.files_integrated} prompts integrated -> .github/prompts/")
if prompt_result.files_updated > 0:
_log_integration(f" └─ {prompt_result.files_updated} prompts updated")
result["links_resolved"] += prompt_result.links_resolved
for tp in prompt_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- agents (.github) ---
agent_result = agent_integrator.integrate_package_agents(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if agent_result.files_integrated > 0:
result["agents"] += agent_result.files_integrated
_log_integration(f" └─ {agent_result.files_integrated} agents integrated -> .github/agents/")
if agent_result.files_updated > 0:
_log_integration(f" └─ {agent_result.files_updated} agents updated")
result["links_resolved"] += agent_result.links_resolved
for tp in agent_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- skills ---
if integrate_vscode or integrate_claude or integrate_opencode:
skill_result = skill_integrator.integrate_package_skill(
package_info, project_root,
diagnostics=diagnostics, managed_files=managed_files, force=force,
)
if skill_result.skill_created:
result["skills"] += 1
_log_integration(f" └─ Skill integrated -> .github/skills/")
if skill_result.sub_skills_promoted > 0:
result["sub_skills"] += skill_result.sub_skills_promoted
_log_integration(f" └─ {skill_result.sub_skills_promoted} skill(s) integrated -> .github/skills/")
for tp in skill_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- instructions (.github) ---
if integrate_vscode:
instruction_result = instruction_integrator.integrate_package_instructions(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if instruction_result.files_integrated > 0:
result["instructions"] += instruction_result.files_integrated
_log_integration(f" └─ {instruction_result.files_integrated} instruction(s) integrated -> .github/instructions/")
result["links_resolved"] += instruction_result.links_resolved
for tp in instruction_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- Cursor rules (.cursor/rules/) ---
cursor_rules_result = instruction_integrator.integrate_package_instructions_cursor(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if cursor_rules_result.files_integrated > 0:
result["instructions"] += cursor_rules_result.files_integrated
_log_integration(f" └─ {cursor_rules_result.files_integrated} rule(s) integrated -> .cursor/rules/")
result["links_resolved"] += cursor_rules_result.links_resolved
for tp in cursor_rules_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- Claude agents (.claude) ---
if integrate_claude:
claude_agent_result = agent_integrator.integrate_package_agents_claude(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if claude_agent_result.files_integrated > 0:
result["agents"] += claude_agent_result.files_integrated
_log_integration(f" └─ {claude_agent_result.files_integrated} agents integrated -> .claude/agents/")
result["links_resolved"] += claude_agent_result.links_resolved
for tp in claude_agent_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- Cursor agents (.cursor) ---
cursor_agent_result = agent_integrator.integrate_package_agents_cursor(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if cursor_agent_result.files_integrated > 0:
result["agents"] += cursor_agent_result.files_integrated
_log_integration(f" └─ {cursor_agent_result.files_integrated} agents integrated -> .cursor/agents/")
result["links_resolved"] += cursor_agent_result.links_resolved
for tp in cursor_agent_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- OpenCode agents (.opencode) ---
opencode_agent_result = agent_integrator.integrate_package_agents_opencode(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if opencode_agent_result.files_integrated > 0:
result["agents"] += opencode_agent_result.files_integrated
_log_integration(f" └─ {opencode_agent_result.files_integrated} agents integrated -> .opencode/agents/")
result["links_resolved"] += opencode_agent_result.links_resolved
for tp in opencode_agent_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- commands (.claude) ---
command_result = command_integrator.integrate_package_commands(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if command_result.files_integrated > 0:
result["commands"] += command_result.files_integrated
_log_integration(f" └─ {command_result.files_integrated} commands integrated -> .claude/commands/")
if command_result.files_updated > 0:
_log_integration(f" └─ {command_result.files_updated} commands updated")
result["links_resolved"] += command_result.links_resolved
for tp in command_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- OpenCode commands (.opencode) ---
opencode_command_result = command_integrator.integrate_package_commands_opencode(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if opencode_command_result.files_integrated > 0:
result["commands"] += opencode_command_result.files_integrated
_log_integration(f" └─ {opencode_command_result.files_integrated} commands integrated -> .opencode/commands/")
result["links_resolved"] += opencode_command_result.links_resolved
for tp in opencode_command_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# --- hooks ---
if integrate_vscode:
hook_result = hook_integrator.integrate_package_hooks(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if hook_result.hooks_integrated > 0:
result["hooks"] += hook_result.hooks_integrated
_log_integration(f" └─ {hook_result.hooks_integrated} hook(s) integrated -> .github/hooks/")
for tp in hook_result.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
if integrate_claude:
hook_result_claude = hook_integrator.integrate_package_hooks_claude(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if hook_result_claude.hooks_integrated > 0:
result["hooks"] += hook_result_claude.hooks_integrated
_log_integration(f" └─ {hook_result_claude.hooks_integrated} hook(s) integrated -> .claude/settings.json")
for tp in hook_result_claude.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
# Cursor hooks (.cursor/hooks.json) — method self-guards on .cursor/ existence
hook_result_cursor = hook_integrator.integrate_package_hooks_cursor(
package_info, project_root,
force=force, managed_files=managed_files,
diagnostics=diagnostics,
)
if hook_result_cursor.hooks_integrated > 0:
result["hooks"] += hook_result_cursor.hooks_integrated
_log_integration(f" └─ {hook_result_cursor.hooks_integrated} hook(s) integrated -> .cursor/hooks.json")
for tp in hook_result_cursor.target_paths:
deployed.append(tp.relative_to(project_root).as_posix())
return result
def _copy_local_package(dep_ref, install_path, project_root):
"""Copy a local package to apm_modules/.
Args:
dep_ref: DependencyReference with is_local=True
install_path: Target path under apm_modules/
project_root: Project root for resolving relative paths
Returns:
install_path on success, None on failure
"""
import shutil
local = Path(dep_ref.local_path).expanduser()
if not local.is_absolute():
local = (project_root / local).resolve()
else:
local = local.resolve()