Skip to content

Commit c2227a7

Browse files
Copilotmnriem
andauthored
feat: add --agent flag to init for pack-based flow with file tracking
- `specify init --agent claude` resolves through the pack system and records all installed files in .specify/agent-manifest-<id>.json via finalize_setup() after the init pipeline finishes - --agent and --ai are mutually exclusive; --agent additionally enables tracked teardown/switch - init-options.json gains "agent_pack" key when --agent is used - 4 new parity tests verify: pack resolution matches AGENT_CONFIG, commands_dir parity, finalize_setup records pipeline-created files, pack metadata matches CommandRegistrar configuration Co-authored-by: mnriem <15701806+mnriem@users.noreply.github.com> Agent-Logs-Url: https://github.com/github/spec-kit/sessions/930d8c4d-ce42-41fb-a40f-561fb1468e81
1 parent c3efd1f commit c2227a7

File tree

2 files changed

+142
-1
lines changed

2 files changed

+142
-1
lines changed

src/specify_cli/__init__.py

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1715,6 +1715,7 @@ def _handle_agent_skills_migration(console: Console, agent_key: str) -> None:
17151715
def init(
17161716
project_name: str = typer.Argument(None, help="Name for your new project directory (optional if using --here, or use '.' for current directory)"),
17171717
ai_assistant: str = typer.Option(None, "--ai", help=AI_ASSISTANT_HELP),
1718+
agent: str = typer.Option(None, "--agent", help="AI agent to use (pack-based flow — resolves through the agent pack system and records installed files for tracked teardown). Accepts the same agent IDs as --ai."),
17181719
ai_commands_dir: str = typer.Option(None, "--ai-commands-dir", help="Directory for agent command files (required with --ai generic, e.g. .myagent/commands/)"),
17191720
script_type: str = typer.Option(None, "--script", help="Script type to use: sh or ps"),
17201721
ignore_agent_tools: bool = typer.Option(False, "--ignore-agent-tools", help="Skip checks for AI agent tools like Claude Code"),
@@ -1753,6 +1754,7 @@ def init(
17531754
Examples:
17541755
specify init my-project
17551756
specify init my-project --ai claude
1757+
specify init my-project --agent claude # Pack-based flow (with file tracking)
17561758
specify init my-project --ai copilot --no-git
17571759
specify init --ignore-agent-tools my-project
17581760
specify init . --ai claude # Initialize in current directory
@@ -1765,13 +1767,25 @@ def init(
17651767
specify init --here --force # Skip confirmation when current directory not empty
17661768
specify init my-project --ai claude --ai-skills # Install agent skills
17671769
specify init --here --ai gemini --ai-skills
1770+
specify init my-project --agent claude --ai-skills # Pack-based flow with skills
17681771
specify init my-project --ai generic --ai-commands-dir .myagent/commands/ # Unsupported agent
17691772
specify init my-project --offline # Use bundled assets (no network access)
17701773
specify init my-project --ai claude --preset healthcare-compliance # With preset
17711774
"""
17721775

17731776
show_banner()
17741777

1778+
# --agent and --ai are interchangeable for agent selection, but --agent
1779+
# additionally opts into the pack-based flow (file tracking via
1780+
# finalize_setup for tracked teardown/switch).
1781+
use_agent_pack = False
1782+
if agent:
1783+
if ai_assistant:
1784+
console.print("[red]Error:[/red] --agent and --ai cannot both be specified. Use one or the other.")
1785+
raise typer.Exit(1)
1786+
ai_assistant = agent
1787+
use_agent_pack = True
1788+
17751789
# Detect when option values are likely misinterpreted flags (parameter ordering issue)
17761790
if ai_assistant and ai_assistant.startswith("--"):
17771791
console.print(f"[red]Error:[/red] Invalid value for --ai: '{ai_assistant}'")
@@ -1802,7 +1816,7 @@ def init(
18021816
raise typer.Exit(1)
18031817

18041818
if ai_skills and not ai_assistant:
1805-
console.print("[red]Error:[/red] --ai-skills requires --ai to be specified")
1819+
console.print("[red]Error:[/red] --ai-skills requires --ai or --agent to be specified")
18061820
console.print("[yellow]Usage:[/yellow] specify init <project> --ai <agent> --ai-skills")
18071821
raise typer.Exit(1)
18081822

@@ -1854,6 +1868,19 @@ def init(
18541868
"copilot"
18551869
)
18561870

1871+
# When --agent is used, validate that the agent resolves through the pack
1872+
# system and prepare the bootstrap for post-init file tracking.
1873+
agent_bootstrap = None
1874+
if use_agent_pack:
1875+
from .agent_pack import resolve_agent_pack, load_bootstrap, PackResolutionError, AgentPackError
1876+
try:
1877+
resolved = resolve_agent_pack(selected_ai)
1878+
agent_bootstrap = load_bootstrap(resolved.path, resolved.manifest)
1879+
console.print(f"[dim]Pack-based flow: {resolved.manifest.name} ({resolved.source})[/dim]")
1880+
except (PackResolutionError, AgentPackError) as exc:
1881+
console.print(f"[red]Error resolving agent pack:[/red] {exc}")
1882+
raise typer.Exit(1)
1883+
18571884
# Agents that have moved from explicit commands/prompts to agent skills.
18581885
if selected_ai in AGENT_SKILLS_MIGRATIONS and not ai_skills:
18591886
# If selected interactively (no --ai provided), automatically enable
@@ -2090,6 +2117,7 @@ def init(
20902117
"ai": selected_ai,
20912118
"ai_skills": ai_skills,
20922119
"ai_commands_dir": ai_commands_dir,
2120+
"agent_pack": use_agent_pack,
20932121
"branch_numbering": branch_numbering or "sequential",
20942122
"here": here,
20952123
"preset": preset,
@@ -2133,6 +2161,13 @@ def init(
21332161
if not use_github:
21342162
tracker.skip("cleanup", "not needed (no download)")
21352163

2164+
# When --agent is used, record all installed agent files for
2165+
# tracked teardown. This runs AFTER the full init pipeline has
2166+
# finished creating files (scaffolding, skills, presets,
2167+
# extensions) so finalize_setup captures everything.
2168+
if use_agent_pack and agent_bootstrap is not None:
2169+
agent_bootstrap.finalize_setup(project_path)
2170+
21362171
tracker.complete("final", "project ready")
21372172
except (typer.Exit, SystemExit):
21382173
raise

tests/test_agent_pack.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,3 +808,109 @@ def test_check_detects_extension_file_modification(self, tmp_path):
808808
modified = check_modified_files(project, "ag")
809809
assert len(modified) == 1
810810
assert ".ag/ext.md" in modified[0]
811+
812+
813+
# ===================================================================
814+
# --agent flag on init (pack-based flow parity)
815+
# ===================================================================
816+
817+
class TestInitAgentFlag:
818+
"""Verify the --agent flag on ``specify init`` resolves through the
819+
pack system and that pack metadata is consistent with AGENT_CONFIG."""
820+
821+
def test_agent_resolves_same_agent_as_ai(self):
822+
"""--agent <id> resolves the same agent as --ai <id> for all
823+
agents in AGENT_CONFIG (except 'generic')."""
824+
from specify_cli import AGENT_CONFIG
825+
826+
for agent_id in AGENT_CONFIG:
827+
if agent_id == "generic":
828+
continue
829+
try:
830+
resolved = resolve_agent_pack(agent_id)
831+
except PackResolutionError:
832+
pytest.fail(f"--agent {agent_id} would fail: no pack found")
833+
834+
assert resolved.manifest.id == agent_id
835+
836+
def test_pack_commands_dir_matches_agent_config(self):
837+
"""The pack's commands_dir matches the directory that the old
838+
flow (AGENT_CONFIG) would use, ensuring both flows write files
839+
to the same location."""
840+
from specify_cli import AGENT_CONFIG
841+
842+
for agent_id, config in AGENT_CONFIG.items():
843+
if agent_id == "generic":
844+
continue
845+
try:
846+
resolved = resolve_agent_pack(agent_id)
847+
except PackResolutionError:
848+
continue
849+
850+
# AGENT_CONFIG stores folder + commands_subdir
851+
folder = config.get("folder", "").rstrip("/")
852+
subdir = config.get("commands_subdir", "commands")
853+
expected_dir = f"{folder}/{subdir}" if folder else ""
854+
# Normalise path separators
855+
expected_dir = expected_dir.lstrip("/")
856+
857+
assert resolved.manifest.commands_dir == expected_dir, (
858+
f"{agent_id}: commands_dir mismatch: "
859+
f"pack={resolved.manifest.commands_dir!r} "
860+
f"config_derived={expected_dir!r}"
861+
)
862+
863+
def test_finalize_setup_records_files_after_init(self, tmp_path):
864+
"""Simulates the --agent init flow: setup → create files →
865+
finalize_setup, then verifies the install manifest is present."""
866+
# Pick any embedded agent (claude)
867+
resolved = resolve_agent_pack("claude")
868+
bootstrap = load_bootstrap(resolved.path, resolved.manifest)
869+
870+
project = tmp_path / "project"
871+
project.mkdir()
872+
(project / ".specify").mkdir()
873+
874+
# setup() creates the directory structure
875+
setup_files = bootstrap.setup(project, "sh", {})
876+
assert isinstance(setup_files, list)
877+
878+
# Simulate the init pipeline creating command files
879+
commands_dir = project / resolved.manifest.commands_dir
880+
commands_dir.mkdir(parents=True, exist_ok=True)
881+
cmd_file = commands_dir / "speckit-plan.md"
882+
cmd_file.write_text("plan command", encoding="utf-8")
883+
884+
# finalize_setup records everything
885+
bootstrap.finalize_setup(project)
886+
887+
manifest_file = _manifest_path(project, "claude")
888+
assert manifest_file.is_file()
889+
890+
data = json.loads(manifest_file.read_text(encoding="utf-8"))
891+
all_tracked = {
892+
**data.get("agent_files", {}),
893+
**data.get("extension_files", {}),
894+
}
895+
assert any("speckit-plan.md" in p for p in all_tracked), (
896+
"finalize_setup should record files created by the init pipeline"
897+
)
898+
899+
def test_pack_metadata_enables_same_extension_registration(self):
900+
"""Pack command_registration metadata matches CommandRegistrar
901+
configuration, ensuring that extension registration via the pack
902+
system writes to the same directories and with the same format as
903+
the old AGENT_CONFIG-based flow."""
904+
from specify_cli.agents import CommandRegistrar
905+
906+
for manifest in list_embedded_agents():
907+
registrar_config = CommandRegistrar.AGENT_CONFIGS.get(manifest.id)
908+
if registrar_config is None:
909+
continue
910+
911+
# These four fields are what CommandRegistrar uses to render
912+
# extension commands — they must match exactly.
913+
assert manifest.commands_dir == registrar_config["dir"]
914+
assert manifest.command_format == registrar_config["format"]
915+
assert manifest.arg_placeholder == registrar_config["args"]
916+
assert manifest.file_extension == registrar_config["extension"]

0 commit comments

Comments
 (0)