-
Notifications
You must be signed in to change notification settings - Fork 7.7k
feat: add question-render fenced markers and Claude transformer #2186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Rohan-1920
wants to merge
5
commits into
github:main
Choose a base branch
from
Rohan-1920:feat/question-render-transformer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ce253be
feat: add question-render fenced markers and Claude transformer
Rohan-1920 625ad19
Merge branch 'main' into feat/question-render-transformer
Rohan-1920 1990cf2
Merge branch 'main' into feat/question-render-transformer
Rohan-1920 b07f4fd
refactor: extension-based skill renderer (registry + Claude modules)
Rohan-1920 aa1557e
fix: restore agents.py from main; set_frontmatter_key for Claude disa…
Rohan-1920 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| # Core utilities for specify-cli. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| """Question block transformer for Claude Code integration.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import re | ||
|
|
||
| _FENCE_RE = re.compile( | ||
| r"<!-- speckit:question-render:begin -->\s*\n(.*?)\n\s*<!-- speckit:question-render:end -->", | ||
| re.DOTALL, | ||
| ) | ||
| _SEPARATOR_RE = re.compile(r"^\|[-| :]+\|$") | ||
|
|
||
| # Markers that promote an option to the top of the list. | ||
| _RECOMMENDED_RE = re.compile(r"\bRecommended\b\s*[\u2014\-]", re.IGNORECASE) | ||
|
|
||
|
|
||
| def _parse_table_rows(block: str) -> list[list[str]]: | ||
| """Return data rows from a Markdown table, skipping header and separator. | ||
|
|
||
| Handles leading indentation (as found in clarify.md / checklist.md). | ||
| Rows with pipe characters inside cell values are not supported by | ||
| standard Markdown tables, so no special handling is needed. | ||
| """ | ||
| rows: list[list[str]] = [] | ||
| header_seen = False | ||
| separator_seen = False | ||
|
|
||
| for line in block.splitlines(): | ||
| stripped = line.strip() | ||
| if not stripped.startswith("|"): | ||
| continue | ||
| if not header_seen: | ||
| header_seen = True | ||
| continue | ||
| if not separator_seen: | ||
| if _SEPARATOR_RE.match(stripped): | ||
| separator_seen = True | ||
| continue | ||
| cells = [c.strip() for c in stripped.split("|")[1:-1]] | ||
| if cells: | ||
| rows.append(cells) | ||
|
|
||
| return rows | ||
|
|
||
|
|
||
| def parse_clarify(block: str) -> list[dict]: | ||
| """Parse clarify.md schema: | Option | Description | | ||
|
|
||
| - Rows matching ``Recommended —`` / ``Recommended -`` (case-insensitive) | ||
| are placed first. | ||
| - Duplicate labels are deduplicated (first occurrence wins). | ||
| """ | ||
| options: list[dict] = [] | ||
| recommended: dict | None = None | ||
| seen_labels: set[str] = set() | ||
|
|
||
| for cells in _parse_table_rows(block): | ||
| if len(cells) < 2: | ||
| continue | ||
| label = cells[0] | ||
| description = cells[1] | ||
| if label in seen_labels: | ||
| continue | ||
| seen_labels.add(label) | ||
| entry = {"label": label, "description": description} | ||
| if _RECOMMENDED_RE.search(description): | ||
| if recommended is None: | ||
| recommended = entry | ||
| else: | ||
| options.append(entry) | ||
|
Rohan-1920 marked this conversation as resolved.
|
||
|
|
||
| if recommended: | ||
| options.insert(0, recommended) | ||
|
|
||
| return options | ||
|
|
||
|
|
||
| def parse_checklist(block: str) -> list[dict]: | ||
| """Parse checklist.md schema: | Option | Candidate | Why It Matters | | ||
|
|
||
| Candidate → label, Why It Matters → description. | ||
| Duplicate labels are deduplicated (first occurrence wins). | ||
| """ | ||
| options: list[dict] = [] | ||
| seen_labels: set[str] = set() | ||
|
|
||
| for cells in _parse_table_rows(block): | ||
| if len(cells) < 3: | ||
| continue | ||
| label = cells[1] | ||
| description = cells[2] | ||
| if label in seen_labels: | ||
| continue | ||
| seen_labels.add(label) | ||
| options.append({"label": label, "description": description}) | ||
|
|
||
| return options | ||
|
|
||
|
|
||
| def _build_payload(options: list[dict]) -> str: | ||
| """Serialise options into a validated AskUserQuestion JSON code block.""" | ||
| # Append "Other" only if not already present. | ||
| if not any(o["label"].lower() == "other" for o in options): | ||
| options = options + [ | ||
| { | ||
| "label": "Other", | ||
| "description": "Provide my own short answer (\u226410 words)", | ||
| } | ||
| ] | ||
|
|
||
| payload: dict = { | ||
| "question": "Please select an option:", | ||
| "multiSelect": False, | ||
| "options": options, | ||
| } | ||
|
|
||
| # Validate round-trip before returning — raises ValueError on bad data. | ||
| raw = json.dumps(payload, ensure_ascii=False, indent=2) | ||
| json.loads(raw) # round-trip check | ||
| return f"```json\n{raw}\n```" | ||
|
|
||
|
|
||
| def transform_question_block(content: str) -> str: | ||
| """Replace fenced question blocks with AskUserQuestion JSON payloads. | ||
|
|
||
| Content without markers is returned byte-identical — safe for all | ||
| non-Claude integrations. | ||
| """ | ||
|
|
||
| def _replace(match: re.Match) -> str: | ||
| block = match.group(1) | ||
| is_checklist = "| Candidate |" in block or "|Candidate|" in block | ||
| options = parse_checklist(block) if is_checklist else parse_clarify(block) | ||
| return _build_payload(options) | ||
|
|
||
| return _FENCE_RE.sub(_replace, content) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| """Extension registry for skill markdown post-processing. | ||
|
|
||
| The core applies registered :class:`RendererExtension` instances in order. | ||
| Concrete transforms (e.g. Claude-specific) live in separate modules outside | ||
| this package's knowledge. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import Protocol, runtime_checkable | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SkillRenderContext: | ||
| """Per-file context passed to each extension.""" | ||
|
|
||
| skill_path: Path | ||
|
|
||
|
|
||
| @runtime_checkable | ||
| class RendererExtension(Protocol): | ||
| """Post-process installed skill markdown.""" | ||
|
|
||
| def transform(self, content: str, ctx: SkillRenderContext) -> str: | ||
| """Return *content* with this extension's transformation applied.""" | ||
| ... | ||
|
|
||
|
|
||
| class ExtensionRegistry: | ||
| """Ordered list of extensions applied sequentially.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self._extensions: list[RendererExtension] = [] | ||
|
|
||
| def register(self, extension: RendererExtension) -> None: | ||
| self._extensions.append(extension) | ||
|
|
||
| def apply(self, content: str, ctx: SkillRenderContext) -> str: | ||
| out = content | ||
| for ext in self._extensions: | ||
| out = ext.transform(out, ctx) | ||
| return out | ||
|
|
||
|
|
||
| def apply_extensions( | ||
| content: str, ctx: SkillRenderContext, registry: ExtensionRegistry | ||
| ) -> str: | ||
| """Apply *registry* to *content* (single entry point for callers).""" | ||
| return registry.apply(content, ctx) |
181 changes: 181 additions & 0 deletions
181
src/specify_cli/core/renderer_extensions/claude_skill.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| """Claude Code skill post-processing (frontmatter flags and argument hints).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
|
|
||
| from . import RendererExtension, SkillRenderContext | ||
|
|
||
| # Note injected into hook sections so Claude maps dot-notation command | ||
| # names (from extensions.yml) to the hyphenated skill names it uses. | ||
| _HOOK_COMMAND_NOTE = ( | ||
| "- When constructing slash commands from hook command names, " | ||
| "replace dots (`.`) with hyphens (`-`). " | ||
| "For example, `speckit.git.commit` → `/speckit-git-commit`.\n" | ||
| ) | ||
|
|
||
| # 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", | ||
| } | ||
|
|
||
|
|
||
| def inject_hook_command_note(content: str) -> str: | ||
| """Insert a dot-to-hyphen note before each hook output instruction. | ||
|
|
||
| Targets the line ``- For each executable hook, output the following`` | ||
| and inserts the note on the line before it, matching its indentation. | ||
| Skips if the note is already present. | ||
| """ | ||
| if "replace dots" in content: | ||
| return content | ||
|
|
||
| def repl(m: re.Match[str]) -> str: | ||
| indent = m.group(1) | ||
| instruction = m.group(2) | ||
| eol = m.group(3) | ||
| return ( | ||
| indent | ||
| + _HOOK_COMMAND_NOTE.rstrip("\n") | ||
| + eol | ||
| + indent | ||
| + instruction | ||
| + eol | ||
| ) | ||
|
|
||
| return re.sub( | ||
| r"(?m)^(\s*)(- For each executable hook, output the following[^\r\n]*)(\r\n|\n|$)", | ||
| repl, | ||
| content, | ||
| ) | ||
|
|
||
|
|
||
| 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) | ||
|
|
||
| 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 | ||
|
|
||
| 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) | ||
| if line.endswith("\r\n"): | ||
| eol = "\r\n" | ||
| elif line.endswith("\n"): | ||
| eol = "\n" | ||
| else: | ||
| eol = "" | ||
| escaped = hint.replace("\\", "\\\\").replace('"', '\\"') | ||
| out.append(f'argument-hint: "{escaped}"{eol}') | ||
| injected = True | ||
| continue | ||
| out.append(line) | ||
| return "".join(out) | ||
|
|
||
|
|
||
| def inject_frontmatter_flag(content: str, key: str, value: str = "true") -> str: | ||
| """Insert ``key: value`` before the closing ``---`` if not already present.""" | ||
| lines = content.splitlines(keepends=True) | ||
|
|
||
| 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(f"{key}:"): | ||
| return content | ||
|
|
||
| out: list[str] = [] | ||
| dash_count = 0 | ||
| injected = False | ||
| for line in lines: | ||
| stripped = line.rstrip("\n\r") | ||
| if stripped == "---": | ||
| dash_count += 1 | ||
| if dash_count == 2 and not injected: | ||
| if line.endswith("\r\n"): | ||
| eol = "\r\n" | ||
| elif line.endswith("\n"): | ||
| eol = "\n" | ||
| else: | ||
| eol = "" | ||
| out.append(f"{key}: {value}{eol}") | ||
| injected = True | ||
| out.append(line) | ||
| return "".join(out) | ||
|
|
||
|
|
||
| def set_frontmatter_key(content: str, key: str, value: str) -> str: | ||
| """Ensure ``key: value`` in the first frontmatter block; replace if *key* exists.""" | ||
| lines = content.splitlines(keepends=True) | ||
| dash_count = 0 | ||
| for i, line in enumerate(lines): | ||
| stripped = line.rstrip("\n\r") | ||
| if stripped == "---": | ||
| dash_count += 1 | ||
| if dash_count == 2: | ||
| break | ||
| continue | ||
| if dash_count == 1 and stripped.startswith(f"{key}:"): | ||
| if line.endswith("\r\n"): | ||
| eol = "\r\n" | ||
| elif line.endswith("\n"): | ||
| eol = "\n" | ||
| else: | ||
| eol = "" | ||
| lines[i] = f"{key}: {value}{eol}" | ||
| return "".join(lines) | ||
| return inject_frontmatter_flag(content, key, value) | ||
|
|
||
|
|
||
| class ClaudeSkillTransformExtension: | ||
| """Inject Claude skill frontmatter flags, hook note, and optional argument-hint.""" | ||
|
|
||
| def transform(self, content: str, ctx: SkillRenderContext) -> str: | ||
| updated = inject_frontmatter_flag(content, "user-invocable") | ||
| updated = set_frontmatter_key(updated, "disable-model-invocation", "false") | ||
| updated = inject_hook_command_note(updated) | ||
|
|
||
| skill_dir_name = ctx.skill_path.parent.name | ||
| stem = skill_dir_name | ||
| if stem.startswith("speckit-"): | ||
| stem = stem[len("speckit-") :] | ||
| hint = ARGUMENT_HINTS.get(stem, "") | ||
| if hint: | ||
| updated = inject_argument_hint(updated, hint) | ||
| return updated |
14 changes: 14 additions & 0 deletions
14
src/specify_cli/core/renderer_extensions/question_render.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| """Fenced ``speckit:question-render`` → AskUserQuestion JSON block.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from ..question_transformer import transform_question_block | ||
| from . import RendererExtension, SkillRenderContext | ||
|
|
||
|
|
||
| class FencedQuestionRenderExtension: | ||
| """Replace question-render marker blocks with JSON payloads.""" | ||
|
|
||
| def transform(self, content: str, ctx: SkillRenderContext) -> str: | ||
| del ctx # path-independent | ||
| return transform_question_block(content) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.