-
Notifications
You must be signed in to change notification settings - Fork 9.5k
Expand file tree
/
Copy pathpresets.py
More file actions
3109 lines (2685 loc) · 126 KB
/
presets.py
File metadata and controls
3109 lines (2685 loc) · 126 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
"""
Preset Manager for Spec Kit
Handles installation, removal, and management of Spec Kit presets.
Presets are self-contained, versioned collections of templates
(artifact, command, and script templates) that can be installed to
customize the Spec-Driven Development workflow.
"""
import copy
import json
import hashlib
import os
import tempfile
import zipfile
import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Dict, List, Any
if TYPE_CHECKING:
from .agents import CommandRegistrar
from datetime import datetime, timezone
import re
import yaml
from packaging import version as pkg_version
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from .extensions import REINSTALL_COMMAND, ExtensionRegistry, normalize_priority
def _substitute_core_template(
body: str,
cmd_name: str,
project_root: "Path",
registrar: "CommandRegistrar",
) -> "tuple[str, dict]":
"""Substitute {CORE_TEMPLATE} with the body of the installed core command template.
Args:
body: Preset command body (may contain {CORE_TEMPLATE} placeholder).
cmd_name: Full command name (e.g. "speckit.git.feature" or "speckit.specify").
project_root: Project root path.
registrar: CommandRegistrar instance for parse_frontmatter.
Returns:
A tuple of (body, core_frontmatter) where body has {CORE_TEMPLATE} replaced
by the core template body and core_frontmatter holds the core template's parsed
frontmatter (so callers can inherit scripts/agent_scripts from it). Both are
unchanged / empty when the placeholder is absent or the core template file does
not exist.
"""
if "{CORE_TEMPLATE}" not in body:
return body, {}
# Derive the short name (strip "speckit." prefix) used by core command templates.
short_name = cmd_name
if short_name.startswith("speckit."):
short_name = short_name[len("speckit."):]
resolver = PresetResolver(project_root)
# Resolution order for the core template:
# 1. resolve_core(cmd_name) — covers tier-1 project overrides and tier-3/4
# name-based lookup (file named <cmd_name>.md). Checked first so that a
# local override always wins, even for extension commands.
# 2. resolve_extension_command_via_manifest(cmd_name) — manifest-based tier-3
# fallback for extension commands whose file is named differently from the
# command name (e.g. speckit.selftest.extension → commands/selftest.md).
# 3. resolve_core(short_name) — core template fallback using the unprefixed
# name (e.g. specify → templates/commands/specify.md).
# resolve_core() skips installed presets (tier 2) to prevent accidental nesting
# where another preset's wrap output is mistaken for the real core.
core_file = (
resolver.resolve_core(cmd_name, "command")
or resolver.resolve_extension_command_via_manifest(cmd_name)
or resolver.resolve_core(short_name, "command")
)
if core_file is None:
return body, {}
core_frontmatter, core_body = registrar.parse_frontmatter(core_file.read_text(encoding="utf-8"))
return body.replace("{CORE_TEMPLATE}", core_body), core_frontmatter
@dataclass
class PresetCatalogEntry:
"""Represents a single entry in the preset catalog stack."""
url: str
name: str
priority: int
install_allowed: bool
description: str = ""
class PresetError(Exception):
"""Base exception for preset-related errors."""
pass
class PresetValidationError(PresetError):
"""Raised when preset manifest validation fails."""
pass
class PresetCompatibilityError(PresetError):
"""Raised when preset is incompatible with current environment."""
pass
VALID_PRESET_TEMPLATE_TYPES = {"template", "command", "script"}
VALID_PRESET_STRATEGIES = {"replace", "prepend", "append", "wrap"}
# Scripts only support replace and wrap (prepend/append don't make semantic sense for executable code)
VALID_SCRIPT_STRATEGIES = {"replace", "wrap"}
class PresetManifest:
"""Represents and validates a preset manifest (preset.yml)."""
SCHEMA_VERSION = "1.0"
REQUIRED_FIELDS = ["schema_version", "preset", "requires", "provides"]
def __init__(self, manifest_path: Path):
"""Load and validate preset manifest.
Args:
manifest_path: Path to preset.yml file
Raises:
PresetValidationError: If manifest is invalid
"""
self.path = manifest_path
self.data = self._load_yaml(manifest_path)
self._validate()
def _load_yaml(self, path: Path) -> dict:
"""Load YAML file safely."""
try:
with open(path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
except yaml.YAMLError as e:
raise PresetValidationError(f"Invalid YAML in {path}: {e}")
except FileNotFoundError:
raise PresetValidationError(f"Manifest not found: {path}")
except UnicodeDecodeError as e:
raise PresetValidationError(
f"Manifest is not valid UTF-8: {path} ({e.reason} at byte {e.start})"
)
except OSError as e:
raise PresetValidationError(f"Could not read manifest {path}: {e}")
if data is None:
return {}
if not isinstance(data, dict):
raise PresetValidationError(
f"Manifest must be a YAML mapping, got {type(data).__name__}: {path}"
)
return data
def _validate(self):
"""Validate manifest structure and required fields."""
# Check required top-level fields
for field in self.REQUIRED_FIELDS:
if field not in self.data:
raise PresetValidationError(f"Missing required field: {field}")
# Validate schema version
if self.data["schema_version"] != self.SCHEMA_VERSION:
raise PresetValidationError(
f"Unsupported schema version: {self.data['schema_version']} "
f"(expected {self.SCHEMA_VERSION})"
)
# Validate preset metadata
pack = self.data["preset"]
for field in ["id", "name", "version", "description"]:
if field not in pack:
raise PresetValidationError(f"Missing preset.{field}")
# Validate pack ID format
if not re.match(r'^[a-z0-9-]+$', pack["id"]):
raise PresetValidationError(
f"Invalid preset ID '{pack['id']}': "
"must be lowercase alphanumeric with hyphens only"
)
# Validate semantic version
try:
pkg_version.Version(pack["version"])
except pkg_version.InvalidVersion:
raise PresetValidationError(f"Invalid version: {pack['version']}")
# Validate requires section
requires = self.data["requires"]
if "speckit_version" not in requires:
raise PresetValidationError("Missing requires.speckit_version")
# Validate provides section
provides = self.data["provides"]
if "templates" not in provides or not provides["templates"]:
raise PresetValidationError(
"Preset must provide at least one template"
)
# Validate templates
for tmpl in provides["templates"]:
if "type" not in tmpl or "name" not in tmpl or "file" not in tmpl:
raise PresetValidationError(
"Template missing 'type', 'name', or 'file'"
)
if tmpl["type"] not in VALID_PRESET_TEMPLATE_TYPES:
raise PresetValidationError(
f"Invalid template type '{tmpl['type']}': "
f"must be one of {sorted(VALID_PRESET_TEMPLATE_TYPES)}"
)
# Validate file path safety: must be relative, no parent traversal
file_path = tmpl["file"]
normalized = os.path.normpath(file_path)
if os.path.isabs(normalized) or normalized.startswith(".."):
raise PresetValidationError(
f"Invalid template file path '{file_path}': "
"must be a relative path within the preset directory"
)
# Validate strategy field (optional, defaults to "replace")
strategy = tmpl.get("strategy", "replace")
if not isinstance(strategy, str):
raise PresetValidationError(
f"Invalid strategy value: must be a string, "
f"got {type(strategy).__name__}"
)
strategy = strategy.lower()
# Persist normalized value so downstream code sees lowercase
if "strategy" in tmpl:
tmpl["strategy"] = strategy
if strategy not in VALID_PRESET_STRATEGIES:
raise PresetValidationError(
f"Invalid strategy '{strategy}': "
f"must be one of {sorted(VALID_PRESET_STRATEGIES)}"
)
if tmpl["type"] == "script" and strategy not in VALID_SCRIPT_STRATEGIES:
raise PresetValidationError(
f"Invalid strategy '{strategy}' for script: "
f"scripts only support {sorted(VALID_SCRIPT_STRATEGIES)}"
)
# Validate template name format
if tmpl["type"] == "command":
# Commands use dot notation (e.g. speckit.specify)
if not re.match(r'^[a-z0-9.-]+$', tmpl["name"]):
raise PresetValidationError(
f"Invalid command name '{tmpl['name']}': "
"must be lowercase alphanumeric with hyphens and dots only"
)
else:
if not re.match(r'^[a-z0-9-]+$', tmpl["name"]):
raise PresetValidationError(
f"Invalid template name '{tmpl['name']}': "
"must be lowercase alphanumeric with hyphens only"
)
@property
def id(self) -> str:
"""Get preset ID."""
return self.data["preset"]["id"]
@property
def name(self) -> str:
"""Get preset name."""
return self.data["preset"]["name"]
@property
def version(self) -> str:
"""Get preset version."""
return self.data["preset"]["version"]
@property
def description(self) -> str:
"""Get preset description."""
return self.data["preset"]["description"]
@property
def author(self) -> str:
"""Get preset author."""
return self.data["preset"].get("author", "")
@property
def requires_speckit_version(self) -> str:
"""Get required spec-kit version range."""
return self.data["requires"]["speckit_version"]
@property
def templates(self) -> List[Dict[str, Any]]:
"""Get list of provided templates."""
return self.data["provides"]["templates"]
@property
def tags(self) -> List[str]:
"""Get preset tags."""
return self.data.get("tags", [])
def get_hash(self) -> str:
"""Calculate SHA256 hash of manifest file."""
with open(self.path, 'rb') as f:
return f"sha256:{hashlib.sha256(f.read()).hexdigest()}"
class PresetRegistry:
"""Manages the registry of installed presets."""
REGISTRY_FILE = ".registry"
SCHEMA_VERSION = "1.0"
def __init__(self, packs_dir: Path):
"""Initialize registry.
Args:
packs_dir: Path to .specify/presets/ directory
"""
self.packs_dir = packs_dir
self.registry_path = packs_dir / self.REGISTRY_FILE
self.data = self._load()
def _load(self) -> dict:
"""Load registry from disk."""
if not self.registry_path.exists():
return {
"schema_version": self.SCHEMA_VERSION,
"presets": {}
}
try:
with open(self.registry_path, 'r') as f:
data = json.load(f)
# Validate loaded data is a dict (handles corrupted registry files)
if not isinstance(data, dict):
return {
"schema_version": self.SCHEMA_VERSION,
"presets": {}
}
# Normalize presets field (handles corrupted presets value)
if not isinstance(data.get("presets"), dict):
data["presets"] = {}
return data
except (json.JSONDecodeError, FileNotFoundError):
return {
"schema_version": self.SCHEMA_VERSION,
"presets": {}
}
def _save(self):
"""Save registry to disk."""
self.packs_dir.mkdir(parents=True, exist_ok=True)
with open(self.registry_path, 'w') as f:
json.dump(self.data, f, indent=2)
def add(self, pack_id: str, metadata: dict):
"""Add preset to registry.
Args:
pack_id: Preset ID
metadata: Pack metadata (version, source, etc.)
"""
self.data["presets"][pack_id] = {
**copy.deepcopy(metadata),
"installed_at": datetime.now(timezone.utc).isoformat()
}
self._save()
def remove(self, pack_id: str):
"""Remove preset from registry.
Args:
pack_id: Preset ID
"""
packs = self.data.get("presets")
if not isinstance(packs, dict):
return
if pack_id in packs:
del packs[pack_id]
self._save()
def update(self, pack_id: str, updates: dict):
"""Update preset metadata in registry.
Merges the provided updates with the existing entry, preserving any
fields not specified. The installed_at timestamp is always preserved
from the original entry.
Args:
pack_id: Preset ID
updates: Partial metadata to merge into existing metadata
Raises:
KeyError: If preset is not installed
"""
packs = self.data.get("presets")
if not isinstance(packs, dict) or pack_id not in packs:
raise KeyError(f"Preset '{pack_id}' not found in registry")
existing = packs[pack_id]
# Handle corrupted registry entries (e.g., string/list instead of dict)
if not isinstance(existing, dict):
existing = {}
# Merge: existing fields preserved, new fields override (deep copy to prevent caller mutation)
merged = {**existing, **copy.deepcopy(updates)}
# Always preserve original installed_at based on key existence, not truthiness,
# to handle cases where the field exists but may be falsy (legacy/corruption)
if "installed_at" in existing:
merged["installed_at"] = existing["installed_at"]
else:
# If not present in existing, explicitly remove from merged if caller provided it
merged.pop("installed_at", None)
packs[pack_id] = merged
self._save()
def restore(self, pack_id: str, metadata: dict):
"""Restore preset metadata to registry without modifying timestamps.
Use this method for rollback scenarios where you have a complete backup
of the registry entry (including installed_at) and want to restore it
exactly as it was.
Args:
pack_id: Preset ID
metadata: Complete preset metadata including installed_at
Raises:
ValueError: If metadata is None or not a dict
"""
if metadata is None or not isinstance(metadata, dict):
raise ValueError(f"Cannot restore '{pack_id}': metadata must be a dict")
# Ensure presets dict exists (handle corrupted registry)
if not isinstance(self.data.get("presets"), dict):
self.data["presets"] = {}
self.data["presets"][pack_id] = copy.deepcopy(metadata)
self._save()
def get(self, pack_id: str) -> Optional[dict]:
"""Get preset metadata from registry.
Returns a deep copy to prevent callers from accidentally mutating
nested internal registry state without going through the write path.
Args:
pack_id: Preset ID
Returns:
Deep copy of preset metadata, or None if not found or corrupted
"""
packs = self.data.get("presets")
if not isinstance(packs, dict):
return None
entry = packs.get(pack_id)
# Return None for missing or corrupted (non-dict) entries
if entry is None or not isinstance(entry, dict):
return None
return copy.deepcopy(entry)
def list(self) -> Dict[str, dict]:
"""Get all installed presets with valid metadata.
Returns a deep copy of presets with dict metadata only.
Corrupted entries (non-dict values) are filtered out.
Returns:
Dictionary of pack_id -> metadata (deep copies), empty dict if corrupted
"""
packs = self.data.get("presets", {}) or {}
if not isinstance(packs, dict):
return {}
# Filter to only valid dict entries to match type contract
return {
pack_id: copy.deepcopy(meta)
for pack_id, meta in packs.items()
if isinstance(meta, dict)
}
def keys(self) -> set:
"""Get all preset IDs including corrupted entries.
Lightweight method that returns IDs without deep-copying metadata.
Use this when you only need to check which presets are tracked.
Returns:
Set of preset IDs (includes corrupted entries)
"""
packs = self.data.get("presets", {}) or {}
if not isinstance(packs, dict):
return set()
return set(packs.keys())
def list_by_priority(self, include_disabled: bool = False) -> List[tuple]:
"""Get all installed presets sorted by priority.
Lower priority number = higher precedence (checked first).
Presets with equal priority are sorted alphabetically by ID
for deterministic ordering.
Args:
include_disabled: If True, include disabled presets. Default False.
Returns:
List of (pack_id, metadata_copy) tuples sorted by priority.
Metadata is deep-copied to prevent accidental mutation.
"""
packs = self.data.get("presets", {}) or {}
if not isinstance(packs, dict):
packs = {}
sortable_packs = []
for pack_id, meta in packs.items():
if not isinstance(meta, dict):
continue
# Skip disabled presets unless explicitly requested
if not include_disabled and not meta.get("enabled", True):
continue
metadata_copy = copy.deepcopy(meta)
metadata_copy["priority"] = normalize_priority(metadata_copy.get("priority", 10))
sortable_packs.append((pack_id, metadata_copy))
return sorted(
sortable_packs,
key=lambda item: (item[1]["priority"], item[0]),
)
def is_installed(self, pack_id: str) -> bool:
"""Check if preset is installed.
Args:
pack_id: Preset ID
Returns:
True if pack is installed, False if not or registry corrupted
"""
packs = self.data.get("presets")
if not isinstance(packs, dict):
return False
return pack_id in packs
class PresetManager:
"""Manages preset lifecycle: installation, removal, updates."""
def __init__(self, project_root: Path):
"""Initialize preset manager.
Args:
project_root: Path to project root directory
"""
self.project_root = project_root
self.presets_dir = project_root / ".specify" / "presets"
self.registry = PresetRegistry(self.presets_dir)
def check_compatibility(
self,
manifest: PresetManifest,
speckit_version: str
) -> bool:
"""Check if preset is compatible with current spec-kit version.
Args:
manifest: Preset manifest
speckit_version: Current spec-kit version
Returns:
True if compatible
Raises:
PresetCompatibilityError: If pack is incompatible
"""
required = manifest.requires_speckit_version
current = pkg_version.Version(speckit_version)
try:
specifier = SpecifierSet(required)
if not specifier.contains(current, prereleases=True):
raise PresetCompatibilityError(
f"Preset requires spec-kit {required}, "
f"but {speckit_version} is installed.\n"
f"Upgrade spec-kit with: {REINSTALL_COMMAND}"
)
except InvalidSpecifier:
raise PresetCompatibilityError(
f"Invalid version specifier: {required}"
)
return True
def _register_commands(
self,
manifest: PresetManifest,
preset_dir: Path
) -> Dict[str, List[str]]:
"""Register preset command overrides with all detected AI agents.
Scans the preset's templates for type "command", reads each command
file, and writes it to every detected agent directory using the
CommandRegistrar from the agents module.
When a command uses a composition strategy (prepend, append, wrap),
the content is composed with the lower-priority command before
registration.
Args:
manifest: Preset manifest
preset_dir: Installed preset directory
Returns:
Dictionary mapping agent names to lists of registered command names
"""
command_templates = [
t for t in manifest.templates if t.get("type") == "command"
]
if not command_templates:
return {}
# Filter out extension command overrides if the extension isn't installed.
# Command names follow the pattern: speckit.<ext-id>.<cmd-name>
# Core commands (e.g. speckit.specify) have only one dot — always register.
extensions_dir = self.project_root / ".specify" / "extensions"
filtered = []
for cmd in command_templates:
parts = cmd["name"].split(".")
if len(parts) >= 3 and parts[0] == "speckit":
ext_id = parts[1]
if not (extensions_dir / ext_id).is_dir():
continue
filtered.append(cmd)
if not filtered:
return {}
# Handle composition strategies: resolve composed content for non-replace commands
resolver = PresetResolver(self.project_root)
composed_dir = None
commands_to_register = []
for cmd in filtered:
strategy = cmd.get("strategy", "replace")
if strategy != "replace":
# Only pre-compose if this preset is the top composing layer.
# If a higher-priority replace already wins, skip composition
# here — reconciliation will write the correct content.
layers = resolver.collect_all_layers(cmd["name"], "command")
top_layer_is_ours = (
layers and layers[0]["path"].is_relative_to(preset_dir)
)
if top_layer_is_ours:
composed = resolver.resolve_content(cmd["name"], "command")
if composed is not None:
if composed_dir is None:
composed_dir = preset_dir / ".composed"
composed_dir.mkdir(parents=True, exist_ok=True)
composed_file = composed_dir / f"{cmd['name']}.md"
composed_file.write_text(composed, encoding="utf-8")
commands_to_register.append({
**cmd,
"file": f".composed/{cmd['name']}.md",
})
else:
raise PresetValidationError(
f"Command '{cmd['name']}' uses '{strategy}' strategy "
f"but no base command layer exists to compose onto. "
f"Ensure a lower-priority preset, extension, or core "
f"command provides this command before using "
f"composition strategies."
)
else:
# Not the top layer — register raw file; reconciliation
# will overwrite with the correct composed/winning content.
# Note: CommandRegistrar may process frontmatter strategy: wrap
# from the raw file (legacy compat), but reconciliation runs
# immediately after install and corrects the final output.
commands_to_register.append(cmd)
else:
commands_to_register.append(cmd)
try:
from .agents import CommandRegistrar
except ImportError:
return {}
registrar = CommandRegistrar()
return registrar.register_commands_for_all_agents(
commands_to_register, manifest.id, preset_dir, self.project_root
)
def _unregister_commands(self, registered_commands: Dict[str, List[str]]) -> None:
"""Remove previously registered command files from agent directories.
Args:
registered_commands: Dict mapping agent names to command name lists
"""
try:
from .agents import CommandRegistrar
except ImportError:
return
registrar = CommandRegistrar()
registrar.unregister_commands(registered_commands, self.project_root)
def _reconcile_composed_commands(self, command_names: List[str]) -> None:
"""Re-resolve and re-register composed commands from the full stack.
After install or remove, recompute the effective content for each
command name that participates in composition, and write the winning
content to the agent directories. This ensures command files always
reflect the current priority stack rather than depending on
install/remove order.
Args:
command_names: List of command names to reconcile
"""
if not command_names:
return
try:
from .agents import CommandRegistrar
except ImportError:
return
resolver = PresetResolver(self.project_root)
registrar = CommandRegistrar()
# Cache registry and manifests outside the loop to avoid
# repeated filesystem reads for each command name.
presets_by_priority = list(self.registry.list_by_priority())
for cmd_name in command_names:
layers = resolver.collect_all_layers(cmd_name, "command")
if not layers:
continue
# If the top layer is replace, it wins entirely — lower layers
# are irrelevant regardless of their strategies.
top_is_replace = layers[0]["strategy"] == "replace"
has_composition = not top_is_replace and any(
layer["strategy"] != "replace" for layer in layers
)
if not has_composition:
# Pure replace — the top layer wins.
top_layer = layers[0]
top_path = top_layer["path"]
# Try to find which preset owns this layer
registered = False
for pack_id, _meta in presets_by_priority:
pack_dir = self.presets_dir / pack_id
if top_path.is_relative_to(pack_dir):
manifest = resolver._get_manifest(pack_dir)
if manifest:
for tmpl in manifest.templates:
if tmpl.get("name") == cmd_name and tmpl.get("type") == "command":
self._register_for_non_skill_agents(
registrar, [tmpl], manifest.id, pack_dir
)
registered = True
break
break
if not registered:
# Top layer is a non-preset source (extension, core, or
# project override). Register directly from the layer path.
source = layers[0]["source"]
if source.startswith("extension:"):
# Use extension's own registration to preserve context formatting
ext_id = source.split(":", 1)[1].split(" ", 1)[0]
ext_dir = self.project_root / ".specify" / "extensions" / ext_id
ext_manifest_path = ext_dir / "extension.yml"
if ext_manifest_path.exists():
try:
from .extensions import ExtensionManifest
ext_manifest = ExtensionManifest(ext_manifest_path)
# Filter to only the command being reconciled
matching_cmds = [
c for c in ext_manifest.commands
if c.get("name") == cmd_name
]
if matching_cmds:
registrar.register_commands_for_non_skill_agents(
matching_cmds, ext_id, ext_dir,
self.project_root,
context_note=f"\n<!-- Extension: {ext_id} -->\n<!-- Config: .specify/extensions/{ext_id}/ -->\n",
)
registered = True
except Exception:
# Extension registration failed; fall back to
# generic path-based registration below.
pass
if not registered:
source_id = source.split(":", 1)[1].split(" ", 1)[0] if source.startswith("extension:") else source
self._register_command_from_path(
registrar, cmd_name, top_path,
source_id=source_id,
)
else:
# Composed command — resolve from full stack
composed = resolver.resolve_content(cmd_name, "command")
if composed is None:
# Composition no longer possible (e.g. base layer removed).
# Unregister any stale command file from non-skill agents.
import warnings
warnings.warn(
f"Cannot compose command '{cmd_name}': no base layer. "
f"Stale command files may remain.",
stacklevel=2,
)
registrar._ensure_configs()
# Include aliases from the top layer's manifest
cmd_names_to_unregister = [cmd_name]
for _pid, _meta in presets_by_priority:
_pd = self.presets_dir / _pid
_m = resolver._get_manifest(_pd)
if _m:
for _t in _m.templates:
if _t.get("name") == cmd_name and _t.get("type") == "command":
for alias in _t.get("aliases", []):
if isinstance(alias, str):
cmd_names_to_unregister.append(alias)
break
registrar.unregister_commands(
{agent: cmd_names_to_unregister for agent in registrar.AGENT_CONFIGS
if registrar.AGENT_CONFIGS[agent].get("extension") != "/SKILL.md"},
self.project_root,
)
continue
# Write to the highest-priority preset's .composed dir
registered = False
for pack_id, _meta in presets_by_priority:
pack_dir = self.presets_dir / pack_id
manifest = resolver._get_manifest(pack_dir)
if not manifest:
continue
for tmpl in manifest.templates:
if tmpl.get("name") == cmd_name and tmpl.get("type") == "command":
composed_dir = pack_dir / ".composed"
composed_dir.mkdir(parents=True, exist_ok=True)
composed_file = composed_dir / f"{cmd_name}.md"
composed_file.write_text(composed, encoding="utf-8")
self._register_for_non_skill_agents(
registrar,
[{**tmpl, "file": f".composed/{cmd_name}.md"}],
manifest.id, pack_dir,
)
registered = True
break
else:
continue
break
if not registered:
# No preset owns this composed command — write to a
# shared .composed dir and register from the top layer.
shared_composed = self.presets_dir / ".composed"
shared_composed.mkdir(parents=True, exist_ok=True)
composed_file = shared_composed / f"{cmd_name}.md"
composed_file.write_text(composed, encoding="utf-8")
source = layers[0]["source"]
if source.startswith("extension:"):
source_id = source.split(":", 1)[1].split(" ", 1)[0]
else:
source_id = source
self._register_command_from_path(
registrar, cmd_name, composed_file,
source_id=source_id,
)
def _register_command_from_path(
self,
registrar: Any,
cmd_name: str,
cmd_path: Path,
source_id: str = "reconciled",
) -> None:
"""Register a single command from a file path (non-preset source).
Used by reconciliation when the winning layer is an extension,
core template, or project override rather than a preset.
Args:
registrar: CommandRegistrar instance
cmd_name: Command name
cmd_path: Path to the command file
source_id: Source attribution for rendered output
"""
if not cmd_path.exists():
return
cmd_tmpl: Dict[str, Any] = {
"name": cmd_name,
"type": "command",
"file": cmd_path.name,
}
# Load aliases from extension manifest when the winning layer is an extension
if source_id and not source_id.startswith("preset:"):
try:
from .extensions import ExtensionManifest
for ext_dir in (self.project_root / ".specify" / "extensions").iterdir():
if not ext_dir.is_dir():
continue
if cmd_path.is_relative_to(ext_dir):
manifest_path = ext_dir / "extension.yml"
if manifest_path.exists():
ext_manifest = ExtensionManifest(manifest_path)
for cmd in ext_manifest.commands:
if cmd.get("name") == cmd_name:
aliases = cmd.get("aliases", [])
if isinstance(aliases, list) and aliases:
cmd_tmpl["aliases"] = aliases
break
break
except Exception:
pass # best-effort alias loading
self._register_for_non_skill_agents(
registrar, [cmd_tmpl], source_id, cmd_path.parent
)
def _register_for_non_skill_agents(
self,
registrar: Any,
commands: List[Dict[str, Any]],
source_id: str,
source_dir: Path,
) -> None:
"""Register commands for non-skill agents during reconciliation.
Skill-based agents (``/SKILL.md`` layout) are handled separately:
- On removal: ``_unregister_skills()`` restores from core/extension,
then ``_reconcile_skills()`` re-runs ``_register_skills()`` for the
next winning preset so SKILL.md files get proper frontmatter and
descriptions.
- On install: ``_register_skills()`` writes formatted SKILL.md, then
``_reconcile_skills()`` ensures the actual priority winner is used.
Writing raw command content to skill agents would produce invalid
SKILL.md files (missing skill frontmatter, descriptions, etc.).
"""
registrar.register_commands_for_non_skill_agents(
commands, source_id, source_dir, self.project_root
)
class _FilteredManifest:
"""Wrapper that exposes only selected command templates from a manifest.
Used by _reconcile_skills to avoid overwriting skills for commands
that aren't being reconciled.
"""
def __init__(self, manifest: "PresetManifest", cmd_names: set):
self._manifest = manifest
self._cmd_names = cmd_names
def __getattr__(self, name: str):
return getattr(self._manifest, name)
@property
def templates(self) -> List[Dict[str, Any]]:
return [
t for t in self._manifest.templates
if t.get("name") in self._cmd_names
]
def _reconcile_skills(self, command_names: List[str]) -> None:
"""Re-register skills for commands whose winning layer changed.
After a preset is removed, finds the next preset in the priority
stack that provides each command and re-runs skill registration
for that preset so SKILL.md files reflect the current winner.
Args:
command_names: List of command names to reconcile skills for
"""
if not command_names:
return
resolver = PresetResolver(self.project_root)
skills_dir = self._get_skills_dir()
# Cache registry once to avoid repeated filesystem reads
presets_by_priority = list(self.registry.list_by_priority())
# Group command names by winning preset to batch _register_skills calls
# while only registering skills for the specific commands being reconciled.
preset_cmds: Dict[str, List[str]] = {}
non_preset_skills: List[tuple] = []
for cmd_name in command_names:
layers = resolver.collect_all_layers(cmd_name, "command")
if not layers:
continue
# Re-create the skill directory only if it was previously managed
# (i.e., listed in some preset's registered_skills). This avoids
# creating new skill dirs that _register_skills would normally skip.
if skills_dir:
skill_name, _ = self._skill_names_for_command(cmd_name)
skill_subdir = skills_dir / skill_name
if not skill_subdir.exists():
# Check if any preset previously registered this skill
was_managed = False
for _pid, meta in presets_by_priority:
if not isinstance(meta, dict):
continue
if skill_name in meta.get("registered_skills", []):
was_managed = True