Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/scripts/create-release-packages.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,46 @@ function Generate-Commands {

$body = $outputLines -join "`n"

# Inject argument-hint for Claude Code commands (Claude-specific frontmatter)
if ($Agent -eq 'claude') {
$hint = switch ($name) {
'specify' { 'Describe the feature you want to specify' }
'plan' { 'Optional guidance for the planning phase' }
'tasks' { 'Optional task generation constraints' }
'implement' { 'Optional implementation guidance or task filter' }
'analyze' { 'Optional focus areas for analysis' }
'clarify' { 'Optional areas to clarify in the spec' }
'constitution' { 'Principles or values for the project constitution' }
'checklist' { 'Domain or focus area for the checklist' }
'taskstoissues' { 'Optional filter or label for GitHub issues' }
default { '' }
}
if (-not [string]::IsNullOrEmpty($hint)) {
# Scope injection to YAML frontmatter only (between first pair of ---)
$bodyLines = $body -split "`n"
$resultLines = @()
$fmDashCount = 0
$inFm = $false
$hintInjected = $false
foreach ($ln in $bodyLines) {
if ($ln -match '^---$') {
$resultLines += $ln
$fmDashCount++
$inFm = ($fmDashCount -eq 1)
continue
}
if ($inFm -and -not $hintInjected -and $ln -match '^description:') {
$resultLines += $ln
$resultLines += "argument-hint: $hint"
$hintInjected = $true
continue
}
$resultLines += $ln
}
$body = $resultLines -join "`n"
}
}

# Apply other substitutions
$body = $body -replace '\{ARGS\}', $ArgFormat
$body = $body -replace '__AGENT__', $Agent
Expand Down
29 changes: 29 additions & 0 deletions .github/workflows/scripts/create-release-packages.sh
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,35 @@ generate_commands() {
{ print }
')

# Inject argument-hint for Claude Code commands (Claude-specific frontmatter)
if [[ "$agent" == "claude" ]]; then
local hint=""
case "$name" in
specify) hint="Describe the feature you want to specify" ;;
plan) hint="Optional guidance for the planning phase" ;;
tasks) hint="Optional task generation constraints" ;;
implement) hint="Optional implementation guidance or task filter" ;;
analyze) hint="Optional focus areas for analysis" ;;
clarify) hint="Optional areas to clarify in the spec" ;;
constitution) hint="Principles or values for the project constitution" ;;
checklist) hint="Domain or focus area for the checklist" ;;
taskstoissues) hint="Optional filter or label for GitHub issues" ;;
esac
if [[ -n "$hint" ]]; then
body=$(printf '%s\n' "$body" | awk -v hint="$hint" '
/^---$/ {
print
if (++dash_count == 1) { in_fm = 1 } else { in_fm = 0 }
next
}
in_fm && !injected && /^description:/ {
print; print "argument-hint: " hint; injected = 1; next
}
{ print }
')
fi
fi

# Apply other substitutions
body=$(printf '%s\n' "$body" | sed "s/{ARGS}/$arg_format/g" | sed "s/__AGENT__/$agent/g" | rewrite_paths)

Expand Down
114 changes: 114 additions & 0 deletions src/specify_cli/integrations/claude/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
"""Claude Code integration."""

from __future__ import annotations

from pathlib import Path
from typing import Any, TYPE_CHECKING

from ..base import MarkdownIntegration

if TYPE_CHECKING:
from ..manifest import IntegrationManifest

# Mapping of command template stem → argument-hint text shown inline
# when a user invokes the slash command in Claude Code.
ARGUMENT_HINTS: dict[str, str] = {
"specify": "Describe the feature you want to specify",
"plan": "Optional guidance for the planning phase",
"tasks": "Optional task generation constraints",
"implement": "Optional implementation guidance or task filter",
"analyze": "Optional focus areas for analysis",
"clarify": "Optional areas to clarify in the spec",
"constitution": "Principles or values for the project constitution",
"checklist": "Domain or focus area for the checklist",
"taskstoissues": "Optional filter or label for GitHub issues",
}


class ClaudeIntegration(MarkdownIntegration):
key = "claude"
Expand All @@ -19,3 +41,95 @@ class ClaudeIntegration(MarkdownIntegration):
"extension": ".md",
}
context_file = "CLAUDE.md"

