-
Notifications
You must be signed in to change notification settings - Fork 10k
Expand file tree
/
Copy path__init__.py
More file actions
4497 lines (3852 loc) · 184 KB
/
Copy path__init__.py
File metadata and controls
4497 lines (3852 loc) · 184 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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "typer",
# "rich",
# "platformdirs",
# "readchar",
# "json5",
# "pyyaml",
# "packaging",
# ]
# ///
"""
Specify CLI - Setup tool for Specify projects
Usage:
uvx specify-cli.py init <project-name>
uvx specify-cli.py init .
uvx specify-cli.py init --here
Or install globally:
uv tool install --from specify-cli.py specify-cli
specify init <project-name>
specify init .
specify init --here
"""
import os
import sys
import zipfile
import json
import yaml
from pathlib import Path
from typing import Any, Optional
import typer
from rich.panel import Panel
from rich.align import Align
from rich.table import Table
from .integration_runtime import (
invoke_separator_for_integration as _invoke_separator_for_integration,
resolve_integration_options as _resolve_integration_options_impl,
with_integration_setting as _with_integration_setting,
)
from .integration_state import (
INTEGRATION_JSON,
INTEGRATION_STATE_SCHEMA,
dedupe_integration_keys as _dedupe_integration_keys,
default_integration_key as _default_integration_key,
installed_integration_keys as _installed_integration_keys,
integration_setting as _integration_setting,
integration_settings as _integration_settings,
try_read_integration_json as _try_read_integration_json,
write_integration_json as _write_integration_json_file,
)
from .shared_infra import (
install_shared_infra as _install_shared_infra_impl,
refresh_shared_templates as _refresh_shared_templates_impl,
)
from ._console import (
BANNER as BANNER,
TAGLINE as TAGLINE,
BannerGroup,
StepTracker,
console,
get_key as get_key,
select_with_arrows as select_with_arrows,
show_banner,
)
from ._assets import (
_locate_bundled_extension,
_locate_bundled_preset,
_locate_bundled_workflow as _locate_bundled_workflow,
_locate_core_pack,
_repo_root,
get_speckit_version as get_speckit_version,
)
from ._utils import (
CLAUDE_LOCAL_PATH as CLAUDE_LOCAL_PATH,
CLAUDE_NPM_LOCAL_PATH as CLAUDE_NPM_LOCAL_PATH,
_display_project_path,
check_tool as check_tool,
handle_vscode_settings as handle_vscode_settings,
init_git_repo as init_git_repo,
is_git_repo as is_git_repo,
merge_json_files as merge_json_files,
run_command as run_command,
)
from ._version import (
GITHUB_API_LATEST as GITHUB_API_LATEST,
self_app as _self_app,
self_check as self_check,
self_upgrade as self_upgrade,
)
from ._agent_config import (
AGENT_CONFIG as AGENT_CONFIG,
AI_ASSISTANT_ALIASES as AI_ASSISTANT_ALIASES,
AI_ASSISTANT_HELP as AI_ASSISTANT_HELP,
DEFAULT_INIT_INTEGRATION as DEFAULT_INIT_INTEGRATION,
SCRIPT_TYPE_CHOICES as SCRIPT_TYPE_CHOICES,
)
app = typer.Typer(
name="specify",
help="Setup tool for Specify spec-driven development projects",
add_completion=False,
invoke_without_command=True,
cls=BannerGroup,
)
def _version_callback(value: bool):
if value:
console.print(f"specify {get_speckit_version()}")
raise typer.Exit()
@app.callback()
def callback(
ctx: typer.Context,
version: bool = typer.Option(False, "--version", "-V", callback=_version_callback, is_eager=True, help="Show version and exit."),
):
"""Show banner when no subcommand is provided."""
if ctx.invoked_subcommand is None and "--help" not in sys.argv and "-h" not in sys.argv:
show_banner()
console.print(Align.center("[dim]Run 'specify --help' for usage information[/dim]"))
console.print()
def _refresh_shared_templates(
project_path: Path,
*,
invoke_separator: str,
force: bool = False,
) -> None:
"""Refresh default-sensitive shared templates without touching scripts."""
_refresh_shared_templates_impl(
project_path,
version=get_speckit_version(),
core_pack=_locate_core_pack(),
repo_root=_repo_root(),
console=console,
invoke_separator=invoke_separator,
force=force,
)
def _install_shared_infra(
project_path: Path,
script_type: str,
tracker: StepTracker | None = None,
force: bool = False,
invoke_separator: str = ".",
refresh_managed: bool = False,
refresh_hint: str | None = None,
) -> bool:
"""Install shared infrastructure files into *project_path*.
Copies ``.specify/scripts/<variant>/`` and ``.specify/templates/`` from
the bundled core_pack or source checkout, where ``<variant>`` is
``bash`` when *script_type* is ``"sh"`` and ``powershell`` when it is
``"ps"``. Tracks all installed files in ``speckit.manifest.json``.
Page templates are processed to resolve ``__SPECKIT_COMMAND_<NAME>__``
placeholders using *invoke_separator* (``"."`` for markdown agents,
``"-"`` for skills agents).
Overwrite policy:
* ``force=True`` — overwrite every existing file (still skips symlinks
to avoid following links outside the project root).
* ``refresh_managed=True`` — overwrite only files whose on-disk hash
still matches the previously recorded manifest hash (i.e. unmodified
files installed by spec-kit). Files with diverging hashes are
treated as user customizations and preserved with a warning.
* Default — only add missing files; existing ones are skipped.
*refresh_hint* — caller-supplied rich-text fragment shown after the
"Preserved customized files" warning to tell the user which flag/command
they should re-run with to overwrite their customizations. Each caller
passes the flag that's actually valid in its CLI surface (e.g.
``--refresh-shared-infra`` for ``integration switch``,
``--force`` for ``init``/``integration upgrade``). When ``None``, no
remediation hint is printed for customizations.
Returns ``True`` on success.
"""
return _install_shared_infra_impl(
project_path,
script_type,
version=get_speckit_version(),
core_pack=_locate_core_pack(),
repo_root=_repo_root(),
console=console,
force=force,
invoke_separator=invoke_separator,
refresh_managed=refresh_managed,
refresh_hint=refresh_hint,
)
def _install_shared_infra_or_exit(
project_path: Path,
script_type: str,
tracker: StepTracker | None = None,
force: bool = False,
invoke_separator: str = ".",
refresh_managed: bool = False,
refresh_hint: str | None = None,
) -> bool:
try:
return _install_shared_infra(
project_path,
script_type,
tracker=tracker,
force=force,
invoke_separator=invoke_separator,
refresh_managed=refresh_managed,
refresh_hint=refresh_hint,
)
except (ValueError, OSError) as exc:
console.print(f"[red]Error:[/red] Failed to install shared infrastructure: {exc}")
raise typer.Exit(1)
def ensure_executable_scripts(project_path: Path, tracker: StepTracker | None = None) -> None:
"""Ensure POSIX .sh scripts under .specify/scripts and .specify/extensions (recursively) have execute bits (no-op on Windows)."""
if os.name == "nt":
return # Windows: skip silently
scan_roots = [
project_path / ".specify" / "scripts",
project_path / ".specify" / "extensions",
]
failures: list[str] = []
updated = 0
for scripts_root in scan_roots:
if not scripts_root.is_dir():
continue
for script in scripts_root.rglob("*.sh"):
try:
if script.is_symlink() or not script.is_file():
continue
try:
with script.open("rb") as f:
if f.read(2) != b"#!":
continue
except Exception:
continue
st = script.stat()
mode = st.st_mode
if mode & 0o111:
continue
new_mode = mode
if mode & 0o400:
new_mode |= 0o100
if mode & 0o040:
new_mode |= 0o010
if mode & 0o004:
new_mode |= 0o001
if not (new_mode & 0o100):
new_mode |= 0o100
os.chmod(script, new_mode)
updated += 1
except Exception as e:
failures.append(f"{_display_project_path(project_path, script)}: {e}")
if tracker:
detail = f"{updated} updated" + (f", {len(failures)} failed" if failures else "")
tracker.add("chmod", "Set script permissions recursively")
(tracker.error if failures else tracker.complete)("chmod", detail)
else:
if updated:
console.print(f"[cyan]Updated execute permissions on {updated} script(s) recursively[/cyan]")
if failures:
console.print("[yellow]Some scripts could not be updated:[/yellow]")
for f in failures:
console.print(f" - {f}")
INIT_OPTIONS_FILE = ".specify/init-options.json"
def save_init_options(project_path: Path, options: dict[str, Any]) -> None:
"""Persist the CLI options used during ``specify init``.
Writes a small JSON file to ``.specify/init-options.json`` so that
later operations (e.g. preset install) can adapt their behaviour
without scanning the filesystem.
"""
dest = project_path / INIT_OPTIONS_FILE
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps(options, indent=2, sort_keys=True))
def load_init_options(project_path: Path) -> dict[str, Any]:
"""Load the init options previously saved by ``specify init``.
Returns an empty dict if the file does not exist or cannot be parsed.
"""
path = project_path / INIT_OPTIONS_FILE
if not path.exists():
return {}
try:
return json.loads(path.read_text())
except (json.JSONDecodeError, OSError):
return {}
def _get_skills_dir(project_path: Path, selected_ai: str) -> Path:
"""Resolve the agent-specific skills directory.
Returns ``project_path / <agent_folder> / "skills"``, falling back
to ``project_path / ".agents/skills"`` for unknown agents.
"""
agent_config = AGENT_CONFIG.get(selected_ai, {})
agent_folder = agent_config.get("folder", "")
if agent_folder:
return project_path / agent_folder.rstrip("/") / "skills"
return project_path / ".agents" / "skills"
# Constants kept for backward compatibility with presets and extensions.
DEFAULT_SKILLS_DIR = ".agents/skills"
SKILL_DESCRIPTIONS = {
"specify": "Create or update feature specifications from natural language descriptions.",
"plan": "Generate technical implementation plans from feature specifications.",
"tasks": "Break down implementation plans into actionable task lists.",
"implement": "Execute all tasks from the task breakdown to build the feature.",
"analyze": "Perform cross-artifact consistency analysis across spec.md, plan.md, and tasks.md.",
"clarify": "Structured clarification workflow for underspecified requirements.",
"constitution": "Create or update project governing principles and development guidelines.",
"checklist": "Generate custom quality checklists for validating requirements completeness and clarity.",
"taskstoissues": "Convert tasks from tasks.md into GitHub issues.",
}
# ===== init command =====
# Moved to commands/init.py — registered here to preserve CLI surface.
from .commands import init as _init_cmd # noqa: E402
_init_cmd.register(app)
@app.command()
def check():
"""Check that all required tools are installed."""
show_banner()
console.print("[bold]Checking for installed tools...[/bold]\n")
tracker = StepTracker("Check Available Tools")
tracker.add("git", "Git version control")
git_ok = check_tool("git", tracker=tracker)
agent_results = {}
for agent_key, agent_config in AGENT_CONFIG.items():
if agent_key == "generic":
continue # Generic is not a real agent to check
agent_name = agent_config["name"]
requires_cli = agent_config["requires_cli"]
tracker.add(agent_key, agent_name)
if requires_cli:
agent_results[agent_key] = check_tool(agent_key, tracker=tracker)
else:
# IDE-based agent - skip CLI check and mark as optional
tracker.skip(agent_key, "IDE-based, no CLI check")
agent_results[agent_key] = False # Don't count IDE agents as "found"
# Check VS Code variants (not in agent config)
tracker.add("code", "Visual Studio Code")
check_tool("code", tracker=tracker)
tracker.add("code-insiders", "Visual Studio Code Insiders")
check_tool("code-insiders", tracker=tracker)
console.print(tracker.render())
console.print("\n[bold green]Specify CLI is ready to use![/bold green]")
if not git_ok:
console.print("[dim]Tip: Install git for repository management[/dim]")
if not any(agent_results.values()):
console.print("[dim]Tip: Install a coding agent for the best experience[/dim]")
def _feature_capabilities() -> dict[str, bool]:
"""Return stable local CLI capability flags for humans and agents."""
return {
"controlled_multi_install_integrations": True,
"integration_use_command": True,
"multi_install_safe_registry_metadata": True,
"integration_upgrade_command": True,
"self_check_command": True,
"workflow_catalog": True,
"bundled_templates": True,
}
@app.command()
def version(
features: bool = typer.Option(
False,
"--features",
help="Show local CLI feature capabilities.",
),
json_output: bool = typer.Option(
False,
"--json",
help="Emit feature capabilities as JSON. Requires --features.",
),
):
"""Display version and system information."""
import platform
cli_version = get_speckit_version()
if json_output and not features:
console.print("[red]Error:[/red] --json requires --features.")
raise typer.Exit(1)
if features:
capabilities = _feature_capabilities()
if json_output:
payload = {"version": cli_version, "features": capabilities}
console.print(json.dumps(payload, indent=2))
return
console.print(f"Spec Kit CLI: {cli_version}")
console.print()
console.print("Features:")
for key, enabled in capabilities.items():
label = key.replace("_", " ")
console.print(f"- {label}: {'yes' if enabled else 'no'}")
return
show_banner()
info_table = Table(show_header=False, box=None, padding=(0, 2))
info_table.add_column("Key", style="cyan", justify="right")
info_table.add_column("Value", style="white")
info_table.add_row("CLI Version", cli_version)
info_table.add_row("", "")
info_table.add_row("Python", platform.python_version())
info_table.add_row("Platform", platform.system())
info_table.add_row("Architecture", platform.machine())
info_table.add_row("OS Version", platform.version())
panel = Panel(
info_table,
title="[bold cyan]Specify CLI Information[/bold cyan]",
border_style="cyan",
padding=(1, 2)
)
console.print(panel)
console.print()
app.add_typer(_self_app, name="self")
# ===== Extension Commands =====
extension_app = typer.Typer(
name="extension",
help="Manage spec-kit extensions",
add_completion=False,
)
app.add_typer(extension_app, name="extension")
catalog_app = typer.Typer(
name="catalog",
help="Manage extension catalogs",
add_completion=False,
)
extension_app.add_typer(catalog_app, name="catalog")
preset_app = typer.Typer(
name="preset",
help="Manage spec-kit presets",
add_completion=False,
)
app.add_typer(preset_app, name="preset")
preset_catalog_app = typer.Typer(
name="catalog",
help="Manage preset catalogs",
add_completion=False,
)
preset_app.add_typer(preset_catalog_app, name="catalog")
# ===== Integration Commands =====
integration_app = typer.Typer(
name="integration",
help="Manage coding agent integrations",
add_completion=False,
)
app.add_typer(integration_app, name="integration")
integration_catalog_app = typer.Typer(
name="catalog",
help="Manage integration catalog sources",
add_completion=False,
)
integration_app.add_typer(integration_catalog_app, name="catalog")
def _read_integration_json(project_root: Path) -> dict[str, Any]:
"""Load ``.specify/integration.json``. Returns normalized state when present.
Delegates the parse / schema-guard logic to the shared
:func:`_try_read_integration_json` helper so the CLI and workflow engine
cannot drift on validation rules. Each error variant is translated into
the existing loud-fail UX (console message + ``typer.Exit(1)``).
"""
path = project_root / INTEGRATION_JSON
state, error = _try_read_integration_json(project_root)
if error is None:
return state or {}
if error.kind == "decode":
console.print(f"[red]Error:[/red] {path} contains invalid JSON or is not valid UTF-8.")
console.print(f"Please fix or delete {INTEGRATION_JSON} and retry.")
console.print(f"[dim]Details:[/dim] {error.detail}")
elif error.kind == "os":
console.print(f"[red]Error:[/red] Could not read {path}.")
console.print(f"Please fix file permissions or delete {INTEGRATION_JSON} and retry.")
console.print(f"[dim]Details:[/dim] {error.detail}")
elif error.kind == "not_object":
console.print(
f"[red]Error:[/red] {path} must contain a JSON object, got {error.detail}."
)
console.print(f"Please fix or delete {INTEGRATION_JSON} and retry.")
elif error.kind == "schema_too_new":
console.print(
f"[red]Error:[/red] {path} uses integration state schema {error.schema}, "
f"but this CLI only supports schema {INTEGRATION_STATE_SCHEMA}."
)
console.print("Please upgrade Spec Kit before modifying integrations.")
raise typer.Exit(1)
def _write_integration_json(
project_root: Path,
integration_key: str | None,
installed_integrations: list[str] | None = None,
integration_settings: dict[str, dict[str, Any]] | None = None,
) -> None:
"""Write ``.specify/integration.json`` with legacy-compatible state."""
_write_integration_json_file(
project_root,
version=get_speckit_version(),
integration_key=integration_key,
installed_integrations=installed_integrations,
settings=integration_settings,
)
def _clear_init_options_for_integration(project_root: Path, integration_key: str) -> None:
"""Clear active integration keys from init-options.json when they match."""
opts = load_init_options(project_root)
if opts.get("integration") == integration_key or opts.get("ai") == integration_key:
opts.pop("integration", None)
opts.pop("ai", None)
opts.pop("ai_skills", None)
opts.pop("context_file", None)
save_init_options(project_root, opts)
def _remove_integration_json(project_root: Path) -> None:
"""Remove ``.specify/integration.json`` if it exists."""
path = project_root / INTEGRATION_JSON
if path.exists():
path.unlink()
_MANIFEST_READ_ERRORS = (ValueError, FileNotFoundError, OSError, UnicodeDecodeError)
class _SharedTemplateRefreshError(RuntimeError):
"""Raised when default integration metadata should not be persisted."""
def _normalize_script_type(script_type: str, source: str) -> str:
"""Normalize and validate a script type from CLI/config sources."""
normalized = script_type.strip().lower()
if normalized in SCRIPT_TYPE_CHOICES:
return normalized
console.print(
f"[red]Error:[/red] Invalid script type {script_type!r} from {source}. "
f"Expected one of: {', '.join(sorted(SCRIPT_TYPE_CHOICES.keys()))}."
)
raise typer.Exit(1)
def _resolve_script_type(project_root: Path, script_type: str | None) -> str:
"""Resolve the script type from the CLI flag or init-options.json."""
if script_type:
return _normalize_script_type(script_type, "--script")
opts = load_init_options(project_root)
saved = opts.get("script")
if isinstance(saved, str) and saved.strip():
return _normalize_script_type(saved, ".specify/init-options.json")
return "ps" if os.name == "nt" else "sh"
def _resolve_integration_script_type(
project_root: Path,
state: dict[str, Any],
key: str,
script_type: str | None = None,
) -> str:
"""Resolve script type for an integration, preferring stored settings."""
if script_type:
return _normalize_script_type(script_type, "--script")
stored = _integration_setting(state, key).get("script")
if isinstance(stored, str) and stored.strip():
return _normalize_script_type(stored, f"{INTEGRATION_JSON} integration_settings.{key}.script")
return _resolve_script_type(project_root, None)
def _resolve_integration_options(
integration: Any,
state: dict[str, Any],
key: str,
raw_options: str | None,
) -> tuple[str | None, dict[str, Any] | None]:
"""Resolve raw and parsed options for an integration operation."""
return _resolve_integration_options_impl(
integration,
state,
key,
raw_options,
parse_options=_parse_integration_options,
)
def _set_default_integration(
project_root: Path,
state: dict[str, Any],
key: str,
integration: Any,
installed_keys: list[str],
*,
script_type: str | None = None,
raw_options: str | None = None,
parsed_options: dict[str, Any] | None = None,
refresh_templates: bool = True,
refresh_templates_force: bool = False,
) -> None:
"""Persist *key* as default and align active runtime metadata."""
resolved_script = _resolve_integration_script_type(project_root, state, key, script_type)
settings = _with_integration_setting(
state,
key,
integration,
script_type=resolved_script,
raw_options=raw_options,
parsed_options=parsed_options,
)
if refresh_templates:
try:
_refresh_shared_templates(
project_root,
invoke_separator=_invoke_separator_for_integration(
integration, {"integration_settings": settings}, key, parsed_options
),
force=refresh_templates_force,
)
except (ValueError, OSError) as exc:
raise _SharedTemplateRefreshError(
f"Failed to refresh shared templates for '{key}': {exc}"
) from exc
_write_integration_json(project_root, key, installed_keys, settings)
_update_init_options_for_integration(project_root, integration, script_type=resolved_script)
def _set_default_integration_or_exit(*args: Any, **kwargs: Any) -> None:
try:
_set_default_integration(*args, **kwargs)
except _SharedTemplateRefreshError as exc:
console.print(f"[red]Error:[/red] {exc}")
raise typer.Exit(1)
def _require_specify_project() -> Path:
"""Return the current project root if it is a spec-kit project, else exit."""
project_root = Path.cwd()
if (project_root / ".specify").is_dir():
return project_root
console.print("[red]Error:[/red] Not a spec-kit project (no .specify/ directory)")
console.print("Run this command from a spec-kit project root")
raise typer.Exit(1)
@integration_app.command("list")
def integration_list(
catalog: bool = typer.Option(False, "--catalog", help="Browse full catalog (built-in + community)"),
):
"""List available integrations and installed status."""
from .integrations import INTEGRATION_REGISTRY
project_root = _require_specify_project()
current = _read_integration_json(project_root)
default_key = _default_integration_key(current)
installed_keys = set(_installed_integration_keys(current))
if catalog:
from .integrations.catalog import IntegrationCatalog, IntegrationCatalogError
ic = IntegrationCatalog(project_root)
try:
entries = ic.search()
except IntegrationCatalogError as exc:
console.print(f"[red]Error:[/red] {exc}")
raise typer.Exit(1)
if not entries:
console.print("[yellow]No integrations found in catalog.[/yellow]")
return
table = Table(title="Integration Catalog")
table.add_column("ID", style="cyan")
table.add_column("Name")
table.add_column("Version")
table.add_column("Source")
table.add_column("Status")
table.add_column("Multi-install Safe")
for entry in sorted(entries, key=lambda e: e["id"]):
eid = entry["id"]
cat_name = entry.get("_catalog_name", "")
install_allowed = entry.get("_install_allowed", True)
if eid == default_key:
status = "[green]installed (default)[/green]"
elif eid in installed_keys:
status = "[green]installed[/green]"
elif eid in INTEGRATION_REGISTRY:
status = "built-in"
elif install_allowed is False:
status = "discovery-only"
else:
status = ""
safe = ""
if eid in INTEGRATION_REGISTRY:
safe = "yes" if getattr(INTEGRATION_REGISTRY[eid], "multi_install_safe", False) else "no"
table.add_row(
eid,
entry.get("name", eid),
entry.get("version", ""),
cat_name,
status,
safe,
)
console.print(table)
return
table = Table(title="Coding Agent Integrations")
table.add_column("Key", style="cyan")
table.add_column("Name")
table.add_column("Status")
table.add_column("CLI Required")
table.add_column("Multi-install Safe")
for key in sorted(INTEGRATION_REGISTRY.keys()):
integration = INTEGRATION_REGISTRY[key]
cfg = integration.config or {}
name = cfg.get("name", key)
requires_cli = cfg.get("requires_cli", False)
if key == default_key:
status = "[green]installed (default)[/green]"
elif key in installed_keys:
status = "[green]installed[/green]"
else:
status = ""
cli_req = "yes" if requires_cli else "no (IDE)"
safe = "yes" if getattr(integration, "multi_install_safe", False) else "no"
table.add_row(key, name, status, cli_req, safe)
console.print(table)
if installed_keys:
console.print(f"\n[dim]Default integration:[/dim] [cyan]{default_key or 'none'}[/cyan]")
console.print(f"[dim]Installed integrations:[/dim] [cyan]{', '.join(sorted(installed_keys))}[/cyan]")
else:
console.print("\n[yellow]No integration currently installed.[/yellow]")
console.print("Install one with: [cyan]specify integration install <key>[/cyan]")
@integration_app.command("install")
def integration_install(
key: str = typer.Argument(help="Integration key to install (e.g. claude, copilot)"),
script: str | None = typer.Option(None, "--script", help="Script type: sh or ps (default: from init-options.json or platform default)"),
force: bool = typer.Option(False, "--force", help="Allow multi-install when integrations are not declared safe"),
integration_options: str | None = typer.Option(None, "--integration-options", help='Options for the integration (e.g. --integration-options="--commands-dir .myagent/cmds")'),
):
"""Install an integration into an existing project."""
from .integrations import INTEGRATION_REGISTRY, get_integration
from .integrations.manifest import IntegrationManifest
project_root = _require_specify_project()
integration = get_integration(key)
if integration is None:
console.print(f"[red]Error:[/red] Unknown integration '{key}'")
available = ", ".join(sorted(INTEGRATION_REGISTRY.keys()))
console.print(f"Available integrations: {available}")
raise typer.Exit(1)
current = _read_integration_json(project_root)
default_key = _default_integration_key(current)
installed_keys = _installed_integration_keys(current)
if key in installed_keys:
console.print(f"[yellow]Integration '{key}' is already installed.[/yellow]")
if default_key == key:
console.print("It is already the default integration.")
else:
console.print(
f"To make it the default integration, run "
f"[cyan]specify integration use {key}[/cyan]."
)
console.print(
f"To refresh its managed files or options, run "
f"[cyan]specify integration upgrade {key}[/cyan]."
)
console.print("No files were changed.")
raise typer.Exit(0)
if installed_keys and not force:
unsafe_keys = []
for installed_key in installed_keys:
installed_integration = get_integration(installed_key)
if not installed_integration or not getattr(installed_integration, "multi_install_safe", False):
unsafe_keys.append(installed_key)
if unsafe_keys or not getattr(integration, "multi_install_safe", False):
console.print(
f"[red]Error:[/red] Installed integrations: {', '.join(installed_keys)}."
)
if default_key:
console.print(f"Default integration: [cyan]{default_key}[/cyan].")
console.print(
"Installing multiple integrations is only automatic when all involved "
"integrations are declared multi-install safe."
)
console.print(
f"To replace the default integration, run "
f"[cyan]specify integration switch {key}[/cyan]."
)
console.print(
f"To install '{key}' alongside the existing integrations anyway, "
"retry the same install command with [cyan]--force[/cyan]."
)
raise typer.Exit(1)
selected_script = _resolve_script_type(project_root, script)
# Build parsed options from --integration-options so the integration
# can determine its effective invoke separator before shared infra
# is installed.
raw_options, parsed_options = _resolve_integration_options(
integration, current, key, integration_options
)
# Ensure shared infrastructure is present (safe to run unconditionally;
# _install_shared_infra merges missing files without overwriting).
infra_integration = integration
infra_key = key
infra_parsed = parsed_options
if default_key:
default_integration = get_integration(default_key)
if default_integration is not None:
infra_integration = default_integration
infra_key = default_key
_, infra_parsed = _resolve_integration_options(
default_integration, current, default_key, None
)
_install_shared_infra_or_exit(
project_root,
selected_script,
invoke_separator=_invoke_separator_for_integration(
infra_integration, current, infra_key, infra_parsed
),
)
if os.name != "nt":
ensure_executable_scripts(project_root)
manifest = IntegrationManifest(
integration.key, project_root, version=get_speckit_version()
)
try:
integration.setup(
project_root, manifest,
parsed_options=parsed_options,
script_type=selected_script,
raw_options=raw_options,
)
manifest.save()
new_installed = _dedupe_integration_keys([*installed_keys, integration.key])
new_default = default_key or integration.key
settings = _with_integration_setting(
current,
integration.key,
integration,
script_type=selected_script,
raw_options=raw_options,
parsed_options=parsed_options,
)
_write_integration_json(project_root, new_default, new_installed, settings)
if new_default == integration.key:
_update_init_options_for_integration(project_root, integration, script_type=selected_script)
except Exception as e:
# Attempt rollback of any files written by setup
try:
integration.teardown(project_root, manifest, force=True)
except Exception as rollback_err:
# Suppress so the original setup error remains the primary failure
console.print(f"[yellow]Warning:[/yellow] Failed to roll back integration changes: {rollback_err}")
if installed_keys:
_write_integration_json(
project_root, default_key, installed_keys, _integration_settings(current)
)
else:
_remove_integration_json(project_root)
console.print(f"[red]Error:[/red] Failed to install integration: {e}")
raise typer.Exit(1)
name = (integration.config or {}).get("name", key)
console.print(f"\n[green]✓[/green] Integration '{name}' installed successfully")
if default_key:
console.print(f"[dim]Default integration remains:[/dim] [cyan]{default_key}[/cyan]")
def _parse_integration_options(integration: Any, raw_options: str) -> dict[str, Any] | None:
"""Parse --integration-options string into a dict matching the integration's declared options.
Returns ``None`` when no options are provided.
"""
import shlex
parsed: dict[str, Any] = {}
tokens = shlex.split(raw_options)
declared_options = list(integration.options())
declared = {opt.name.lstrip("-"): opt for opt in declared_options}
allowed = ", ".join(sorted(opt.name for opt in declared_options))
i = 0
while i < len(tokens):
token = tokens[i]
if not token.startswith("-"):
console.print(f"[red]Error:[/red] Unexpected integration option value '{token}'.")
if allowed:
console.print(f"Allowed options: {allowed}")
raise typer.Exit(1)
name = token.lstrip("-")
value: str | None = None
# Handle --name=value syntax
if "=" in name:
name, value = name.split("=", 1)
opt = declared.get(name)
if not opt:
console.print(f"[red]Error:[/red] Unknown integration option '{token}'.")
if allowed:
console.print(f"Allowed options: {allowed}")
raise typer.Exit(1)
key = name.replace("-", "_")
if opt.is_flag:
if value is not None:
console.print(f"[red]Error:[/red] Option '{opt.name}' is a flag and does not accept a value.")
raise typer.Exit(1)
parsed[key] = True
i += 1
elif value is not None:
parsed[key] = value
i += 1
elif i + 1 < len(tokens) and not tokens[i + 1].startswith("-"):
parsed[key] = tokens[i + 1]
i += 2
else:
console.print(f"[red]Error:[/red] Option '{opt.name}' requires a value.")
raise typer.Exit(1)
return parsed or None
def _update_init_options_for_integration(
project_root: Path,
integration: Any,
script_type: str | None = None,
) -> None:
"""Update ``init-options.json`` to reflect *integration* as the active one."""
from .integrations.base import SkillsIntegration
opts = load_init_options(project_root)
opts["integration"] = integration.key