nexus-dev-toolkit-jev 3.1.9__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.
Files changed (39) hide show
  1. nexus_cli.py +1031 -0
  2. nexus_dev_toolkit_jev-3.1.9.dist-info/METADATA +262 -0
  3. nexus_dev_toolkit_jev-3.1.9.dist-info/RECORD +39 -0
  4. nexus_dev_toolkit_jev-3.1.9.dist-info/WHEEL +5 -0
  5. nexus_dev_toolkit_jev-3.1.9.dist-info/entry_points.txt +3 -0
  6. nexus_dev_toolkit_jev-3.1.9.dist-info/licenses/LICENSE +21 -0
  7. nexus_dev_toolkit_jev-3.1.9.dist-info/top_level.txt +3 -0
  8. nexus_server.py +16 -0
  9. tools/__init__.py +0 -0
  10. tools/agents/__init__.py +0 -0
  11. tools/agents/code-reviewer.md +86 -0
  12. tools/agents/database-reviewer.md +95 -0
  13. tools/agents/deployment-reviewer.md +97 -0
  14. tools/agents/monitoring-reviewer.md +95 -0
  15. tools/agents/performance-reviewer.md +98 -0
  16. tools/agents/pr-verifier.md +63 -0
  17. tools/epav/__init__.py +14 -0
  18. tools/epav/arch_ingest.py +299 -0
  19. tools/epav/graph_backend.py +88 -0
  20. tools/epav/judgment.py +50 -0
  21. tools/epav/package_resolver.py +624 -0
  22. tools/epav/project_rules.py +267 -0
  23. tools/epav/skills/__init__.py +0 -0
  24. tools/epav/skills/apply.md +44 -0
  25. tools/epav/skills/code-review.md +24 -0
  26. tools/epav/skills/commit.md +48 -0
  27. tools/epav/skills/create-pr.md +64 -0
  28. tools/epav/skills/database-review.md +91 -0
  29. tools/epav/skills/deployment-review.md +94 -0
  30. tools/epav/skills/dev-tasks-planner.md +196 -0
  31. tools/epav/skills/epav.md +46 -0
  32. tools/epav/skills/evaluate.md +45 -0
  33. tools/epav/skills/monitoring-review.md +91 -0
  34. tools/epav/skills/performance-review.md +93 -0
  35. tools/epav/skills/plan.md +46 -0
  36. tools/epav/skills/pr-review.md +35 -0
  37. tools/epav/skills/scaffold.md +419 -0
  38. tools/epav/skills/validate.md +57 -0
  39. tools/epav/task_loader.py +228 -0
