-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
927 lines (809 loc) · 35.1 KB
/
Copy pathcli.py
File metadata and controls
927 lines (809 loc) · 35.1 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
"""APM dependency management CLI commands."""
import shutil
import sys
from pathlib import Path
import click
# Import existing APM components
from ...constants import APM_MODULES_DIR, APM_YML_FILENAME, SKILL_MD_FILENAME
from ...core.command_logger import CommandLogger
from ...core.target_detection import TargetParamType
from ...models.apm_package import APMPackage, ValidationResult, validate_apm_package # noqa: F401
from .._helpers import _expand_with_ancestors, _standalone_installed_packages
from ._utils import (
_count_primitives,
_get_package_display_info,
_is_nested_under_package,
)
# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------
def _format_primitive_counts(primitives):
"""Format primitive type counts into a comma-separated summary string."""
parts = []
for ptype, count in primitives.items():
if count > 0:
parts.append(f"{count} {ptype}")
return ", ".join(parts)
def _deps_list_source_label(
host: str | None,
*,
is_local: bool = False,
lockfile_source: str | None = None,
) -> str:
"""Map host / local flags to the ``apm deps list`` Source column."""
from ...utils.github_host import is_azure_devops_hostname, is_gitlab_hostname
if is_local or lockfile_source == "local":
return "local"
if host and is_azure_devops_hostname(host):
return "azure-devops"
if host and is_gitlab_hostname(host):
return "gitlab"
return "github"
def _dep_display_name(dep) -> str:
"""Get display name for a locked dependency (key@version)."""
key = dep.get_unique_key()
version = (
dep.version
or (dep.resolved_commit[:7] if dep.resolved_commit else None)
or dep.resolved_ref
or "latest"
)
return f"{key}@{version}"
def _add_tree_children(parent_branch, parent_repo_url, children_map, has_rich, depth=0):
"""Recursively add transitive deps as nested children of a tree node."""
kids = children_map.get(parent_repo_url, [])
for child_dep in kids:
child_name = _dep_display_name(child_dep)
child_branch = parent_branch.add(f"[dim]{child_name}[/dim]") if has_rich else child_name
if depth < 5: # Prevent infinite recursion
_add_tree_children(child_branch, child_dep.repo_url, children_map, has_rich, depth + 1)
# ---------------------------------------------------------------------------
# Data resolution — deps list
# ---------------------------------------------------------------------------
def _resolve_scope_deps(apm_dir, logger, insecure_only=False):
"""Resolve installed packages and orphan status for a single scope.
Returns ``(installed_packages, orphaned_packages)`` where
*installed_packages* is a list of dicts and *orphaned_packages* is a
list of name strings, or ``(None, None)`` when no ``apm_modules``
directory exists.
"""
from ...deps.lockfile import LockFile, get_lockfile_path
apm_modules_path = apm_dir / APM_MODULES_DIR
insecure_lock_deps = {}
# Check if apm_modules exists
if not apm_modules_path.exists():
return None, None
# Load project dependencies to check for orphaned packages
# GitHub: owner/repo or owner/virtual-pkg-name (2 levels)
# Azure DevOps: org/project/repo or org/project/virtual-pkg-name (3 levels)
declared_sources = {} # dep_path -> 'github' | 'gitlab' | 'azure-devops' | 'local'
try:
apm_yml_path = apm_dir / APM_YML_FILENAME
if apm_yml_path.exists():
project_package = APMPackage.from_apm_yml(apm_yml_path)
for dep in project_package.get_apm_dependencies():
# Build the expected installed package name
repo_parts = dep.repo_url.split("/")
source = _deps_list_source_label(dep.host, is_local=dep.is_local)
is_ado = dep.is_azure_devops() and len(repo_parts) >= 3
is_gh = len(repo_parts) >= 2
if not dep.is_virtual:
# Regular package: use full repo_url path
if is_ado:
declared_sources[f"{repo_parts[0]}/{repo_parts[1]}/{repo_parts[2]}"] = (
source
)
elif is_gh:
declared_sources[f"{repo_parts[0]}/{repo_parts[1]}"] = source
continue
if dep.is_virtual_subdirectory() and dep.virtual_path:
# Virtual subdirectory packages keep natural path structure.
if is_ado:
declared_sources[
f"{repo_parts[0]}/{repo_parts[1]}/{repo_parts[2]}/{dep.virtual_path}"
] = source
elif is_gh:
declared_sources[f"{repo_parts[0]}/{repo_parts[1]}/{dep.virtual_path}"] = (
source
)
continue
# Virtual file/collection packages are flattened.
package_name = dep.get_virtual_package_name()
if is_ado:
declared_sources[f"{repo_parts[0]}/{repo_parts[1]}/{package_name}"] = source
elif is_gh:
declared_sources[f"{repo_parts[0]}/{package_name}"] = source
except Exception:
pass # Continue without orphan detection if apm.yml parsing fails
# Also load lockfile deps to avoid false orphan flags on transitive deps
try:
lockfile_path = get_lockfile_path(apm_dir)
if lockfile_path.exists():
lockfile = LockFile.read(lockfile_path)
for dep in lockfile.dependencies.values():
# Lockfile keys match declared_sources format (owner/repo)
dep_key = dep.get_unique_key()
if dep_key and dep_key not in declared_sources:
declared_sources[dep_key] = _deps_list_source_label(
dep.host,
lockfile_source=dep.source,
)
if getattr(dep, "is_insecure", False):
insecure_lock_deps[dep_key] = dep
except Exception:
pass # Continue without lockfile if it can't be read
# Scan for installed packages in org-namespaced structure
# Walks the tree to find directories containing apm.yml or SKILL.md,
# handling GitHub (2-level), ADO (3-level), and subdirectory (4+ level) packages.
# First pass: collect valid candidate paths for ancestor-aware orphan check.
scanned_candidates = []
for candidate in apm_modules_path.rglob("*"):
if not candidate.is_dir() or candidate.name.startswith("."):
continue
has_apm_yml = (candidate / APM_YML_FILENAME).exists()
has_skill_md = (candidate / SKILL_MD_FILENAME).exists()
if not has_apm_yml and not has_skill_md:
continue
rel_parts = candidate.relative_to(apm_modules_path).parts
if len(rel_parts) < 2:
continue
# Skip sub-skills inside .apm/ directories -- they belong to the parent package
if ".apm" in rel_parts:
continue
# Skip skill sub-dirs nested inside another package (e.g. plugin
# skills/ directories that are deployment artifacts, not packages).
if (
has_skill_md
and not has_apm_yml
and _is_nested_under_package(candidate, apm_modules_path)
):
continue
scanned_candidates.append((candidate, "/".join(rel_parts), has_apm_yml, has_skill_md))
# Precompute expected paths + ancestors for O(1) orphan checks.
# Mirror prune.py / _check_orphaned_packages: pass the standalone
# installed paths (lockfile-membership + apm.yml fallback) so a
# genuinely orphaned ``owner/repo`` package is not masked when a
# sibling subdirectory dep shares the same install root.
try:
try:
lockfile_path_for_check = get_lockfile_path(apm_dir)
lockfile_for_check = (
LockFile.read(lockfile_path_for_check) if lockfile_path_for_check.exists() else None
)
except Exception:
lockfile_for_check = None
scanned_names = [name for _c, name, _h, _s in scanned_candidates]
standalone_installed_for_check = _standalone_installed_packages(
scanned_names, apm_modules_path, lockfile=lockfile_for_check
)
except Exception:
standalone_installed_for_check = []
declared_with_ancestors = _expand_with_ancestors(
declared_sources.keys(), standalone_installed_for_check
)
installed_packages = []
orphaned_packages = []
for candidate, org_repo_name, has_apm_yml, _has_skill_md in scanned_candidates:
try:
version = "unknown"
if has_apm_yml:
package = APMPackage.from_apm_yml(candidate / APM_YML_FILENAME)
version = package.version or "unknown"
primitives = _count_primitives(candidate)
is_orphaned = org_repo_name not in declared_with_ancestors
if is_orphaned:
orphaned_packages.append(org_repo_name)
locked_dep = insecure_lock_deps.get(org_repo_name)
installed_packages.append(
{
"name": org_repo_name,
"version": version,
"source": "orphaned"
if is_orphaned
else declared_sources.get(org_repo_name, "github"),
"primitives": primitives,
"path": str(candidate),
"is_orphaned": is_orphaned,
"is_insecure": locked_dep is not None,
"insecure_via": (
f"via {locked_dep.resolved_by}"
if locked_dep and locked_dep.resolved_by
else "direct"
),
}
)
except Exception as e:
logger.warning(f"Failed to read package {org_repo_name}: {e}")
if insecure_only:
installed_packages = [pkg for pkg in installed_packages if pkg["is_insecure"]]
return installed_packages, sorted(orphaned_packages)
@click.group(help="Manage APM package dependencies")
def deps():
"""APM dependency management commands."""
pass
def _show_scope_deps(scope_label, apm_dir, logger, console, has_rich, insecure_only=False):
"""Display dependencies for a single scope (Project or Global)."""
installed_packages, orphaned_packages = _resolve_scope_deps(apm_dir, logger, insecure_only)
if installed_packages is None:
logger.progress(f"No APM dependencies installed ({scope_label} scope)")
logger.verbose_detail("Run 'apm install' to install dependencies from apm.yml")
return
if not installed_packages:
if insecure_only:
logger.progress(f"No insecure APM dependencies installed ({scope_label} scope)")
else:
logger.progress(
f"apm_modules/ directory exists but contains no valid packages ({scope_label} scope)"
)
return
# Display packages in table format
if has_rich:
from rich.table import Table
table = Table(
title=(
f" Insecure APM Dependencies ({scope_label})"
if insecure_only
else f" APM Dependencies ({scope_label})"
),
show_header=True,
header_style="bold cyan",
)
table.add_column("Package", style="bold white")
table.add_column("Version", style="yellow")
table.add_column("Source", style="blue")
if insecure_only:
table.add_column("Origin", style="bold red")
table.add_column("Prompts", style="magenta", justify="center")
table.add_column("Instructions", style="green", justify="center")
table.add_column("Agents", style="cyan", justify="center")
table.add_column("Skills", style="yellow", justify="center")
table.add_column("Hooks", style="red", justify="center")
for pkg in installed_packages:
p = pkg["primitives"]
table.add_row(
pkg["name"],
pkg["version"],
pkg["source"],
*([pkg["insecure_via"]] if insecure_only else []),
str(p.get("prompts", 0)) if p.get("prompts", 0) > 0 else "-",
str(p.get("instructions", 0)) if p.get("instructions", 0) > 0 else "-",
str(p.get("agents", 0)) if p.get("agents", 0) > 0 else "-",
str(p.get("skills", 0)) if p.get("skills", 0) > 0 else "-",
str(p.get("hooks", 0)) if p.get("hooks", 0) > 0 else "-",
)
console.print(table)
# Show orphaned packages warning -- routed through CommandLogger
# so output goes through the central STATUS_SYMBOLS prefix path
# (no raw `[!]` literal that Rich would parse as markup) and so
# behaviour is consistent with prune.py.
if orphaned_packages:
logger.warning(f"{len(orphaned_packages)} orphaned package(s) found (not in apm.yml):")
for pkg in orphaned_packages:
logger.warning(f" - {pkg}")
logger.info("Run 'apm prune' to remove orphaned packages")
else:
# Fallback text table
if insecure_only:
click.echo(f" Insecure APM Dependencies ({scope_label}):")
click.echo(
f"{'Package':<30} {'Version':<10} {'Source':<12} {'Origin':<18} "
f"{'Prompts':>7} {'Instr':>7} {'Agents':>7} {'Skills':>7} {'Hooks':>7}"
)
click.echo("-" * 117)
else:
click.echo(f" APM Dependencies ({scope_label}):")
click.echo(
f"{'Package':<30} {'Version':<10} {'Source':<12} {'Prompts':>7} {'Instr':>7} {'Agents':>7} {'Skills':>7} {'Hooks':>7}"
)
click.echo("-" * 98)
for pkg in installed_packages:
p = pkg["primitives"]
name = pkg["name"][:28]
version = pkg["version"][:8]
source = pkg["source"][:10]
insecure_via = pkg["insecure_via"][:16]
prompts = str(p.get("prompts", 0)) if p.get("prompts", 0) > 0 else "-"
instructions = str(p.get("instructions", 0)) if p.get("instructions", 0) > 0 else "-"
agents = str(p.get("agents", 0)) if p.get("agents", 0) > 0 else "-"
skills = str(p.get("skills", 0)) if p.get("skills", 0) > 0 else "-"
hooks = str(p.get("hooks", 0)) if p.get("hooks", 0) > 0 else "-"
if insecure_only:
click.echo(
f"{name:<30} {version:<10} {source:<12} {insecure_via:<18} "
f"{prompts:>7} {instructions:>7} {agents:>7} {skills:>7} {hooks:>7}"
)
else:
click.echo(
f"{name:<30} {version:<10} {source:<12} {prompts:>7} {instructions:>7} {agents:>7} {skills:>7} {hooks:>7}"
)
# Show orphaned packages warning -- route through CommandLogger
# for consistency with the rich branch above and with prune.py.
if orphaned_packages:
logger.warning(f"{len(orphaned_packages)} orphaned package(s) found (not in apm.yml):")
for pkg in orphaned_packages:
logger.warning(f" - {pkg}")
logger.info("Run 'apm prune' to remove orphaned packages")
@deps.command(name="list", help="List installed APM dependencies")
@click.option(
"--global",
"-g",
"global_",
is_flag=True,
default=False,
help="List user-scope dependencies (~/.apm/) instead of project",
)
@click.option(
"--all",
"show_all",
is_flag=True,
default=False,
help="Show both project and user-scope dependencies",
)
@click.option(
"--insecure",
"insecure_only",
is_flag=True,
default=False,
help="Show only installed dependencies locked to http:// sources",
)
def list_packages(global_, show_all, insecure_only):
"""Show all installed APM dependencies with context files and agent workflows."""
logger = CommandLogger("deps-list")
try:
# Import Rich components with fallback
import shutil
from rich.console import Console
term_width = shutil.get_terminal_size((120, 24)).columns
console = Console(width=max(120, term_width), height=24)
has_rich = True
except ImportError:
has_rich = False
console = None
try:
from ...core.scope import InstallScope, get_apm_dir
if show_all:
# Show both scopes
_show_scope_deps(
"Project",
get_apm_dir(InstallScope.PROJECT),
logger,
console,
has_rich,
insecure_only=insecure_only,
)
if console and has_rich:
console.print() # spacing between tables
_show_scope_deps(
"Global",
get_apm_dir(InstallScope.USER),
logger,
console,
has_rich,
insecure_only=insecure_only,
)
elif global_:
_show_scope_deps(
"Global",
get_apm_dir(InstallScope.USER),
logger,
console,
has_rich,
insecure_only=insecure_only,
)
else:
_show_scope_deps(
"Project",
get_apm_dir(InstallScope.PROJECT),
logger,
console,
has_rich,
insecure_only=insecure_only,
)
except Exception as e:
logger.error(f"Error listing dependencies: {e}")
sys.exit(1)
# ---------------------------------------------------------------------------
# Data resolution — deps tree
# ---------------------------------------------------------------------------
def _build_dep_tree(apm_dir):
"""Build dependency tree data from lockfile or directory scan.
Returns a dict describing the tree structure::
{
'project_name': str,
'apm_modules_path': Path,
'source': 'lockfile' | 'directory',
'direct': [dep, ...], # lockfile mode only
'children_map': {url: [dep]}, # lockfile mode only
'scanned_packages': [{...}], # directory fallback only
'has_modules': bool,
}
"""
apm_modules_path = apm_dir / APM_MODULES_DIR
# Load project info
project_name = "my-project"
try:
apm_yml_path = apm_dir / APM_YML_FILENAME
if apm_yml_path.exists():
root_package = APMPackage.from_apm_yml(apm_yml_path)
project_name = root_package.name
except Exception:
pass
result = {
"project_name": project_name,
"apm_modules_path": apm_modules_path,
"source": "directory",
"direct": [],
"children_map": {},
"scanned_packages": [],
"has_modules": apm_modules_path.exists(),
}
# Try to load lockfile for accurate tree with depth/parent info
try:
from ...deps.lockfile import LockFile, get_lockfile_path
lockfile_path = get_lockfile_path(apm_dir)
if lockfile_path.exists():
lockfile = LockFile.read(lockfile_path)
if lockfile:
lockfile_deps = lockfile.get_package_dependencies()
if lockfile_deps:
result["source"] = "lockfile"
result["direct"] = [d for d in lockfile_deps if d.depth <= 1]
transitive = [d for d in lockfile_deps if d.depth > 1]
children_map: dict[str, list] = {}
for dep in transitive:
parent_key = dep.resolved_by or ""
if parent_key not in children_map:
children_map[parent_key] = []
children_map[parent_key].append(dep)
result["children_map"] = children_map
return result
except Exception:
pass
# Fallback: scan apm_modules directory (no lockfile)
if not apm_modules_path.exists():
return result
scanned = []
for candidate in sorted(apm_modules_path.rglob("*")):
if not candidate.is_dir() or candidate.name.startswith("."):
continue
has_apm = (candidate / APM_YML_FILENAME).exists()
has_skill = (candidate / SKILL_MD_FILENAME).exists()
if not has_apm and not has_skill:
continue
rel_parts = candidate.relative_to(apm_modules_path).parts
if len(rel_parts) < 2:
continue
if ".apm" in rel_parts:
continue
if has_skill and not has_apm and _is_nested_under_package(candidate, apm_modules_path):
continue
info = _get_package_display_info(candidate)
primitives = _count_primitives(candidate)
scanned.append(
{
"display_name": info["display_name"],
"primitives": primitives,
}
)
result["scanned_packages"] = scanned
return result
@deps.command(help="Show dependency tree structure")
@click.option(
"--global",
"-g",
"global_",
is_flag=True,
default=False,
help="Show user-scope dependency tree (~/.apm/)",
)
def tree(global_):
"""Display dependencies in hierarchical tree format using lockfile."""
logger = CommandLogger("deps-tree")
try:
# Import Rich components with fallback
from rich.console import Console
from rich.tree import Tree
console = Console()
has_rich = True
except ImportError:
has_rich = False
console = None
try:
from ...core.scope import InstallScope, get_apm_dir
scope = InstallScope.USER if global_ else InstallScope.PROJECT
apm_dir = get_apm_dir(scope)
tree_data = _build_dep_tree(apm_dir)
project_name = tree_data["project_name"]
apm_modules_path = tree_data["apm_modules_path"]
if tree_data["source"] == "lockfile":
direct = tree_data["direct"]
children_map = tree_data["children_map"]
if has_rich:
root_tree = Tree(f"[bold cyan]{project_name}[/bold cyan] (local)")
if not direct:
root_tree.add("[dim]No dependencies installed[/dim]")
else:
for dep in direct:
display = _dep_display_name(dep)
install_key = dep.get_unique_key()
install_path = apm_modules_path / install_key
branch = root_tree.add(f"[green]{display}[/green]")
if install_path.exists():
prim_summary = _format_primitive_counts(_count_primitives(install_path))
if prim_summary:
branch.add(f"[dim]{prim_summary}[/dim]")
_add_tree_children(branch, dep.repo_url, children_map, has_rich)
console.print(root_tree)
else:
click.echo(f"{project_name} (local)")
if not direct:
click.echo("+-- No dependencies installed")
else:
for i, dep in enumerate(direct):
is_last = i == len(direct) - 1
prefix = "+-- " if is_last else "|-- "
display = _dep_display_name(dep)
click.echo(f"{prefix}{display}")
# Show transitive deps
kids = children_map.get(dep.repo_url, [])
sub_prefix = " " if is_last else "| "
for j, child in enumerate(kids):
child_is_last = j == len(kids) - 1
child_prefix = "+-- " if child_is_last else "|-- "
click.echo(f"{sub_prefix}{child_prefix}{_dep_display_name(child)}")
# Fallback: scan apm_modules directory (no lockfile)
elif has_rich:
root_tree = Tree(f"[bold cyan]{project_name}[/bold cyan] (local)")
if not tree_data["has_modules"]:
root_tree.add("[dim]No dependencies installed[/dim]")
else:
for pkg in tree_data["scanned_packages"]:
branch = root_tree.add(f"[green]{pkg['display_name']}[/green]")
prim_summary = _format_primitive_counts(pkg["primitives"])
if prim_summary:
branch.add(f"[dim]{prim_summary}[/dim]")
console.print(root_tree)
else:
click.echo(f"{project_name} (local)")
if not tree_data["has_modules"]:
click.echo("+-- No dependencies installed")
except Exception as e:
logger.error(f"Error showing dependency tree: {e}")
sys.exit(1)
@deps.command(help="Remove all APM dependencies")
@click.option(
"--dry-run", is_flag=True, default=False, help="Show what would be removed without removing"
)
@click.option("--yes", "-y", is_flag=True, default=False, help="Skip confirmation prompt")
def clean(dry_run: bool, yes: bool):
"""Remove entire apm_modules/ directory."""
logger = CommandLogger("deps-clean")
project_root = Path(".")
apm_modules_path = project_root / APM_MODULES_DIR
if not apm_modules_path.exists():
logger.progress("No apm_modules/ directory found - already clean")
return
# Count actual installed packages (not just top-level dirs like org namespaces or _local)
from ._utils import _scan_installed_packages
packages = _scan_installed_packages(apm_modules_path)
package_count = len(packages)
if dry_run:
logger.progress(f"Dry run: would remove apm_modules/ ({package_count} package(s))")
for pkg in sorted(packages):
logger.progress(f" - {pkg}")
return
logger.warning(
f"This will remove the entire apm_modules/ directory ({package_count} package(s))"
)
# Confirmation prompt (skip if --yes provided)
if not yes:
try:
from rich.prompt import Confirm
confirm = Confirm.ask("Continue?")
except ImportError:
confirm = click.confirm("Continue?")
if not confirm:
logger.progress("Operation cancelled")
return
try:
shutil.rmtree(apm_modules_path)
logger.success("Successfully removed apm_modules/ directory")
except Exception as e:
logger.error(f"Error removing apm_modules/: {e}")
sys.exit(1)
@deps.command(help="Update APM dependencies to latest refs")
@click.argument("packages", nargs=-1)
@click.option("--verbose", "-v", is_flag=True, help="Show detailed update information")
@click.option(
"--force",
is_flag=True,
help="Overwrite locally-authored files on collision",
)
@click.option(
"--target",
"-t",
type=TargetParamType(),
default=None,
help="Target platform (comma-separated). Values: copilot, claude, cursor, opencode, codex, gemini, windsurf, agent-skills, all. 'agent-skills' deploys to .agents/skills/ (cross-client). 'all' = copilot+claude+cursor+opencode+codex+gemini+windsurf (excludes agent-skills); combine with 'agent-skills' for both. 'copilot-cowork' is also accepted when the copilot-cowork experimental flag is enabled (run 'apm experimental enable copilot-cowork').",
)
@click.option(
"--parallel-downloads",
type=int,
default=4,
show_default=True,
help="Max concurrent package downloads (0 to disable parallelism)",
)
@click.option(
"--global",
"-g",
"global_",
is_flag=True,
default=False,
help="Update user-scope dependencies (~/.apm/)",
)
@click.option(
"--legacy-skill-paths",
"legacy_skill_paths",
is_flag=True,
default=False,
help=(
"Deploy skill files to per-client paths (e.g. .cursor/skills/) instead of "
"the shared .agents/skills/ directory. Compatibility flag for projects that "
"need per-client skill layouts."
),
)
def update(packages, verbose, force, target, parallel_downloads, global_, legacy_skill_paths):
"""Update APM dependencies to latest git refs.
Re-resolves git references (branches/tags) to their current SHAs,
downloads updated content, re-integrates primitives, and regenerates
the lockfile.
\b
Examples:
apm deps update # Update all packages
apm deps update org/repo # Update one package
apm deps update org/a org/b # Update specific packages
apm deps update --verbose # Show detailed progress
"""
from ...core.auth import AuthResolver
from ...core.command_logger import InstallLogger
from ..install import (
_APM_IMPORT_ERROR,
APM_DEPS_AVAILABLE,
_install_apm_dependencies,
)
logger = InstallLogger(verbose=verbose, partial=bool(packages))
if not APM_DEPS_AVAILABLE:
logger.error("APM dependency system not available")
if _APM_IMPORT_ERROR:
logger.progress(f"Import error: {_APM_IMPORT_ERROR}")
sys.exit(1)
from ...core.scope import InstallScope, get_apm_dir
scope = InstallScope.USER if global_ else InstallScope.PROJECT
project_root = get_apm_dir(scope)
apm_yml_path = project_root / APM_YML_FILENAME
if not apm_yml_path.exists():
scope_hint = "~/.apm/" if global_ else "current directory"
logger.error(f"No {APM_YML_FILENAME} found in {scope_hint}")
sys.exit(1)
try:
apm_package = APMPackage.from_apm_yml(apm_yml_path)
except Exception as e:
logger.error(f"Failed to parse {APM_YML_FILENAME}: {e}")
sys.exit(1)
all_deps = apm_package.get_apm_dependencies() + apm_package.get_dev_apm_dependencies()
if not all_deps:
logger.progress("No APM dependencies defined in apm.yml")
return
# Validate and normalize requested packages to canonical dependency keys.
# The install engine matches only_packages by DependencyReference identity
# (e.g. "owner/repo"), so short names like "compliance-rules" must be
# mapped to their canonical form before calling the engine.
only_pkgs = None
if packages:
token_to_canonical: dict[str, str] = {}
for dep in all_deps:
canonical_key = dep.get_unique_key() or dep.repo_url or dep.get_display_name()
tokens = {canonical_key, dep.get_display_name(), dep.repo_url}
if hasattr(dep, "alias") and dep.alias:
tokens.add(dep.alias)
parts = dep.repo_url.split("/")
if len(parts) >= 2:
tokens.add(parts[-1])
for token in tokens:
if token and token not in token_to_canonical:
token_to_canonical[token] = canonical_key
only_pkgs = []
seen: dict[str, bool] = {}
for pkg in packages:
canonical = token_to_canonical.get(pkg)
if not canonical:
available = ", ".join(dep.get_display_name() for dep in all_deps)
logger.error(f"Package '{pkg}' not found in {APM_YML_FILENAME}")
logger.progress(f"Available: {available}")
sys.exit(1)
if canonical not in seen:
seen[canonical] = True
only_pkgs.append(canonical)
# Migrate legacy lockfile first, then snapshot SHAs for before/after diff
from ...deps.lockfile import LockFile, get_lockfile_path, migrate_lockfile_if_needed
lockfile_path = get_lockfile_path(project_root)
migrate_lockfile_if_needed(project_root)
old_lockfile = LockFile.read(lockfile_path)
had_baseline = old_lockfile is not None
old_shas: dict = {}
if old_lockfile:
for key, dep in old_lockfile.dependencies.items():
old_shas[key] = dep.resolved_commit
auth_resolver = AuthResolver()
noun = f"{len(packages)} package(s)" if packages else f"all {len(all_deps)} dependencies"
# Resolve --legacy-skill-paths: CLI flag wins, then env var fallback.
if not legacy_skill_paths:
from ...integration.targets import should_use_legacy_skill_paths
legacy_skill_paths = should_use_legacy_skill_paths()
logger.start(f"Updating {noun}...")
try:
install_result = _install_apm_dependencies(
apm_package,
update_refs=True,
verbose=verbose,
only_packages=only_pkgs,
force=force,
parallel_downloads=parallel_downloads,
logger=logger,
auth_resolver=auth_resolver,
target=target,
scope=scope,
legacy_skill_paths=legacy_skill_paths,
)
except Exception as e:
logger.error(f"Update failed: {e}")
if not verbose:
logger.progress("Run with --verbose for detailed diagnostics")
sys.exit(1)
# Show diagnostics if any
if install_result.diagnostics and install_result.diagnostics.has_diagnostics:
install_result.diagnostics.render_summary()
# Compare old vs new lockfile SHAs to show what changed
new_lockfile = LockFile.read(lockfile_path)
changed: list = []
if new_lockfile:
for key, dep in new_lockfile.dependencies.items():
old_sha = old_shas.get(key)
new_sha = dep.resolved_commit
if old_sha and new_sha and old_sha != new_sha:
changed.append((key, old_sha[:8], new_sha[:8], dep.resolved_ref or ""))
error_count = 0
if install_result.diagnostics:
try:
error_count = int(install_result.diagnostics.error_count)
except (TypeError, ValueError):
error_count = 0
if changed:
pkg_noun = "package" if len(changed) == 1 else "packages"
if error_count > 0:
logger.warning(f"Updated {len(changed)} {pkg_noun} with {error_count} error(s).")
else:
logger.success(f"Updated {len(changed)} {pkg_noun}:")
for key, old_sha, new_sha, ref in changed:
ref_str = f" ({ref})" if ref else ""
click.echo(f" {key}{ref_str}: {old_sha} -> {new_sha}")
elif error_count > 0:
logger.error(f"Update failed with {error_count} error(s).")
elif not had_baseline:
logger.success("Update complete.")
else:
logger.success("All packages already at latest refs.")
@deps.command(help="Show detailed package information")
@click.argument("package", required=True)
def info(package: str):
"""Show detailed information about a specific package including context files and workflows."""
from ..view import display_package_info, resolve_package_path
logger = CommandLogger("deps-info")
project_root = Path(".")
apm_modules_path = project_root / APM_MODULES_DIR
if not apm_modules_path.exists():
logger.error("No apm_modules/ directory found")
logger.progress("Run 'apm install' to install dependencies first")
sys.exit(1)
package_path = resolve_package_path(package, apm_modules_path, logger)
display_package_info(package, package_path, logger)