@staticmethod
def inject_argument_hint(content: str, hint: str) -> str:
"""Insert ``argument-hint`` after the first ``description:`` in YAML frontmatter.

Skips injection if ``argument-hint:`` already exists in the
frontmatter to avoid duplicate keys.
"""
lines = content.splitlines(keepends=True)

# Pre-scan: bail out if argument-hint already present in frontmatter
dash_count = 0
for line in lines:
stripped = line.rstrip("\n\r")
if stripped == "---":
dash_count += 1
if dash_count == 2:
break
continue
if dash_count == 1 and stripped.startswith("argument-hint:"):
return content # already present

out: list[str] = []
in_fm = False
dash_count = 0
injected = False
for line in lines:
stripped = line.rstrip("\n\r")
if stripped == "---":
dash_count += 1
in_fm = dash_count == 1
out.append(line)
continue
if in_fm and not injected and stripped.startswith("description:"):
out.append(line)
# Preserve the line-ending style of the file
eol = "\n" if line.endswith("\n") else ""
Comment thread
mnriem marked this conversation as resolved.
Outdated
out.append(f"argument-hint: {hint}{eol}")
injected = True
Comment thread
mnriem marked this conversation as resolved.
continue
Comment thread
mnriem marked this conversation as resolved.
out.append(line)
return "".join(out)

def setup(
self,
project_root: Path,
manifest: IntegrationManifest,
parsed_options: dict[str, Any] | None = None,
**opts: Any,
) -> list[Path]:
templates = self.list_command_templates()
if not templates:
return []

project_root_resolved = project_root.resolve()
if manifest.project_root != project_root_resolved:
raise ValueError(
f"manifest.project_root ({manifest.project_root}) does not match "
f"project_root ({project_root_resolved})"
)

dest = self.commands_dest(project_root).resolve()
try:
dest.relative_to(project_root_resolved)
except ValueError as exc:
raise ValueError(
f"Integration destination {dest} escapes "
f"project root {project_root_resolved}"
) from exc
dest.mkdir(parents=True, exist_ok=True)

script_type = opts.get("script_type", "sh")
arg_placeholder = self.registrar_config.get("args", "$ARGUMENTS") if self.registrar_config else "$ARGUMENTS"
created: list[Path] = []

for src_file in templates:
raw = src_file.read_text(encoding="utf-8")
processed = self.process_template(raw, self.key, script_type, arg_placeholder)

# Inject argument-hint for Claude Code commands
hint = ARGUMENT_HINTS.get(src_file.stem, "")
if hint:
processed = self.inject_argument_hint(processed, hint)

Comment thread
mnriem marked this conversation as resolved.
Comment thread
mnriem marked this conversation as resolved.
Outdated
dst_name = self.command_filename(src_file.stem)
dst_file = self.write_file_and_record(
processed, dest / dst_name, project_root, manifest
)
created.append(dst_file)