nexus_cli.py ADDED
@@ -0,0 +1,1031 @@
1
+ import json
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ import urllib.request
7
+ from pathlib import Path
8
+
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.markup import escape
12
+ from rich.table import Table
13
+
14
+ from tools.epav import graph_backend
15
+
16
+ _VERSION = "3.1.9-jev" # local disambiguation marker only -- see CHANGELOG/pyproject before treating this as a real release version
17
+
18
+ # This branch is published/installed under a distinct package + binary identity
19
+ # from the real "nexus-dev-toolkit" so both can be installed side by side without
20
+ # one silently overwriting the other's `uv tool install` slot -- `uv tool install`
21
+ # keys by package name, not by script name alone. Every place that names the
22
+ # package for install/upgrade/PyPI-lookup purposes must use this constant, not a
23
+ # literal "nexus-dev-toolkit" -- e.g. `nexus-jev update` must upgrade THIS package,
24
+ # never the real one.
25
+ _PACKAGE_NAME = "nexus-dev-toolkit-jev"
26
+ _CLI_BIN = "nexus-jev"
27
+ _MCP_BIN = "nexus-jev-mcp"
28
+
29
+ app = typer.Typer(name=_CLI_BIN, no_args_is_help=False, help="nexus-dev-toolkit (jev build) — Day 0 scaffold + Day 1 EPAV workflow for Claude Code and OpenCode")
30
+ skill_app = typer.Typer(name="skill", no_args_is_help=True, help="Manage skills in .claude/commands/")
31
+ rule_app = typer.Typer(name="rule", no_args_is_help=True, help="Manage rules in knowledge/rules/")
32
+ agent_app = typer.Typer(name="agent", no_args_is_help=True, help="Manage subagents in .claude/agents/")
33
+ app.add_typer(skill_app, name="skill")
34
+ app.add_typer(rule_app, name="rule")
35
+ app.add_typer(agent_app, name="agent")
36
+
37
+ console = Console()
38
+
39
+
40
+ def _fetch_latest_pypi_version() -> str | None:
41
+ """Fetch the latest published version from PyPI. None on any failure — offline, timeout,
42
+ bad response, or package not published under this name — never raises."""
43
+ try:
44
+ with urllib.request.urlopen(
45
+ f"https://pypi.org/pypi/{_PACKAGE_NAME}/json", timeout=3
46
+ ) as resp:
47
+ return json.loads(resp.read())["info"]["version"]
48
+ except Exception:
49
+ return None
50
+
51
+
52
+ def _version_tuple(v: str) -> tuple[int, ...]:
53
+ core = v.split("-", 1)[0].split("+", 1)[0] # strip a local suffix, e.g. "3.1.9-jev" -> "3.1.9"
54
+ return tuple(int(part) for part in core.split("."))
55
+
56
+
57
+ def _is_outdated(installed: str, latest: str) -> bool:
58
+ try:
59
+ return _version_tuple(latest) > _version_tuple(installed)
60
+ except Exception:
61
+ return False # malformed version string from PyPI — don't false-alarm
62
+
63
+
64
+ _LOGO = """\
65
+ [cyan]███╗ ██╗███████╗██╗ ██╗██╗ ██╗███████╗[/cyan]
66
+ [cyan]████╗ ██║██╔════╝╚██╗██╔╝██║ ██║██╔════╝[/cyan]
67
+ [cyan]██╔██╗ ██║█████╗ ╚███╔╝ ██║ ██║███████╗[/cyan]
68
+ [cyan]██║╚██╗██║██╔══╝ ██╔██╗ ██║ ██║╚════██║[/cyan]
69
+ [cyan]██║ ╚████║███████╗██╔╝ ██╗╚██████╔╝███████║[/cyan]
70
+ [cyan]╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝[/cyan]
71
+ [dim white]dev toolkit[/dim white] [dim cyan]v{version}[/dim cyan]"""
72
+
73
+
74
+ def _print_logo() -> None:
75
+ from rich.padding import Padding
76
+ console.print()
77
+ console.print(Padding(_LOGO.format(version=_VERSION), (0, 2)))
78
+ console.print()
79
+
80
+
81
+ def _version_callback(value: bool) -> None:
82
+ if value:
83
+ console.print(f"{_PACKAGE_NAME} v{_VERSION}")
84
+ raise typer.Exit()
85
+
86
+
87
+ @app.callback(invoke_without_command=True)
88
+ def _callback(
89
+ ctx: typer.Context,
90
+ version: bool = typer.Option(None, "--version", "-V", callback=_version_callback, is_eager=True, help="Show version and exit."),
91
+ ) -> None:
92
+ if ctx.invoked_subcommand is None:
93
+ _print_logo()
94
+ console.print(ctx.get_help())
95
+
96
+ # ── Built-in skills shipped with the package ──────────────────────────────────
97
+
98
+ _SKILLS_SRC = Path(__file__).parent / "tools" / "epav" / "skills"
99
+
100
+ _BUILTIN_SKILLS = [
101
+ "scaffold.md",
102
+ "evaluate.md",
103
+ "plan.md",
104
+ "apply.md",
105
+ "validate.md",
106
+ "epav.md",
107
+ "code-review.md",
108
+ "database-review.md",
109
+ "deployment-review.md",
110
+ "performance-review.md",
111
+ "monitoring-review.md",
112
+ "commit.md",
113
+ "create-pr.md",
114
+ "pr-review.md",
115
+ "dev-tasks-planner.md",
116
+ ]
117
+
118
+ _AGENTS_SRC = Path(__file__).parent / "tools" / "agents"
119
+
120
+ _BUILTIN_AGENTS = [
121
+ "deployment-reviewer.md",
122
+ "code-reviewer.md",
123
+ "performance-reviewer.md",
124
+ "monitoring-reviewer.md",
125
+ "database-reviewer.md",
126
+ "pr-verifier.md",
127
+ ]
128
+
129
+
130
+ # ── .claude/settings.json ────────────────────────────────────────────────────
131
+
132
+ _CLAUDE_SETTINGS = {
133
+ "hooks": {
134
+ "PostToolUse": [
135
+ {
136
+ "matcher": ".*",
137
+ "hooks": [
138
+ {
139
+ "type": "command",
140
+ "command": "graphify update . --force 2>/dev/null || true"
141
+ }
142
+ ]
143
+ }
144
+ ]
145
+ }
146
+ }
147
+
148
+ # ── knowledge/ scaffold ───────────────────────────────────────────────────────
149
+
150
+ _KNOWLEDGE_DIRS = [
151
+ "knowledge/rules",
152
+ "knowledge/patterns",
153
+ "knowledge/prompts/dev",
154
+ "knowledge/retros",
155
+ ]
156
+
157
+ # ── MCP config ────────────────────────────────────────────────────────────────
158
+
159
+ def _mcp_package_spec(enable_typesafe: bool) -> str:
160
+ return f"{_PACKAGE_NAME}[typesafe]" if enable_typesafe else _PACKAGE_NAME
161
+
162
+
163
+ def _mcp_block(enable_typesafe: bool) -> dict:
164
+ return {
165
+ "nexus-jev": {
166
+ "command": "uvx",
167
+ "args": ["--refresh", "--from", _mcp_package_spec(enable_typesafe), _MCP_BIN],
168
+ }
169
+ }
170
+
171
+
172
+ def _opencode_mcp_block(enable_typesafe: bool) -> dict:
173
+ return {
174
+ "nexus-jev-mcp": {
175
+ "type": "local",
176
+ "command": ["uvx", "--refresh", "--from", _mcp_package_spec(enable_typesafe), _MCP_BIN],
177
+ }
178
+ }
179
+
180
+ _OPENCODE_GRAPHIFY_PLUGIN = """\
181
+ // .opencode/plugins/graphify.js
182
+ // Auto-updates the graphify knowledge graph after every tool execution.
183
+ import { execSync } from "node:child_process"
184
+
185
+ export const GraphifyPlugin = async ({ directory }) => {
186
+ return {
187
+ "tool.execute.after": async () => {
188
+ try {
189
+ execSync("graphify update . --force", { cwd: directory, stdio: "ignore" })
190
+ } catch (_) {}
191
+ },
192
+ }
193
+ }
194
+ """
195
+
196
+
197
+ def _init_project(project_dir: Path, backend: str = "graphify") -> list[str]:
198
+ """
199
+ nexus init — sets up:
200
+ .claude/commands/ ← built-in skills
201
+ .claude/agents/ ← built-in subagents
202
+ .claude/settings.json ← PostToolUse graphify hook (only when backend == "graphify")
203
+ knowledge/ ← empty scaffold
204
+ """
205
+ created = []
206
+
207
+ # .claude/commands/ — copy built-in skills
208
+ commands_dir = project_dir / ".claude" / "commands"
209
+ commands_dir.mkdir(parents=True, exist_ok=True)
210
+
211
+ for skill_name in _BUILTIN_SKILLS:
212
+ src = _SKILLS_SRC / skill_name
213
+ dest = commands_dir / skill_name
214
+ if src.exists() and not dest.exists():
215
+ shutil.copy2(src, dest)
216
+ created.append(f".claude/commands/{skill_name}")
217
+
218
+ # .claude/agents/ — copy built-in subagents
219
+ agents_dir = project_dir / ".claude" / "agents"
220
+ agents_dir.mkdir(parents=True, exist_ok=True)
221
+
222
+ for agent_name in _BUILTIN_AGENTS:
223
+ src = _AGENTS_SRC / agent_name
224
+ dest = agents_dir / agent_name
225
+ if src.exists() and not dest.exists():
226
+ shutil.copy2(src, dest)
227
+ created.append(f".claude/agents/{agent_name}")
228
+
229
+ # .claude/settings.json — PostToolUse graphify hook (codegraph syncs itself, no hook needed)
230
+ if backend == "graphify":
231
+ settings_path = project_dir / ".claude" / "settings.json"
232
+ if not settings_path.exists():
233
+ settings_path.write_text(json.dumps(_CLAUDE_SETTINGS, indent=2))
234
+ created.append(".claude/settings.json")
235
+
236
+ # knowledge/ scaffold
237
+ for d in _KNOWLEDGE_DIRS:
238
+ target = project_dir / d
239
+ target.mkdir(parents=True, exist_ok=True)
240
+
241
+ return created
242
+
243
+
244
+ def _strip_claude_frontmatter(content: str) -> str:
245
+ """Remove Claude Code-only frontmatter fields (tools, model) for OpenCode compatibility."""
246
+ if not content.startswith("---"):
247
+ return content
248
+ parts = content.split("---", 2)
249
+ if len(parts) < 3:
250
+ return content
251
+ lines = [
252
+ line for line in parts[1].splitlines()
253
+ if not line.startswith("tools:") and not line.startswith("model:")
254
+ ]
255
+ return "---" + "\n".join(lines) + "---" + parts[2]
256
+
257
+
258
+ def _init_opencode(project_dir: Path, backend: str = "graphify", enable_typesafe: bool = False) -> list[str]:
259
+ """
260
+ nexus init --tool opencode — sets up:
261
+ .opencode/commands/ ← built-in skills
262
+ .opencode/agents/ ← built-in subagents
263
+ .opencode/plugins/ ← graphify PostToolUse hook (only when backend == "graphify")
264
+ opencode.json ← MCP server config
265
+ knowledge/ ← empty scaffold
266
+ """
267
+ created = []
268
+
269
+ # .opencode/commands/ — copy built-in skills
270
+ commands_dir = project_dir / ".opencode" / "commands"
271
+ commands_dir.mkdir(parents=True, exist_ok=True)
272
+ for skill_name in _BUILTIN_SKILLS:
273
+ src = _SKILLS_SRC / skill_name
274
+ dest = commands_dir / skill_name
275
+ if src.exists() and not dest.exists():
276
+ shutil.copy2(src, dest)
277
+ created.append(f".opencode/commands/{skill_name}")
278
+
279
+ # .opencode/agents/ — copy built-in subagents, stripping Claude Code-only frontmatter
280
+ agents_dir = project_dir / ".opencode" / "agents"
281
+ agents_dir.mkdir(parents=True, exist_ok=True)
282
+ for agent_name in _BUILTIN_AGENTS:
283
+ src = _AGENTS_SRC / agent_name
284
+ dest = agents_dir / agent_name
285
+ if src.exists() and not dest.exists():
286
+ dest.write_text(_strip_claude_frontmatter(src.read_text()), encoding="utf-8")
287
+ created.append(f".opencode/agents/{agent_name}")
288
+
289
+ # .opencode/plugins/graphify.js — PostToolUse hook (codegraph syncs itself, no hook needed)
290
+ if backend == "graphify":
291
+ plugins_dir = project_dir / ".opencode" / "plugins"
292
+ plugins_dir.mkdir(parents=True, exist_ok=True)
293
+ plugin_path = plugins_dir / "graphify.js"
294
+ if not plugin_path.exists():
295
+ plugin_path.write_text(_OPENCODE_GRAPHIFY_PLUGIN, encoding="utf-8")
296
+ created.append(".opencode/plugins/graphify.js")
297
+
298
+ # opencode.json — MCP server config
299
+ opencode_json = project_dir / "opencode.json"
300
+ existing: dict = {}
301
+ if opencode_json.exists():
302
+ try:
303
+ existing = json.loads(opencode_json.read_text())
304
+ except Exception:
305
+ pass
306
+ already_has_mcp = "nexus-jev-mcp" in existing.get("mcp", {})
307
+ existing.setdefault("$schema", "https://opencode.ai/config.json")
308
+ existing.setdefault("mcp", {}).update(_opencode_mcp_block(enable_typesafe))
309
+ opencode_json.write_text(json.dumps(existing, indent=2))
310
+ if not already_has_mcp:
311
+ created.append("opencode.json")
312
+
313
+ # knowledge/ scaffold
314
+ for d in _KNOWLEDGE_DIRS:
315
+ (project_dir / d).mkdir(parents=True, exist_ok=True)
316
+
317
+ return created
318
+
319
+
320
+ def _write_mcp_config(project_dir: Path, enable_typesafe: bool = False) -> str:
321
+ mcp_path = project_dir / ".mcp.json"
322
+ existing: dict = {}
323
+ if mcp_path.exists():
324
+ try:
325
+ existing = json.loads(mcp_path.read_text())
326
+ except Exception:
327
+ pass
328
+ existing.setdefault("mcpServers", {}).update(_mcp_block(enable_typesafe))
329
+ mcp_path.write_text(json.dumps(existing, indent=2))
330
+ return ".mcp.json"
331
+
332
+
333
+ # ── Commands ──────────────────────────────────────────────────────────────────
334
+
335
+ _SUPPORTED_TOOLS = ["claude", "opencode"]
336
+
337
+ _TOOL_CHECK = {
338
+ "claude": {
339
+ "bin": "claude",
340
+ "name": "Claude Code",
341
+ "install": "npm install -g @anthropic-ai/claude-code && claude login",
342
+ "install_cmd": ["npm", "install", "-g", "@anthropic-ai/claude-code"],
343
+ },
344
+ "opencode": {
345
+ "bin": "opencode",
346
+ "name": "OpenCode",
347
+ "install": "curl -fsSL https://opencode.ai/install | bash",
348
+ "install_cmd": None, # pipe install — run via shell
349
+ },
350
+ }
351
+
352
+
353
+ def _check_and_offer_install(tool: str) -> None:
354
+ info = _TOOL_CHECK[tool]
355
+ if shutil.which(info["bin"]):
356
+ return
357
+
358
+ console.print(f" [yellow]⚠[/yellow] {info['name']} not found — you need it to use nexus.\n")
359
+
360
+ if not sys.stdin.isatty():
361
+ console.print(f" [dim]Install manually: {info['install']}[/dim]\n")
362
+ return
363
+
364
+ answer = console.input(f" Install {info['name']} now? {escape('[y/N]')} ").strip().lower()
365
+ if answer != "y":
366
+ console.print(f" [dim]Skipping. Install manually: {info['install']}[/dim]\n")
367
+ return
368
+
369
+ console.print(f" [cyan]▶[/cyan] Installing {info['name']}…\n")
370
+ if info["install_cmd"]:
371
+ result = subprocess.run(info["install_cmd"])
372
+ else:
373
+ result = subprocess.run(info["install"], shell=True)
374
+
375
+ if result.returncode == 0:
376
+ console.print(f" [green]✓[/green] {info['name']} installed.\n")
377
+ else:
378
+ console.print(f" [red]✗[/red] Install failed. Run manually: {info['install']}\n")
379
+
380
+
381
+ _GRAPH_BACKENDS = {
382
+ "graphify": "existing default — this scaffolds the PostToolUse hook that auto-updates it",
383
+ "codegraph": "you run `codegraph install && codegraph init` yourself — it syncs itself, no hook needed",
384
+ "none": "skip for now — set either up later, doctor will detect it",
385
+ }
386
+
387
+
388
+ def _resolve_graph_backend(explicit: str | None) -> str:
389
+ if explicit:
390
+ if explicit not in _GRAPH_BACKENDS:
391
+ console.print(f" [red]✗[/red] Unknown --graph-backend '{explicit}'. Choose from: {', '.join(_GRAPH_BACKENDS)}")
392
+ raise typer.Exit(1)
393
+ return explicit
394
+
395
+ if not sys.stdin.isatty():
396
+ return "graphify" # unchanged behavior for CI/scripted `nexus init`
397
+
398
+ console.print(f" Which knowledge graph do you want {_CLI_BIN} to wire up?")
399
+ console.print(" [cyan]1[/cyan] graphify (default)")
400
+ console.print(" [cyan]2[/cyan] codegraph")
401
+ console.print(" [cyan]3[/cyan] skip for now")
402
+ answer = console.input(f" Choice {escape('[1]')}: ").strip()
403
+ return {"2": "codegraph", "3": "none"}.get(answer, "graphify")
404
+
405
+
406
+ def _resolve_typesafe(explicit: bool | None) -> bool:
407
+ if explicit is not None:
408
+ return explicit
409
+
410
+ if not sys.stdin.isatty():
411
+ return False # unchanged behavior for CI/scripted `nexus init`
412
+
413
+ console.print(" Enable TypeSafe/Jev-powered smart detection for EPAV tools?")
414
+ console.print(
415
+ " [dim]Architecture-doc parsing, stack inference, and package-manager\n"
416
+ " selection get AI judgment instead of keyword matching. Needs a\n"
417
+ " TYPESAFE_API_KEY; falls back to built-in heuristics either way if\n"
418
+ " one isn't set, so this is safe to skip and enable later.[/dim]"
419
+ )
420
+ answer = console.input(f" Enable TypeSafe? {escape('[y/N]')} ").strip().lower()
421
+ return answer == "y"
422
+
423
+
424
+ @app.command()
425
+ def init(
426
+ project_dir: str = typer.Argument(".", help="Project directory to initialize"),
427
+ tool: str = typer.Option("claude", "--tool", "-t", help=f"AI coding tool to set up for ({', '.join(_SUPPORTED_TOOLS)})"),
428
+ graph_backend: str = typer.Option(None, "--graph-backend", "-g", help=f"Knowledge graph tool to wire up ({', '.join(_GRAPH_BACKENDS)}). Prompts interactively if omitted."),
429
+ typesafe: bool = typer.Option(None, "--typesafe/--no-typesafe", help="Enable TypeSafe/Jev-powered smart detection for EPAV tools (needs TYPESAFE_API_KEY). Prompts interactively if omitted."),
430
+ ) -> None:
431
+ """Initialize nexus in a project directory. Defaults to Claude Code."""
432
+ if tool not in _SUPPORTED_TOOLS:
433
+ console.print(f" [red]✗[/red] Unknown tool '{tool}'. Supported: {', '.join(_SUPPORTED_TOOLS)}")
434
+ raise typer.Exit(1)
435
+
436
+ _check_and_offer_install(tool)
437
+
438
+ backend = _resolve_graph_backend(graph_backend)
439
+ enable_typesafe = _resolve_typesafe(typesafe)
440
+
441
+ root = Path(project_dir).resolve()
442
+ console.print(f" [cyan]▶[/cyan] Initializing {_CLI_BIN} for [bold]{tool}[/bold] in [bold]{root}[/bold]\n")
443
+
444
+ if tool == "opencode":
445
+ created = _init_opencode(root, backend, enable_typesafe)
446
+ for f in created:
447
+ console.print(f" [green]✓[/green] {f}")
448
+ if not created:
449
+ console.print(" [yellow]·[/yellow] Already initialized — nothing to do")
450
+ return
451
+ console.print(f"\n [bold green]Done.[/bold green] Open [bold]{root}[/bold] in OpenCode and type [cyan]/scaffold[/cyan]\n")
452
+ else:
453
+ created = _init_project(root, backend)
454
+ for f in created:
455
+ console.print(f" [green]✓[/green] {f}")
456
+ if not created:
457
+ console.print(" [yellow]·[/yellow] Already initialized — nothing to do")
458
+ return
459
+ mcp = _write_mcp_config(root, enable_typesafe)
460
+ console.print(f" [green]✓[/green] {mcp}")
461
+ console.print(f"\n [bold green]Done.[/bold green] Open [bold]{root}[/bold] in Claude Code and type [cyan]/scaffold[/cyan]\n")
462
+
463
+ if backend == "codegraph":
464
+ console.print(" [cyan]→[/cyan] Next: run [bold]codegraph install && codegraph init[/bold] to wire codegraph into this project (it manages its own auto-sync — no hook needed).\n")
465
+
466
+ if enable_typesafe:
467
+ console.print(" [cyan]→[/cyan] Next: set [bold]TYPESAFE_API_KEY[/bold] (create one at https://console.typesafe.ai/) — without it, EPAV tools fall back to built-in heuristics automatically.\n")
468
+
469
+
470
+ @app.command()
471
+ def update(
472
+ also_sync: bool = typer.Option(False, "--sync", "-s", help="Also sync built-in skills/agents in the current directory after upgrading."),
473
+ ) -> None:
474
+ """Update nexus-dev-toolkit to the latest version."""
475
+ latest_version = _fetch_latest_pypi_version()
476
+ upgraded = False
477
+ if latest_version and not _is_outdated(_VERSION, latest_version):
478
+ console.print(f"\n [green]✓[/green] Already up to date (v{_VERSION}).\n")
479
+ else:
480
+ console.print(f"\n [cyan]▶[/cyan] Updating {_PACKAGE_NAME}…\n")
481
+ if shutil.which("uv"):
482
+ subprocess.run(["uv", "tool", "upgrade", _PACKAGE_NAME])
483
+ else:
484
+ subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", _PACKAGE_NAME])
485
+ console.print("\n [green]✓[/green] Done.\n")
486
+ upgraded = True
487
+
488
+ if not also_sync:
489
+ if sys.stdin.isatty():
490
+ answer = console.input(f" Also sync built-in skills/agents in the current directory? {escape('[y/N]')} ").strip().lower()
491
+ also_sync = answer == "y"
492
+
493
+ if not also_sync:
494
+ console.print(
495
+ f" [dim]This only updated the {_CLI_BIN} CLI itself. Run [/dim][cyan]{_CLI_BIN} sync[/cyan][dim] in each "
496
+ "project to pull the updated skills/agents into .claude/ or .opencode/ — or pass "
497
+ "[/dim][cyan]--sync[/cyan][dim] next time to do both at once.[/dim]\n"
498
+ )
499
+ return
500
+
501
+ root = Path(".").resolve()
502
+
503
+ if upgraded:
504
+ # This process's own _BUILTIN_SKILLS/_BUILTIN_AGENTS were imported before the upgrade
505
+ # subprocess above ran, so syncing in-process here would silently miss anything newly
506
+ # added in the version just installed. Re-exec `<_CLI_BIN> sync` as a fresh process
507
+ # instead -- must be this build's own binary, not the real "nexus", or it would re-exec
508
+ # the stable install's sync (wrong codebase, wrong skill set) instead of this one's.
509
+ nexus_bin = shutil.which(_CLI_BIN)
510
+ if nexus_bin:
511
+ subprocess.run([nexus_bin, "sync", str(root)])
512
+ return
513
+ console.print(
514
+ f" [yellow]⚠[/yellow] Couldn't find [bold]{_CLI_BIN}[/bold] on PATH to re-run sync in a fresh "
515
+ "process — syncing in-process instead, which may miss anything added in this exact "
516
+ f"upgrade. Run [cyan]{_CLI_BIN} sync[/cyan] again afterward to be sure.\n"
517
+ )
518
+
519
+ table = _sync_project(root)
520
+ if table is None:
521
+ console.print(" [yellow]⚠[/yellow] Current directory isn't a nexus-jev project — skipping sync.\n")
522
+ return
523
+
524
+ console.print(f" [cyan]▶[/cyan] Syncing built-ins in [bold]{root}[/bold]\n")
525
+ console.print(table)
526
+ console.print()
527
+
528
+
529
+ def _sync_project(root: Path) -> Table | None:
530
+ """Sync built-in skills/agents into root. None if root isn't a nexus project (neither
531
+ .claude/ nor .opencode/ present) — callers decide how to handle that case."""
532
+ has_claude = (root / ".claude").is_dir()
533
+ has_opencode = (root / ".opencode").is_dir()
534
+
535
+ if not has_claude and not has_opencode:
536
+ return None
537
+
538
+ table = Table(show_header=True, header_style="dim")
539
+ table.add_column("File")
540
+ table.add_column("Status")
541
+
542
+ if has_claude:
543
+ (root / ".claude" / "commands").mkdir(parents=True, exist_ok=True)
544
+ (root / ".claude" / "agents").mkdir(parents=True, exist_ok=True)
545
+
546
+ for fname in _BUILTIN_SKILLS:
547
+ src = _SKILLS_SRC / fname
548
+ if not src.exists():
549
+ continue
550
+ dst = root / ".claude" / "commands" / fname
551
+ src_text = src.read_text(encoding="utf-8")
552
+ if dst.exists() and dst.read_text(encoding="utf-8") == src_text:
553
+ table.add_row(f".claude/commands/{fname}", "[dim green]ok[/dim green]")
554
+ else:
555
+ dst.write_text(src_text, encoding="utf-8")
556
+ table.add_row(f".claude/commands/{fname}", "[cyan]updated[/cyan]")
557
+
558
+ for fname in _BUILTIN_AGENTS:
559
+ src = _AGENTS_SRC / fname
560
+ if not src.exists():
561
+ continue
562
+ dst = root / ".claude" / "agents" / fname
563
+ src_text = src.read_text(encoding="utf-8")
564
+ if dst.exists() and dst.read_text(encoding="utf-8") == src_text:
565
+ table.add_row(f".claude/agents/{fname}", "[dim green]ok[/dim green]")
566
+ else:
567
+ dst.write_text(src_text, encoding="utf-8")
568
+ table.add_row(f".claude/agents/{fname}", "[cyan]updated[/cyan]")
569
+
570
+ if has_opencode:
571
+ (root / ".opencode" / "commands").mkdir(parents=True, exist_ok=True)
572
+ (root / ".opencode" / "agents").mkdir(parents=True, exist_ok=True)
573
+ (root / ".opencode" / "plugins").mkdir(parents=True, exist_ok=True)
574
+
575
+ for fname in _BUILTIN_SKILLS:
576
+ src = _SKILLS_SRC / fname
577
+ if not src.exists():
578
+ continue
579
+ dst = root / ".opencode" / "commands" / fname
580
+ src_text = src.read_text(encoding="utf-8")
581
+ if dst.exists() and dst.read_text(encoding="utf-8") == src_text:
582
+ table.add_row(f".opencode/commands/{fname}", "[dim green]ok[/dim green]")
583
+ else:
584
+ dst.write_text(src_text, encoding="utf-8")
585
+ table.add_row(f".opencode/commands/{fname}", "[cyan]updated[/cyan]")
586
+
587
+ for fname in _BUILTIN_AGENTS:
588
+ src = _AGENTS_SRC / fname
589
+ if not src.exists():
590
+ continue
591
+ dst = root / ".opencode" / "agents" / fname
592
+ src_text = _strip_claude_frontmatter(src.read_text(encoding="utf-8"))
593
+ if dst.exists() and dst.read_text(encoding="utf-8") == src_text:
594
+ table.add_row(f".opencode/agents/{fname}", "[dim green]ok[/dim green]")
595
+ else:
596
+ dst.write_text(src_text, encoding="utf-8")
597
+ table.add_row(f".opencode/agents/{fname}", "[cyan]updated[/cyan]")
598
+
599
+ plugin_dst = root / ".opencode" / "plugins" / "graphify.js"
600
+ if plugin_dst.exists() and plugin_dst.read_text(encoding="utf-8") == _OPENCODE_GRAPHIFY_PLUGIN:
601
+ table.add_row(".opencode/plugins/graphify.js", "[dim green]ok[/dim green]")
602
+ else:
603
+ plugin_dst.write_text(_OPENCODE_GRAPHIFY_PLUGIN, encoding="utf-8")
604
+ table.add_row(".opencode/plugins/graphify.js", "[cyan]updated[/cyan]")
605
+
606
+ return table
607
+
608
+
609
+ @app.command()
610
+ def sync(
611
+ project_dir: str = typer.Argument(".", help="Project directory to sync"),
612
+ ) -> None:
613
+ """Sync built-in skills and agents to their latest versions (custom files untouched)."""
614
+ root = Path(project_dir).resolve()
615
+ table = _sync_project(root)
616
+ if table is None:
617
+ console.print(f" [red]✗[/red] Not a nexus project. Run [cyan]{_CLI_BIN} init[/cyan] first.\n")
618
+ raise typer.Exit(1)
619
+
620
+ console.print(f"\n [cyan]▶[/cyan] Syncing built-ins in [bold]{root}[/bold]\n")
621
+ console.print(table)
622
+ console.print()
623
+
624
+
625
+ @app.command()
626
+ def doctor(
627
+ project_dir: str = typer.Argument(".", help="Project directory to check"),
628
+ ) -> None:
629
+ """Validate the nexus project setup and show what's working or missing."""
630
+ root = Path(project_dir).resolve()
631
+
632
+ table = Table(show_header=True, header_style="dim", show_lines=False)
633
+ table.add_column("Check", style="dim white")
634
+ table.add_column("Status")
635
+
636
+ has_failure = False
637
+
638
+ def ok(msg: str) -> str:
639
+ return f"[green]✓[/green] {msg}"
640
+
641
+ def warn(msg: str) -> str:
642
+ return f"[yellow]⚠[/yellow] {msg}"
643
+
644
+ def fail(msg: str) -> str:
645
+ nonlocal has_failure
646
+ has_failure = True
647
+ return f"[red]✗[/red] {msg}"
648
+
649
+ # ── nexus ────────────────────────────────────────────────────────────────
650
+ latest_version = _fetch_latest_pypi_version()
651
+ if latest_version:
652
+ if _is_outdated(_VERSION, latest_version):
653
+ table.add_row(_PACKAGE_NAME, warn(f"update available: v{_VERSION} → v{latest_version} (run: {_CLI_BIN} update)"))
654
+ else:
655
+ table.add_row(_PACKAGE_NAME, ok(f"up to date (v{_VERSION})"))
656
+
657
+ # ── Tool ─────────────────────────────────────────────────────────────────
658
+ has_claude_bin = bool(shutil.which("claude"))
659
+ has_opencode_bin = bool(shutil.which("opencode"))
660
+ table.add_row("Claude Code", ok("installed") if has_claude_bin else warn("not found — install: npm install -g @anthropic-ai/claude-code"))
661
+ table.add_row("OpenCode", ok("installed") if has_opencode_bin else warn("not found — install: curl -fsSL https://opencode.ai/install | bash"))
662
+
663
+ # ── Project ──────────────────────────────────────────────────────────────
664
+ has_claude_dir = (root / ".claude").is_dir()
665
+ has_opencode_dir = (root / ".opencode").is_dir()
666
+ initialized = has_claude_dir or has_opencode_dir
667
+ table.add_row(
668
+ f"{_CLI_BIN} initialized",
669
+ ok(f"yes ({', '.join(filter(None, ['claude' if has_claude_dir else '', 'opencode' if has_opencode_dir else '']))})")
670
+ if initialized else fail(f"no — run {_CLI_BIN} init")
671
+ )
672
+
673
+ # MCP config — Claude Code
674
+ if has_claude_dir:
675
+ mcp_path = root / ".mcp.json"
676
+ if not mcp_path.exists():
677
+ table.add_row(".mcp.json", fail("missing"))
678
+ else:
679
+ try:
680
+ mcp_data = json.loads(mcp_path.read_text())
681
+ if "nexus-jev" in mcp_data.get("mcpServers", {}):
682
+ table.add_row(".mcp.json", ok("nexus-jev entry present"))
683
+ else:
684
+ table.add_row(".mcp.json", warn("exists but no nexus-jev entry"))
685
+ except Exception:
686
+ table.add_row(".mcp.json", warn("invalid JSON"))
687
+
688
+ # MCP config — OpenCode
689
+ if has_opencode_dir:
690
+ oc_json = root / "opencode.json"
691
+ if not oc_json.exists():
692
+ table.add_row("opencode.json", fail("missing"))
693
+ else:
694
+ try:
695
+ oc_data = json.loads(oc_json.read_text())
696
+ if "nexus-jev-mcp" in oc_data.get("mcp", {}):
697
+ table.add_row("opencode.json", ok("nexus-jev entry present"))
698
+ else:
699
+ table.add_row("opencode.json", warn("exists but no nexus-jev-mcp entry"))
700
+ except Exception:
701
+ table.add_row("opencode.json", warn("invalid JSON"))
702
+
703
+ # ── TypeSafe / Jev ───────────────────────────────────────────────────────
704
+ typesafe_wired = False
705
+ if has_claude_dir and (root / ".mcp.json").exists():
706
+ try:
707
+ args = json.loads((root / ".mcp.json").read_text()).get("mcpServers", {}).get("nexus-jev", {}).get("args", [])
708
+ typesafe_wired = typesafe_wired or "[typesafe]" in " ".join(args)
709
+ except Exception:
710
+ pass
711
+ if has_opencode_dir and (root / "opencode.json").exists():
712
+ try:
713
+ cmd = json.loads((root / "opencode.json").read_text()).get("mcp", {}).get("nexus-jev-mcp", {}).get("command", [])
714
+ typesafe_wired = typesafe_wired or "[typesafe]" in " ".join(cmd)
715
+ except Exception:
716
+ pass
717
+
718
+ if typesafe_wired:
719
+ if os.environ.get("TYPESAFE_API_KEY", "").strip():
720
+ table.add_row("TypeSafe / Jev", ok("enabled — arch-doc parsing, stack inference, and package-manager selection are TypeSafe-powered"))
721
+ else:
722
+ table.add_row("TypeSafe / Jev", warn("wired but TYPESAFE_API_KEY not set — falling back to built-in heuristics"))
723
+ else:
724
+ table.add_row("TypeSafe / Jev", f"[dim]not enabled (optional) — run `{_CLI_BIN} init --typesafe` to wire it up[/dim]")
725
+
726
+ # ── Skills & Agents ──────────────────────────────────────────────────────
727
+ if has_claude_dir:
728
+ cmd_dir = root / ".claude" / "commands"
729
+ present = [f for f in _BUILTIN_SKILLS if (cmd_dir / f).exists()]
730
+ missing = len(_BUILTIN_SKILLS) - len(present)
731
+ if missing == 0:
732
+ table.add_row("Built-in skills (Claude)", ok(f"all {len(_BUILTIN_SKILLS)} present"))
733
+ else:
734
+ table.add_row("Built-in skills (Claude)", warn(f"{missing} missing — run {_CLI_BIN} sync"))
735
+
736
+ ag_dir = root / ".claude" / "agents"
737
+ present_ag = [f for f in _BUILTIN_AGENTS if (ag_dir / f).exists()]
738
+ missing_ag = len(_BUILTIN_AGENTS) - len(present_ag)
739
+ if missing_ag == 0:
740
+ table.add_row("Built-in agents (Claude)", ok(f"all {len(_BUILTIN_AGENTS)} present"))
741
+ else:
742
+ table.add_row("Built-in agents (Claude)", warn(f"{missing_ag} missing — run {_CLI_BIN} sync"))
743
+
744
+ if has_opencode_dir:
745
+ oc_cmd_dir = root / ".opencode" / "commands"
746
+ present_oc = [f for f in _BUILTIN_SKILLS if (oc_cmd_dir / f).exists()]
747
+ missing_oc = len(_BUILTIN_SKILLS) - len(present_oc)
748
+ if missing_oc == 0:
749
+ table.add_row("Built-in skills (OpenCode)", ok(f"all {len(_BUILTIN_SKILLS)} present"))
750
+ else:
751
+ table.add_row("Built-in skills (OpenCode)", warn(f"{missing_oc} missing — run {_CLI_BIN} sync"))
752
+
753
+ oc_ag_dir = root / ".opencode" / "agents"
754
+ present_oc_ag = [f for f in _BUILTIN_AGENTS if (oc_ag_dir / f).exists()]
755
+ missing_oc_ag = len(_BUILTIN_AGENTS) - len(present_oc_ag)
756
+ if missing_oc_ag == 0:
757
+ table.add_row("Built-in agents (OpenCode)", ok(f"all {len(_BUILTIN_AGENTS)} present"))
758
+ else:
759
+ table.add_row("Built-in agents (OpenCode)", warn(f"{missing_oc_ag} missing — run {_CLI_BIN} sync"))
760
+
761
+ # ── Knowledge ────────────────────────────────────────────────────────────
762
+ missing_dirs = [d for d in _KNOWLEDGE_DIRS if not (root / d).is_dir()]
763
+ if not missing_dirs:
764
+ table.add_row("Knowledge dirs", ok(f"all {len(_KNOWLEDGE_DIRS)} present"))
765
+ else:
766
+ table.add_row("Knowledge dirs", warn(f"missing: {', '.join(missing_dirs)}"))
767
+
768
+ # ── Knowledge graph backends ────────────────────────────────────────────
769
+ has_graphify = graph_backend.backend_installed("graphify")
770
+ table.add_row("graphify", ok("installed") if has_graphify else warn("not installed — uv tool install graphifyy"))
771
+
772
+ has_codegraph = graph_backend.backend_installed("codegraph")
773
+ table.add_row("codegraph", ok("installed") if has_codegraph else warn("not installed — npm i -g @colbymchenry/codegraph"))
774
+
775
+ graphify_built = graph_backend.graph_exists("graphify", root)
776
+ codegraph_built = graph_backend.graph_exists("codegraph", root)
777
+ override = graph_backend.get_override()
778
+ active = graph_backend.detect_backend(root)
779
+
780
+ if graphify_built and codegraph_built:
781
+ if override in graph_backend.BACKEND_NAMES and graph_backend.graph_exists(override, root):
782
+ reason = f"forced via {graph_backend.ENV_VAR}={override}"
783
+ else:
784
+ reason = "graphify wins ties by default"
785
+ table.add_row("Knowledge graph", warn(f"both graphify and codegraph graphs present — using {active} ({reason})"))
786
+ elif graphify_built or codegraph_built:
787
+ built = "graphify" if graphify_built else "codegraph"
788
+ output = "graphify-out/graph.json" if built == "graphify" else ".codegraph/codegraph.db"
789
+ table.add_row("Knowledge graph", ok(f"{output} exists ({built})"))
790
+ else:
791
+ table.add_row("Knowledge graph", warn("not built — run: graphify . (or codegraph init)"))
792
+
793
+ if override and (override not in graph_backend.BACKEND_NAMES or not graph_backend.graph_exists(override, root)):
794
+ table.add_row(
795
+ graph_backend.ENV_VAR,
796
+ warn(f"set to '{override}' but its graph isn't built — ignoring override, run the matching init/build command"),
797
+ )
798
+
799
+ if graph_backend.has_graphify_hook(root) and codegraph_built and active == "codegraph":
800
+ table.add_row("Stale hook", warn("graphify PostToolUse hook present but codegraph is the active backend — harmless no-op, remove manually if unwanted"))
801
+
802
+ console.print()
803
+ console.print(" [dim]Some tools below are alternatives, not companions (e.g. graphify vs codegraph) — nexus-jev flags conflicts here when both are present.[/dim]")
804
+ console.print()
805
+ console.print(table)
806
+ console.print()
807
+
808
+ if has_failure:
809
+ raise typer.Exit(1)
810
+
811
+
812
+ # ── skill subcommands ─────────────────────────────────────────────────────────
813
+
814
+ _SKILL_TEMPLATE = """\
815
+ # /{name}
816
+
817
+ **{name}** — describe what this skill does.
818
+
819
+ ## When to use
820
+
821
+ Describe the trigger or context.
822
+
823
+ ## Steps
824
+
825
+ ### 1 — First step
826
+
827
+ What to do.
828
+
829
+ ### 2 — Second step
830
+
831
+ What to do next.
832
+
833
+ ### 3 — Output
834
+
835
+ What the AI should produce when done.
836
+ """
837
+
838
+
839
+ @skill_app.command("add")
840
+ def skill_add(
841
+ name: str = typer.Argument(..., help="Skill name (e.g. 'code-review')"),
842
+ project_dir: str = typer.Option(".", "--dir", "-d"),
843
+ ) -> None:
844
+ """Create a new skill in .claude/commands/."""
845
+ root = Path(project_dir).resolve()
846
+ dest = root / ".claude" / "commands" / f"{name}.md"
847
+ dest.parent.mkdir(parents=True, exist_ok=True)
848
+
849
+ if dest.exists():
850
+ console.print(f" [yellow]·[/yellow] .claude/commands/{name}.md already exists")
851
+ return
852
+
853
+ dest.write_text(_SKILL_TEMPLATE.format(name=name), encoding="utf-8")
854
+ console.print(f" [green]✓[/green] Created .claude/commands/{name}.md")
855
+ console.print(f" [dim]Edit it and type [cyan]/{name}[/cyan] in Claude Code.[/dim]")
856
+
857
+
858
+ @skill_app.command("list")
859
+ def skill_list(
860
+ project_dir: str = typer.Option(".", "--dir", "-d"),
861
+ ) -> None:
862
+ """List all skills in .claude/commands/."""
863
+ root = Path(project_dir).resolve()
864
+ commands_dir = root / ".claude" / "commands"
865
+
866
+ if not commands_dir.exists():
867
+ console.print(f" [yellow]·[/yellow] No .claude/commands/ found. Run [cyan]{_CLI_BIN} init[/cyan] first.")
868
+ return
869
+
870
+ skills = sorted(commands_dir.glob("*.md"))
871
+ if not skills:
872
+ console.print(f" [yellow]·[/yellow] No skills yet. Run [cyan]{_CLI_BIN} skill add <name>[/cyan]")
873
+ return
874
+
875
+ table = Table(show_header=True, header_style="dim")
876
+ table.add_column("Skill", style="cyan")
877
+ table.add_column("Source")
878
+
879
+ builtins = set(_BUILTIN_SKILLS)
880
+ for s in skills:
881
+ source = "built-in" if s.name in builtins else "custom"
882
+ table.add_row(f"/{s.stem}", source)
883
+
884
+ console.print(table)
885
+
886
+
887
+ # ── rule subcommands ──────────────────────────────────────────────────────────
888
+
889
+ _RULE_TEMPLATE = """\
890
+ # {name}
891
+
892
+ _Project rule — read by AI tools via AGENTS.md._
893
+
894
+ ## Rules
895
+
896
+ - Rule one
897
+ - Rule two
898
+ - Rule three
899
+
900
+ ## Rationale
901
+
902
+ Why these rules exist.
903
+ """
904
+
905
+
906
+ @rule_app.command("add")
907
+ def rule_add(
908
+ name: str = typer.Argument(..., help="Rule name (e.g. 'api-standards')"),
909
+ project_dir: str = typer.Option(".", "--dir", "-d"),
910
+ ) -> None:
911
+ """Create a new rule in knowledge/rules/."""
912
+ root = Path(project_dir).resolve()
913
+ dest = root / "knowledge" / "rules" / f"{name}.md"
914
+ dest.parent.mkdir(parents=True, exist_ok=True)
915
+
916
+ if dest.exists():
917
+ console.print(f" [yellow]·[/yellow] knowledge/rules/{name}.md already exists")
918
+ return
919
+
920
+ dest.write_text(_RULE_TEMPLATE.format(name=name), encoding="utf-8")
921
+ console.print(f" [green]✓[/green] Created knowledge/rules/{name}.md")
922
+
923
+
924
+ @rule_app.command("list")
925
+ def rule_list(
926
+ project_dir: str = typer.Option(".", "--dir", "-d"),
927
+ ) -> None:
928
+ """List all rules in knowledge/rules/."""
929
+ root = Path(project_dir).resolve()
930
+ rules_dir = root / "knowledge" / "rules"
931
+
932
+ if not rules_dir.exists():
933
+ console.print(f" [yellow]·[/yellow] No knowledge/rules/ found. Run [cyan]{_CLI_BIN} init[/cyan] first.")
934
+ return
935
+
936
+ rules = sorted(rules_dir.glob("*.md"))
937
+ if not rules:
938
+ console.print(f" [yellow]·[/yellow] No rules yet. Run [cyan]{_CLI_BIN} rule add <name>[/cyan]")
939
+ return
940
+
941
+ table = Table(show_header=True, header_style="dim")
942
+ table.add_column("Rule", style="cyan")
943
+ for r in rules:
944
+ table.add_row(r.stem)
945
+ console.print(table)
946
+
947
+
948
+ # ── agent subcommands ─────────────────────────────────────────────────────────
949
+
950
+ _AGENT_TEMPLATE = """\
951
+ ---
952
+ name: {name}
953
+ description: Describe when Claude should spawn this agent (role, not action — e.g. "reviews X for Y")
954
+ ---
955
+
956
+ # {name}
957
+
958
+ ## Role
959
+
960
+ Describe what this agent does.
961
+
962
+ ## Steps
963
+
964
+ ### 1 — Discover context
965
+
966
+ Read CLAUDE.md, project manifest, and relevant source files.
967
+
968
+ ### 2 — Perform task
969
+
970
+ What the agent should do.
971
+
972
+ ### 3 — Output
973
+
974
+ What the agent should return when done.
975
+ """
976
+
977
+
978
+ @agent_app.command("add")
979
+ def agent_add(
980
+ name: str = typer.Argument(..., help="Agent name (e.g. 'security-reviewer')"),
981
+ project_dir: str = typer.Option(".", "--dir", "-d"),
982
+ ) -> None:
983
+ """Create a new subagent in .claude/agents/."""
984
+ root = Path(project_dir).resolve()
985
+ dest = root / ".claude" / "agents" / f"{name}.md"
986
+ dest.parent.mkdir(parents=True, exist_ok=True)
987
+
988
+ if dest.exists():
989
+ console.print(f" [yellow]·[/yellow] .claude/agents/{name}.md already exists")
990
+ return
991
+
992
+ dest.write_text(_AGENT_TEMPLATE.format(name=name), encoding="utf-8")
993
+ console.print(f" [green]✓[/green] Created .claude/agents/{name}.md")
994
+ console.print(f" [dim]Edit the description so Claude knows when to spawn it.[/dim]")
995
+
996
+
997
+ @agent_app.command("list")
998
+ def agent_list(
999
+ project_dir: str = typer.Option(".", "--dir", "-d"),
1000
+ ) -> None:
1001
+ """List all subagents in .claude/agents/."""
1002
+ root = Path(project_dir).resolve()
1003
+ agents_dir = root / ".claude" / "agents"
1004
+
1005
+ if not agents_dir.exists():
1006
+ console.print(f" [yellow]·[/yellow] No .claude/agents/ found. Run [cyan]{_CLI_BIN} init[/cyan] first.")
1007
+ return
1008
+
1009
+ agents = sorted(agents_dir.glob("*.md"))
1010
+ if not agents:
1011
+ console.print(f" [yellow]·[/yellow] No agents yet. Run [cyan]{_CLI_BIN} agent add <name>[/cyan]")
1012
+ return
1013
+
1014
+ table = Table(show_header=True, header_style="dim")
1015
+ table.add_column("Agent", style="cyan")
1016
+ table.add_column("Source")
1017
+
1018
+ builtins = set(_BUILTIN_AGENTS)
1019
+ for a in agents:
1020
+ source = "built-in" if a.name in builtins else "custom"
1021
+ table.add_row(a.stem, source)
1022
+
1023
+ console.print(table)
1024
+
1025
+
1026
+ def main() -> None:
1027
+ app()
1028
+
1029
+
1030
+ if __name__ == "__main__":
1031
+ main()