From efa9151c962806a7bab499430ef5d32e6e0e0e9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 01:11:16 +0800 Subject: [PATCH 01/11] fix(junie): hyphenate dotted command references in registered extension and preset commands docs/integrations/junie.md documents that extension and preset command content is normalized to hyphenated command names, matching Cline, because Junie registers hyphenated .junie/commands/speckit-.md files and does not recognize dotted /speckit.* invocations. However, JunieIntegration did not override process_registered_command(), leaving dotted references such as /speckit.git.status and non-gent: frontmatter references un-hyphenated when CommandRegistrar registers extension or preset commands. Implement JunieIntegration.process_registered_command() for non-core sources while preserving speckit.*.md file paths, and document the file-path preservation rules in docs/integrations/junie.md. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- docs/integrations/junie.md | 11 +- .../integrations/junie/__init__.py | 121 ++++++++++++++++++ tests/integrations/test_integration_junie.py | 108 +++++++++++++++- 3 files changed, 237 insertions(+), 3 deletions(-) diff --git a/docs/integrations/junie.md b/docs/integrations/junie.md index 470e300193..60f932db82 100644 --- a/docs/integrations/junie.md +++ b/docs/integrations/junie.md @@ -24,8 +24,15 @@ filenames such as `speckit-specify.md`. Invoke them in Junie's chat as `/speckit-specify` or `/speckit-bug-assess` for the installed bug extension, not dotted commands. -Handoff references and extension/preset command content are also normalized to -hyphenated names. +Handoff references and extension/preset command content are also normalized +to hyphenated command names, so `/speckit.git.commit` in an extension command +becomes `/speckit-git-commit`. A `speckit.*.md` file name inside a path, such +as `.specify/extensions/git/commands/speckit.git.commit.md`, +`C:\speckit.foo.md`, `C:\Program Files (x86)\speckit.foo.md`, +`%TEMP%\speckit.foo.md`, or `./commands[old]/speckit.foo.md`, keeps its dots +and `.md` extension. A bare or slash-prefixed token such as `/speckit.foo.md` +is treated as a command reference and hyphenated. Core command content is not +rewritten this way. ## Workflow Dispatch diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 8aa589d8ea..75cf31bad7 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -49,6 +49,110 @@ def format_junie_command_name(cmd_name: str) -> str: return cmd_name +# Dotted ``speckit.*`` references in extension and preset command content. +_SPECKIT_DOTTED_REF = re.compile(r"\bspeckit\.[A-Za-z0-9-_]+(?:\.[A-Za-z0-9-_]+)*\b") + + +def _is_path_char(ch: str) -> bool: + """Whether *ch* can end the directory part of a path before a separator.""" + return ch.isalnum() or ch in "._-~/\\}$" + + +# A ``%VAR%`` environment variable reference ending a directory name +# (``%TEMP%``, ``%ProgramFiles(x86)%``). +_ENV_VAR_DIR = re.compile(r"%[A-Za-z_][A-Za-z0-9_()]*%\Z") + +_BRACKET_OPENERS = {")": "(", "]": "["} + + +def _ends_directory(text: str, sep: int) -> bool: + """Whether the text before the separator at *sep* ends a directory name. + + Besides plain path-name characters this accepts a closing bracket that + closes a whitespace-free group (``Program Files (x86)``, + ``commands[old]``) and a ``%VAR%`` environment variable reference + (``%TEMP%``). An opening bracket, or a closing one around prose such as + ``(see docs)``, does not end a directory, so ``[/speckit.foo.md]`` and + ``(/speckit.foo.md)`` stay command references. + """ + ch = text[sep - 1] + if _is_path_char(ch): + return True + if ch in _BRACKET_OPENERS: + opener = text.rfind(_BRACKET_OPENERS[ch], 0, sep - 1) + group = text[opener + 1 : sep - 1] + return ( + opener >= 0 + and bool(group) + and ch not in group + and not any(c.isspace() for c in group) + ) + if ch == "%": + return _ENV_VAR_DIR.search(text, 0, sep) is not None + return False + + +def _is_drive_prefix(text: str, sep: int) -> bool: + """Whether a Windows drive (``C:``) ends right before the separator at *sep*. + + The drive letter must stand alone, so ``C:\\speckit.foo.md`` and + ``C:/speckit.foo.md`` count as root-level paths while ``ab:/speckit.foo.md`` + does not. + """ + return ( + sep >= 2 + and text[sep - 1] == ":" + and text[sep - 2].isascii() + and text[sep - 2].isalpha() + and (sep == 2 or not _is_path_char(text[sep - 3])) + ) + + +def _hyphenate_ref_match(match: re.Match[str]) -> str: + """Hyphenate one dotted speckit reference, leaving ``.md`` file names alone. + + Command names may themselves end in an ``md`` segment: extension + commands are ``speckit..`` and preset command names + may contain further dots, so ``/speckit.foo.md`` and + ``speckit.foo.bar.md`` can both be valid command references. The + ``.md`` suffix and the segment count therefore cannot tell a file name + apart from a command. A ``.md`` token is kept as a file name only when + it sits inside a path (``commands/speckit.git.commit.md``), that is, + when the separator before it ends a directory name (see + ``_ends_directory``: ``commands/``, ``C:\\Program Files (x86)\\``, + ``%TEMP%\\``, ``commands[old]/``) or follows a Windows drive + (``C:\\speckit.foo.md``, ``C:/speckit.foo.md``). A bare or + slash-prefixed token is treated as a command reference, including after + an opening bracket or other punctuation (``[/speckit.foo.md]``, + ``(/speckit.foo.md)``). + """ + ref = match.group(0) + if ref.endswith(".md"): + start = match.start() + text = match.string + if start >= 2 and text[start - 1] in "/\\" and ( + _ends_directory(text, start - 1) or _is_drive_prefix(text, start - 1) + ): + return ref + return ref.replace(".", "-") + + +def hyphenate_command_refs(text: str) -> str: + """Hyphenate dotted ``speckit.*`` command references in *text*.""" + return _SPECKIT_DOTTED_REF.sub(_hyphenate_ref_match, text) + + +def _hyphenate_frontmatter_refs(val: Any) -> Any: + """Recursively hyphenate dotted ``speckit.*`` references in frontmatter values.""" + if isinstance(val, dict): + return {k: _hyphenate_frontmatter_refs(v) for k, v in val.items()} + if isinstance(val, list): + return [_hyphenate_frontmatter_refs(x) for x in val] + if isinstance(val, str): + return hyphenate_command_refs(val) + return val + + class JunieIntegration(MarkdownIntegration): key = "junie" config = { @@ -133,6 +237,23 @@ def _rewrite_handoff_references(content: str) -> str: lambda m: f"{m.group(1)}{format_junie_command_name(m.group(2))}", content, ) + + def process_registered_command( + self, frontmatter: dict[str, Any], body: str, *, source_id: str + ) -> tuple[dict[str, Any], str]: + """Hyphenate dotted command references in extension and preset commands. + + Junie only registers hyphenated slash commands, so references such as + ``/speckit.git.commit`` in extension and preset command content are + rewritten to ``/speckit-git-commit``. ``speckit.*.md`` file names + inside a path keep their extension. Core commands (``source_id == + "core"``) are left unchanged; their references are rendered through + ``invoke_separator`` instead. + """ + if source_id == "core": + return frontmatter, body + return _hyphenate_frontmatter_refs(frontmatter), hyphenate_command_refs(body) + def post_process_command_content(self, content: str) -> str: """Apply Junie-specific transformations to command content. diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 186052db42..376420cad4 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -4,7 +4,11 @@ import pytest from specify_cli.integrations import get_integration -from specify_cli.integrations.junie import format_junie_command_name +from specify_cli.integrations.junie import ( + _hyphenate_frontmatter_refs, + format_junie_command_name, + hyphenate_command_refs, +) from .test_integration_base_markdown import MarkdownIntegrationTests class TestJunieCommandNameFormatter: @@ -85,6 +89,108 @@ def test_junie_handoff_rewrite(self): rewritten = junie._rewrite_handoff_references(content) assert rewritten == "---\nagent: speckit-plan\n---\n" + def test_junie_body_refs_keep_md_file_names(self): + """Command references are hyphenated but ``speckit.*.md`` file names keep ``.md``.""" + body = ( + "Edit `.specify/extensions/git/commands/speckit.git.commit.md`, " + "then run /speckit.git.commit." + ) + assert hyphenate_command_refs(body) == ( + "Edit `.specify/extensions/git/commands/speckit.git.commit.md`, " + "then run /speckit-git-commit." + ) + + def test_junie_refs_keep_md_file_names_at_a_windows_drive_root_and_env_paths(self): + """Drive roots, ``(x86)``, ``[old]`` and ``%VAR%`` paths stay file names; commands hyphenate.""" + body = ( + "Open C:\\speckit.foo.md, C:\\Program Files (x86)\\speckit.git.commit.md, " + "%TEMP%\\speckit.git.commit.md or ./commands[old]/speckit.git.commit.md, " + "then run /speckit.foo.md and [/speckit.bar.md]." + ) + assert hyphenate_command_refs(body) == ( + "Open C:\\speckit.foo.md, C:\\Program Files (x86)\\speckit.git.commit.md, " + "%TEMP%\\speckit.git.commit.md or ./commands[old]/speckit.git.commit.md, " + "then run /speckit-foo-md and [/speckit-bar-md]." + ) + refs = _hyphenate_frontmatter_refs( + {"file": "C:\\speckit.foo.md", "agent": "speckit.foo.md"} + ) + assert refs == {"file": "C:\\speckit.foo.md", "agent": "speckit-foo-md"} + + def _register_junie_command(self, tmp_path, source_id, body, frontmatter=""): + from specify_cli.agents import CommandRegistrar + + source = tmp_path / "src" + (source / "commands").mkdir(parents=True) + (source / "commands" / "commit.md").write_text( + f"---\ndescription: Commit\n{frontmatter}---\n\n{body}", + encoding="utf-8", + ) + project = tmp_path / "project" + project.mkdir() + CommandRegistrar().register_commands( + "junie", + [{"name": "speckit.git.commit", "file": "commands/commit.md"}], + source_id, + source, + project, + ) + out = project / ".junie" / "commands" / "speckit-git-commit.md" + return out.read_text(encoding="utf-8") + + def test_registered_extension_command_keeps_md_file_names(self, tmp_path): + """Registering an extension command for Junie hyphenates command + references in the body and frontmatter but keeps ``.md`` file names.""" + text = self._register_junie_command( + tmp_path, + "git", + "Edit `.specify/extensions/git/commands/speckit.git.commit.md`, " + "then run /speckit.git.status.\n", + frontmatter="handoff: speckit.git.status\nsource_file: commands/speckit.git.commit.md\n", + ) + assert "`.specify/extensions/git/commands/speckit.git.commit.md`" in text + assert "then run /speckit-git-status." in text + assert "handoff: speckit-git-status" in text + assert "source_file: commands/speckit.git.commit.md" in text + assert "speckit-git-commit-md" not in text + + def test_registered_extension_command_keeps_bracketed_and_env_paths(self, tmp_path): + """Registration keeps ``.md`` file names under ``(x86)``, ``[old]`` and + ``%TEMP%`` directories in the body and frontmatter.""" + text = self._register_junie_command( + tmp_path, + "git", + "Copy C:\\Program Files (x86)\\speckit.git.commit.md and " + "./commands[old]/speckit.git.commit.md, then run /speckit.git.status.\n", + frontmatter="source_file: '%TEMP%\\speckit.git.commit.md'\n", + ) + assert "C:\\Program Files (x86)\\speckit.git.commit.md" in text + assert "./commands[old]/speckit.git.commit.md" in text + assert "%TEMP%\\speckit.git.commit.md" in text + assert "then run /speckit-git-status." in text + assert "speckit-git-commit-md" not in text + + def test_registered_core_command_is_not_rewritten(self, tmp_path): + """The rewrite stays limited to extension and preset commands.""" + text = self._register_junie_command( + tmp_path, "core", "Then run /speckit.git.status.\n" + ) + assert "Then run /speckit.git.status." in text + + def test_process_registered_command_hook(self): + junie = get_integration("junie") + frontmatter = {"handoff": "speckit.plan", "file": "commands/speckit.plan.md"} + body = "Run /speckit.plan; see commands/speckit.plan.md." + assert junie.process_registered_command( + frontmatter, body, source_id="core" + ) == (frontmatter, body) + assert junie.process_registered_command( + frontmatter, body, source_id="my-preset" + ) == ( + {"handoff": "speckit-plan", "file": "commands/speckit.plan.md"}, + "Run /speckit-plan; see commands/speckit.plan.md.", + ) + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From 6e1341af9f251900cb75ab6e29ca2fe31dda4444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 01:44:55 +0800 Subject: [PATCH 02/11] fix(junie): preserve non-md paths and memoize YAML aliases in registration Apply directory and Windows-drive guards in _hyphenate_ref_match regardless of file suffix and preserve dotted ancestor directory segments followed by a path separator. Memoize dict and list containers by identity in _hyphenate_frontmatter_refs to support shared and cyclic YAML aliases, and update docs/integrations/junie.md and regression tests accordingly. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- docs/integrations/junie.md | 13 +-- .../integrations/junie/__init__.py | 75 +++++++++------ tests/integrations/test_integration_junie.py | 93 ++++++++++++++++++- 3 files changed, 146 insertions(+), 35 deletions(-) diff --git a/docs/integrations/junie.md b/docs/integrations/junie.md index 60f932db82..df4afbdba5 100644 --- a/docs/integrations/junie.md +++ b/docs/integrations/junie.md @@ -26,13 +26,14 @@ Invoke them in Junie's chat as `/speckit-specify` or Handoff references and extension/preset command content are also normalized to hyphenated command names, so `/speckit.git.commit` in an extension command -becomes `/speckit-git-commit`. A `speckit.*.md` file name inside a path, such -as `.specify/extensions/git/commands/speckit.git.commit.md`, +becomes `/speckit-git-commit`. Path-qualified names and dotted directory +segments—such as `.specify/extensions/git/commands/speckit.git.commit.md`, +`scripts/speckit.git.commit.sh`, `/tmp/speckit.demo/commands/speckit.git.commit.md`, `C:\speckit.foo.md`, `C:\Program Files (x86)\speckit.foo.md`, -`%TEMP%\speckit.foo.md`, or `./commands[old]/speckit.foo.md`, keeps its dots -and `.md` extension. A bare or slash-prefixed token such as `/speckit.foo.md` -is treated as a command reference and hyphenated. Core command content is not -rewritten this way. +`%TEMP%\speckit.foo.md`, and `./commands[old]/speckit.foo.md`—keep their dots. +A bare or slash-prefixed token such as `/speckit.foo.md` is treated as a +command reference and hyphenated. Core command content is not rewritten this +way. ## Workflow Dispatch diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 75cf31bad7..9055901e2b 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -109,31 +109,29 @@ def _is_drive_prefix(text: str, sep: int) -> bool: def _hyphenate_ref_match(match: re.Match[str]) -> str: - """Hyphenate one dotted speckit reference, leaving ``.md`` file names alone. - - Command names may themselves end in an ``md`` segment: extension - commands are ``speckit..`` and preset command names - may contain further dots, so ``/speckit.foo.md`` and - ``speckit.foo.bar.md`` can both be valid command references. The - ``.md`` suffix and the segment count therefore cannot tell a file name - apart from a command. A ``.md`` token is kept as a file name only when - it sits inside a path (``commands/speckit.git.commit.md``), that is, - when the separator before it ends a directory name (see - ``_ends_directory``: ``commands/``, ``C:\\Program Files (x86)\\``, - ``%TEMP%\\``, ``commands[old]/``) or follows a Windows drive - (``C:\\speckit.foo.md``, ``C:/speckit.foo.md``). A bare or - slash-prefixed token is treated as a command reference, including after - an opening bracket or other punctuation (``[/speckit.foo.md]``, - ``(/speckit.foo.md)``). + """Hyphenate one dotted speckit reference, leaving path components alone. + + Command names may themselves end in a file-like segment (for example + ``/speckit.foo.md`` or ``speckit.foo.bar.md``), so suffix alone cannot tell + a path apart from a command. A token is preserved verbatim when it sits + inside a path regardless of suffix: either preceded by a directory name or + Windows drive (``commands/speckit.git.commit.md``, + ``scripts/speckit.git.commit.sh``, ``C:\\speckit.foo.md``), or directly + followed by a path separator as an ancestor directory segment + (``/tmp/speckit.demo/commands/...``, ``speckit.demo/commands/...``). A bare + or slash-prefixed command reference stays hyphenated, including after + punctuation such as ``[/speckit.foo.md]`` or ``(/speckit.foo.md)``. """ ref = match.group(0) - if ref.endswith(".md"): - start = match.start() - text = match.string - if start >= 2 and text[start - 1] in "/\\" and ( - _ends_directory(text, start - 1) or _is_drive_prefix(text, start - 1) - ): - return ref + start = match.start() + end = match.end() + text = match.string + if start >= 2 and text[start - 1] in "/\\" and ( + _ends_directory(text, start - 1) or _is_drive_prefix(text, start - 1) + ): + return ref + if end < len(text) and text[end] in "/\\": + return ref return ref.replace(".", "-") @@ -142,12 +140,32 @@ def hyphenate_command_refs(text: str) -> str: return _SPECKIT_DOTTED_REF.sub(_hyphenate_ref_match, text) -def _hyphenate_frontmatter_refs(val: Any) -> Any: +def _hyphenate_frontmatter_refs( + val: Any, _memo: dict[int, Any] | None = None +) -> Any: """Recursively hyphenate dotted ``speckit.*`` references in frontmatter values.""" if isinstance(val, dict): - return {k: _hyphenate_frontmatter_refs(v) for k, v in val.items()} + if _memo is None: + _memo = {} + obj_id = id(val) + if obj_id in _memo: + return _memo[obj_id] + out_dict: dict[Any, Any] = {} + _memo[obj_id] = out_dict + for k, v in val.items(): + out_dict[k] = _hyphenate_frontmatter_refs(v, _memo) + return out_dict if isinstance(val, list): - return [_hyphenate_frontmatter_refs(x) for x in val] + if _memo is None: + _memo = {} + obj_id = id(val) + if obj_id in _memo: + return _memo[obj_id] + out_list: list[Any] = [] + _memo[obj_id] = out_list + for item in val: + out_list.append(_hyphenate_frontmatter_refs(item, _memo)) + return out_list if isinstance(val, str): return hyphenate_command_refs(val) return val @@ -245,8 +263,9 @@ def process_registered_command( Junie only registers hyphenated slash commands, so references such as ``/speckit.git.commit`` in extension and preset command content are - rewritten to ``/speckit-git-commit``. ``speckit.*.md`` file names - inside a path keep their extension. Core commands (``source_id == + rewritten to ``/speckit-git-commit``. Path components (``speckit.*.md`` + file names, script paths, and dotted ancestor directories) keep their + dots. Core commands (``source_id == "core"``) are left unchanged; their references are rendered through ``invoke_separator`` instead. """ diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 376420cad4..2d0b14e1c9 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -117,7 +117,9 @@ def test_junie_refs_keep_md_file_names_at_a_windows_drive_root_and_env_paths(sel ) assert refs == {"file": "C:\\speckit.foo.md", "agent": "speckit-foo-md"} - def _register_junie_command(self, tmp_path, source_id, body, frontmatter=""): + def _register_junie_command( + self, tmp_path, source_id, body, frontmatter="", *, extension_id=None + ): from specify_cli.agents import CommandRegistrar source = tmp_path / "src" @@ -134,6 +136,7 @@ def _register_junie_command(self, tmp_path, source_id, body, frontmatter=""): source_id, source, project, + extension_id=extension_id, ) out = project / ".junie" / "commands" / "speckit-git-commit.md" return out.read_text(encoding="utf-8") @@ -191,6 +194,94 @@ def test_process_registered_command_hook(self): "Run /speckit-plan; see commands/speckit.plan.md.", ) + def test_registered_extension_command_keeps_script_paths_and_dotted_directories( + self, tmp_path + ): + """Non-.md path-qualified names, `{SCRIPT}`, and dotted directories keep dots.""" + text = self._register_junie_command( + tmp_path, + "git", + "Invoke {SCRIPT}, read scripts/speckit.git.commit.sh, " + "open /tmp/speckit.demo/commands/speckit.git.commit.md and " + "speckit.demo/commands/speckit.git.commit.md, " + "then run /speckit.git.status and /speckit.foo.sh.\n", + frontmatter=( + "scripts:\n" + ' sh: \'scripts/speckit.git.commit.sh "{ARGS}"\'\n' + "notes: /tmp/speckit.demo/commands/speckit.git.commit.md\n" + ), + extension_id="git", + ) + assert '.specify/extensions/git/scripts/speckit.git.commit.sh "$ARGUMENTS"' in text + assert "scripts/speckit.git.commit.sh" in text + assert "/tmp/speckit.demo/commands/speckit.git.commit.md" in text + assert "speckit.demo/commands/speckit.git.commit.md" in text + assert "notes: /tmp/speckit.demo/commands/speckit.git.commit.md" in text + assert "then run /speckit-git-status and /speckit-foo-sh." in text + assert "speckit-demo" not in text + assert "speckit-git-commit-sh" not in text + + def test_frontmatter_refs_memoize_shared_and_cyclic_yaml_aliases(self, tmp_path): + """Shared YAML aliases keep identity and cyclic containers do not overflow.""" + import yaml + from specify_cli.agents import CommandRegistrar + + shared_yaml = ( + "shared: &shared\n" + " next: /speckit.git.status\n" + " script: scripts/speckit.git.commit.sh\n" + "first: *shared\n" + "second: *shared\n" + ) + loaded = yaml.safe_load(shared_yaml) + out = _hyphenate_frontmatter_refs(loaded) + assert out["first"] is out["second"] + assert out["shared"] is out["first"] + assert out["first"] == { + "next": "/speckit-git-status", + "script": "scripts/speckit.git.commit.sh", + } + assert loaded["shared"]["next"] == "/speckit.git.status" + + # End-to-end registration with YAML aliases in frontmatter. + source = tmp_path / "src" + (source / "commands").mkdir(parents=True) + (source / "commands" / "commit.md").write_text( + f"---\ndescription: Commit\n{shared_yaml}---\n\nRun /speckit.git.status.\n", + encoding="utf-8", + ) + project = tmp_path / "project" + project.mkdir() + CommandRegistrar().register_commands( + "junie", + [{"name": "speckit.git.commit", "file": "commands/commit.md"}], + "git", + source, + project, + ) + rendered = ( + project / ".junie" / "commands" / "speckit-git-commit.md" + ).read_text(encoding="utf-8") + assert "/speckit-git-status" in rendered + assert "scripts/speckit.git.commit.sh" in rendered + + # Cyclic dict and cyclic list must not recurse infinitely or mutate inputs. + cyclic_dict: dict[str, object] = {"cmd": "speckit.plan"} + cyclic_dict["self"] = cyclic_dict + transformed_dict = _hyphenate_frontmatter_refs(cyclic_dict) + assert transformed_dict is not cyclic_dict + assert transformed_dict["cmd"] == "speckit-plan" + assert transformed_dict["self"] is transformed_dict + assert cyclic_dict["cmd"] == "speckit.plan" + + cyclic_list: list[object] = ["speckit.plan"] + cyclic_list.append(cyclic_list) + transformed_list = _hyphenate_frontmatter_refs(cyclic_list) + assert transformed_list is not cyclic_list + assert transformed_list[0] == "speckit-plan" + assert transformed_list[1] is transformed_list + assert cyclic_list[0] == "speckit.plan" + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From b5739d5ad2fe2811c480dbb2fe25dda8b7a77094 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 02:32:23 +0800 Subject: [PATCH 03/11] fix(junie): preserve prefixed filenames and spaced bracket directories in paths Expand each dotted speckit match to its containing filename or directory segment before checking surrounding path separators so embedded matches like scripts/run-speckit.git.commit.sh and commands/archived.speckit.git.commit.md stay intact. Allow spaced bracketed directory segments in _ends_directory when preceded by an explicit path prefix, and update docs/integrations/junie.md and regression tests. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- docs/integrations/junie.md | 9 +- .../integrations/junie/__init__.py | 88 ++++++++++++++----- tests/integrations/test_integration_junie.py | 39 ++++++++ 3 files changed, 111 insertions(+), 25 deletions(-) diff --git a/docs/integrations/junie.md b/docs/integrations/junie.md index df4afbdba5..d5c79db478 100644 --- a/docs/integrations/junie.md +++ b/docs/integrations/junie.md @@ -28,9 +28,12 @@ Handoff references and extension/preset command content are also normalized to hyphenated command names, so `/speckit.git.commit` in an extension command becomes `/speckit-git-commit`. Path-qualified names and dotted directory segments—such as `.specify/extensions/git/commands/speckit.git.commit.md`, -`scripts/speckit.git.commit.sh`, `/tmp/speckit.demo/commands/speckit.git.commit.md`, -`C:\speckit.foo.md`, `C:\Program Files (x86)\speckit.foo.md`, -`%TEMP%\speckit.foo.md`, and `./commands[old]/speckit.foo.md`—keep their dots. +`scripts/speckit.git.commit.sh`, `scripts/run-speckit.git.commit.sh`, +`/tmp/speckit.demo/commands/speckit.git.commit.md`, `C:\speckit.foo.md`, +`C:\Program Files (x86)\speckit.foo.md`, +`C:\Program Files (old versions)\speckit.foo.md`, `%TEMP%\speckit.foo.md`, +`./commands[old]/speckit.foo.md`, and +`./commands[old files]/speckit.foo.md`—keep their dots. A bare or slash-prefixed token such as `/speckit.foo.md` is treated as a command reference and hyphenated. Core command content is not rewritten this way. diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 9055901e2b..e55f7dae71 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -65,15 +65,49 @@ def _is_path_char(ch: str) -> bool: _BRACKET_OPENERS = {")": "(", "]": "["} +_SEGMENT_CHARS = frozenset("._-~+@$%") + + +def _is_segment_char(ch: str) -> bool: + """Whether *ch* can appear inside an unquoted filename or directory segment.""" + return ch.isalnum() or ch in _SEGMENT_CHARS + + +def _has_explicit_path_prefix(text: str, opener: int) -> bool: + """Whether *opener* (``(`` or ``[``) sits inside an explicit directory path.""" + if opener > 0 and _is_segment_char(text[opener - 1]): + return True + prev_sep = max(text.rfind("/", 0, opener), text.rfind("\\", 0, opener)) + if prev_sep < 0: + return False + between = text[prev_sep + 1 : opener] + if not all(_is_segment_char(c) or c == " " for c in between): + return False + if prev_sep >= 1 and ( + _ends_directory(text, prev_sep) or _is_drive_prefix(text, prev_sep) + ): + return True + return ( + text[prev_sep] == "/" + and (prev_sep == 0 or text[prev_sep - 1] in ' \t\r\n"\'`([<{') + and bool(between) + and _is_segment_char(between[0]) + and not between.startswith("speckit.") + ) + + def _ends_directory(text: str, sep: int) -> bool: """Whether the text before the separator at *sep* ends a directory name. Besides plain path-name characters this accepts a closing bracket that closes a whitespace-free group (``Program Files (x86)``, - ``commands[old]``) and a ``%VAR%`` environment variable reference - (``%TEMP%``). An opening bracket, or a closing one around prose such as - ``(see docs)``, does not end a directory, so ``[/speckit.foo.md]`` and - ``(/speckit.foo.md)`` stay command references. + ``commands[old]``), a whitespace-containing group attached to an explicit + path prefix (``C:\\Program Files (old versions)\\``, + ``./commands[old files]/``), and a ``%VAR%`` environment variable + reference (``%TEMP%``). An opening bracket, or a closing one around + unprefixed prose such as ``(see docs)`` or ``[Run command]``, does not + end a directory, so ``[/speckit.foo.md]`` and ``(see docs)/speckit.foo.md`` + stay command references. """ ch = text[sep - 1] if _is_path_char(ch): @@ -81,12 +115,17 @@ def _ends_directory(text: str, sep: int) -> bool: if ch in _BRACKET_OPENERS: opener = text.rfind(_BRACKET_OPENERS[ch], 0, sep - 1) group = text[opener + 1 : sep - 1] - return ( - opener >= 0 - and bool(group) - and ch not in group - and not any(c.isspace() for c in group) - ) + if ( + opener < 0 + or not group + or ch in group + or "\n" in group + or "\r" in group + ): + return False + if not any(c.isspace() for c in group): + return True + return _has_explicit_path_prefix(text, opener) if ch == "%": return _ENV_VAR_DIR.search(text, 0, sep) is not None return False @@ -113,24 +152,29 @@ def _hyphenate_ref_match(match: re.Match[str]) -> str: Command names may themselves end in a file-like segment (for example ``/speckit.foo.md`` or ``speckit.foo.bar.md``), so suffix alone cannot tell - a path apart from a command. A token is preserved verbatim when it sits - inside a path regardless of suffix: either preceded by a directory name or - Windows drive (``commands/speckit.git.commit.md``, - ``scripts/speckit.git.commit.sh``, ``C:\\speckit.foo.md``), or directly - followed by a path separator as an ancestor directory segment - (``/tmp/speckit.demo/commands/...``, ``speckit.demo/commands/...``). A bare - or slash-prefixed command reference stays hyphenated, including after + a path apart from a command. A token is preserved verbatim whenever its + containing path segment sits inside a path regardless of suffix or + filename prefix: either preceded by a directory name or Windows drive + (``commands/speckit.git.commit.md``, ``scripts/run-speckit.git.commit.sh``, + ``commands/archived.speckit.git.commit.md``, ``C:\\speckit.foo.md``), or + directly followed by a path separator as an ancestor directory segment + (``/tmp/speckit.demo/commands/...``, ``/tmp/my-speckit.demo/commands/...``). + A bare or slash-prefixed command reference stays hyphenated, including after punctuation such as ``[/speckit.foo.md]`` or ``(/speckit.foo.md)``. """ ref = match.group(0) - start = match.start() - end = match.end() text = match.string - if start >= 2 and text[start - 1] in "/\\" and ( - _ends_directory(text, start - 1) or _is_drive_prefix(text, start - 1) + seg_start = match.start() + while seg_start > 0 and _is_segment_char(text[seg_start - 1]): + seg_start -= 1 + seg_end = match.end() + while seg_end < len(text) and _is_segment_char(text[seg_end]): + seg_end += 1 + if seg_start >= 2 and text[seg_start - 1] in "/\\" and ( + _ends_directory(text, seg_start - 1) or _is_drive_prefix(text, seg_start - 1) ): return ref - if end < len(text) and text[end] in "/\\": + if seg_end < len(text) and text[seg_end] in "/\\": return ref return ref.replace(".", "-") diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 2d0b14e1c9..78c10f931a 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -282,6 +282,45 @@ def test_frontmatter_refs_memoize_shared_and_cyclic_yaml_aliases(self, tmp_path) assert transformed_list[1] is transformed_list assert cyclic_list[0] == "speckit.plan" + def test_registered_extension_command_keeps_prefixed_filenames_and_spaced_bracket_dirs( + self, tmp_path + ): + """Prefixed filenames inside paths and spaced bracketed directories stay intact.""" + text = self._register_junie_command( + tmp_path, + "git", + "Invoke {SCRIPT}, read commands/archived.speckit.git.commit.md, " + "open C:\\Program Files (old versions)\\speckit.git.commit.md, " + "C:/Program Files (old versions)/speckit.git.commit.md, " + "./commands[old files]/speckit.git.commit.md, " + "commands[old files]/speckit.git.commit.md, and " + "/tmp/my-speckit.demo (old versions)/commands/archived.speckit.git.commit.md. " + "Also check (see docs)/speckit.foo.md, [Run command]/speckit.foo.md, " + "Edit C:\\foo\\bar.txt, then run (see docs)/speckit.foo.md, " + "and /speckit.git.status.\n", + frontmatter=( + "scripts:\n" + ' sh: \'scripts/run-speckit.git.commit.sh "{ARGS}"\'\n' + "spaced_dir: 'C:\\Program Files (old versions)\\speckit.git.commit.md'\n" + "archived: commands/archived.speckit.git.commit.md\n" + ), + extension_id="git", + ) + assert '.specify/extensions/git/scripts/run-speckit.git.commit.sh "$ARGUMENTS"' in text + assert "commands/archived.speckit.git.commit.md" in text + assert "C:\\Program Files (old versions)\\speckit.git.commit.md" in text + assert "C:/Program Files (old versions)/speckit.git.commit.md" in text + assert "./commands[old files]/speckit.git.commit.md" in text + assert "commands[old files]/speckit.git.commit.md" in text + assert "/tmp/my-speckit.demo (old versions)/commands/archived.speckit.git.commit.md" in text + assert "(see docs)/speckit-foo-md" in text + assert "[Run command]/speckit-foo-md" in text + assert "Edit C:\\foo\\bar.txt, then run (see docs)/speckit-foo-md" in text + assert "and /speckit-git-status." in text + assert "run-speckit-git-commit-sh" not in text + assert "archived-speckit-git-commit-md" not in text + assert "my-speckit-demo" not in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From 601ef5a41331b0a713b3b9da10f211dbb9497f8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 02:50:08 +0800 Subject: [PATCH 04/11] fix(junie): linearize command-ref path scanning and preserve quoted/C++ paths Replace per-match segment rescanning in hyphenate_command_refs with linear-time scans over directory separators, inline bracket groups, containing path segments, and same-line quoted paths. Add '+' to _is_path_char for C++ directory names, preserve standalone path strings in frontmatter values, and add linear-scaling and path regression tests. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- docs/integrations/junie.md | 8 +- .../integrations/junie/__init__.py | 390 +++++++++++++----- tests/integrations/test_integration_junie.py | 64 +++ 3 files changed, 363 insertions(+), 99 deletions(-) diff --git a/docs/integrations/junie.md b/docs/integrations/junie.md index d5c79db478..2f429f2f0b 100644 --- a/docs/integrations/junie.md +++ b/docs/integrations/junie.md @@ -26,9 +26,13 @@ Invoke them in Junie's chat as `/speckit-specify` or Handoff references and extension/preset command content are also normalized to hyphenated command names, so `/speckit.git.commit` in an extension command -becomes `/speckit-git-commit`. Path-qualified names and dotted directory -segments—such as `.specify/extensions/git/commands/speckit.git.commit.md`, +becomes `/speckit-git-commit`. Path-qualified names, quoted paths, and +bracketed or dotted directory segments—such as +`.specify/extensions/git/commands/speckit.git.commit.md`, `scripts/speckit.git.commit.sh`, `scripts/run-speckit.git.commit.sh`, +`scripts/C++/speckit.git.commit.sh`, `"scripts/my speckit.git.commit.sh"`, +`commands/[old]speckit.git.commit.md`, +`speckit.demo[old]/commands/speckit.git.commit.md`, `/tmp/speckit.demo/commands/speckit.git.commit.md`, `C:\speckit.foo.md`, `C:\Program Files (x86)\speckit.foo.md`, `C:\Program Files (old versions)\speckit.foo.md`, `%TEMP%\speckit.foo.md`, diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index e55f7dae71..d47ee3d479 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -55,17 +55,12 @@ def format_junie_command_name(cmd_name: str) -> str: def _is_path_char(ch: str) -> bool: """Whether *ch* can end the directory part of a path before a separator.""" - return ch.isalnum() or ch in "._-~/\\}$" - - -# A ``%VAR%`` environment variable reference ending a directory name -# (``%TEMP%``, ``%ProgramFiles(x86)%``). -_ENV_VAR_DIR = re.compile(r"%[A-Za-z_][A-Za-z0-9_()]*%\Z") - -_BRACKET_OPENERS = {")": "(", "]": "["} + return ch.isalnum() or ch in "._-~/\\}$+" _SEGMENT_CHARS = frozenset("._-~+@$%") +_QUOTE_OPEN_BOUNDARY = frozenset(' \t\r\n"\'`([<{:=-') +_SEP_LEADING_BOUNDARY = frozenset(' \t\r\n"\'`([<{') def _is_segment_char(ch: str) -> bool: @@ -73,64 +68,6 @@ def _is_segment_char(ch: str) -> bool: return ch.isalnum() or ch in _SEGMENT_CHARS -def _has_explicit_path_prefix(text: str, opener: int) -> bool: - """Whether *opener* (``(`` or ``[``) sits inside an explicit directory path.""" - if opener > 0 and _is_segment_char(text[opener - 1]): - return True - prev_sep = max(text.rfind("/", 0, opener), text.rfind("\\", 0, opener)) - if prev_sep < 0: - return False - between = text[prev_sep + 1 : opener] - if not all(_is_segment_char(c) or c == " " for c in between): - return False - if prev_sep >= 1 and ( - _ends_directory(text, prev_sep) or _is_drive_prefix(text, prev_sep) - ): - return True - return ( - text[prev_sep] == "/" - and (prev_sep == 0 or text[prev_sep - 1] in ' \t\r\n"\'`([<{') - and bool(between) - and _is_segment_char(between[0]) - and not between.startswith("speckit.") - ) - - -def _ends_directory(text: str, sep: int) -> bool: - """Whether the text before the separator at *sep* ends a directory name. - - Besides plain path-name characters this accepts a closing bracket that - closes a whitespace-free group (``Program Files (x86)``, - ``commands[old]``), a whitespace-containing group attached to an explicit - path prefix (``C:\\Program Files (old versions)\\``, - ``./commands[old files]/``), and a ``%VAR%`` environment variable - reference (``%TEMP%``). An opening bracket, or a closing one around - unprefixed prose such as ``(see docs)`` or ``[Run command]``, does not - end a directory, so ``[/speckit.foo.md]`` and ``(see docs)/speckit.foo.md`` - stay command references. - """ - ch = text[sep - 1] - if _is_path_char(ch): - return True - if ch in _BRACKET_OPENERS: - opener = text.rfind(_BRACKET_OPENERS[ch], 0, sep - 1) - group = text[opener + 1 : sep - 1] - if ( - opener < 0 - or not group - or ch in group - or "\n" in group - or "\r" in group - ): - return False - if not any(c.isspace() for c in group): - return True - return _has_explicit_path_prefix(text, opener) - if ch == "%": - return _ENV_VAR_DIR.search(text, 0, sep) is not None - return False - - def _is_drive_prefix(text: str, sep: int) -> bool: """Whether a Windows drive (``C:``) ends right before the separator at *sep*. @@ -147,41 +84,295 @@ def _is_drive_prefix(text: str, sep: int) -> bool: ) -def _hyphenate_ref_match(match: re.Match[str]) -> str: - """Hyphenate one dotted speckit reference, leaving path components alone. - - Command names may themselves end in a file-like segment (for example - ``/speckit.foo.md`` or ``speckit.foo.bar.md``), so suffix alone cannot tell - a path apart from a command. A token is preserved verbatim whenever its - containing path segment sits inside a path regardless of suffix or - filename prefix: either preceded by a directory name or Windows drive - (``commands/speckit.git.commit.md``, ``scripts/run-speckit.git.commit.sh``, - ``commands/archived.speckit.git.commit.md``, ``C:\\speckit.foo.md``), or - directly followed by a path separator as an ancestor directory segment - (``/tmp/speckit.demo/commands/...``, ``/tmp/my-speckit.demo/commands/...``). - A bare or slash-prefixed command reference stays hyphenated, including after - punctuation such as ``[/speckit.foo.md]`` or ``(/speckit.foo.md)``. - """ - ref = match.group(0) - text = match.string - seg_start = match.start() - while seg_start > 0 and _is_segment_char(text[seg_start - 1]): - seg_start -= 1 - seg_end = match.end() - while seg_end < len(text) and _is_segment_char(text[seg_end]): - seg_end += 1 - if seg_start >= 2 and text[seg_start - 1] in "/\\" and ( - _ends_directory(text, seg_start - 1) or _is_drive_prefix(text, seg_start - 1) +def _scan_path_structure(text: str) -> tuple[set[int], dict[int, int]]: + """Precompute directory separators and inline bracket pairs in one linear pass.""" + dir_seps: set[int] = set() + bracket_end: dict[int, int] = {} + + # Tracks open bracket candidates on the current line: + # (open_idx, closer_char, has_prefix, space_count_at_open, slash_count_at_open). + open_stack: list[tuple[int, str, bool, int, int]] = [] + # Latest same-line closing bracket immediately preceding index idx: + # (close_idx, has_space, has_prefix). + last_closed_bracket: tuple[int, bool, bool] | None = None + + # Linear %VAR% state machine. + pct_start = -1 + pct_valid_body = False + pct_valid_end = -1 + + # Linear tracking of the latest separator on the current line. + last_sep = -1 + last_sep_explicit = False + since_sep_valid = True + between_starts_speckit = False + since_sep_len = 0 + + space_count = 0 + slash_count = 0 + + for idx, ch in enumerate(text): + if ch in "\r\n": + open_stack.clear() + last_closed_bracket = None + pct_start = -1 + pct_valid_body = False + last_sep = -1 + last_sep_explicit = False + since_sep_valid = True + between_starts_speckit = False + since_sep_len = 0 + slash_count += 1 + continue + + if ch in "/\\": + is_dir = False + if idx >= 1: + prev = text[idx - 1] + if _is_path_char(prev) or _is_drive_prefix(text, idx): + is_dir = True + elif ( + last_closed_bracket is not None + and last_closed_bracket[0] == idx - 1 + and (not last_closed_bracket[1] or last_closed_bracket[2]) + ): + is_dir = True + elif pct_valid_end == idx - 1: + is_dir = True + + if is_dir: + dir_seps.add(idx) + + last_sep = idx + last_sep_explicit = is_dir or ( + ch == "/" and (idx == 0 or text[idx - 1] in _SEP_LEADING_BOUNDARY) + ) + since_sep_valid = True + between_starts_speckit = False + since_sep_len = 0 + slash_count += 1 + pct_start = -1 + pct_valid_body = False + continue + + if ch in ("(", "["): + closer = ")" if ch == "(" else "]" + has_prefix = False + if idx > 0 and _is_segment_char(text[idx - 1]): + has_prefix = True + elif ( + last_sep >= 0 + and since_sep_valid + and since_sep_len > 0 + and last_sep_explicit + and not (last_sep not in dir_seps and between_starts_speckit) + ): + has_prefix = True + open_stack.append((idx, closer, has_prefix, space_count, slash_count)) + elif ch in (")", "]"): + if open_stack and open_stack[-1][1] == ch: + open_idx, _, has_prefix, open_spaces, open_slashes = open_stack.pop() + if slash_count == open_slashes and idx > open_idx + 1: + bracket_end[open_idx] = idx + last_closed_bracket = ( + idx, + space_count > open_spaces, + has_prefix, + ) + else: + open_stack.clear() + + if ch == " ": + space_count += 1 + elif ch.isspace(): + space_count += 1 + since_sep_valid = False + elif not _is_segment_char(ch): + since_sep_valid = False + + if last_sep >= 0: + if since_sep_len == 0: + between_starts_speckit = text.startswith("speckit.", last_sep + 1) + since_sep_len += 1 + + if ch == "%": + if pct_start >= 0 and pct_valid_body and idx > pct_start + 1: + pct_valid_end = idx + pct_start = -1 + pct_valid_body = False + else: + pct_start = idx + pct_valid_body = True + elif pct_start >= 0: + rel = idx - pct_start + if rel == 1: + if not (ch.isascii() and (ch.isalpha() or ch == "_")): + pct_start = -1 + pct_valid_body = False + elif not (ch.isascii() and (ch.isalnum() or ch in "_()")): + pct_start = -1 + pct_valid_body = False + + return dir_seps, bracket_end + + +def _is_path_content( + text: str, inner_start: int, inner_end: int, dir_seps: set[int] +) -> bool: + """Whether ``text[inner_start:inner_end]`` is an explicit directory-qualified path.""" + inner = text[inner_start:inner_end] + if ( + not inner + or inner[0].isspace() + or inner[-1].isspace() + or "," in inner + or ";" in inner + or " /" in inner + or " \\" in inner ): - return ref - if seg_end < len(text) and text[seg_end] in "/\\": - return ref - return ref.replace(".", "-") + return False + + slash = inner.find("/") + backslash = inner.find("\\") + if slash < 0: + rel_sep = backslash + elif backslash < 0: + rel_sep = slash + else: + rel_sep = min(slash, backslash) + if rel_sep < 0: + return False + + if rel_sep > 0: + head = inner[:rel_sep] + return not any(c.isspace() for c in head) and ( + (inner_start + rel_sep) in dir_seps + ) + + next_slash = inner.find("/", 1) + next_backslash = inner.find("\\", 1) + if next_slash < 0: + rel_sep2 = next_backslash + elif next_backslash < 0: + rel_sep2 = next_slash + else: + rel_sep2 = min(next_slash, next_backslash) + if rel_sep2 < 2: + return False + first_seg = inner[1:rel_sep2] + return not any(c.isspace() for c in first_seg) and ( + (inner_start + rel_sep2) in dir_seps + ) + + +def _find_quoted_path_spans( + text: str, dir_seps: set[int] +) -> list[tuple[int, int]]: + """Find content spans of explicit same-line quoted paths in linear time.""" + spans: list[tuple[int, int]] = [] + n = len(text) + for quote in ('"', "'", "`"): + if quote not in text: + continue + open_idx = -1 + idx = text.find(quote) + while idx >= 0: + if open_idx >= 0 and ("\n" in text[open_idx:idx] or "\r" in text[open_idx:idx]): + open_idx = -1 + if quote == "'" and 0 < idx < n - 1 and text[idx - 1].isalnum() and text[idx + 1].isalpha(): + idx = text.find(quote, idx + 1) + continue + if open_idx < 0: + if idx == 0 or text[idx - 1] in _QUOTE_OPEN_BOUNDARY: + open_idx = idx + else: + if _is_path_content(text, open_idx + 1, idx, dir_seps): + spans.append((open_idx + 1, idx)) + open_idx = -1 + idx = text.find(quote, idx + 1) + return spans + + +def _find_protected_segments( + text: str, dir_seps: set[int], bracket_end: dict[int, int] +) -> list[tuple[int, int]]: + """Compute unquoted path-qualified segments in a single linear pass.""" + spans: list[tuple[int, int]] = [] + n = len(text) + i = 0 + while i < n: + if _is_segment_char(text[i]) or i in bracket_end: + seg_start = i + while i < n: + if _is_segment_char(text[i]): + i += 1 + elif i in bracket_end: + i = bracket_end[i] + 1 + else: + break + seg_end = i + if (seg_start >= 2 and (seg_start - 1) in dir_seps) or ( + seg_end < n and seg_end in dir_seps + ): + spans.append((seg_start, seg_end)) + else: + i += 1 + return spans def hyphenate_command_refs(text: str) -> str: - """Hyphenate dotted ``speckit.*`` command references in *text*.""" - return _SPECKIT_DOTTED_REF.sub(_hyphenate_ref_match, text) + """Hyphenate dotted ``speckit.*`` command references in *text*. + + Uses linear-time passes to preserve directory-qualified file names, + script paths, dotted ancestor directories, bracketed path components, and + quoted paths containing spaces, while hyphenating bare, slash-prefixed, + and punctuation-wrapped command references. + """ + if "speckit." not in text: + return text + + dir_seps, bracket_end = _scan_path_structure(text) + raw_spans = _find_protected_segments(text, dir_seps, bracket_end) + raw_spans.extend(_find_quoted_path_spans(text, dir_seps)) + + merged: list[tuple[int, int]] = [] + if raw_spans: + raw_spans.sort() + cur_start, cur_end = raw_spans[0] + for start, end in raw_spans[1:]: + if start <= cur_end: + if end > cur_end: + cur_end = end + else: + merged.append((cur_start, cur_end)) + cur_start, cur_end = start, end + merged.append((cur_start, cur_end)) + + parts: list[str] = [] + last = 0 + span_idx = 0 + span_count = len(merged) + + for match in _SPECKIT_DOTTED_REF.finditer(text): + m_start = match.start() + m_end = match.end() + while span_idx < span_count and merged[span_idx][1] < m_end: + span_idx += 1 + parts.append(text[last:m_start]) + if ( + span_idx < span_count + and merged[span_idx][0] <= m_start + and m_end <= merged[span_idx][1] + ): + parts.append(match.group(0)) + else: + parts.append(match.group(0).replace(".", "-")) + last = m_end + + if last == 0: + return text + parts.append(text[last:]) + return "".join(parts) def _hyphenate_frontmatter_refs( @@ -211,6 +402,11 @@ def _hyphenate_frontmatter_refs( out_list.append(_hyphenate_frontmatter_refs(item, _memo)) return out_list if isinstance(val, str): + if "speckit." not in val: + return val + dir_seps, _ = _scan_path_structure(val) + if _is_path_content(val, 0, len(val), dir_seps): + return val return hyphenate_command_refs(val) return val diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 78c10f931a..3c4e189fd8 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -321,6 +321,70 @@ def test_registered_extension_command_keeps_prefixed_filenames_and_spaced_bracke assert "archived-speckit-git-commit-md" not in text assert "my-speckit-demo" not in text + def test_registered_extension_command_keeps_plus_quoted_and_bracketed_paths( + self, tmp_path + ): + """Plus-named dirs, quoted spaced paths, and bracketed segments stay intact.""" + text = self._register_junie_command( + tmp_path, + "git", + "Invoke {SCRIPT}, read C:\\C++\\speckit.git.commit.md, " + '"scripts/my speckit.git.commit.sh", ' + "'scripts/my speckit.git.commit.sh', " + "`scripts/my speckit.git.commit.sh`, " + '"C:\\Program Files\\my speckit.git.commit.sh", ' + '"/tmp/my dir/my speckit.git.commit.md", ' + "commands/[old]speckit.git.commit.md, " + "speckit.demo[old]/commands/speckit.git.commit.md, and " + "speckit.demo[old files]/commands/speckit.git.commit.md. " + 'Compare "Run /speckit.git.commit", "/speckit.foo.md", ' + '"ab:/speckit.foo.md", "Run speckit.plan and edit scripts/foo.sh", ' + '"don\'t run /speckit.git.status", [/speckit.foo.md], ' + "([/speckit.foo.md]), and [Run](/speckit.foo.md).\n", + frontmatter=( + "scripts:\n" + ' sh: \'scripts/C++/speckit.git.commit.sh "{ARGS}"\'\n' + 'quoted: "scripts/my speckit.git.commit.sh"\n' + "bracketed: commands/[old]speckit.git.commit.md\n" + ), + extension_id="git", + ) + assert '.specify/extensions/git/scripts/C++/speckit.git.commit.sh "$ARGUMENTS"' in text + assert "C:\\C++\\speckit.git.commit.md" in text + assert '".specify/extensions/git/scripts/my speckit.git.commit.sh"' in text + assert "'.specify/extensions/git/scripts/my speckit.git.commit.sh'" in text + assert "`.specify/extensions/git/scripts/my speckit.git.commit.sh`" in text + assert '"C:\\Program Files\\my speckit.git.commit.sh"' in text + assert '"/tmp/my dir/my speckit.git.commit.md"' in text + assert "commands/[old]speckit.git.commit.md" in text + assert "speckit.demo[old]/commands/speckit.git.commit.md" in text + assert "speckit.demo[old files]/commands/speckit.git.commit.md" in text + assert "quoted: scripts/my speckit.git.commit.sh" in text + assert "bracketed: commands/[old]speckit.git.commit.md" in text + assert '"Run /speckit-git-commit"' in text + assert '"/speckit-foo-md"' in text + assert '"ab:/speckit-foo-md"' in text + assert '"Run speckit-plan and edit .specify/extensions/git/scripts/foo.sh"' in text + assert '"don\'t run /speckit-git-status"' in text + assert "[/speckit-foo-md], ([/speckit-foo-md]), and [Run](/speckit-foo-md)." in text + assert "my speckit-git-commit" not in text + + def test_hyphenate_command_refs_linear_scaling_in_long_segment(self): + """Scanning many matches in one segment or unmatched brackets scales linearly.""" + import time + + t0 = time.monotonic() + non_path = "a" + "-speckit.x" * 10_000 + assert hyphenate_command_refs(non_path) == "a" + "-speckit-x" * 10_000 + + path_seg = "scripts/a" + "-speckit.x" * 10_000 + assert hyphenate_command_refs(path_seg) == path_seg + + unmatched = "]" * 20_000 + "/speckit.foo" + assert hyphenate_command_refs(unmatched) == "]" * 20_000 + "/speckit-foo" + elapsed = time.monotonic() - t0 + assert elapsed < 5.0, f"linear normalization took too long: {elapsed:.2f}s" + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From fa115d2965c3979587159fef72c03f49c002be4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 03:04:23 +0800 Subject: [PATCH 05/11] fix(junie): stream command-ref normalization with bounded memory and stricter path matching Replace full-document separator and span tables in hyphenate_command_refs with line-by-line O(1)-state streaming so large files do not amplify memory. Skip contraction apostrophes cleanly without prefix slicing, preserve quoted/frontmatter paths whose first directory contains spaces, and reject multiline values and path-leading prose when matching whole path values. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- docs/integrations/junie.md | 2 +- .../integrations/junie/__init__.py | 571 ++++++++++-------- tests/integrations/test_integration_junie.py | 64 ++ 3 files changed, 387 insertions(+), 250 deletions(-) diff --git a/docs/integrations/junie.md b/docs/integrations/junie.md index 2f429f2f0b..44ca3857ac 100644 --- a/docs/integrations/junie.md +++ b/docs/integrations/junie.md @@ -31,7 +31,7 @@ bracketed or dotted directory segments—such as `.specify/extensions/git/commands/speckit.git.commit.md`, `scripts/speckit.git.commit.sh`, `scripts/run-speckit.git.commit.sh`, `scripts/C++/speckit.git.commit.sh`, `"scripts/my speckit.git.commit.sh"`, -`commands/[old]speckit.git.commit.md`, +`"my scripts/my speckit.git.commit.sh"`, `commands/[old]speckit.git.commit.md`, `speckit.demo[old]/commands/speckit.git.commit.md`, `/tmp/speckit.demo/commands/speckit.git.commit.md`, `C:\speckit.foo.md`, `C:\Program Files (x86)\speckit.foo.md`, diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index d47ee3d479..652f68096d 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -61,6 +61,34 @@ def _is_path_char(ch: str) -> bool: _SEGMENT_CHARS = frozenset("._-~+@$%") _QUOTE_OPEN_BOUNDARY = frozenset(' \t\r\n"\'`([<{:=-') _SEP_LEADING_BOUNDARY = frozenset(' \t\r\n"\'`([<{') +_PATH_FILE_EXTENSIONS = frozenset( + { + "md", + "sh", + "ps1", + "py", + "js", + "ts", + "mjs", + "cjs", + "json", + "yml", + "yaml", + "toml", + "txt", + "bat", + "cmd", + "exe", + "rb", + "pl", + "cfg", + "ini", + "conf", + "xml", + "csv", + "log", + } +) def _is_segment_char(ch: str) -> bool: @@ -84,147 +112,75 @@ def _is_drive_prefix(text: str, sep: int) -> bool: ) -def _scan_path_structure(text: str) -> tuple[set[int], dict[int, int]]: - """Precompute directory separators and inline bracket pairs in one linear pass.""" - dir_seps: set[int] = set() - bracket_end: dict[int, int] = {} +def _is_valid_env_var_end(text: str, seg_start: int, seg_end: int) -> bool: + """Whether ``text[seg_start:seg_end]`` ends with a ``%VAR%`` directory token.""" + if seg_end - seg_start < 3 or text[seg_end - 1] != "%": + return False + pct_open = text.rfind("%", seg_start, seg_end - 1) + if pct_open < 0 or seg_end - pct_open < 3: + return False + first = text[pct_open + 1] + if not (first.isascii() and (first.isalpha() or first == "_")): + return False + return all( + c.isascii() and (c.isalnum() or c in "_()") + for c in text[pct_open + 2 : seg_end - 1] + ) - # Tracks open bracket candidates on the current line: - # (open_idx, closer_char, has_prefix, space_count_at_open, slash_count_at_open). - open_stack: list[tuple[int, str, bool, int, int]] = [] - # Latest same-line closing bracket immediately preceding index idx: - # (close_idx, has_space, has_prefix). - last_closed_bracket: tuple[int, bool, bool] | None = None - # Linear %VAR% state machine. - pct_start = -1 - pct_valid_body = False - pct_valid_end = -1 +def _find_inline_bracket_end(line: str, open_idx: int) -> int: + """Return the closing bracket index for a single-line non-path bracket group.""" + open_ch = line[open_idx] + closer = ")" if open_ch == "(" else "]" + n = len(line) + idx = open_idx + 1 + while idx < n: + ch = line[idx] + if ch == closer: + return idx if idx > open_idx + 1 else -1 + if ch in "/\\" or ch == open_ch: + return -1 + idx += 1 + return -1 - # Linear tracking of the latest separator on the current line. - last_sep = -1 - last_sep_explicit = False - since_sep_valid = True - between_starts_speckit = False - since_sep_len = 0 - space_count = 0 - slash_count = 0 - - for idx, ch in enumerate(text): - if ch in "\r\n": - open_stack.clear() - last_closed_bracket = None - pct_start = -1 - pct_valid_body = False - last_sep = -1 - last_sep_explicit = False - since_sep_valid = True - between_starts_speckit = False - since_sep_len = 0 - slash_count += 1 - continue +def _is_contraction_apostrophe(line: str, idx: int) -> bool: + """Whether ``line[idx]`` is an in-word apostrophe (e.g. ``don't``).""" + return 0 < idx < len(line) - 1 and line[idx - 1].isalnum() and line[idx + 1].isalpha() - if ch in "/\\": - is_dir = False - if idx >= 1: - prev = text[idx - 1] - if _is_path_char(prev) or _is_drive_prefix(text, idx): - is_dir = True - elif ( - last_closed_bracket is not None - and last_closed_bracket[0] == idx - 1 - and (not last_closed_bracket[1] or last_closed_bracket[2]) - ): - is_dir = True - elif pct_valid_end == idx - 1: - is_dir = True - - if is_dir: - dir_seps.add(idx) - last_sep = idx - last_sep_explicit = is_dir or ( - ch == "/" and (idx == 0 or text[idx - 1] in _SEP_LEADING_BOUNDARY) - ) - since_sep_valid = True - between_starts_speckit = False - since_sep_len = 0 - slash_count += 1 - pct_start = -1 - pct_valid_body = False - continue - - if ch in ("(", "["): - closer = ")" if ch == "(" else "]" - has_prefix = False - if idx > 0 and _is_segment_char(text[idx - 1]): - has_prefix = True - elif ( - last_sep >= 0 - and since_sep_valid - and since_sep_len > 0 - and last_sep_explicit - and not (last_sep not in dir_seps and between_starts_speckit) - ): - has_prefix = True - open_stack.append((idx, closer, has_prefix, space_count, slash_count)) - elif ch in (")", "]"): - if open_stack and open_stack[-1][1] == ch: - open_idx, _, has_prefix, open_spaces, open_slashes = open_stack.pop() - if slash_count == open_slashes and idx > open_idx + 1: - bracket_end[open_idx] = idx - last_closed_bracket = ( - idx, - space_count > open_spaces, - has_prefix, - ) - else: - open_stack.clear() - - if ch == " ": - space_count += 1 - elif ch.isspace(): - space_count += 1 - since_sep_valid = False - elif not _is_segment_char(ch): - since_sep_valid = False - - if last_sep >= 0: - if since_sep_len == 0: - between_starts_speckit = text.startswith("speckit.", last_sep + 1) - since_sep_len += 1 - - if ch == "%": - if pct_start >= 0 and pct_valid_body and idx > pct_start + 1: - pct_valid_end = idx - pct_start = -1 - pct_valid_body = False - else: - pct_start = idx - pct_valid_body = True - elif pct_start >= 0: - rel = idx - pct_start - if rel == 1: - if not (ch.isascii() and (ch.isalpha() or ch == "_")): - pct_start = -1 - pct_valid_body = False - elif not (ch.isascii() and (ch.isalnum() or ch in "_()")): - pct_start = -1 - pct_valid_body = False - - return dir_seps, bracket_end - - -def _is_path_content( - text: str, inner_start: int, inner_end: int, dir_seps: set[int] -) -> bool: - """Whether ``text[inner_start:inner_end]`` is an explicit directory-qualified path.""" - inner = text[inner_start:inner_end] +def _is_valid_dir_component(comp: str, is_first: bool) -> bool: + """Validate one directory component inside a standalone path string.""" + if not comp: + return False + if is_first and len(comp) == 2 and comp[0].isascii() and comp[0].isalpha() and comp[1] == ":": + return True + if comp.endswith(":"): + return False + if comp.endswith("%"): + return _is_valid_env_var_end(comp, 0, len(comp)) + if is_first and comp[0] in "([": + closer = ")" if comp[0] == "(" else "]" + if comp.endswith(closer) and any(c.isspace() for c in comp[1:-1]): + return False + if " " in comp: + for word in comp.split(): + stripped = word.lstrip("/") + if _SPECKIT_DOTTED_REF.fullmatch(stripped) is not None: + return False + return _is_path_char(comp[-1]) or comp[-1] in ")]" + + +def _is_standalone_path(text: str, start: int, end: int) -> bool: + """Whether ``text[start:end]`` is a standalone single-line directory path.""" + inner = text[start:end] if ( not inner or inner[0].isspace() or inner[-1].isspace() + or "\n" in inner + or "\r" in inner + or "\t" in inner or "," in inner or ";" in inner or " /" in inner @@ -232,147 +188,265 @@ def _is_path_content( ): return False - slash = inner.find("/") - backslash = inner.find("\\") - if slash < 0: - rel_sep = backslash - elif backslash < 0: - rel_sep = slash - else: - rel_sep = min(slash, backslash) - if rel_sep < 0: + last_sep = max(inner.rfind("/"), inner.rfind("\\")) + if last_sep <= 0: return False - if rel_sep > 0: - head = inner[:rel_sep] - return not any(c.isspace() for c in head) and ( - (inner_start + rel_sep) in dir_seps - ) + dir_part = inner[:last_sep].replace("\\", "/") + if dir_part.startswith("/"): + dir_part = dir_part[1:] + if not dir_part: + return False + dir_comps = dir_part.split("/") + for idx, comp in enumerate(dir_comps): + if not _is_valid_dir_component(comp, idx == 0): + return False - next_slash = inner.find("/", 1) - next_backslash = inner.find("\\", 1) - if next_slash < 0: - rel_sep2 = next_backslash - elif next_backslash < 0: - rel_sep2 = next_slash - else: - rel_sep2 = min(next_slash, next_backslash) - if rel_sep2 < 2: + base = inner[last_sep + 1 :] + if not base: return False - first_seg = inner[1:rel_sep2] - return not any(c.isspace() for c in first_seg) and ( - (inner_start + rel_sep2) in dir_seps - ) + if " " not in base: + return True + words = base.split() + if any("." in w for w in words[:-1]): + return False + last_word = words[-1] + if "." not in last_word: + return False + return last_word.rsplit(".", 1)[-1].lower() in _PATH_FILE_EXTENSIONS -def _find_quoted_path_spans( - text: str, dir_seps: set[int] -) -> list[tuple[int, int]]: - """Find content spans of explicit same-line quoted paths in linear time.""" - spans: list[tuple[int, int]] = [] - n = len(text) - for quote in ('"', "'", "`"): - if quote not in text: - continue - open_idx = -1 - idx = text.find(quote) - while idx >= 0: - if open_idx >= 0 and ("\n" in text[open_idx:idx] or "\r" in text[open_idx:idx]): - open_idx = -1 - if quote == "'" and 0 < idx < n - 1 and text[idx - 1].isalnum() and text[idx + 1].isalpha(): - idx = text.find(quote, idx + 1) - continue - if open_idx < 0: - if idx == 0 or text[idx - 1] in _QUOTE_OPEN_BOUNDARY: - open_idx = idx - else: - if _is_path_content(text, open_idx + 1, idx, dir_seps): - spans.append((open_idx + 1, idx)) - open_idx = -1 - idx = text.find(quote, idx + 1) - return spans - - -def _find_protected_segments( - text: str, dir_seps: set[int], bracket_end: dict[int, int] -) -> list[tuple[int, int]]: - """Compute unquoted path-qualified segments in a single linear pass.""" - spans: list[tuple[int, int]] = [] - n = len(text) + +def _rewrite_segment(segment: str) -> str: + """Hyphenate ``speckit.*`` matches inside one unprotected segment.""" + if "speckit." not in segment: + return segment + return _SPECKIT_DOTTED_REF.sub(lambda m: m.group(0).replace(".", "-"), segment) + + +def _hyphenate_line(line: str) -> str: + """Stream-normalize dotted ``speckit.*`` refs on one line with O(1) extra memory.""" + if "speckit." not in line: + return line + + n = len(line) i = 0 + out: list[str] | None = None + last_emitted = 0 + + last_sep = -1 + last_sep_is_dir = False + last_sep_explicit = False + since_sep_valid = True + since_sep_len = 0 + between_starts_speckit = False + last_closed_bracket_end = -1 + last_closed_bracket_has_space = False + last_closed_bracket_has_prefix = False + last_env_var_end = -1 + no_more_quote = {"'": False, '"': False, "`": False} + + def emit_replacement(start: int, end: int, replacement: str) -> None: + nonlocal out, last_emitted + if out is None: + out = [] + if start > last_emitted: + out.append(line[last_emitted:start]) + out.append(replacement) + last_emitted = end + while i < n: - if _is_segment_char(text[i]) or i in bracket_end: + ch = line[i] + + if ch in ('"', "'", "`"): + if ( + not no_more_quote[ch] + and not (ch == "'" and _is_contraction_apostrophe(line, i)) + and (i == 0 or line[i - 1] in _QUOTE_OPEN_BOUNDARY) + ): + close_idx = line.find(ch, i + 1) + while ( + close_idx >= 0 + and ch == "'" + and _is_contraction_apostrophe(line, close_idx) + ): + close_idx = line.find(ch, close_idx + 1) + if close_idx < 0: + no_more_quote[ch] = True + elif _is_standalone_path(line, i + 1, close_idx): + since_sep_valid = False + last_closed_bracket_end = -1 + last_env_var_end = -1 + i = close_idx + 1 + continue + since_sep_valid = False + last_closed_bracket_end = -1 + last_env_var_end = -1 + if last_sep >= 0: + if since_sep_len == 0: + between_starts_speckit = line.startswith("speckit.", last_sep + 1) + since_sep_len += 1 + i += 1 + continue + + if ch in "/\\": + is_dir = False + if i >= 1: + prev = line[i - 1] + if _is_path_char(prev) or _is_drive_prefix(line, i): + is_dir = True + elif ( + last_closed_bracket_end == i - 1 + and (not last_closed_bracket_has_space or last_closed_bracket_has_prefix) + ): + is_dir = True + elif last_env_var_end == i - 1: + is_dir = True + last_sep = i + last_sep_is_dir = is_dir + last_sep_explicit = is_dir or ( + ch == "/" and (i == 0 or line[i - 1] in _SEP_LEADING_BOUNDARY) + ) + since_sep_valid = True + since_sep_len = 0 + between_starts_speckit = False + last_closed_bracket_end = -1 + last_env_var_end = -1 + i += 1 + continue + + if _is_segment_char(ch) or ( + ch in ("(", "[") and _find_inline_bracket_end(line, i) >= 0 + ): seg_start = i + seg_bracket_end = -1 + seg_bracket_has_space = False + seg_bracket_has_prefix = False while i < n: - if _is_segment_char(text[i]): + cur = line[i] + if _is_segment_char(cur): + if last_sep >= 0: + if since_sep_len == 0: + between_starts_speckit = line.startswith("speckit.", last_sep + 1) + since_sep_len += 1 i += 1 - elif i in bracket_end: - i = bracket_end[i] + 1 + elif cur in ("(", "["): + b_end = _find_inline_bracket_end(line, i) + if b_end < 0: + break + b_prefix = (i > 0 and _is_segment_char(line[i - 1])) or ( + last_sep >= 0 + and since_sep_valid + and since_sep_len > 0 + and last_sep_explicit + and not (not last_sep_is_dir and between_starts_speckit) + ) + b_space = any(c.isspace() for c in line[i + 1 : b_end]) + b_has_non_space_ws = any( + c.isspace() and c != " " for c in line[i + 1 : b_end] + ) + if b_has_non_space_ws: + since_sep_valid = False + if last_sep >= 0: + if since_sep_len == 0: + between_starts_speckit = line.startswith("speckit.", last_sep + 1) + since_sep_len += b_end - i + 1 + seg_bracket_end = b_end + seg_bracket_has_space = b_space + seg_bracket_has_prefix = b_prefix + i = b_end + 1 else: break + seg_end = i - if (seg_start >= 2 and (seg_start - 1) in dir_seps) or ( - seg_end < n and seg_end in dir_seps - ): - spans.append((seg_start, seg_end)) + if seg_bracket_end == seg_end - 1: + last_closed_bracket_end = seg_bracket_end + last_closed_bracket_has_space = seg_bracket_has_space + last_closed_bracket_has_prefix = seg_bracket_has_prefix + else: + last_closed_bracket_end = -1 + last_env_var_end = ( + seg_end - 1 + if line[seg_end - 1] == "%" + and _is_valid_env_var_end(line, seg_start, seg_end) + else -1 + ) + + preceded_by_dir = seg_start >= 2 and line[seg_start - 1] in "/\\" and last_sep_is_dir + followed_by_dir = False + if seg_end < n and line[seg_end] in "/\\": + end_ch = line[seg_end - 1] + if end_ch == "%": + followed_by_dir = last_env_var_end == seg_end - 1 + elif _is_path_char(end_ch): + followed_by_dir = True + elif seg_bracket_end == seg_end - 1 and ( + not seg_bracket_has_space or seg_bracket_has_prefix + ): + followed_by_dir = True + if not (preceded_by_dir or followed_by_dir): + seg = line[seg_start:seg_end] + if "speckit." in seg: + rewritten = _rewrite_segment(seg) + if rewritten != seg: + emit_replacement(seg_start, seg_end, rewritten) + continue + + if ch == " ": + if last_sep >= 0: + if since_sep_len == 0: + between_starts_speckit = line.startswith("speckit.", last_sep + 1) + since_sep_len += 1 else: - i += 1 - return spans + since_sep_valid = False + last_closed_bracket_end = -1 + last_env_var_end = -1 + i += 1 + + if out is None: + return line + if last_emitted < n: + out.append(line[last_emitted:]) + return "".join(out) def hyphenate_command_refs(text: str) -> str: """Hyphenate dotted ``speckit.*`` command references in *text*. - Uses linear-time passes to preserve directory-qualified file names, - script paths, dotted ancestor directories, bracketed path components, and - quoted paths containing spaces, while hyphenating bare, slash-prefixed, - and punctuation-wrapped command references. + Streams line-by-line with O(1) extra state per line to preserve + directory-qualified file names, script paths, dotted ancestor directories, + bracketed path components, and same-line quoted paths containing spaces, + while hyphenating bare, slash-prefixed, and punctuation-wrapped command + references. """ if "speckit." not in text: return text - dir_seps, bracket_end = _scan_path_structure(text) - raw_spans = _find_protected_segments(text, dir_seps, bracket_end) - raw_spans.extend(_find_quoted_path_spans(text, dir_seps)) - - merged: list[tuple[int, int]] = [] - if raw_spans: - raw_spans.sort() - cur_start, cur_end = raw_spans[0] - for start, end in raw_spans[1:]: - if start <= cur_end: - if end > cur_end: - cur_end = end - else: - merged.append((cur_start, cur_end)) - cur_start, cur_end = start, end - merged.append((cur_start, cur_end)) - - parts: list[str] = [] - last = 0 - span_idx = 0 - span_count = len(merged) - - for match in _SPECKIT_DOTTED_REF.finditer(text): - m_start = match.start() - m_end = match.end() - while span_idx < span_count and merged[span_idx][1] < m_end: - span_idx += 1 - parts.append(text[last:m_start]) - if ( - span_idx < span_count - and merged[span_idx][0] <= m_start - and m_end <= merged[span_idx][1] - ): - parts.append(match.group(0)) - else: - parts.append(match.group(0).replace(".", "-")) - last = m_end - - if last == 0: + n = len(text) + pos = 0 + out: list[str] | None = None + last_emitted = 0 + + while pos < n: + nl = text.find("\n", pos) + line_end = n if nl < 0 else nl + 1 + line = text[pos:line_end] + if "speckit." in line: + normalized = _hyphenate_line(line) + if normalized != line: + if out is None: + out = [] + if pos > last_emitted: + out.append(text[last_emitted:pos]) + out.append(normalized) + last_emitted = line_end + pos = line_end + + if out is None: return text - parts.append(text[last:]) - return "".join(parts) + if last_emitted < n: + out.append(text[last_emitted:]) + return "".join(out) def _hyphenate_frontmatter_refs( @@ -404,8 +478,7 @@ def _hyphenate_frontmatter_refs( if isinstance(val, str): if "speckit." not in val: return val - dir_seps, _ = _scan_path_structure(val) - if _is_path_content(val, 0, len(val), dir_seps): + if _is_standalone_path(val, 0, len(val)): return val return hyphenate_command_refs(val) return val diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 3c4e189fd8..813f6cd5e1 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -382,9 +382,73 @@ def test_hyphenate_command_refs_linear_scaling_in_long_segment(self): unmatched = "]" * 20_000 + "/speckit.foo" assert hyphenate_command_refs(unmatched) == "]" * 20_000 + "/speckit-foo" + + contractions = "'" + "don't " * 10_000 + "/speckit.foo'" + assert hyphenate_command_refs(contractions) == "'" + "don't " * 10_000 + "/speckit-foo'" elapsed = time.monotonic() - t0 assert elapsed < 5.0, f"linear normalization took too long: {elapsed:.2f}s" + def test_spaced_first_dir_quoted_path_leading_prose_and_bounded_memory(self, tmp_path): + """Spaced initial directory paths stay intact, path-leading/multiline prose still hyphenates, and large inputs stay memory-bounded.""" + import tracemalloc + + # Spaced first directory component in quoted body & frontmatter. + assert ( + hyphenate_command_refs('"my scripts/my speckit.git.commit.sh"') + == '"my scripts/my speckit.git.commit.sh"' + ) + assert _hyphenate_frontmatter_refs( + {"spaced_first": "my scripts/my speckit.git.commit.sh"} + ) == {"spaced_first": "my scripts/my speckit.git.commit.sh"} + + # Path-leading prose and multiline frontmatter values still hyphenate commands. + assert ( + hyphenate_command_refs('"docs/setup.md then run speckit.plan"') + == '"docs/setup.md then run speckit-plan"' + ) + fm_prose = _hyphenate_frontmatter_refs( + { + "prose_path": "docs/setup.md then run speckit.plan", + "multiline": "docs/usage.md\n/speckit.plan", + } + ) + assert fm_prose == { + "prose_path": "docs/setup.md then run speckit-plan", + "multiline": "docs/usage.md\n/speckit-plan", + } + + text = self._register_junie_command( + tmp_path, + "git", + '"my scripts/my speckit.git.commit.sh" vs "docs/setup.md then run speckit.plan".\n', + frontmatter=( + 'spaced_first: "my scripts/my speckit.git.commit.sh"\n' + 'prose_path: "docs/setup.md then run speckit.plan"\n' + 'multiline: |\n' + ' docs/usage.md\n' + ' /speckit.plan\n' + ), + ) + assert '"my .specify/scripts/my speckit.git.commit.sh"' in text + assert '"docs/setup.md then run speckit-plan"' in text + assert "spaced_first: my scripts/my speckit.git.commit.sh" in text + assert "prose_path: docs/setup.md then run speckit-plan" in text + assert "/speckit-plan" in text + + # Bounded extra memory on ~1 MiB commands (both multi-line and single-line). + big_line = "a/b[c]/d/e(f)/" * 8 + big_doc = (big_line + "\n") * 9_000 + "Run /speckit.git.status\n" + single_line = big_line * 8_000 + " Run /speckit.git.status" + for sample in (big_doc, single_line): + tracemalloc.start() + try: + normalized = hyphenate_command_refs(sample) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert normalized.rstrip("\n").endswith("Run /speckit-git-status") + assert peak < 4 * len(sample), f"excessive peak memory: {peak} bytes" + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From 547297b1649ebf27b03ec46f346d06f9d52d976d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 03:17:28 +0800 Subject: [PATCH 06/11] fix(junie): support # dirs, spaced dotted paths, arbitrary suffixes, and punctuated prose Include '#' (and '@', '&') in directory/segment path characters, allow spaced dotted directory components such as "speckit.demo files" and spaced filenames with numeric/version prefixes or arbitrary extensions such as "scripts/v1.0 speckit.git.commit.sh" and "migrations/my speckit.schema.sql", and reject punctuation-wrapped prose commands when classifying standalone or quoted path spans. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- docs/integrations/junie.md | 5 +- .../integrations/junie/__init__.py | 86 ++++++++++++------- tests/integrations/test_integration_junie.py | 76 ++++++++++++++++ 3 files changed, 132 insertions(+), 35 deletions(-) diff --git a/docs/integrations/junie.md b/docs/integrations/junie.md index 44ca3857ac..31c6da6f11 100644 --- a/docs/integrations/junie.md +++ b/docs/integrations/junie.md @@ -31,10 +31,11 @@ bracketed or dotted directory segments—such as `.specify/extensions/git/commands/speckit.git.commit.md`, `scripts/speckit.git.commit.sh`, `scripts/run-speckit.git.commit.sh`, `scripts/C++/speckit.git.commit.sh`, `"scripts/my speckit.git.commit.sh"`, -`"my scripts/my speckit.git.commit.sh"`, `commands/[old]speckit.git.commit.md`, +`"my scripts/my speckit.git.commit.sh"`, `"migrations/my speckit.schema.sql"`, +`commands/[old]speckit.git.commit.md`, `speckit.demo[old]/commands/speckit.git.commit.md`, `/tmp/speckit.demo/commands/speckit.git.commit.md`, `C:\speckit.foo.md`, -`C:\Program Files (x86)\speckit.foo.md`, +`C:\C#\speckit.git.commit.md`, `C:\Program Files (x86)\speckit.foo.md`, `C:\Program Files (old versions)\speckit.foo.md`, `%TEMP%\speckit.foo.md`, `./commands[old]/speckit.foo.md`, and `./commands[old files]/speckit.foo.md`—keep their dots. diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 652f68096d..a5c9e48c32 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -55,38 +55,30 @@ def format_junie_command_name(cmd_name: str) -> str: def _is_path_char(ch: str) -> bool: """Whether *ch* can end the directory part of a path before a separator.""" - return ch.isalnum() or ch in "._-~/\\}$+" + return ch.isalnum() or ch in "._-~/\\}$+#@&" -_SEGMENT_CHARS = frozenset("._-~+@$%") +_SEGMENT_CHARS = frozenset("._-~+@$%#&") _QUOTE_OPEN_BOUNDARY = frozenset(' \t\r\n"\'`([<{:=-') _SEP_LEADING_BOUNDARY = frozenset(' \t\r\n"\'`([<{') -_PATH_FILE_EXTENSIONS = frozenset( +_WRAP_PUNCT = "\"'`.,;:!?()[]{}\u2018\u2019\u201c\u201d" +_PROSE_CONNECTORS = frozenset( { - "md", - "sh", - "ps1", - "py", - "js", - "ts", - "mjs", - "cjs", - "json", - "yml", - "yaml", - "toml", - "txt", - "bat", - "cmd", - "exe", - "rb", - "pl", - "cfg", - "ini", - "conf", - "xml", - "csv", - "log", + "then", + "and", + "or", + "before", + "after", + "run", + "read", + "edit", + "use", + "open", + "see", + "check", + "invoke", + "execute", + "call", } ) @@ -149,6 +141,15 @@ def _is_contraction_apostrophe(line: str, idx: int) -> bool: return 0 < idx < len(line) - 1 and line[idx - 1].isalnum() and line[idx + 1].isalpha() +def _has_punct_wrapped_speckit(word: str) -> bool: + """Whether *word* is a punctuation-wrapped ``speckit.*`` prose reference.""" + return ( + bool(word) + and (word[0] in _WRAP_PUNCT or word[-1] in _WRAP_PUNCT) + and _SPECKIT_DOTTED_REF.search(word) is not None + ) + + def _is_valid_dir_component(comp: str, is_first: bool) -> bool: """Validate one directory component inside a standalone path string.""" if not comp: @@ -164,10 +165,20 @@ def _is_valid_dir_component(comp: str, is_first: bool) -> bool: if comp.endswith(closer) and any(c.isspace() for c in comp[1:-1]): return False if " " in comp: - for word in comp.split(): + words = comp.split() + for idx, word in enumerate(words): + if _has_punct_wrapped_speckit(word): + return False stripped = word.lstrip("/") if _SPECKIT_DOTTED_REF.fullmatch(stripped) is not None: - return False + if 0 < idx < len(words) - 1: + return False + if len(words) >= 3 and any( + other.lower() in _PROSE_CONNECTORS + for j, other in enumerate(words) + if j != idx + ): + return False return _is_path_char(comp[-1]) or comp[-1] in ")]" @@ -183,6 +194,14 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: or "\t" in inner or "," in inner or ";" in inner + or "`" in inner + or '"' in inner + or ". " in inner + or ": " in inner + or "?" in inner + or "!" in inner + or "<" in inner + or ">" in inner or " /" in inner or " \\" in inner ): @@ -209,12 +228,13 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: return True words = base.split() - if any("." in w for w in words[:-1]): + if any(_has_punct_wrapped_speckit(w) for w in words): + return False + if any("." in w and w.rsplit(".", 1)[-1].isalpha() for w in words[:-1]): return False - last_word = words[-1] - if "." not in last_word: + if len(words) >= 3 and any(w.lower() in _PROSE_CONNECTORS for w in words[1:-1]): return False - return last_word.rsplit(".", 1)[-1].lower() in _PATH_FILE_EXTENSIONS + return True def _rewrite_segment(segment: str) -> str: diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 813f6cd5e1..5cb44a3be1 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -449,6 +449,82 @@ def test_spaced_first_dir_quoted_path_leading_prose_and_bounded_memory(self, tmp assert normalized.rstrip("\n").endswith("Run /speckit-git-status") assert peak < 4 * len(sample), f"excessive peak memory: {peak} bytes" + def test_round5_hash_dirs_spaced_dotted_dirs_arbitrary_suffixes_and_punct_prose( + self, tmp_path + ): + """# dirs, spaced dotted dirs, arbitrary spaced suffixes, and punctuated prose.""" + assert ( + hyphenate_command_refs("Open C:\\C#\\speckit.git.commit.md") + == "Open C:\\C#\\speckit.git.commit.md" + ) + assert ( + hyphenate_command_refs('"speckit.demo files/commands/speckit.git.commit.md"') + == '"speckit.demo files/commands/speckit.git.commit.md"' + ) + assert ( + hyphenate_command_refs('"scripts/v1.0 speckit.git.commit.sh"') + == '"scripts/v1.0 speckit.git.commit.sh"' + ) + assert ( + hyphenate_command_refs('"migrations/my speckit.schema.sql"') + == '"migrations/my speckit.schema.sql"' + ) + assert ( + hyphenate_command_refs('"Run speckit.plan. Then read docs/usage.md"') + == '"Run speckit-plan. Then read docs/usage.md"' + ) + assert ( + hyphenate_command_refs('"Run `speckit.plan` then read docs/setup.md"') + == '"Run `speckit-plan` then read docs/setup.md"' + ) + + fm_in = { + "csharp": "C:\\C#\\speckit.git.commit.md", + "dotted_dir": "speckit.demo files/commands/speckit.git.commit.md", + "versioned": "scripts/v1.0 speckit.git.commit.sh", + "migration": "migrations/my speckit.schema.sql", + "sentence": "Run speckit.plan. Then read docs/usage.md", + "backticked": "Run `speckit.plan` then read docs/setup.md", + } + assert _hyphenate_frontmatter_refs(fm_in) == { + "csharp": "C:\\C#\\speckit.git.commit.md", + "dotted_dir": "speckit.demo files/commands/speckit.git.commit.md", + "versioned": "scripts/v1.0 speckit.git.commit.sh", + "migration": "migrations/my speckit.schema.sql", + "sentence": "Run speckit-plan. Then read docs/usage.md", + "backticked": "Run `speckit-plan` then read docs/setup.md", + } + + text = self._register_junie_command( + tmp_path, + "git", + 'Invoke {SCRIPT}, Open C:\\C#\\speckit.git.commit.md, ' + '"speckit.demo files/commands/speckit.git.commit.md", ' + '"migrations/my speckit.schema.sql", "Run speckit.plan. Then read docs/usage.md", ' + 'and "Run `speckit.plan` then read docs/setup.md".\n', + frontmatter=( + "scripts:\n" + ' sh: \'"scripts/v1.0 speckit.git.commit.sh" "{ARGS}"\'\n' + "csharp: C:\\C#\\speckit.git.commit.md\n" + "dotted_dir: speckit.demo files/commands/speckit.git.commit.md\n" + "migration: migrations/my speckit.schema.sql\n" + 'sentence: "Run speckit.plan. Then read docs/usage.md"\n' + 'backticked: "Run `speckit.plan` then read docs/setup.md"\n' + ), + extension_id="git", + ) + assert "Open C:\\C#\\speckit.git.commit.md" in text + assert '"speckit.demo files/commands/speckit.git.commit.md"' in text + assert '"migrations/my speckit.schema.sql"' in text + assert '"Run speckit-plan. Then read docs/usage.md"' in text + assert '"Run `speckit-plan` then read docs/setup.md"' in text + assert "csharp: C:\\C#\\speckit.git.commit.md" in text + assert "dotted_dir: speckit.demo files/commands/speckit.git.commit.md" in text + assert "migration: migrations/my speckit.schema.sql" in text + assert "sentence: Run speckit-plan. Then read docs/usage.md" in text + assert "backticked: Run `speckit-plan` then read docs/setup.md" in text + assert '".specify/extensions/git/scripts/v1.0 speckit.git.commit.sh" "$ARGUMENTS"' in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From a29d94fc82f9067dfbc21c0ffcf4228078cb7e17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Sat, 28 Nov 2026 09:20:48 +0800 Subject: [PATCH 07/11] fix(junie): do not exempt leading slash-commands with path arguments Reject quoted or standalone frontmatter strings in _is_standalone_path when they begin with a dotted slash-command token (/speckit.) followed by whitespace and arguments, so invocations like `/speckit.plan docs/design.md` hyphenate the command while keeping the path argument intact. Assisted-by: Antigravity (model: Gemini 4, autonomous) --- .../integrations/junie/__init__.py | 11 ++++ tests/integrations/test_integration_junie.py | 53 +++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index a5c9e48c32..aca7bacc7d 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -207,6 +207,17 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: ): return False + if inner.startswith("/speckit."): + first_ws = inner.find(" ") + if first_ws > 1: + first_tok = inner[1:first_ws] + if ( + "/" not in first_tok + and "\\" not in first_tok + and _SPECKIT_DOTTED_REF.fullmatch(first_tok) is not None + ): + return False + last_sep = max(inner.rfind("/"), inner.rfind("\\")) if last_sep <= 0: return False diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 5cb44a3be1..681aab05ef 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -525,6 +525,59 @@ def test_round5_hash_dirs_spaced_dotted_dirs_arbitrary_suffixes_and_punct_prose( assert "backticked: Run `speckit-plan` then read docs/setup.md" in text assert '".specify/extensions/git/scripts/v1.0 speckit.git.commit.sh" "$ARGUMENTS"' in text + def test_quoted_and_frontmatter_slash_commands_with_path_args(self, tmp_path): + """Leading slash-commands with path arguments still hyphenate in quotes and frontmatter.""" + assert ( + hyphenate_command_refs("Run `/speckit.plan docs/design.md` now.") + == "Run `/speckit-plan docs/design.md` now." + ) + assert ( + hyphenate_command_refs('Run "/speckit.plan generates specs/plan.md".') + == 'Run "/speckit-plan generates specs/plan.md".' + ) + assert ( + hyphenate_command_refs("See `/speckit.foo.md docs/speckit.git.commit.md`.") + == "See `/speckit-foo-md docs/speckit.git.commit.md`." + ) + assert ( + hyphenate_command_refs('Open "/speckit.demo/my dir/my speckit.git.commit.md".') + == 'Open "/speckit.demo/my dir/my speckit.git.commit.md".' + ) + + fm_out = _hyphenate_frontmatter_refs( + { + "cmd": "/speckit.plan docs/design.md", + "summary": "/speckit.plan generates specs/plan.md", + "abs_path": "/speckit.demo/my dir/my speckit.git.commit.md", + } + ) + assert fm_out == { + "cmd": "/speckit-plan docs/design.md", + "summary": "/speckit-plan generates specs/plan.md", + "abs_path": "/speckit.demo/my dir/my speckit.git.commit.md", + } + + text = self._register_junie_command( + tmp_path, + "git", + "Run `/speckit.plan docs/design.md`, " + '"/speckit.plan generates specs/plan.md", ' + "and `/speckit.foo.md docs/speckit.git.commit.md`. " + 'Keep "/speckit.demo/my dir/my speckit.git.commit.md".\n', + frontmatter=( + "cmd: /speckit.plan docs/design.md\n" + "summary: /speckit.plan generates specs/plan.md\n" + "abs_path: /speckit.demo/my dir/my speckit.git.commit.md\n" + ), + ) + assert "`/speckit-plan docs/design.md`" in text + assert '"/speckit-plan generates specs/plan.md"' in text + assert "`/speckit-foo-md docs/speckit.git.commit.md`" in text + assert '"/speckit.demo/my dir/my speckit.git.commit.md"' in text + assert "cmd: /speckit-plan docs/design.md" in text + assert "summary: /speckit-plan generates specs/plan.md" in text + assert "abs_path: /speckit.demo/my dir/my speckit.git.commit.md" in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From a07e459922bf76e08d96cdbb70ecd3c11d030cb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Tue, 1 Dec 2026 08:41:09 +0800 Subject: [PATCH 08/11] fix(junie): do not exempt bare commands with path arguments Assisted-by: Antigravity (model: Gemini 4, autonomous) --- .../integrations/junie/__init__.py | 22 ++++++ tests/integrations/test_integration_junie.py | 71 +++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index aca7bacc7d..27530d73f0 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -232,6 +232,28 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: if not _is_valid_dir_component(comp, idx == 0): return False + if inner.startswith("speckit."): + first_ws = inner.find(" ") + if first_ws > 0: + first_tok = inner[:first_ws] + if ( + "/" not in first_tok + and "\\" not in first_tok + and _SPECKIT_DOTTED_REF.fullmatch(first_tok) is not None + ): + first_comp_words = dir_comps[0].split() + first_sep = min( + pos for pos in (inner.find("/"), inner.find("\\")) if pos >= 0 + ) + after_first_sep = inner[first_sep + 1 :] + if ( + len(first_comp_words) >= 3 + or (len(first_comp_words) >= 2 and first_comp_words[1][0] in ".~-") + or len(dir_comps) == 1 + or "speckit." not in after_first_sep + ): + return False + base = inner[last_sep + 1 :] if not base: return False diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 681aab05ef..3634b948de 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -578,6 +578,77 @@ def test_quoted_and_frontmatter_slash_commands_with_path_args(self, tmp_path): assert "summary: /speckit-plan generates specs/plan.md" in text assert "abs_path: /speckit.demo/my dir/my speckit.git.commit.md" in text + def test_quoted_and_frontmatter_bare_commands_with_path_args(self, tmp_path): + """Bare command invocations with path arguments hyphenate while spaced dotted dirs stay intact.""" + assert ( + hyphenate_command_refs("Run `speckit.plan docs/design.md` now.") + == "Run `speckit-plan docs/design.md` now." + ) + assert ( + hyphenate_command_refs('Run "speckit.plan generates specs/plan.md".') + == 'Run "speckit-plan generates specs/plan.md".' + ) + assert ( + hyphenate_command_refs("See `speckit.foo.md docs/speckit.git.commit.md`.") + == "See `speckit-foo-md docs/speckit.git.commit.md`." + ) + assert ( + hyphenate_command_refs('Run "speckit.plan docs/specs/design.md".') + == 'Run "speckit-plan docs/specs/design.md".' + ) + assert ( + hyphenate_command_refs( + 'Run "speckit.plan .specify/extensions/git/commands/speckit.git.commit.md".' + ) + == 'Run "speckit-plan .specify/extensions/git/commands/speckit.git.commit.md".' + ) + assert ( + hyphenate_command_refs('"speckit.demo files/commands/speckit.git.commit.md"') + == '"speckit.demo files/commands/speckit.git.commit.md"' + ) + + fm_out = _hyphenate_frontmatter_refs( + { + "cmd": "speckit.plan docs/design.md", + "summary": "speckit.plan generates specs/plan.md", + "nested": "speckit.plan docs/specs/design.md", + "dotpath": "speckit.plan .specify/extensions/git/commands/speckit.git.commit.md", + "spaced_dir": "speckit.demo files/commands/speckit.git.commit.md", + } + ) + assert fm_out == { + "cmd": "speckit-plan docs/design.md", + "summary": "speckit-plan generates specs/plan.md", + "nested": "speckit-plan docs/specs/design.md", + "dotpath": "speckit-plan .specify/extensions/git/commands/speckit.git.commit.md", + "spaced_dir": "speckit.demo files/commands/speckit.git.commit.md", + } + + text = self._register_junie_command( + tmp_path, + "git", + "Run `speckit.plan docs/design.md`, " + '"speckit.plan generates specs/plan.md", ' + "and `speckit.foo.md docs/speckit.git.commit.md`. " + 'Keep "speckit.demo files/commands/speckit.git.commit.md".\n', + frontmatter=( + "cmd: speckit.plan docs/design.md\n" + "summary: speckit.plan generates specs/plan.md\n" + "nested: speckit.plan docs/specs/design.md\n" + "dotpath: speckit.plan .specify/extensions/git/commands/speckit.git.commit.md\n" + "spaced_dir: speckit.demo files/commands/speckit.git.commit.md\n" + ), + ) + assert "`speckit-plan docs/design.md`" in text + assert '"speckit-plan generates specs/plan.md"' in text + assert "`speckit-foo-md docs/speckit.git.commit.md`" in text + assert '"speckit.demo files/commands/speckit.git.commit.md"' in text + assert "cmd: speckit-plan docs/design.md" in text + assert "summary: speckit-plan generates specs/plan.md" in text + assert "nested: speckit-plan docs/specs/design.md" in text + assert "dotpath: speckit-plan .specify/extensions/git/commands/speckit.git.commit.md" in text + assert "spaced_dir: speckit.demo files/commands/speckit.git.commit.md" in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From 3e9c7ef37aaae53a789fa1cada400e7099b918eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Wed, 2 Dec 2026 09:01:38 +0800 Subject: [PATCH 09/11] fix(junie): handle comma/dotted filenames, command context, and underline emphasis --- .../integrations/junie/__init__.py | 176 +++++++++++++++--- tests/integrations/test_integration_junie.py | 159 ++++++++++++++++ 2 files changed, 311 insertions(+), 24 deletions(-) diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 27530d73f0..5c03701665 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -81,6 +81,37 @@ def _is_path_char(ch: str) -> bool: "call", } ) +_CORE_SPECKIT_COMMANDS = frozenset( + { + "speckit.analyze", + "speckit.checklist", + "speckit.clarify", + "speckit.constitution", + "speckit.converge", + "speckit.implement", + "speckit.plan", + "speckit.specify", + "speckit.tasks", + "speckit.taskstoissues", + } +) +_INVOCATION_VERBS = frozenset({"run", "use", "invoke", "execute", "call"}) +_INVOCATION_FM_KEYS = frozenset( + { + "cmd", + "command", + "commands", + "handoff", + "handoffs", + "prompt", + "summary", + "description", + "usage", + "example", + "examples", + "instructions", + } +) def _is_segment_char(ch: str) -> bool: @@ -182,7 +213,74 @@ def _is_valid_dir_component(comp: str, is_first: bool) -> bool: return _is_path_char(comp[-1]) or comp[-1] in ")]" -def _is_standalone_path(text: str, start: int, end: int) -> bool: +def _has_matching_emphasis_close(line: str, slash_idx: int, run_len: int) -> bool: + """Whether ``line`` closes an underscore emphasis span before another opener.""" + delim = "_" * run_len + n = len(line) + pos = slash_idx + 1 + while pos < n: + idx = line.find(delim, pos) + if idx < 0: + return False + after = idx + run_len + if (idx > 0 and line[idx - 1] == "_") or (after < n and line[after] == "_"): + while after < n and line[after] == "_": + after += 1 + pos = after + continue + prev_ch = line[idx - 1] if idx > 0 else " " + next_ch = line[after] if after < n else " " + if ( + idx > slash_idx + 1 + and not prev_ch.isspace() + and (after == n or (not next_ch.isalnum() and next_ch != "_")) + ): + return True + if ( + (idx == 0 or prev_ch.isspace() or prev_ch in _SEP_LEADING_BOUNDARY) + and after < n + and not next_ch.isspace() + ): + return False + pos = after + return False + + +def _is_emphasis_underline_before_slash(line: str, slash_idx: int) -> bool: + """Whether underscores right before *slash_idx* open Markdown emphasis around ``/speckit.*``.""" + if slash_idx < 1 or line[slash_idx] != "/" or line[slash_idx - 1] != "_": + return False + run_start = slash_idx - 1 + while run_start > 0 and line[run_start - 1] == "_": + run_start -= 1 + run_len = slash_idx - run_start + if run_len > 3: + return False + if run_start > 0 and ( + line[run_start - 1].isalnum() or line[run_start - 1] in "/\\_" + ): + return False + if not line.startswith("speckit.", slash_idx + 1): + return False + return _has_matching_emphasis_close(line, slash_idx, run_len) + + +def _preceding_word_is_invocation(line: str, quote_idx: int) -> bool: + """Whether the word right before *quote_idx* is a command invocation verb.""" + j = quote_idx - 1 + while j >= 0 and line[j] == " ": + j -= 1 + if j < 0 or not line[j].isalpha(): + return False + end = j + 1 + while j >= 0 and line[j].isalpha(): + j -= 1 + return line[j + 1 : end].lower() in _INVOCATION_VERBS + + +def _is_standalone_path( + text: str, start: int, end: int, *, context: str | None = None +) -> bool: """Whether ``text[start:end]`` is a standalone single-line directory path.""" inner = text[start:end] if ( @@ -192,7 +290,6 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: or "\n" in inner or "\r" in inner or "\t" in inner - or "," in inner or ";" in inner or "`" in inner or '"' in inner @@ -218,6 +315,15 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: ): return False + if inner.startswith("_"): + run_len = len(inner) - len(inner.lstrip("_")) + if ( + 1 <= run_len <= 3 + and inner.startswith("/speckit.", run_len) + and _has_matching_emphasis_close(inner, run_len, run_len) + ): + return False + last_sep = max(inner.rfind("/"), inner.rfind("\\")) if last_sep <= 0: return False @@ -242,15 +348,12 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: and _SPECKIT_DOTTED_REF.fullmatch(first_tok) is not None ): first_comp_words = dir_comps[0].split() - first_sep = min( - pos for pos in (inner.find("/"), inner.find("\\")) if pos >= 0 - ) - after_first_sep = inner[first_sep + 1 :] if ( - len(first_comp_words) >= 3 + context == "invocation" + or first_tok.lower() in _CORE_SPECKIT_COMMANDS + or len(first_comp_words) >= 3 or (len(first_comp_words) >= 2 and first_comp_words[1][0] in ".~-") or len(dir_comps) == 1 - or "speckit." not in after_first_sep ): return False @@ -263,9 +366,14 @@ def _is_standalone_path(text: str, start: int, end: int) -> bool: words = base.split() if any(_has_punct_wrapped_speckit(w) for w in words): return False - if any("." in w and w.rsplit(".", 1)[-1].isalpha() for w in words[:-1]): + if any( + w.endswith(",") and "." in w[:-1] and w[:-1].rsplit(".", 1)[-1].isalpha() + for w in words[:-1] + ): return False - if len(words) >= 3 and any(w.lower() in _PROSE_CONNECTORS for w in words[1:-1]): + if len(words) >= 3 and any( + w.rstrip(",").lower() in _PROSE_CONNECTORS for w in words[1:-1] + ): return False return True @@ -326,7 +434,14 @@ def emit_replacement(start: int, end: int, replacement: str) -> None: close_idx = line.find(ch, close_idx + 1) if close_idx < 0: no_more_quote[ch] = True - elif _is_standalone_path(line, i + 1, close_idx): + elif _is_standalone_path( + line, + i + 1, + close_idx, + context="invocation" + if _preceding_word_is_invocation(line, i) + else None, + ): since_sep_valid = False last_closed_bracket_end = -1 last_env_var_end = -1 @@ -346,7 +461,12 @@ def emit_replacement(start: int, end: int, replacement: str) -> None: is_dir = False if i >= 1: prev = line[i - 1] - if _is_path_char(prev) or _is_drive_prefix(line, i): + if ( + _is_path_char(prev) + and not ( + prev == "_" and _is_emphasis_underline_before_slash(line, i) + ) + ) or _is_drive_prefix(line, i): is_dir = True elif ( last_closed_bracket_end == i - 1 @@ -503,35 +623,43 @@ def hyphenate_command_refs(text: str) -> str: def _hyphenate_frontmatter_refs( - val: Any, _memo: dict[int, Any] | None = None + val: Any, + _memo: dict[tuple[int, str | None], Any] | None = None, + *, + _context: str | None = None, ) -> Any: """Recursively hyphenate dotted ``speckit.*`` references in frontmatter values.""" if isinstance(val, dict): if _memo is None: _memo = {} - obj_id = id(val) - if obj_id in _memo: - return _memo[obj_id] + key = (id(val), _context) + if key in _memo: + return _memo[key] out_dict: dict[Any, Any] = {} - _memo[obj_id] = out_dict + _memo[key] = out_dict for k, v in val.items(): - out_dict[k] = _hyphenate_frontmatter_refs(v, _memo) + child_ctx = ( + "invocation" + if isinstance(k, str) and k.lower() in _INVOCATION_FM_KEYS + else None + ) + out_dict[k] = _hyphenate_frontmatter_refs(v, _memo, _context=child_ctx) return out_dict if isinstance(val, list): if _memo is None: _memo = {} - obj_id = id(val) - if obj_id in _memo: - return _memo[obj_id] + key = (id(val), _context) + if key in _memo: + return _memo[key] out_list: list[Any] = [] - _memo[obj_id] = out_list + _memo[key] = out_list for item in val: - out_list.append(_hyphenate_frontmatter_refs(item, _memo)) + out_list.append(_hyphenate_frontmatter_refs(item, _memo, _context=_context)) return out_list if isinstance(val, str): if "speckit." not in val: return val - if _is_standalone_path(val, 0, len(val)): + if _is_standalone_path(val, 0, len(val), context=_context): return val return hyphenate_command_refs(val) return val diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 3634b948de..1d2daf91ba 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -649,6 +649,165 @@ def test_quoted_and_frontmatter_bare_commands_with_path_args(self, tmp_path): assert "dotpath: speckit-plan .specify/extensions/git/commands/speckit.git.commit.md" in text assert "spaced_dir: speckit.demo files/commands/speckit.git.commit.md" in text + def test_comma_and_dotted_word_spaced_filenames_and_prose(self, tmp_path): + """Preserve comma/dotted-word spaced filenames while still hyphenating prose.""" + assert ( + hyphenate_command_refs('"scripts/my, speckit.git.commit.sh"') + == '"scripts/my, speckit.git.commit.sh"' + ) + assert ( + hyphenate_command_refs('"scripts/release.old speckit.git.commit.sh"') + == '"scripts/release.old speckit.git.commit.sh"' + ) + assert ( + hyphenate_command_refs('"docs/setup.md, then run speckit.plan"') + == '"docs/setup.md, then run speckit-plan"' + ) + assert ( + hyphenate_command_refs('"docs/setup.md, speckit.plan"') + == '"docs/setup.md, speckit-plan"' + ) + assert ( + hyphenate_command_refs('"docs/setup.md then run speckit.plan"') + == '"docs/setup.md then run speckit-plan"' + ) + + fm_out = _hyphenate_frontmatter_refs( + { + "comma_script": "scripts/my, speckit.git.commit.sh", + "old_script": "scripts/release.old speckit.git.commit.sh", + "prose_comma": "docs/setup.md, then run speckit.plan", + "prose_short": "docs/setup.md, speckit.plan", + } + ) + assert fm_out == { + "comma_script": "scripts/my, speckit.git.commit.sh", + "old_script": "scripts/release.old speckit.git.commit.sh", + "prose_comma": "docs/setup.md, then run speckit-plan", + "prose_short": "docs/setup.md, speckit-plan", + } + + text = self._register_junie_command( + tmp_path, + "git", + '"scripts/my, speckit.git.commit.sh" and "scripts/release.old speckit.git.commit.sh" ' + 'and "docs/setup.md, then run speckit.plan".\n', + frontmatter=( + 'comma_script: "scripts/my, speckit.git.commit.sh"\n' + 'old_script: "scripts/release.old speckit.git.commit.sh"\n' + 'prose_comma: "docs/setup.md, then run speckit.plan"\n' + ), + ) + assert '".specify/scripts/my, speckit.git.commit.sh"' in text + assert '".specify/scripts/release.old speckit.git.commit.sh"' in text + assert '"docs/setup.md, then run speckit-plan"' in text + assert "comma_script: scripts/my, speckit.git.commit.sh" in text + assert "old_script: scripts/release.old speckit.git.commit.sh" in text + assert "prose_comma: docs/setup.md, then run speckit-plan" in text + + def test_spaced_dotted_dir_non_speckit_basename_and_nested_speckit_arg( + self, tmp_path + ): + """Decide path vs command from context, not a later speckit. substring.""" + assert ( + hyphenate_command_refs('"speckit.demo files/commands/README.md"') + == '"speckit.demo files/commands/README.md"' + ) + assert ( + hyphenate_command_refs('Run "speckit.plan docs/specs/speckit.git.commit.md".') + == 'Run "speckit-plan docs/specs/speckit.git.commit.md".' + ) + assert ( + hyphenate_command_refs("`speckit.plan docs/specs/speckit.git.commit.md`") + == "`speckit-plan docs/specs/speckit.git.commit.md`" + ) + assert ( + hyphenate_command_refs( + 'Run "speckit.git.commit docs/specs/speckit.git.commit.md".' + ) + == 'Run "speckit-git-commit docs/specs/speckit.git.commit.md".' + ) + + fm_out = _hyphenate_frontmatter_refs( + { + "spaced_readme": "speckit.demo files/commands/README.md", + "nested_speckit": "speckit.plan docs/specs/speckit.git.commit.md", + "cmd": "speckit.git.commit docs/specs/speckit.git.commit.md", + } + ) + assert fm_out == { + "spaced_readme": "speckit.demo files/commands/README.md", + "nested_speckit": "speckit-plan docs/specs/speckit.git.commit.md", + "cmd": "speckit-git-commit docs/specs/speckit.git.commit.md", + } + + text = self._register_junie_command( + tmp_path, + "git", + 'Keep "speckit.demo files/commands/README.md" and ' + 'Run "speckit.plan docs/specs/speckit.git.commit.md".\n', + frontmatter=( + 'spaced_readme: "speckit.demo files/commands/README.md"\n' + 'nested_speckit: "speckit.plan docs/specs/speckit.git.commit.md"\n' + 'cmd: "speckit.git.commit docs/specs/speckit.git.commit.md"\n' + ), + ) + assert '"speckit.demo files/commands/README.md"' in text + assert 'Run "speckit-plan docs/specs/speckit.git.commit.md".' in text + assert "spaced_readme: speckit.demo files/commands/README.md" in text + assert "nested_speckit: speckit-plan docs/specs/speckit.git.commit.md" in text + assert "cmd: speckit-git-commit docs/specs/speckit.git.commit.md" in text + + def test_underscore_emphasis_slash_commands_and_real_underscore_paths( + self, tmp_path + ): + """Hyphenate _/speckit.*_ emphasis while preserving real underscore paths.""" + import time + + assert hyphenate_command_refs("Run _/speckit.plan_ next.") == "Run _/speckit-plan_ next." + assert ( + hyphenate_command_refs("Run __/speckit.plan__ next.") + == "Run __/speckit-plan__ next." + ) + assert ( + hyphenate_command_refs("(_/speckit.git.commit_)") + == "(_/speckit-git-commit_)" + ) + assert ( + hyphenate_command_refs("Run _/speckit.plan_ and _/speckit.git.status_ now.") + == "Run _/speckit-plan_ and _/speckit-git-status_ now." + ) + assert _hyphenate_frontmatter_refs({"note": "_/speckit.plan_"}) == { + "note": "_/speckit-plan_" + } + + for preserved in ( + "Open _/speckit.git.commit.md now.", + "Open _/speckit.git.commit.md and see _notes_ later.", + "Open foo_/speckit.git.commit.md now.", + "Open a/_/speckit.git.commit.md now.", + "Open _dir/speckit.git.commit.md now.", + "Open _/speckit.git.commit_v2.md now.", + ): + assert hyphenate_command_refs(preserved) == preserved + + t0 = time.monotonic() + repeated = " _/speckit.x" * 10_000 + assert hyphenate_command_refs(repeated) == repeated + mixed = " _/speckit.x" + " a_b" * 10_000 + assert hyphenate_command_refs(mixed) == mixed + assert time.monotonic() - t0 < 5.0 + + text = self._register_junie_command( + tmp_path, + "git", + "Run _/speckit.plan_ next and open _dir/speckit.git.commit.md.\n", + frontmatter="note: _/speckit.plan_\n", + ) + assert "Run _/speckit-plan_ next" in text + assert "_dir/speckit.git.commit.md" in text + assert "note: _/speckit-plan_" in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From 8839ed3b1e2d0c89de498676d3ff68295336c692 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Thu, 3 Dec 2026 00:12:31 +0800 Subject: [PATCH 10/11] fix(junie): normalize command refs after em-dash and dash prose separators --- .../integrations/junie/__init__.py | 16 ++++++ tests/integrations/test_integration_junie.py | 54 +++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 5c03701665..846e2a672d 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -360,6 +360,9 @@ def _is_standalone_path( base = inner[last_sep + 1 :] if not base: return False + for sep in ("\u2014", "\u2013", "\u2192"): + if sep in base and "speckit." in base.split(sep, 1)[1]: + return False if " " not in base: return True @@ -371,6 +374,19 @@ def _is_standalone_path( for w in words[:-1] ): return False + if len(words) >= 3 and any( + ( + w == "--" + or ( + w == "-" + and "." in words[idx] + and words[idx].rsplit(".", 1)[-1].isalpha() + ) + ) + and any("speckit." in after for after in words[idx + 2 :]) + for idx, w in enumerate(words[1:-1]) + ): + return False if len(words) >= 3 and any( w.rstrip(",").lower() in _PROSE_CONNECTORS for w in words[1:-1] ): diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 1d2daf91ba..d7de24140e 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -808,6 +808,60 @@ def test_underscore_emphasis_slash_commands_and_real_underscore_paths( assert "_dir/speckit.git.commit.md" in text assert "note: _/speckit-plan_" in text + def test_em_dash_and_dash_separated_prose_after_paths(self, tmp_path): + """Normalize speckit.* commands separated from prose paths by dashes.""" + assert ( + hyphenate_command_refs('"Read docs/setup.md — speckit.plan"') + == '"Read docs/setup.md — speckit-plan"' + ) + assert ( + hyphenate_command_refs('"Read docs/setup.md—speckit.plan"') + == '"Read docs/setup.md—speckit-plan"' + ) + assert ( + hyphenate_command_refs('"Read docs/setup.md – speckit.plan"') + == '"Read docs/setup.md – speckit-plan"' + ) + assert ( + hyphenate_command_refs('"Read docs/setup.md -- speckit.plan"') + == '"Read docs/setup.md -- speckit-plan"' + ) + assert ( + hyphenate_command_refs('"Read docs/setup.md - speckit.plan"') + == '"Read docs/setup.md - speckit-plan"' + ) + assert ( + hyphenate_command_refs('"Read docs/speckit.setup.md — speckit.plan"') + == '"Read docs/speckit.setup.md — speckit-plan"' + ) + + for preserved in ( + '"docs/notes — draft/speckit.git.commit.md"', + '"docs/speckit.demo.md — notes"', + '"scripts/v1.0 - speckit.git.commit.sh"', + ): + assert hyphenate_command_refs(preserved) == preserved + + fm_out = _hyphenate_frontmatter_refs( + { + "note": "Read docs/setup.md — speckit.plan", + "dir_dash": "docs/notes — draft/speckit.git.commit.md", + } + ) + assert fm_out == { + "note": "Read docs/setup.md — speckit-plan", + "dir_dash": "docs/notes — draft/speckit.git.commit.md", + } + + text = self._register_junie_command( + tmp_path, + "git", + '"Read docs/setup.md — speckit.plan".\n', + frontmatter='note: "Read docs/setup.md — speckit.plan"\n', + ) + assert '"Read docs/setup.md — speckit-plan".' in text + assert "note: Read docs/setup.md — speckit-plan" in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie") From 1b8caf9cda123ada1cb8c50bde6c9ca9f668b25e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E6=B6=A6=E6=B3=BD?= <506166760@qq.com> Date: Fri, 4 Dec 2026 00:13:38 +0800 Subject: [PATCH 11/11] fix(junie): fix dash scan scaling, bare underscore emphasis, UNC paths, punctuation filenames, and connector prose --- .../integrations/junie/__init__.py | 208 +++++++++++--- tests/integrations/test_integration_junie.py | 255 ++++++++++++++++++ 2 files changed, 427 insertions(+), 36 deletions(-) diff --git a/src/specify_cli/integrations/junie/__init__.py b/src/specify_cli/integrations/junie/__init__.py index 846e2a672d..b9e2605995 100644 --- a/src/specify_cli/integrations/junie/__init__.py +++ b/src/specify_cli/integrations/junie/__init__.py @@ -51,6 +51,9 @@ def format_junie_command_name(cmd_name: str) -> str: # Dotted ``speckit.*`` references in extension and preset command content. _SPECKIT_DOTTED_REF = re.compile(r"\bspeckit\.[A-Za-z0-9-_]+(?:\.[A-Za-z0-9-_]+)*\b") +_SPECKIT_REWRITE_REF = re.compile( + r"(? bool: @@ -70,15 +73,21 @@ def _is_path_char(ch: str) -> bool: "before", "after", "run", + "running", "read", "edit", "use", + "using", + "via", "open", "see", "check", "invoke", + "invoking", "execute", + "executing", "call", + "calling", } ) _CORE_SPECKIT_COMMANDS = frozenset( @@ -189,6 +198,8 @@ def _is_valid_dir_component(comp: str, is_first: bool) -> bool: return True if comp.endswith(":"): return False + if ";" in comp and "speckit." in comp.split(";", 1)[1]: + return False if comp.endswith("%"): return _is_valid_env_var_end(comp, 0, len(comp)) if is_first and comp[0] in "([": @@ -197,27 +208,58 @@ def _is_valid_dir_component(comp: str, is_first: bool) -> bool: return False if " " in comp: words = comp.split() + has_connector = len(words) >= 3 and any( + w.lower() in _PROSE_CONNECTORS for w in words + ) for idx, word in enumerate(words): if _has_punct_wrapped_speckit(word): return False + if idx < len(words) - 1 and word.endswith(("!", ";")): + nxt = words[idx + 1] + stem = word[:-1] + is_dotted_file = "." in stem and stem.rsplit(".", 1)[-1].isalpha() + if nxt[0].isupper() or nxt.lower() in _PROSE_CONNECTORS or stem.lower() in _PROSE_CONNECTORS or is_dotted_file: + return False + if word.endswith(";") and ( + _SPECKIT_DOTTED_REF.fullmatch(nxt.lstrip("/")) is not None + or words[0].lower() + in { + "cd", + "cat", + "sh", + "bash", + "zsh", + "python", + "python3", + "pwsh", + "powershell", + "echo", + "ls", + "cp", + "mv", + "rm", + "mkdir", + } + ): + return False stripped = word.lstrip("/") if _SPECKIT_DOTTED_REF.fullmatch(stripped) is not None: if 0 < idx < len(words) - 1: return False - if len(words) >= 3 and any( - other.lower() in _PROSE_CONNECTORS - for j, other in enumerate(words) - if j != idx - ): + if has_connector: return False - return _is_path_char(comp[-1]) or comp[-1] in ")]" + return ( + _is_path_char(comp[-1]) + or comp[-1] in ")]" + or (comp[-1] == "!" and len(comp) >= 2 and comp[-2].isalnum()) + ) -def _has_matching_emphasis_close(line: str, slash_idx: int, run_len: int) -> bool: +def _has_matching_emphasis_close(line: str, anchor_idx: int, run_len: int) -> bool: """Whether ``line`` closes an underscore emphasis span before another opener.""" delim = "_" * run_len n = len(line) - pos = slash_idx + 1 + pos = anchor_idx + 1 while pos < n: idx = line.find(delim, pos) if idx < 0: @@ -231,13 +273,22 @@ def _has_matching_emphasis_close(line: str, slash_idx: int, run_len: int) -> boo prev_ch = line[idx - 1] if idx > 0 else " " next_ch = line[after] if after < n else " " if ( - idx > slash_idx + 1 + idx > anchor_idx + 1 and not prev_ch.isspace() and (after == n or (not next_ch.isalnum() and next_ch != "_")) ): return True if ( - (idx == 0 or prev_ch.isspace() or prev_ch in _SEP_LEADING_BOUNDARY) + ( + idx == 0 + or prev_ch.isspace() + or prev_ch in _SEP_LEADING_BOUNDARY + or ( + not prev_ch.isalnum() + and prev_ch not in "/\\_" + and next_ch.isalnum() + ) + ) and after < n and not next_ch.isspace() ): @@ -290,13 +341,11 @@ def _is_standalone_path( or "\n" in inner or "\r" in inner or "\t" in inner - or ";" in inner or "`" in inner or '"' in inner or ". " in inner or ": " in inner or "?" in inner - or "!" in inner or "<" in inner or ">" in inner or " /" in inner @@ -317,25 +366,45 @@ def _is_standalone_path( if inner.startswith("_"): run_len = len(inner) - len(inner.lstrip("_")) - if ( - 1 <= run_len <= 3 - and inner.startswith("/speckit.", run_len) - and _has_matching_emphasis_close(inner, run_len, run_len) - ): - return False + if 1 <= run_len <= 3: + if inner.startswith("/speckit.", run_len) and _has_matching_emphasis_close( + inner, run_len, run_len + ): + return False + if inner.startswith("speckit.", run_len): + first_ws = inner.find(" ", run_len) + if ( + first_ws > run_len + and "/" not in inner[run_len:first_ws] + and "\\" not in inner[run_len:first_ws] + and _has_matching_emphasis_close(inner, run_len - 1, run_len) + ): + return False last_sep = max(inner.rfind("/"), inner.rfind("\\")) if last_sep <= 0: return False dir_part = inner[:last_sep].replace("\\", "/") - if dir_part.startswith("/"): + is_unc = False + if dir_part.startswith("//"): + if dir_part.startswith("///"): + return False + is_unc = True + dir_part = dir_part[2:] + elif dir_part.startswith("/"): dir_part = dir_part[1:] if not dir_part: return False dir_comps = dir_part.split("/") + if is_unc and ( + len(dir_comps) < 2 + or any(c.isspace() for c in dir_comps[0]) + or ":" in dir_comps[0] + ): + return False for idx, comp in enumerate(dir_comps): - if not _is_valid_dir_component(comp, idx == 0): + if not _is_valid_dir_component(comp, idx == 0 and not is_unc): return False if inner.startswith("speckit."): @@ -363,6 +432,14 @@ def _is_standalone_path( for sep in ("\u2014", "\u2013", "\u2192"): if sep in base and "speckit." in base.split(sep, 1)[1]: return False + if ";" in base or "!" in base: + for w in base.split(): + if ";" in w and "speckit." in w.split(";", 1)[1]: + return False + if "!" in w: + head, tail = w.split("!", 1) + if "speckit." in tail and "." in head and head.rsplit(".", 1)[-1].isalpha(): + return False if " " not in base: return True @@ -370,35 +447,94 @@ def _is_standalone_path( if any(_has_punct_wrapped_speckit(w) for w in words): return False if any( - w.endswith(",") and "." in w[:-1] and w[:-1].rsplit(".", 1)[-1].isalpha() + w.endswith((",", "!", ";")) and "." in w[:-1] and w[:-1].rsplit(".", 1)[-1].isalpha() for w in words[:-1] ): return False - if len(words) >= 3 and any( - ( - w == "--" - or ( + for idx, w in enumerate(words[:-1]): + if w.endswith("!"): + nxt = words[idx + 1] + if ( + nxt[0].isupper() + or nxt.lower() in _PROSE_CONNECTORS + or nxt.lower() in _CORE_SPECKIT_COMMANDS + or ( + context == "invocation" + and _SPECKIT_DOTTED_REF.fullmatch(nxt.lstrip("/")) is not None + ) + ): + return False + elif w.endswith(";"): + nxt = words[idx + 1] + if ( + nxt.lower() in _PROSE_CONNECTORS + or nxt.lower() in _CORE_SPECKIT_COMMANDS + or context == "invocation" + or " " in dir_comps[0] + or nxt.startswith("/") + ): + return False + last_speckit_word = -1 + for idx in range(len(words) - 1, -1, -1): + if "speckit." in words[idx]: + last_speckit_word = idx + break + if len(words) >= 3 and last_speckit_word >= 2: + for idx in range(1, min(len(words) - 1, last_speckit_word)): + w = words[idx] + if w == "--" or ( w == "-" - and "." in words[idx] - and words[idx].rsplit(".", 1)[-1].isalpha() - ) - ) - and any("speckit." in after for after in words[idx + 2 :]) - for idx, w in enumerate(words[1:-1]) - ): - return False + and "." in words[idx - 1] + and words[idx - 1].rsplit(".", 1)[-1].isalpha() + ): + return False if len(words) >= 3 and any( w.rstrip(",").lower() in _PROSE_CONNECTORS for w in words[1:-1] ): return False + if "." in words[0] and words[0].rsplit(".", 1)[-1].isalpha(): + first_dir_words = dir_comps[0].split() + if ( + len(first_dir_words) >= 2 + and first_dir_words[0].lower() in _PROSE_CONNECTORS + ): + return False + if context == "invocation" and any( + w.lower() in _CORE_SPECKIT_COMMANDS for w in words[1:] + ): + return False return True -def _rewrite_segment(segment: str) -> str: +def _rewrite_segment( + segment: str, line: str | None = None, seg_start: int = 0 +) -> str: """Hyphenate ``speckit.*`` matches inside one unprotected segment.""" if "speckit." not in segment: return segment - return _SPECKIT_DOTTED_REF.sub(lambda m: m.group(0).replace(".", "-"), segment) + full_line = segment if line is None else line + + def repl(m: re.Match[str]) -> str: + lead = m.group(1) + ref = m.group(2) + abs_start = seg_start + m.start(1) + if lead: + if abs_start > 0 and ( + full_line[abs_start - 1].isalnum() + or full_line[abs_start - 1] in "/\\_" + ): + return m.group(0) + if not _has_matching_emphasis_close( + full_line, abs_start + len(lead) - 1, len(lead) + ): + return m.group(0) + elif abs_start > 0 and ( + full_line[abs_start - 1].isalnum() or full_line[abs_start - 1] == "_" + ): + return m.group(0) + return f"{lead}{ref.replace('.', '-')}" + + return _SPECKIT_REWRITE_REF.sub(repl, segment) def _hyphenate_line(line: str) -> str: @@ -576,7 +712,7 @@ def emit_replacement(start: int, end: int, replacement: str) -> None: if not (preceded_by_dir or followed_by_dir): seg = line[seg_start:seg_end] if "speckit." in seg: - rewritten = _rewrite_segment(seg) + rewritten = _rewrite_segment(seg, line, seg_start) if rewritten != seg: emit_replacement(seg_start, seg_end, rewritten) continue diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index d7de24140e..c7eb2f5f71 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -862,6 +862,261 @@ def test_em_dash_and_dash_separated_prose_after_paths(self, tmp_path): assert '"Read docs/setup.md — speckit-plan".' in text assert "note: Read docs/setup.md — speckit-plan" in text + def test_repeated_dash_tokens_scale_linearly(self): + """Repeated ``--`` tokens after a path must scale linearly in O(n).""" + import time + + t0 = time.monotonic() + preserved = '"speckit.demo/files/readme' + " --" * 15_000 + '"' + assert hyphenate_command_refs(preserved) == preserved + assert _hyphenate_frontmatter_refs({"note": preserved.strip('"')}) == { + "note": preserved.strip('"') + } + + prose = '"speckit.demo/files/readme' + " --" * 15_000 + ' speckit.plan"' + expected_prose = ( + '"speckit.demo/files/readme' + " --" * 15_000 + ' speckit-plan"' + ) + assert hyphenate_command_refs(prose) == expected_prose + elapsed = time.monotonic() - t0 + assert elapsed < 2.0, f"repeated dash scan took too long: {elapsed:.2f}s" + + def test_bare_underscore_emphasis_commands_and_identifiers(self, tmp_path): + """Normalize _speckit.*_ / __speckit.*__ emphasis while preserving identifiers.""" + import time + + assert ( + hyphenate_command_refs("Run _speckit.plan_ next.") + == "Run _speckit-plan_ next." + ) + assert ( + hyphenate_command_refs("Run __speckit.git.status__ next.") + == "Run __speckit-git-status__ next." + ) + assert ( + hyphenate_command_refs("Run ___speckit.plan___ next.") + == "Run ___speckit-plan___ next." + ) + assert ( + hyphenate_command_refs("(_speckit.git.commit_).") + == "(_speckit-git-commit_)." + ) + assert ( + hyphenate_command_refs("Run _speckit.plan_. Next.") + == "Run _speckit-plan_. Next." + ) + assert ( + hyphenate_command_refs("Run _speckit.plan now_.") + == "Run _speckit-plan now_." + ) + assert ( + hyphenate_command_refs('"_speckit.plan docs/design.md_"') + == '"_speckit-plan docs/design.md_"' + ) + + fm_out = _hyphenate_frontmatter_refs( + { + "note": "Run _speckit.plan_ next.", + "bold": "Run __speckit.git.status__ next.", + "cmd": "_speckit.plan docs/design.md_", + } + ) + assert fm_out == { + "note": "Run _speckit-plan_ next.", + "bold": "Run __speckit-git-status__ next.", + "cmd": "_speckit-plan docs/design.md_", + } + + for preserved in ( + "foo_speckit.plan", + "foo_speckit.plan_", + "_speckit.plan", + "__speckit.git.status", + "_speckit.git.commit_v2", + "____speckit.plan____", + "_speckit.demo_/commands/speckit.git.commit.md", + '"_speckit.demo_/commands/speckit.git.commit.md"', + ): + assert hyphenate_command_refs(preserved) == preserved + + t0 = time.monotonic() + comma_openers = ",_speckit.x" * 10_000 + assert hyphenate_command_refs(comma_openers) == comma_openers + space_openers = " _speckit.x" * 10_000 + assert hyphenate_command_refs(space_openers) == space_openers + assert time.monotonic() - t0 < 2.0 + + text = self._register_junie_command( + tmp_path, + "git", + "Run _speckit.plan_ and __speckit.git.status__, keep foo_speckit.plan.\n", + frontmatter=( + "note: Run _speckit.plan_ next.\n" + "bold: Run __speckit.git.status__ next.\n" + ), + ) + assert "Run _speckit-plan_ and __speckit-git-status__, keep foo_speckit.plan." in text + assert "note: Run _speckit-plan_ next." in text + assert "bold: Run __speckit-git-status__ next." in text + + def test_quoted_and_frontmatter_unc_paths(self, tmp_path): + """Quoted and frontmatter UNC paths keep dots while UNC-like prose hyphenates.""" + for preserved in ( + '"\\\\server\\share\\my speckit.git.commit.md"', + '"\\\\server\\my share\\sub\\my speckit.git.commit.md"', + '"//server/share/my speckit.git.commit.md"', + ): + assert hyphenate_command_refs(preserved) == preserved + + assert ( + hyphenate_command_refs('"// Run speckit.plan and edit docs/a.md"') + == '"// Run speckit-plan and edit docs/a.md"' + ) + assert ( + hyphenate_command_refs('"//server/my speckit.plan"') + == '"//server/my speckit-plan"' + ) + assert ( + hyphenate_command_refs( + '"\\\\server\\share\\docs\\setup.md then run speckit.plan"' + ) + == '"\\\\server\\share\\docs\\setup.md then run speckit-plan"' + ) + + fm_out = _hyphenate_frontmatter_refs( + {"unc": "\\\\server\\share\\my speckit.git.commit.md"} + ) + assert fm_out == {"unc": "\\\\server\\share\\my speckit.git.commit.md"} + + text = self._register_junie_command( + tmp_path, + "git", + '"\\\\server\\share\\my speckit.git.commit.md" and ' + '"// Run speckit.plan and edit docs/a.md".\n', + frontmatter="unc: '\\\\server\\share\\my speckit.git.commit.md'\n", + ) + assert '"\\\\server\\share\\my speckit.git.commit.md"' in text + assert '"// Run speckit-plan and edit docs/a.md"' in text + assert "unc: \\\\server\\share\\my speckit.git.commit.md" in text + + def test_quoted_and_frontmatter_bang_and_semicolon_filenames_vs_prose( + self, tmp_path + ): + """Filenames containing ! or ; stay intact while prose and shell chains hyphenate.""" + for preserved in ( + '"scripts/my! speckit.git.commit.sh"', + '"scripts/my; speckit.git.commit.sh"', + '"scripts/a;b speckit.git.commit.sh"', + '"scripts/v1!/my speckit.git.commit.sh"', + ): + assert hyphenate_command_refs(preserved) == preserved + + assert _hyphenate_frontmatter_refs( + { + "file": "scripts/my! speckit.git.commit.sh", + "semi": "scripts/my; speckit.git.commit.sh", + } + ) == { + "file": "scripts/my! speckit.git.commit.sh", + "semi": "scripts/my; speckit.git.commit.sh", + } + + assert ( + hyphenate_command_refs('"docs/setup.md! speckit.plan"') + == '"docs/setup.md! speckit-plan"' + ) + assert ( + hyphenate_command_refs('"docs/setup.md; speckit.git.status"') + == '"docs/setup.md; speckit-git-status"' + ) + assert ( + hyphenate_command_refs('"scripts/run.sh;speckit.plan"') + == '"scripts/run.sh;speckit-plan"' + ) + assert ( + hyphenate_command_refs('"docs/readme! Run speckit.plan"') + == '"docs/readme! Run speckit-plan"' + ) + assert ( + hyphenate_command_refs('"cd scripts/foo; speckit.git.status"') + == '"cd scripts/foo; speckit-git-status"' + ) + assert ( + hyphenate_command_refs('"docs/readme; speckit.plan"') + == '"docs/readme; speckit-plan"' + ) + assert _hyphenate_frontmatter_refs( + {"description": "Read docs/readme; speckit.git.status"} + ) == {"description": "Read docs/readme; speckit-git-status"} + + text = self._register_junie_command( + tmp_path, + "git", + '"scripts/my! speckit.git.commit.sh" and "docs/readme! Run speckit.plan".\n', + frontmatter=( + 'file: "scripts/my! speckit.git.commit.sh"\n' + 'semi: "scripts/my; speckit.git.commit.sh"\n' + 'description: "Read docs/readme; speckit.git.status"\n' + ), + ) + assert '".specify/scripts/my! speckit.git.commit.sh"' in text + assert '"docs/readme! Run speckit-plan"' in text + assert "file: scripts/my! speckit.git.commit.sh" in text + assert "semi: scripts/my; speckit.git.commit.sh" in text + assert "description: Read docs/readme; speckit-git-status" in text + + def test_using_and_invocation_prose_after_paths(self, tmp_path): + """Connector prose with ``using``/``via``/``with`` hyphenates while spaced paths stay intact.""" + assert ( + hyphenate_command_refs('"Read docs/setup.md using speckit.plan"') + == '"Read docs/setup.md using speckit-plan"' + ) + assert ( + hyphenate_command_refs('"docs/setup.md using speckit.plan"') + == '"docs/setup.md using speckit-plan"' + ) + assert ( + hyphenate_command_refs('"docs/setup.md via speckit.plan"') + == '"docs/setup.md via speckit-plan"' + ) + assert ( + hyphenate_command_refs('"Read docs/setup.md with speckit.plan"') + == '"Read docs/setup.md with speckit-plan"' + ) + + assert ( + hyphenate_command_refs('"scripts/release.old speckit.git.commit.sh"') + == '"scripts/release.old speckit.git.commit.sh"' + ) + assert ( + hyphenate_command_refs('"docs/notes for speckit.git.commit.md"') + == '"docs/notes for speckit.git.commit.md"' + ) + + fm_out = _hyphenate_frontmatter_refs( + { + "description": "Read docs/setup.md using speckit.plan", + "note": "Read docs/setup.md using speckit.plan", + "kept": "scripts/release.old speckit.git.commit.sh", + } + ) + assert fm_out == { + "description": "Read docs/setup.md using speckit-plan", + "note": "Read docs/setup.md using speckit-plan", + "kept": "scripts/release.old speckit.git.commit.sh", + } + + text = self._register_junie_command( + tmp_path, + "git", + '"Read docs/setup.md using speckit.plan" and ' + '"docs/notes for speckit.git.commit.md".\n', + frontmatter='description: "Read docs/setup.md using speckit.plan"\n', + ) + assert '"Read docs/setup.md using speckit-plan"' in text + assert '"docs/notes for speckit.git.commit.md"' in text + assert "description: Read docs/setup.md using speckit-plan" in text + def test_junie_hook_instruction_injection(self): """Verify junie injects the dot-to-hyphen note for hooks.""" junie = get_integration("junie")