created.extend(self.install_scripts(project_root, manifest))
Comment thread
mnriem marked this conversation as resolved.
Outdated
return created
118 changes: 118 additions & 0 deletions tests/integrations/test_integration_claude.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Tests for ClaudeIntegration."""

from specify_cli.integrations import get_integration
from specify_cli.integrations.claude import ARGUMENT_HINTS
from specify_cli.integrations.manifest import IntegrationManifest

from .test_integration_base_markdown import MarkdownIntegrationTests


Expand All @@ -9,3 +13,117 @@ class TestClaudeIntegration(MarkdownIntegrationTests):
COMMANDS_SUBDIR = "commands"
REGISTRAR_DIR = ".claude/commands"
CONTEXT_FILE = "CLAUDE.md"


class TestClaudeArgumentHints:
"""Verify that argument-hint frontmatter is injected for Claude commands."""

def test_all_commands_have_hints(self, tmp_path):
"""Every generated command file must contain an argument-hint line."""
i = get_integration("claude")
m = IntegrationManifest("claude", tmp_path)
created = i.setup(tmp_path, m)
cmd_files = [f for f in created if "scripts" not in f.parts]
assert len(cmd_files) > 0
for f in cmd_files:
content = f.read_text(encoding="utf-8")
assert "argument-hint:" in content, (
f"{f.name} is missing argument-hint frontmatter"
)

def test_hints_match_expected_values(self, tmp_path):
"""Each command's argument-hint must match the expected text."""
i = get_integration("claude")
m = IntegrationManifest("claude", tmp_path)
created = i.setup(tmp_path, m)
cmd_files = [f for f in created if "scripts" not in f.parts]
for f in cmd_files:
# Extract stem: speckit.plan.md -> plan
stem = f.name.replace("speckit.", "").replace(".md", "")
expected_hint = ARGUMENT_HINTS.get(stem)
assert expected_hint is not None, (
f"No expected hint defined for command '{stem}'"
)
content = f.read_text(encoding="utf-8")
assert f"argument-hint: {expected_hint}" in content, (
f"{f.name}: expected hint '{expected_hint}' not found"
)

def test_hint_is_inside_frontmatter(self, tmp_path):
"""argument-hint must appear between the --- delimiters, not in the body."""
i = get_integration("claude")
m = IntegrationManifest("claude", tmp_path)
created = i.setup(tmp_path, m)
cmd_files = [f for f in created if "scripts" not in f.parts]
for f in cmd_files:
content = f.read_text(encoding="utf-8")
parts = content.split("---", 2)
assert len(parts) >= 3, f"No frontmatter in {f.name}"
frontmatter = parts[1]
body = parts[2]
assert "argument-hint:" in frontmatter, (
f"{f.name}: argument-hint not in frontmatter section"
)
assert "argument-hint:" not in body, (
f"{f.name}: argument-hint leaked into body"
)

def test_hint_appears_after_description(self, tmp_path):
"""argument-hint must immediately follow the description line."""
i = get_integration("claude")
m = IntegrationManifest("claude", tmp_path)
created = i.setup(tmp_path, m)
cmd_files = [f for f in created if "scripts" not in f.parts]
for f in cmd_files:
content = f.read_text(encoding="utf-8")
lines = content.splitlines()
found_description = False
for idx, line in enumerate(lines):
if line.startswith("description:"):
found_description = True
assert idx + 1 < len(lines), (
f"{f.name}: description is last line"
)
assert lines[idx + 1].startswith("argument-hint:"), (
f"{f.name}: argument-hint does not follow description"
)
break
Comment thread
mnriem marked this conversation as resolved.
assert found_description, (
f"{f.name}: no description: line found in output"
)

def test_inject_argument_hint_only_in_frontmatter(self):
"""inject_argument_hint must not modify description: lines in the body."""
from specify_cli.integrations.claude import ClaudeIntegration

content = (
"---\n"
"description: My command\n"
"---\n"
"\n"
"description: this is body text\n"
)
result = ClaudeIntegration.inject_argument_hint(content, "Test hint")
lines = result.splitlines()
hint_count = sum(1 for ln in lines if ln.startswith("argument-hint:"))
assert hint_count == 1, (
f"Expected exactly 1 argument-hint line, found {hint_count}"
)

def test_inject_argument_hint_skips_if_already_present(self):
"""inject_argument_hint must not duplicate if argument-hint already exists."""
from specify_cli.integrations.claude import ClaudeIntegration

content = (
"---\n"
"description: My command\n"
"argument-hint: Existing hint\n"
"---\n"
"\n"
"Body text\n"
)
result = ClaudeIntegration.inject_argument_hint(content, "New hint")
assert result == content, "Content should be unchanged when hint already exists"
lines = result.splitlines()
hint_count = sum(1 for ln in lines if ln.startswith("argument-hint:"))
assert hint_count == 1
Loading