specify-cli 0.0.20__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1210 @@
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "typer",
6
+ # "rich",
7
+ # "platformdirs",
8
+ # "readchar",
9
+ # "httpx",
10
+ # ]
11
+ # ///
12
+ """
13
+ Specify CLI - Setup tool for Specify projects
14
+
15
+ Usage:
16
+ uvx specify-cli.py init <project-name>
17
+ uvx specify-cli.py init .
18
+ uvx specify-cli.py init --here
19
+
20
+ Or install globally:
21
+ uv tool install --from specify-cli.py specify-cli
22
+ specify init <project-name>
23
+ specify init .
24
+ specify init --here
25
+ """
26
+
27
+ import os
28
+ import subprocess
29
+ import sys
30
+ import zipfile
31
+ import tempfile
32
+ import shutil
33
+ import shlex
34
+ import json
35
+ from pathlib import Path
36
+ from typing import Optional, Tuple
37
+
38
+ import typer
39
+ import httpx
40
+ from rich.console import Console
41
+ from rich.panel import Panel
42
+ from rich.progress import Progress, SpinnerColumn, TextColumn
43
+ from rich.text import Text
44
+ from rich.live import Live
45
+ from rich.align import Align
46
+ from rich.table import Table
47
+ from rich.tree import Tree
48
+ from typer.core import TyperGroup
49
+
50
+ # For cross-platform keyboard input
51
+ import readchar
52
+ import ssl
53
+ import truststore
54
+
55
+ ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
56
+ client = httpx.Client(verify=ssl_context)
57
+
58
+ def _github_token(cli_token: str | None = None) -> str | None:
59
+ """Return sanitized GitHub token (cli arg takes precedence) or None."""
60
+ return ((cli_token or os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN") or "").strip()) or None
61
+
62
+ def _github_auth_headers(cli_token: str | None = None) -> dict:
63
+ """Return Authorization header dict only when a non-empty token exists."""
64
+ token = _github_token(cli_token)
65
+ return {"Authorization": f"Bearer {token}"} if token else {}
66
+
67
+ # Agent configuration with name, folder, install URL, and CLI tool requirement
68
+ AGENT_CONFIG = {
69
+ "copilot": {
70
+ "name": "GitHub Copilot",
71
+ "folder": ".github/",
72
+ "install_url": None, # IDE-based, no CLI check needed
73
+ "requires_cli": False,
74
+ },
75
+ "claude": {
76
+ "name": "Claude Code",
77
+ "folder": ".claude/",
78
+ "install_url": "https://docs.anthropic.com/en/docs/claude-code/setup",
79
+ "requires_cli": True,
80
+ },
81
+ "gemini": {
82
+ "name": "Gemini CLI",
83
+ "folder": ".gemini/",
84
+ "install_url": "https://github.com/google-gemini/gemini-cli",
85
+ "requires_cli": True,
86
+ },
87
+ "cursor-agent": {
88
+ "name": "Cursor",
89
+ "folder": ".cursor/",
90
+ "install_url": None, # IDE-based
91
+ "requires_cli": False,
92
+ },
93
+ "qwen": {
94
+ "name": "Qwen Code",
95
+ "folder": ".qwen/",
96
+ "install_url": "https://github.com/QwenLM/qwen-code",
97
+ "requires_cli": True,
98
+ },
99
+ "opencode": {
100
+ "name": "opencode",
101
+ "folder": ".opencode/",
102
+ "install_url": "https://opencode.ai",
103
+ "requires_cli": True,
104
+ },
105
+ "codex": {
106
+ "name": "Codex CLI",
107
+ "folder": ".codex/",
108
+ "install_url": "https://github.com/openai/codex",
109
+ "requires_cli": True,
110
+ },
111
+ "windsurf": {
112
+ "name": "Windsurf",
113
+ "folder": ".windsurf/",
114
+ "install_url": None, # IDE-based
115
+ "requires_cli": False,
116
+ },
117
+ "kilocode": {
118
+ "name": "Kilo Code",
119
+ "folder": ".kilocode/",
120
+ "install_url": None, # IDE-based
121
+ "requires_cli": False,
122
+ },
123
+ "auggie": {
124
+ "name": "Auggie CLI",
125
+ "folder": ".augment/",
126
+ "install_url": "https://docs.augmentcode.com/cli/setup-auggie/install-auggie-cli",
127
+ "requires_cli": True,
128
+ },
129
+ "codebuddy": {
130
+ "name": "CodeBuddy",
131
+ "folder": ".codebuddy/",
132
+ "install_url": "https://www.codebuddy.ai/cli",
133
+ "requires_cli": True,
134
+ },
135
+ "roo": {
136
+ "name": "Roo Code",
137
+ "folder": ".roo/",
138
+ "install_url": None, # IDE-based
139
+ "requires_cli": False,
140
+ },
141
+ "q": {
142
+ "name": "Amazon Q Developer CLI",
143
+ "folder": ".amazonq/",
144
+ "install_url": "https://aws.amazon.com/developer/learning/q-developer-cli/",
145
+ "requires_cli": True,
146
+ },
147
+ "amp": {
148
+ "name": "Amp",
149
+ "folder": ".agents/",
150
+ "install_url": "https://ampcode.com/manual#install",
151
+ "requires_cli": True,
152
+ },
153
+ }
154
+
155
+ SCRIPT_TYPE_CHOICES = {"sh": "POSIX Shell (bash/zsh)", "ps": "PowerShell"}
156
+
157
+ CLAUDE_LOCAL_PATH = Path.home() / ".claude" / "local" / "claude"
158
+
159
+ BANNER = """
160
+ ███████╗██████╗ ███████╗ ██████╗██╗███████╗██╗ ██╗
161
+ ██╔════╝██╔══██╗██╔════╝██╔════╝██║██╔════╝╚██╗ ██╔╝
162
+ ███████╗██████╔╝█████╗ ██║ ██║█████╗ ╚████╔╝
163
+ ╚════██║██╔═══╝ ██╔══╝ ██║ ██║██╔══╝ ╚██╔╝
164
+ ███████║██║ ███████╗╚██████╗██║██║ ██║
165
+ ╚══════╝╚═╝ ╚══════╝ ╚═════╝╚═╝╚═╝ ╚═╝
166
+ """
167
+
168
+ TAGLINE = "GitHub Spec Kit - Spec-Driven Development Toolkit"
169
+ class StepTracker:
170
+ """Track and render hierarchical steps without emojis, similar to Claude Code tree output.
171
+ Supports live auto-refresh via an attached refresh callback.
172
+ """
173
+ def __init__(self, title: str):
174
+ self.title = title
175
+ self.steps = [] # list of dicts: {key, label, status, detail}
176
+ self.status_order = {"pending": 0, "running": 1, "done": 2, "error": 3, "skipped": 4}
177
+ self._refresh_cb = None # callable to trigger UI refresh
178
+
179
+ def attach_refresh(self, cb):
180
+ self._refresh_cb = cb
181
+
182
+ def add(self, key: str, label: str):
183
+ if key not in [s["key"] for s in self.steps]:
184
+ self.steps.append({"key": key, "label": label, "status": "pending", "detail": ""})
185
+ self._maybe_refresh()
186
+
187
+ def start(self, key: str, detail: str = ""):
188
+ self._update(key, status="running", detail=detail)
189
+
190
+ def complete(self, key: str, detail: str = ""):
191
+ self._update(key, status="done", detail=detail)
192
+
193
+ def error(self, key: str, detail: str = ""):
194
+ self._update(key, status="error", detail=detail)
195
+
196
+ def skip(self, key: str, detail: str = ""):
197
+ self._update(key, status="skipped", detail=detail)
198
+
199
+ def _update(self, key: str, status: str, detail: str):
200
+ for s in self.steps:
201
+ if s["key"] == key:
202
+ s["status"] = status
203
+ if detail:
204
+ s["detail"] = detail
205
+ self._maybe_refresh()
206
+ return
207
+
208
+ self.steps.append({"key": key, "label": key, "status": status, "detail": detail})
209
+ self._maybe_refresh()
210
+
211
+ def _maybe_refresh(self):
212
+ if self._refresh_cb:
213
+ try:
214
+ self._refresh_cb()
215
+ except Exception:
216
+ pass
217
+
218
+ def render(self):
219
+ tree = Tree(f"[cyan]{self.title}[/cyan]", guide_style="grey50")
220
+ for step in self.steps:
221
+ label = step["label"]
222
+ detail_text = step["detail"].strip() if step["detail"] else ""
223
+
224
+ status = step["status"]
225
+ if status == "done":
226
+ symbol = "[green]●[/green]"
227
+ elif status == "pending":
228
+ symbol = "[green dim]○[/green dim]"
229
+ elif status == "running":
230
+ symbol = "[cyan]○[/cyan]"
231
+ elif status == "error":
232
+ symbol = "[red]●[/red]"
233
+ elif status == "skipped":
234
+ symbol = "[yellow]○[/yellow]"
235
+ else:
236
+ symbol = " "
237
+
238
+ if status == "pending":
239
+ # Entire line light gray (pending)
240
+ if detail_text:
241
+ line = f"{symbol} [bright_black]{label} ({detail_text})[/bright_black]"
242
+ else:
243
+ line = f"{symbol} [bright_black]{label}[/bright_black]"
244
+ else:
245
+ # Label white, detail (if any) light gray in parentheses
246
+ if detail_text:
247
+ line = f"{symbol} [white]{label}[/white] [bright_black]({detail_text})[/bright_black]"
248
+ else:
249
+ line = f"{symbol} [white]{label}[/white]"
250
+
251
+ tree.add(line)
252
+ return tree
253
+
254
+ def get_key():
255
+ """Get a single keypress in a cross-platform way using readchar."""
256
+ key = readchar.readkey()
257
+
258
+ if key == readchar.key.UP or key == readchar.key.CTRL_P:
259
+ return 'up'
260
+ if key == readchar.key.DOWN or key == readchar.key.CTRL_N:
261
+ return 'down'
262
+
263
+ if key == readchar.key.ENTER:
264
+ return 'enter'
265
+
266
+ if key == readchar.key.ESC:
267
+ return 'escape'
268
+
269
+ if key == readchar.key.CTRL_C:
270
+ raise KeyboardInterrupt
271
+
272
+ return key
273
+
274
+ def select_with_arrows(options: dict, prompt_text: str = "Select an option", default_key: str = None) -> str:
275
+ """
276
+ Interactive selection using arrow keys with Rich Live display.
277
+
278
+ Args:
279
+ options: Dict with keys as option keys and values as descriptions
280
+ prompt_text: Text to show above the options
281
+ default_key: Default option key to start with
282
+
283
+ Returns:
284
+ Selected option key
285
+ """
286
+ option_keys = list(options.keys())
287
+ if default_key and default_key in option_keys:
288
+ selected_index = option_keys.index(default_key)
289
+ else:
290
+ selected_index = 0
291
+
292
+ selected_key = None
293
+
294
+ def create_selection_panel():
295
+ """Create the selection panel with current selection highlighted."""
296
+ table = Table.grid(padding=(0, 2))
297
+ table.add_column(style="cyan", justify="left", width=3)
298
+ table.add_column(style="white", justify="left")
299
+
300
+ for i, key in enumerate(option_keys):
301
+ if i == selected_index:
302
+ table.add_row("▶", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]")
303
+ else:
304
+ table.add_row(" ", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]")
305
+
306
+ table.add_row("", "")
307
+ table.add_row("", "[dim]Use ↑/↓ to navigate, Enter to select, Esc to cancel[/dim]")
308
+
309
+ return Panel(
310
+ table,
311
+ title=f"[bold]{prompt_text}[/bold]",
312
+ border_style="cyan",
313
+ padding=(1, 2)
314
+ )
315
+
316
+ console.print()
317
+
318
+ def run_selection_loop():
319
+ nonlocal selected_key, selected_index
320
+ with Live(create_selection_panel(), console=console, transient=True, auto_refresh=False) as live:
321
+ while True:
322
+ try:
323
+ key = get_key()
324
+ if key == 'up':
325
+ selected_index = (selected_index - 1) % len(option_keys)
326
+ elif key == 'down':
327
+ selected_index = (selected_index + 1) % len(option_keys)
328
+ elif key == 'enter':
329
+ selected_key = option_keys[selected_index]
330
+ break
331
+ elif key == 'escape':
332
+ console.print("\n[yellow]Selection cancelled[/yellow]")
333
+ raise typer.Exit(1)
334
+
335
+ live.update(create_selection_panel(), refresh=True)
336
+
337
+ except KeyboardInterrupt:
338
+ console.print("\n[yellow]Selection cancelled[/yellow]")
339
+ raise typer.Exit(1)
340
+
341
+ run_selection_loop()
342
+
343
+ if selected_key is None:
344
+ console.print("\n[red]Selection failed.[/red]")
345
+ raise typer.Exit(1)
346
+
347
+ return selected_key
348
+
349
+ console = Console()
350
+
351
+ class BannerGroup(TyperGroup):
352
+ """Custom group that shows banner before help."""
353
+
354
+ def format_help(self, ctx, formatter):
355
+ # Show banner before help
356
+ show_banner()
357
+ super().format_help(ctx, formatter)
358
+
359
+
360
+ app = typer.Typer(
361
+ name="specify",
362
+ help="Setup tool for Specify spec-driven development projects",
363
+ add_completion=False,
364
+ invoke_without_command=True,
365
+ cls=BannerGroup,
366
+ )
367
+
368
+ def show_banner():
369
+ """Display the ASCII art banner."""
370
+ banner_lines = BANNER.strip().split('\n')
371
+ colors = ["bright_blue", "blue", "cyan", "bright_cyan", "white", "bright_white"]
372
+
373
+ styled_banner = Text()
374
+ for i, line in enumerate(banner_lines):
375
+ color = colors[i % len(colors)]
376
+ styled_banner.append(line + "\n", style=color)
377
+
378
+ console.print(Align.center(styled_banner))
379
+ console.print(Align.center(Text(TAGLINE, style="italic bright_yellow")))
380
+ console.print()
381
+
382
+ @app.callback()
383
+ def callback(ctx: typer.Context):
384
+ """Show banner when no subcommand is provided."""
385
+ if ctx.invoked_subcommand is None and "--help" not in sys.argv and "-h" not in sys.argv:
386
+ show_banner()
387
+ console.print(Align.center("[dim]Run 'specify --help' for usage information[/dim]"))
388
+ console.print()
389
+
390
+ def run_command(cmd: list[str], check_return: bool = True, capture: bool = False, shell: bool = False) -> Optional[str]:
391
+ """Run a shell command and optionally capture output."""
392
+ try:
393
+ if capture:
394
+ result = subprocess.run(cmd, check=check_return, capture_output=True, text=True, shell=shell)
395
+ return result.stdout.strip()
396
+ else:
397
+ subprocess.run(cmd, check=check_return, shell=shell)
398
+ return None
399
+ except subprocess.CalledProcessError as e:
400
+ if check_return:
401
+ console.print(f"[red]Error running command:[/red] {' '.join(cmd)}")
402
+ console.print(f"[red]Exit code:[/red] {e.returncode}")
403
+ if hasattr(e, 'stderr') and e.stderr:
404
+ console.print(f"[red]Error output:[/red] {e.stderr}")
405
+ raise
406
+ return None
407
+
408
+ def check_tool(tool: str, tracker: StepTracker = None) -> bool:
409
+ """Check if a tool is installed. Optionally update tracker.
410
+
411
+ Args:
412
+ tool: Name of the tool to check
413
+ tracker: Optional StepTracker to update with results
414
+
415
+ Returns:
416
+ True if tool is found, False otherwise
417
+ """
418
+ # Special handling for Claude CLI after `claude migrate-installer`
419
+ # See: https://github.com/github/spec-kit/issues/123
420
+ # The migrate-installer command REMOVES the original executable from PATH
421
+ # and creates an alias at ~/.claude/local/claude instead
422
+ # This path should be prioritized over other claude executables in PATH
423
+ if tool == "claude":
424
+ if CLAUDE_LOCAL_PATH.exists() and CLAUDE_LOCAL_PATH.is_file():
425
+ if tracker:
426
+ tracker.complete(tool, "available")
427
+ return True
428
+
429
+ found = shutil.which(tool) is not None
430
+
431
+ if tracker:
432
+ if found:
433
+ tracker.complete(tool, "available")
434
+ else:
435
+ tracker.error(tool, "not found")
436
+
437
+ return found
438
+
439
+ def is_git_repo(path: Path = None) -> bool:
440
+ """Check if the specified path is inside a git repository."""
441
+ if path is None:
442
+ path = Path.cwd()
443
+
444
+ if not path.is_dir():
445
+ return False
446
+
447
+ try:
448
+ # Use git command to check if inside a work tree
449
+ subprocess.run(
450
+ ["git", "rev-parse", "--is-inside-work-tree"],
451
+ check=True,
452
+ capture_output=True,
453
+ cwd=path,
454
+ )
455
+ return True
456
+ except (subprocess.CalledProcessError, FileNotFoundError):
457
+ return False
458
+
459
+ def init_git_repo(project_path: Path, quiet: bool = False) -> Tuple[bool, Optional[str]]:
460
+ """Initialize a git repository in the specified path.
461
+
462
+ Args:
463
+ project_path: Path to initialize git repository in
464
+ quiet: if True suppress console output (tracker handles status)
465
+
466
+ Returns:
467
+ Tuple of (success: bool, error_message: Optional[str])
468
+ """
469
+ try:
470
+ original_cwd = Path.cwd()
471
+ os.chdir(project_path)
472
+ if not quiet:
473
+ console.print("[cyan]Initializing git repository...[/cyan]")
474
+ subprocess.run(["git", "init"], check=True, capture_output=True, text=True)
475
+ subprocess.run(["git", "add", "."], check=True, capture_output=True, text=True)
476
+ subprocess.run(["git", "commit", "-m", "Initial commit from Specify template"], check=True, capture_output=True, text=True)
477
+ if not quiet:
478
+ console.print("[green]✓[/green] Git repository initialized")
479
+ return True, None
480
+
481
+ except subprocess.CalledProcessError as e:
482
+ error_msg = f"Command: {' '.join(e.cmd)}\nExit code: {e.returncode}"
483
+ if e.stderr:
484
+ error_msg += f"\nError: {e.stderr.strip()}"
485
+ elif e.stdout:
486
+ error_msg += f"\nOutput: {e.stdout.strip()}"
487
+
488
+ if not quiet:
489
+ console.print(f"[red]Error initializing git repository:[/red] {e}")
490
+ return False, error_msg
491
+ finally:
492
+ os.chdir(original_cwd)
493
+
494
+ def handle_vscode_settings(sub_item, dest_file, rel_path, verbose=False, tracker=None) -> None:
495
+ """Handle merging or copying of .vscode/settings.json files."""
496
+ def log(message, color="green"):
497
+ if verbose and not tracker:
498
+ console.print(f"[{color}]{message}[/] {rel_path}")
499
+
500
+ try:
501
+ with open(sub_item, 'r', encoding='utf-8') as f:
502
+ new_settings = json.load(f)
503
+
504
+ if dest_file.exists():
505
+ merged = merge_json_files(dest_file, new_settings, verbose=verbose and not tracker)
506
+ with open(dest_file, 'w', encoding='utf-8') as f:
507
+ json.dump(merged, f, indent=4)
508
+ f.write('\n')
509
+ log("Merged:", "green")
510
+ else:
511
+ shutil.copy2(sub_item, dest_file)
512
+ log("Copied (no existing settings.json):", "blue")
513
+
514
+ except Exception as e:
515
+ log(f"Warning: Could not merge, copying instead: {e}", "yellow")
516
+ shutil.copy2(sub_item, dest_file)
517
+
518
+ def merge_json_files(existing_path: Path, new_content: dict, verbose: bool = False) -> dict:
519
+ """Merge new JSON content into existing JSON file.
520
+
521
+ Performs a deep merge where:
522
+ - New keys are added
523
+ - Existing keys are preserved unless overwritten by new content
524
+ - Nested dictionaries are merged recursively
525
+ - Lists and other values are replaced (not merged)
526
+
527
+ Args:
528
+ existing_path: Path to existing JSON file
529
+ new_content: New JSON content to merge in
530
+ verbose: Whether to print merge details
531
+
532
+ Returns:
533
+ Merged JSON content as dict
534
+ """
535
+ try:
536
+ with open(existing_path, 'r', encoding='utf-8') as f:
537
+ existing_content = json.load(f)
538
+ except (FileNotFoundError, json.JSONDecodeError):
539
+ # If file doesn't exist or is invalid, just use new content
540
+ return new_content
541
+
542
+ def deep_merge(base: dict, update: dict) -> dict:
543
+ """Recursively merge update dict into base dict."""
544
+ result = base.copy()
545
+ for key, value in update.items():
546
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
547
+ # Recursively merge nested dictionaries
548
+ result[key] = deep_merge(result[key], value)
549
+ else:
550
+ # Add new key or replace existing value
551
+ result[key] = value
552
+ return result
553
+
554
+ merged = deep_merge(existing_content, new_content)
555
+
556
+ if verbose:
557
+ console.print(f"[cyan]Merged JSON file:[/cyan] {existing_path.name}")
558
+
559
+ return merged
560
+
561
+ def download_template_from_github(ai_assistant: str, download_dir: Path, *, script_type: str = "sh", verbose: bool = True, show_progress: bool = True, client: httpx.Client = None, debug: bool = False, github_token: str = None) -> Tuple[Path, dict]:
562
+ repo_owner = "github"
563
+ repo_name = "spec-kit"
564
+ if client is None:
565
+ client = httpx.Client(verify=ssl_context)
566
+
567
+ if verbose:
568
+ console.print("[cyan]Fetching latest release information...[/cyan]")
569
+ api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
570
+
571
+ try:
572
+ response = client.get(
573
+ api_url,
574
+ timeout=30,
575
+ follow_redirects=True,
576
+ headers=_github_auth_headers(github_token),
577
+ )
578
+ status = response.status_code
579
+ if status != 200:
580
+ msg = f"GitHub API returned {status} for {api_url}"
581
+ if debug:
582
+ msg += f"\nResponse headers: {response.headers}\nBody (truncated 500): {response.text[:500]}"
583
+ raise RuntimeError(msg)
584
+ try:
585
+ release_data = response.json()
586
+ except ValueError as je:
587
+ raise RuntimeError(f"Failed to parse release JSON: {je}\nRaw (truncated 400): {response.text[:400]}")
588
+ except Exception as e:
589
+ console.print(f"[red]Error fetching release information[/red]")
590
+ console.print(Panel(str(e), title="Fetch Error", border_style="red"))
591
+ raise typer.Exit(1)
592
+
593
+ assets = release_data.get("assets", [])
594
+ pattern = f"spec-kit-template-{ai_assistant}-{script_type}"
595
+ matching_assets = [
596
+ asset for asset in assets
597
+ if pattern in asset["name"] and asset["name"].endswith(".zip")
598
+ ]
599
+
600
+ asset = matching_assets[0] if matching_assets else None
601
+
602
+ if asset is None:
603
+ console.print(f"[red]No matching release asset found[/red] for [bold]{ai_assistant}[/bold] (expected pattern: [bold]{pattern}[/bold])")
604
+ asset_names = [a.get('name', '?') for a in assets]
605
+ console.print(Panel("\n".join(asset_names) or "(no assets)", title="Available Assets", border_style="yellow"))
606
+ raise typer.Exit(1)
607
+
608
+ download_url = asset["browser_download_url"]
609
+ filename = asset["name"]
610
+ file_size = asset["size"]
611
+
612
+ if verbose:
613
+ console.print(f"[cyan]Found template:[/cyan] {filename}")
614
+ console.print(f"[cyan]Size:[/cyan] {file_size:,} bytes")
615
+ console.print(f"[cyan]Release:[/cyan] {release_data['tag_name']}")
616
+
617
+ zip_path = download_dir / filename
618
+ if verbose:
619
+ console.print(f"[cyan]Downloading template...[/cyan]")
620
+
621
+ try:
622
+ with client.stream(
623
+ "GET",
624
+ download_url,
625
+ timeout=60,
626
+ follow_redirects=True,
627
+ headers=_github_auth_headers(github_token),
628
+ ) as response:
629
+ if response.status_code != 200:
630
+ body_sample = response.text[:400]
631
+ raise RuntimeError(f"Download failed with {response.status_code}\nHeaders: {response.headers}\nBody (truncated): {body_sample}")
632
+ total_size = int(response.headers.get('content-length', 0))
633
+ with open(zip_path, 'wb') as f:
634
+ if total_size == 0:
635
+ for chunk in response.iter_bytes(chunk_size=8192):
636
+ f.write(chunk)
637
+ else:
638
+ if show_progress:
639
+ with Progress(
640
+ SpinnerColumn(),
641
+ TextColumn("[progress.description]{task.description}"),
642
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
643
+ console=console,
644
+ ) as progress:
645
+ task = progress.add_task("Downloading...", total=total_size)
646
+ downloaded = 0
647
+ for chunk in response.iter_bytes(chunk_size=8192):
648
+ f.write(chunk)
649
+ downloaded += len(chunk)
650
+ progress.update(task, completed=downloaded)
651
+ else:
652
+ for chunk in response.iter_bytes(chunk_size=8192):
653
+ f.write(chunk)
654
+ except Exception as e:
655
+ console.print(f"[red]Error downloading template[/red]")
656
+ detail = str(e)
657
+ if zip_path.exists():
658
+ zip_path.unlink()
659
+ console.print(Panel(detail, title="Download Error", border_style="red"))
660
+ raise typer.Exit(1)
661
+ if verbose:
662
+ console.print(f"Downloaded: {filename}")
663
+ metadata = {
664
+ "filename": filename,
665
+ "size": file_size,
666
+ "release": release_data["tag_name"],
667
+ "asset_url": download_url
668
+ }
669
+ return zip_path, metadata
670
+
671
+ def download_and_extract_template(project_path: Path, ai_assistant: str, script_type: str, is_current_dir: bool = False, *, verbose: bool = True, tracker: StepTracker | None = None, client: httpx.Client = None, debug: bool = False, github_token: str = None) -> Path:
672
+ """Download the latest release and extract it to create a new project.
673
+ Returns project_path. Uses tracker if provided (with keys: fetch, download, extract, cleanup)
674
+ """
675
+ current_dir = Path.cwd()
676
+
677
+ if tracker:
678
+ tracker.start("fetch", "contacting GitHub API")
679
+ try:
680
+ zip_path, meta = download_template_from_github(
681
+ ai_assistant,
682
+ current_dir,
683
+ script_type=script_type,
684
+ verbose=verbose and tracker is None,
685
+ show_progress=(tracker is None),
686
+ client=client,
687
+ debug=debug,
688
+ github_token=github_token
689
+ )
690
+ if tracker:
691
+ tracker.complete("fetch", f"release {meta['release']} ({meta['size']:,} bytes)")
692
+ tracker.add("download", "Download template")
693
+ tracker.complete("download", meta['filename'])
694
+ except Exception as e:
695
+ if tracker:
696
+ tracker.error("fetch", str(e))
697
+ else:
698
+ if verbose:
699
+ console.print(f"[red]Error downloading template:[/red] {e}")
700
+ raise
701
+
702
+ if tracker:
703
+ tracker.add("extract", "Extract template")
704
+ tracker.start("extract")
705
+ elif verbose:
706
+ console.print("Extracting template...")
707
+
708
+ try:
709
+ if not is_current_dir:
710
+ project_path.mkdir(parents=True)
711
+
712
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
713
+ zip_contents = zip_ref.namelist()
714
+ if tracker:
715
+ tracker.start("zip-list")
716
+ tracker.complete("zip-list", f"{len(zip_contents)} entries")
717
+ elif verbose:
718
+ console.print(f"[cyan]ZIP contains {len(zip_contents)} items[/cyan]")
719
+
720
+ if is_current_dir:
721
+ with tempfile.TemporaryDirectory() as temp_dir:
722
+ temp_path = Path(temp_dir)
723
+ zip_ref.extractall(temp_path)
724
+
725
+ extracted_items = list(temp_path.iterdir())
726
+ if tracker:
727
+ tracker.start("extracted-summary")
728
+ tracker.complete("extracted-summary", f"temp {len(extracted_items)} items")
729
+ elif verbose:
730
+ console.print(f"[cyan]Extracted {len(extracted_items)} items to temp location[/cyan]")
731
+
732
+ source_dir = temp_path
733
+ if len(extracted_items) == 1 and extracted_items[0].is_dir():
734
+ source_dir = extracted_items[0]
735
+ if tracker:
736
+ tracker.add("flatten", "Flatten nested directory")
737
+ tracker.complete("flatten")
738
+ elif verbose:
739
+ console.print(f"[cyan]Found nested directory structure[/cyan]")
740
+
741
+ for item in source_dir.iterdir():
742
+ dest_path = project_path / item.name
743
+ if item.is_dir():
744
+ if dest_path.exists():
745
+ if verbose and not tracker:
746
+ console.print(f"[yellow]Merging directory:[/yellow] {item.name}")
747
+ for sub_item in item.rglob('*'):
748
+ if sub_item.is_file():
749
+ rel_path = sub_item.relative_to(item)
750
+ dest_file = dest_path / rel_path
751
+ dest_file.parent.mkdir(parents=True, exist_ok=True)
752
+ # Special handling for .vscode/settings.json - merge instead of overwrite
753
+ if dest_file.name == "settings.json" and dest_file.parent.name == ".vscode":
754
+ handle_vscode_settings(sub_item, dest_file, rel_path, verbose, tracker)
755
+ else:
756
+ shutil.copy2(sub_item, dest_file)
757
+ else:
758
+ shutil.copytree(item, dest_path)
759
+ else:
760
+ if dest_path.exists() and verbose and not tracker:
761
+ console.print(f"[yellow]Overwriting file:[/yellow] {item.name}")
762
+ shutil.copy2(item, dest_path)
763
+ if verbose and not tracker:
764
+ console.print(f"[cyan]Template files merged into current directory[/cyan]")
765
+ else:
766
+ zip_ref.extractall(project_path)
767
+
768
+ extracted_items = list(project_path.iterdir())
769
+ if tracker:
770
+ tracker.start("extracted-summary")
771
+ tracker.complete("extracted-summary", f"{len(extracted_items)} top-level items")
772
+ elif verbose:
773
+ console.print(f"[cyan]Extracted {len(extracted_items)} items to {project_path}:[/cyan]")
774
+ for item in extracted_items:
775
+ console.print(f" - {item.name} ({'dir' if item.is_dir() else 'file'})")
776
+
777
+ if len(extracted_items) == 1 and extracted_items[0].is_dir():
778
+ nested_dir = extracted_items[0]
779
+ temp_move_dir = project_path.parent / f"{project_path.name}_temp"
780
+
781
+ shutil.move(str(nested_dir), str(temp_move_dir))
782
+
783
+ project_path.rmdir()
784
+
785
+ shutil.move(str(temp_move_dir), str(project_path))
786
+ if tracker:
787
+ tracker.add("flatten", "Flatten nested directory")
788
+ tracker.complete("flatten")
789
+ elif verbose:
790
+ console.print(f"[cyan]Flattened nested directory structure[/cyan]")
791
+
792
+ except Exception as e:
793
+ if tracker:
794
+ tracker.error("extract", str(e))
795
+ else:
796
+ if verbose:
797
+ console.print(f"[red]Error extracting template:[/red] {e}")
798
+ if debug:
799
+ console.print(Panel(str(e), title="Extraction Error", border_style="red"))
800
+
801
+ if not is_current_dir and project_path.exists():
802
+ shutil.rmtree(project_path)
803
+ raise typer.Exit(1)
804
+ else:
805
+ if tracker:
806
+ tracker.complete("extract")
807
+ finally:
808
+ if tracker:
809
+ tracker.add("cleanup", "Remove temporary archive")
810
+
811
+ if zip_path.exists():
812
+ zip_path.unlink()
813
+ if tracker:
814
+ tracker.complete("cleanup")
815
+ elif verbose:
816
+ console.print(f"Cleaned up: {zip_path.name}")
817
+
818
+ return project_path
819
+
820
+
821
+ def ensure_executable_scripts(project_path: Path, tracker: StepTracker | None = None) -> None:
822
+ """Ensure POSIX .sh scripts under .specify/scripts (recursively) have execute bits (no-op on Windows)."""
823
+ if os.name == "nt":
824
+ return # Windows: skip silently
825
+ scripts_root = project_path / ".specify" / "scripts"
826
+ if not scripts_root.is_dir():
827
+ return
828
+ failures: list[str] = []
829
+ updated = 0
830
+ for script in scripts_root.rglob("*.sh"):
831
+ try:
832
+ if script.is_symlink() or not script.is_file():
833
+ continue
834
+ try:
835
+ with script.open("rb") as f:
836
+ if f.read(2) != b"#!":
837
+ continue
838
+ except Exception:
839
+ continue
840
+ st = script.stat(); mode = st.st_mode
841
+ if mode & 0o111:
842
+ continue
843
+ new_mode = mode
844
+ if mode & 0o400: new_mode |= 0o100
845
+ if mode & 0o040: new_mode |= 0o010
846
+ if mode & 0o004: new_mode |= 0o001
847
+ if not (new_mode & 0o100):
848
+ new_mode |= 0o100
849
+ os.chmod(script, new_mode)
850
+ updated += 1
851
+ except Exception as e:
852
+ failures.append(f"{script.relative_to(scripts_root)}: {e}")
853
+ if tracker:
854
+ detail = f"{updated} updated" + (f", {len(failures)} failed" if failures else "")
855
+ tracker.add("chmod", "Set script permissions recursively")
856
+ (tracker.error if failures else tracker.complete)("chmod", detail)
857
+ else:
858
+ if updated:
859
+ console.print(f"[cyan]Updated execute permissions on {updated} script(s) recursively[/cyan]")
860
+ if failures:
861
+ console.print("[yellow]Some scripts could not be updated:[/yellow]")
862
+ for f in failures:
863
+ console.print(f" - {f}")
864
+
865
+ @app.command()
866
+ def init(
867
+ project_name: str = typer.Argument(None, help="Name for your new project directory (optional if using --here, or use '.' for current directory)"),
868
+ ai_assistant: str = typer.Option(None, "--ai", help="AI assistant to use: claude, gemini, copilot, cursor-agent, qwen, opencode, codex, windsurf, kilocode, auggie, codebuddy, amp, or q"),
869
+ script_type: str = typer.Option(None, "--script", help="Script type to use: sh or ps"),
870
+ ignore_agent_tools: bool = typer.Option(False, "--ignore-agent-tools", help="Skip checks for AI agent tools like Claude Code"),
871
+ no_git: bool = typer.Option(False, "--no-git", help="Skip git repository initialization"),
872
+ here: bool = typer.Option(False, "--here", help="Initialize project in the current directory instead of creating a new one"),
873
+ force: bool = typer.Option(False, "--force", help="Force merge/overwrite when using --here (skip confirmation)"),
874
+ skip_tls: bool = typer.Option(False, "--skip-tls", help="Skip SSL/TLS verification (not recommended)"),
875
+ debug: bool = typer.Option(False, "--debug", help="Show verbose diagnostic output for network and extraction failures"),
876
+ github_token: str = typer.Option(None, "--github-token", help="GitHub token to use for API requests (or set GH_TOKEN or GITHUB_TOKEN environment variable)"),
877
+ ):
878
+ """
879
+ Initialize a new Specify project from the latest template.
880
+
881
+ This command will:
882
+ 1. Check that required tools are installed (git is optional)
883
+ 2. Let you choose your AI assistant
884
+ 3. Download the appropriate template from GitHub
885
+ 4. Extract the template to a new project directory or current directory
886
+ 5. Initialize a fresh git repository (if not --no-git and no existing repo)
887
+ 6. Optionally set up AI assistant commands
888
+
889
+ Examples:
890
+ specify init my-project
891
+ specify init my-project --ai claude
892
+ specify init my-project --ai copilot --no-git
893
+ specify init --ignore-agent-tools my-project
894
+ specify init . --ai claude # Initialize in current directory
895
+ specify init . # Initialize in current directory (interactive AI selection)
896
+ specify init --here --ai claude # Alternative syntax for current directory
897
+ specify init --here --ai codex
898
+ specify init --here --ai codebuddy
899
+ specify init --here
900
+ specify init --here --force # Skip confirmation when current directory not empty
901
+ """
902
+
903
+ show_banner()
904
+
905
+ if project_name == ".":
906
+ here = True
907
+ project_name = None # Clear project_name to use existing validation logic
908
+
909
+ if here and project_name:
910
+ console.print("[red]Error:[/red] Cannot specify both project name and --here flag")
911
+ raise typer.Exit(1)
912
+
913
+ if not here and not project_name:
914
+ console.print("[red]Error:[/red] Must specify either a project name, use '.' for current directory, or use --here flag")
915
+ raise typer.Exit(1)
916
+
917
+ if here:
918
+ project_name = Path.cwd().name
919
+ project_path = Path.cwd()
920
+
921
+ existing_items = list(project_path.iterdir())
922
+ if existing_items:
923
+ console.print(f"[yellow]Warning:[/yellow] Current directory is not empty ({len(existing_items)} items)")
924
+ console.print("[yellow]Template files will be merged with existing content and may overwrite existing files[/yellow]")
925
+ if force:
926
+ console.print("[cyan]--force supplied: skipping confirmation and proceeding with merge[/cyan]")
927
+ else:
928
+ response = typer.confirm("Do you want to continue?")
929
+ if not response:
930
+ console.print("[yellow]Operation cancelled[/yellow]")
931
+ raise typer.Exit(0)
932
+ else:
933
+ project_path = Path(project_name).resolve()
934
+ if project_path.exists():
935
+ error_panel = Panel(
936
+ f"Directory '[cyan]{project_name}[/cyan]' already exists\n"
937
+ "Please choose a different project name or remove the existing directory.",
938
+ title="[red]Directory Conflict[/red]",
939
+ border_style="red",
940
+ padding=(1, 2)
941
+ )
942
+ console.print()
943
+ console.print(error_panel)
944
+ raise typer.Exit(1)
945
+
946
+ current_dir = Path.cwd()
947
+
948
+ setup_lines = [
949
+ "[cyan]Specify Project Setup[/cyan]",
950
+ "",
951
+ f"{'Project':<15} [green]{project_path.name}[/green]",
952
+ f"{'Working Path':<15} [dim]{current_dir}[/dim]",
953
+ ]
954
+
955
+ if not here:
956
+ setup_lines.append(f"{'Target Path':<15} [dim]{project_path}[/dim]")
957
+
958
+ console.print(Panel("\n".join(setup_lines), border_style="cyan", padding=(1, 2)))
959
+
960
+ should_init_git = False
961
+ if not no_git:
962
+ should_init_git = check_tool("git")
963
+ if not should_init_git:
964
+ console.print("[yellow]Git not found - will skip repository initialization[/yellow]")
965
+
966
+ if ai_assistant:
967
+ if ai_assistant not in AGENT_CONFIG:
968
+ console.print(f"[red]Error:[/red] Invalid AI assistant '{ai_assistant}'. Choose from: {', '.join(AGENT_CONFIG.keys())}")
969
+ raise typer.Exit(1)
970
+ selected_ai = ai_assistant
971
+ else:
972
+ # Create options dict for selection (agent_key: display_name)
973
+ ai_choices = {key: config["name"] for key, config in AGENT_CONFIG.items()}
974
+ selected_ai = select_with_arrows(
975
+ ai_choices,
976
+ "Choose your AI assistant:",
977
+ "copilot"
978
+ )
979
+
980
+ if not ignore_agent_tools:
981
+ agent_config = AGENT_CONFIG.get(selected_ai)
982
+ if agent_config and agent_config["requires_cli"]:
983
+ install_url = agent_config["install_url"]
984
+ if not check_tool(selected_ai):
985
+ error_panel = Panel(
986
+ f"[cyan]{selected_ai}[/cyan] not found\n"
987
+ f"Install from: [cyan]{install_url}[/cyan]\n"
988
+ f"{agent_config['name']} is required to continue with this project type.\n\n"
989
+ "Tip: Use [cyan]--ignore-agent-tools[/cyan] to skip this check",
990
+ title="[red]Agent Detection Error[/red]",
991
+ border_style="red",
992
+ padding=(1, 2)
993
+ )
994
+ console.print()
995
+ console.print(error_panel)
996
+ raise typer.Exit(1)
997
+
998
+ if script_type:
999
+ if script_type not in SCRIPT_TYPE_CHOICES:
1000
+ console.print(f"[red]Error:[/red] Invalid script type '{script_type}'. Choose from: {', '.join(SCRIPT_TYPE_CHOICES.keys())}")
1001
+ raise typer.Exit(1)
1002
+ selected_script = script_type
1003
+ else:
1004
+ default_script = "ps" if os.name == "nt" else "sh"
1005
+
1006
+ if sys.stdin.isatty():
1007
+ selected_script = select_with_arrows(SCRIPT_TYPE_CHOICES, "Choose script type (or press Enter)", default_script)
1008
+ else:
1009
+ selected_script = default_script
1010
+
1011
+ console.print(f"[cyan]Selected AI assistant:[/cyan] {selected_ai}")
1012
+ console.print(f"[cyan]Selected script type:[/cyan] {selected_script}")
1013
+
1014
+ tracker = StepTracker("Initialize Specify Project")
1015
+
1016
+ sys._specify_tracker_active = True
1017
+
1018
+ tracker.add("precheck", "Check required tools")
1019
+ tracker.complete("precheck", "ok")
1020
+ tracker.add("ai-select", "Select AI assistant")
1021
+ tracker.complete("ai-select", f"{selected_ai}")
1022
+ tracker.add("script-select", "Select script type")
1023
+ tracker.complete("script-select", selected_script)
1024
+ for key, label in [
1025
+ ("fetch", "Fetch latest release"),
1026
+ ("download", "Download template"),
1027
+ ("extract", "Extract template"),
1028
+ ("zip-list", "Archive contents"),
1029
+ ("extracted-summary", "Extraction summary"),
1030
+ ("chmod", "Ensure scripts executable"),
1031
+ ("cleanup", "Cleanup"),
1032
+ ("git", "Initialize git repository"),
1033
+ ("final", "Finalize")
1034
+ ]:
1035
+ tracker.add(key, label)
1036
+
1037
+ # Track git error message outside Live context so it persists
1038
+ git_error_message = None
1039
+
1040
+ with Live(tracker.render(), console=console, refresh_per_second=8, transient=True) as live:
1041
+ tracker.attach_refresh(lambda: live.update(tracker.render()))
1042
+ try:
1043
+ verify = not skip_tls
1044
+ local_ssl_context = ssl_context if verify else False
1045
+ local_client = httpx.Client(verify=local_ssl_context)
1046
+
1047
+ download_and_extract_template(project_path, selected_ai, selected_script, here, verbose=False, tracker=tracker, client=local_client, debug=debug, github_token=github_token)
1048
+
1049
+ ensure_executable_scripts(project_path, tracker=tracker)
1050
+
1051
+ if not no_git:
1052
+ tracker.start("git")
1053
+ if is_git_repo(project_path):
1054
+ tracker.complete("git", "existing repo detected")
1055
+ elif should_init_git:
1056
+ success, error_msg = init_git_repo(project_path, quiet=True)
1057
+ if success:
1058
+ tracker.complete("git", "initialized")
1059
+ else:
1060
+ tracker.error("git", "init failed")
1061
+ git_error_message = error_msg
1062
+ else:
1063
+ tracker.skip("git", "git not available")
1064
+ else:
1065
+ tracker.skip("git", "--no-git flag")
1066
+
1067
+ tracker.complete("final", "project ready")
1068
+ except Exception as e:
1069
+ tracker.error("final", str(e))
1070
+ console.print(Panel(f"Initialization failed: {e}", title="Failure", border_style="red"))
1071
+ if debug:
1072
+ _env_pairs = [
1073
+ ("Python", sys.version.split()[0]),
1074
+ ("Platform", sys.platform),
1075
+ ("CWD", str(Path.cwd())),
1076
+ ]
1077
+ _label_width = max(len(k) for k, _ in _env_pairs)
1078
+ env_lines = [f"{k.ljust(_label_width)} → [bright_black]{v}[/bright_black]" for k, v in _env_pairs]
1079
+ console.print(Panel("\n".join(env_lines), title="Debug Environment", border_style="magenta"))
1080
+ if not here and project_path.exists():
1081
+ shutil.rmtree(project_path)
1082
+ raise typer.Exit(1)
1083
+ finally:
1084
+ pass
1085
+
1086
+ console.print(tracker.render())
1087
+ console.print("\n[bold green]Project ready.[/bold green]")
1088
+
1089
+ # Show git error details if initialization failed
1090
+ if git_error_message:
1091
+ console.print()
1092
+ git_error_panel = Panel(
1093
+ f"[yellow]Warning:[/yellow] Git repository initialization failed\n\n"
1094
+ f"{git_error_message}\n\n"
1095
+ f"[dim]You can initialize git manually later with:[/dim]\n"
1096
+ f"[cyan]cd {project_path if not here else '.'}[/cyan]\n"
1097
+ f"[cyan]git init[/cyan]\n"
1098
+ f"[cyan]git add .[/cyan]\n"
1099
+ f"[cyan]git commit -m \"Initial commit\"[/cyan]",
1100
+ title="[red]Git Initialization Failed[/red]",
1101
+ border_style="red",
1102
+ padding=(1, 2)
1103
+ )
1104
+ console.print(git_error_panel)
1105
+
1106
+ # Agent folder security notice
1107
+ agent_config = AGENT_CONFIG.get(selected_ai)
1108
+ if agent_config:
1109
+ agent_folder = agent_config["folder"]
1110
+ security_notice = Panel(
1111
+ f"Some agents may store credentials, auth tokens, or other identifying and private artifacts in the agent folder within your project.\n"
1112
+ f"Consider adding [cyan]{agent_folder}[/cyan] (or parts of it) to [cyan].gitignore[/cyan] to prevent accidental credential leakage.",
1113
+ title="[yellow]Agent Folder Security[/yellow]",
1114
+ border_style="yellow",
1115
+ padding=(1, 2)
1116
+ )
1117
+ console.print()
1118
+ console.print(security_notice)
1119
+
1120
+ steps_lines = []
1121
+ if not here:
1122
+ steps_lines.append(f"1. Go to the project folder: [cyan]cd {project_name}[/cyan]")
1123
+ step_num = 2
1124
+ else:
1125
+ steps_lines.append("1. You're already in the project directory!")
1126
+ step_num = 2
1127
+
1128
+ # Add Codex-specific setup step if needed
1129
+ if selected_ai == "codex":
1130
+ codex_path = project_path / ".codex"
1131
+ quoted_path = shlex.quote(str(codex_path))
1132
+ if os.name == "nt": # Windows
1133
+ cmd = f"setx CODEX_HOME {quoted_path}"
1134
+ else: # Unix-like systems
1135
+ cmd = f"export CODEX_HOME={quoted_path}"
1136
+
1137
+ steps_lines.append(f"{step_num}. Set [cyan]CODEX_HOME[/cyan] environment variable before running Codex: [cyan]{cmd}[/cyan]")
1138
+ step_num += 1
1139
+
1140
+ steps_lines.append(f"{step_num}. Start using slash commands with your AI agent:")
1141
+
1142
+ steps_lines.append(" 2.1 [cyan]/speckit.constitution[/] - Establish project principles")
1143
+ steps_lines.append(" 2.2 [cyan]/speckit.specify[/] - Create baseline specification")
1144
+ steps_lines.append(" 2.3 [cyan]/speckit.plan[/] - Create implementation plan")
1145
+ steps_lines.append(" 2.4 [cyan]/speckit.tasks[/] - Generate actionable tasks")
1146
+ steps_lines.append(" 2.5 [cyan]/speckit.implement[/] - Execute implementation")
1147
+
1148
+ steps_panel = Panel("\n".join(steps_lines), title="Next Steps", border_style="cyan", padding=(1,2))
1149
+ console.print()
1150
+ console.print(steps_panel)
1151
+
1152
+ enhancement_lines = [
1153
+ "Optional commands that you can use for your specs [bright_black](improve quality & confidence)[/bright_black]",
1154
+ "",
1155
+ f"○ [cyan]/speckit.clarify[/] [bright_black](optional)[/bright_black] - Ask structured questions to de-risk ambiguous areas before planning (run before [cyan]/speckit.plan[/] if used)",
1156
+ f"○ [cyan]/speckit.analyze[/] [bright_black](optional)[/bright_black] - Cross-artifact consistency & alignment report (after [cyan]/speckit.tasks[/], before [cyan]/speckit.implement[/])",
1157
+ f"○ [cyan]/speckit.checklist[/] [bright_black](optional)[/bright_black] - Generate quality checklists to validate requirements completeness, clarity, and consistency (after [cyan]/speckit.plan[/])"
1158
+ ]
1159
+ enhancements_panel = Panel("\n".join(enhancement_lines), title="Enhancement Commands", border_style="cyan", padding=(1,2))
1160
+ console.print()
1161
+ console.print(enhancements_panel)
1162
+
1163
+ @app.command()
1164
+ def check():
1165
+ """Check that all required tools are installed."""
1166
+ show_banner()
1167
+ console.print("[bold]Checking for installed tools...[/bold]\n")
1168
+
1169
+ tracker = StepTracker("Check Available Tools")
1170
+
1171
+ tracker.add("git", "Git version control")
1172
+ git_ok = check_tool("git", tracker=tracker)
1173
+
1174
+ agent_results = {}
1175
+ for agent_key, agent_config in AGENT_CONFIG.items():
1176
+ agent_name = agent_config["name"]
1177
+ requires_cli = agent_config["requires_cli"]
1178
+
1179
+ tracker.add(agent_key, agent_name)
1180
+
1181
+ if requires_cli:
1182
+ agent_results[agent_key] = check_tool(agent_key, tracker=tracker)
1183
+ else:
1184
+ # IDE-based agent - skip CLI check and mark as optional
1185
+ tracker.skip(agent_key, "IDE-based, no CLI check")
1186
+ agent_results[agent_key] = False # Don't count IDE agents as "found"
1187
+
1188
+ # Check VS Code variants (not in agent config)
1189
+ tracker.add("code", "Visual Studio Code")
1190
+ code_ok = check_tool("code", tracker=tracker)
1191
+
1192
+ tracker.add("code-insiders", "Visual Studio Code Insiders")
1193
+ code_insiders_ok = check_tool("code-insiders", tracker=tracker)
1194
+
1195
+ console.print(tracker.render())
1196
+
1197
+ console.print("\n[bold green]Specify CLI is ready to use![/bold green]")
1198
+
1199
+ if not git_ok:
1200
+ console.print("[dim]Tip: Install git for repository management[/dim]")
1201
+
1202
+ if not any(agent_results.values()):
1203
+ console.print("[dim]Tip: Install an AI assistant for the best experience[/dim]")
1204
+
1205
+ def main():
1206
+ app()
1207
+
1208
+ if __name__ == "__main__":
1209
+ main()
1210
+
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: specify-cli
3
+ Version: 0.0.20
4
+ Summary: Specify CLI, part of GitHub Spec Kit. A tool to bootstrap your projects for Spec-Driven Development (SDD).
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: httpx[socks]
8
+ Requires-Dist: platformdirs
9
+ Requires-Dist: readchar
10
+ Requires-Dist: rich
11
+ Requires-Dist: truststore>=0.10.4
12
+ Requires-Dist: typer
@@ -0,0 +1,6 @@
1
+ specify_cli/__init__.py,sha256=1bXGvc4W-G3tl56wxV43p1jHjic9iQbXE3ajt5B7-dw,48501
2
+ specify_cli-0.0.20.dist-info/METADATA,sha256=6QBMB9l7Ylv_u1R4ryS3xDnEQsWN0YM7lr8fZBlJm2Q,373
3
+ specify_cli-0.0.20.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
4
+ specify_cli-0.0.20.dist-info/entry_points.txt,sha256=zO7Jooxo-O6FCM02xdzsNB8WNakvnPDv5bpZr1P4Pmo,45
5
+ specify_cli-0.0.20.dist-info/licenses/LICENSE,sha256=1ZO1XiGXPh4Z6A3DtVqQj0dLJlMA-NNMVNG546WkpI8,1061
6
+ specify_cli-0.0.20.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ specify = specify_cli:main
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright GitHub, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+