Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(distill): safe cmd.exe argv rendering, honest missed-savings tip, correct permission docs (#1071)

Raghav Chamadiya1d860b2ae153
diff --git a/docs/agent/DISTILL.md b/docs/agent/DISTILL.md
index 968c172e9..d3a83e559 100644
--- a/docs/agent/DISTILL.md
+++ b/docs/agent/DISTILL.md
@@ -74,10 +74,12 @@ MCP clients without a shell can resolve the same refs through
### 3. The command-rewrite hook (Claude Code + Codex)
A PreToolUse hook rewrites noisy agent commands —
-`pytest -x` → `repowise distill pytest -x` — **pending your approval**: the
-default posture is `ask`, so Claude Code shows you the modified command before
-running it. `repowise init` offers to install it (default: yes); install
-manually with:
+`pytest -x` → `repowise distill pytest -x`. The default posture is `allow`, so
+the rewrite runs without a prompt; it is a bounded substitution, never a new
+command (see [Safety model](#safety-model-in-one-place)). Set
+`permission: ask` in `.repowise/config.yaml` to review each rewrite instead.
+`repowise init` offers to install the hook (default: yes); install manually
+with:
```bash
repowise hook rewrite install # or opt in during `repowise init`
@@ -97,10 +99,10 @@ two honest caveats its hook protocol imposes:
on every shell call). `repowise hook rewrite status` reports what your
build can do.
- Codex has **no ask-with-mutation** — a rewrite can only be auto-allowed,
- never shown for approval. So under Codex, rewrites fire **only for command
- families you set to `permission: allow`** in `.repowise/config.yaml`;
- `ask` families always pass through unchanged. We never silently mutate a
- command you didn't opt into.
+ never shown for approval. So under Codex, rewrites fire **only for families
+ resolving to `permission: allow`** in `.repowise/config.yaml`, which the
+ default posture already is; any family you set to `ask` passes through
+ unchanged there rather than being silently escalated.
The hook entry lands in `~/.codex/hooks.json` (one install covers every
repo); Codex requires new hooks to be reviewed — run `/hooks` inside Codex to
@@ -389,7 +391,7 @@ distill:
enabled: true # master switch for this repo
commands:
enabled: true # the command path (CLI + hook rewrites)
- permission: ask # ask | allow | off — hook posture
+ permission: allow # ask | allow | off — hook posture (default allow)
families: # per-filter overrides
test_output: allow # auto-allow rewrites for test runs
git_diff: deny # never rewrite git diff here
@@ -411,7 +413,7 @@ and whether the rewrite hook is installed.
| Risk | Mitigation |
|---|---|
| A filter eats a critical line | errors-first invariant + fixture tests + `expand` recovery + fallback-to-raw |
-| Silent permission escalation | rewrites default to `ask`; the user sees the modified command. Codex has no ask primitive, so only families explicitly set to `allow` rewrite there |
+| Silent permission escalation | rewrites default to `allow`, which is not an escalation: a rewrite is always `repowise distill <one recognized command>` drawn from a closed family set, never an arbitrary command smuggled behind the wrapper. Set `permission: ask` to approve each one. Codex has no ask primitive, so only families explicitly set to `allow` rewrite there |
| Marker with nothing behind it | content stored *before* the marker renders; store failure ⇒ raw output |
| Compound-command semantics | compound commands, substitution and redirects are never rewritten. The one pipe shape that is (a single stage into a bare stdin filter, macOS/Linux only) is passed through as one quoted token and runs verbatim in distill's shell; anything that could break out of that quoting bails |
| Unindexed or stale repo | filters work index-free; index only improves ranking |
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index 2167959e7..5d4063b00 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -22,7 +22,7 @@ crashes or blocks your agent.
| **Post-commit auto-sync** | git | `repowise hook install` (or the `repowise init` prompt) | every `git commit` | Runs `repowise update` in the background so the wiki tracks your code |
| **SessionStart context** | Claude Code | `repowise init` | session `startup` / `resume` / `clear` | Live index-freshness line, core-tool trust rule, and the standing decisions relevant to this session |
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / `Bash` / `PowerShell` / repowise MCP calls | Graph context on searches, git/edit freshness, read-intelligence notices, and edit-time "governed by" decision notices |
-| **Command-rewrite (distill)** | Claude Code | `repowise hook rewrite install` (opt-in) | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>`, pending your approval |
+| **Command-rewrite (distill)** | Claude Code | `repowise hook rewrite install` (opt-in) | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>`; auto-allowed by default, set `permission: ask` to approve each one |
| **Codex context + staleness** | Codex | `repowise init --codex` | SessionStart / UserPromptSubmit / edit / Bash | Reminds Codex to use the MCP tools and flags stale context after edits |
---
@@ -152,7 +152,11 @@ repowise hook rewrite status
repowise hook rewrite uninstall
```
-- Defaults to **`ask`**, so you approve every rewritten command before it runs.
+- Defaults to **`allow`**, so a rewrite runs without a prompt. That is not a
+ permission escalation: a rewrite is always `repowise distill <one recognized
+ command>` from a closed family set, never an arbitrary command smuggled
+ behind the wrapper. Set `permission: ask` under `distill.commands` in
+ `.repowise/config.yaml` to approve each one instead.
- Never rewrites compound commands, redirections, or watch modes. The one pipe
shape it handles (macOS/Linux) is a single stage into `head`, `tail`, `grep`
or `rg`, quoted whole so it runs unchanged inside distill's own shell.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 42778ff77..de8daa7fe 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -964,8 +964,9 @@ When `~/.codex` exists, `install` also writes a Codex hook entry to
`~/.codex/hooks.json` (Codex ≥ 0.137 only, older builds can't apply a
rewrite) and maintains an "Output Distillation" section in the repo's
`AGENTS.md` that works without any hook. Codex cannot show a rewritten
-command for approval, so there rewrites fire only for families set to
-`permission: allow`; `status` reports exactly what your build supports. See
+command for approval, so there rewrites fire only for families resolving to
+`permission: allow` (the default) and a family set to `ask` passes through
+unchanged; `status` reports exactly what your build supports. See
[DISTILL.md](../agent/DISTILL.md#3-the-command-rewrite-hook-claude-code--codex).
---
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 1f343b2cb..010b0fe35 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -128,7 +128,7 @@ distill:
enabled: true # master switch for this repo
commands:
enabled: true # the command path (CLI + hook rewrites)
- permission: ask # ask | allow | off (rewrite-hook posture)
+ permission: allow # ask | allow | off (rewrite-hook posture)
families: # per-filter overrides
test_output: allow # auto-allow rewrites for test runs
git_diff: deny # never rewrite git diff here
@@ -138,8 +138,12 @@ distill:
max_mb: 50 # size cap; oldest entries pruned first
```
-- `permission: ask` (the default) means the agent's rewritten command is shown
- for approval; `allow` auto-approves rewrites; `off` disables rewrites here.
+- `permission: allow` (the default) auto-approves rewrites, uniformly across
+ the main agent and every subagent. This is not a permission escalation: a
+ rewrite is always `repowise distill <one recognized command>` from a closed
+ family set, never an arbitrary command smuggled behind the wrapper. Set
+ `ask` to have each rewritten command shown for approval instead, or `off` to
+ disable rewrites in this repo.
- `families` keys are filter names (`test_output`, `build_output`,
`lint_output`, `install_output`, `infra_plan`, `git_status`, `git_log`,
`git_diff`, `search_results`, `file_listing`, `logs`) and accept
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index 0fd5659bb..0caf86e53 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -248,7 +248,8 @@ repowise saved # tokens and dollars saved so far
Distill compresses noisy command output before your agent reads it, 60-90% fewer
tokens on noisy commands with no error lines dropped. Opt into the rewrite hook
during `init` (or `repowise hook rewrite install`) to have it applied
-automatically, with each rewrite shown to you for approval.
+automatically. Rewrites run without a prompt and only ever wrap a recognized
+command; set `permission: ask` to review each one.
See [Distill](../agent/DISTILL.md).
## More than one repo
diff --git a/packages/cli/src/repowise/cli/commands/distill_cmd.py b/packages/cli/src/repowise/cli/commands/distill_cmd.py
index 981793613..637cf48be 100644
--- a/packages/cli/src/repowise/cli/commands/distill_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/distill_cmd.py
@@ -9,6 +9,8 @@ and agent tool calls alike.
from __future__ import annotations
+import os
+import re
import subprocess
import sys
from pathlib import Path
@@ -49,7 +51,12 @@ def distill_command(source: str, command: tuple[str, ...]) -> None:
restore it with ``repowise expand <ref>``. On any filter problem the raw
output is printed unchanged. The command's exit code is preserved.
"""
- command_str = _render_command(command)
+ try:
+ command_str = _render_command(command)
+ except UnrenderableCommand as exc:
+ # Refusing is the safe half of the trade: running a command the user
+ # did not type is worse than not running one they did.
+ raise click.ClickException(str(exc)) from exc
# shell=True on purpose: the user's own command may be a shell builtin
# or a .cmd shim (npm on Windows); we execute exactly what they typed.
proc = subprocess.run(
@@ -69,15 +76,85 @@ def distill_command(source: str, command: tuple[str, ...]) -> None:
sys.exit(proc.returncode)
+# cmd.exe consumes these before the child ever sees them. ``^`` escapes each
+# one for exactly one round of parsing, which is all ``cmd /c`` does.
+_CMD_METACHARS = frozenset('"&|<>^()')
+
+# A ``%NAME%`` pair cmd.exe would expand. Percent expansion happens in a pass
+# before caret handling, so there is nothing to escape it with.
+_CMD_VAR_RE = re.compile(r"%(\w+)%")
+
+
+class UnrenderableCommand(Exception):
+ """A token cmd.exe cannot be handed over without changing the command."""
+
+
def _render_command(tokens: tuple[str, ...]) -> str:
- """Rejoin click's pre-split tokens into one shell command string."""
+ """Rejoin click's pre-split tokens into one shell command string.
+
+ A single token is passed through untouched: the user quoted the whole
+ command themselves, so shell syntax in it is what they asked for.
+
+ Multiple tokens are an argv the shell must not reinterpret.
+ ``list2cmdline`` alone is not enough on Windows: it quotes for the C
+ runtime's argv parser, which only cares about spaces and quotes, so a
+ token like ``--grep=a&whoami`` comes back unquoted and cmd.exe reads the
+ ``&`` as a command separator.
+
+ So the arguments are caret-escaped — cmd strips one layer and hands the
+ literal text to the child, and because every ``"`` is escaped too, cmd
+ never enters a quoted state where the carets would stop working. The
+ executable is the exception: it keeps real grouping quotes, because cmd
+ resolves the program name before caret processing and a caret-escaped
+ quote is not a grouping quote, which would split ``C:\\Program
+ Files\\...`` at its first space.
+
+ Two shapes cannot be rendered at all and raise rather than run something
+ the user did not type. Both are rejected, not escaped, because cmd offers
+ no escape for either:
+
+ - ``%NAME%`` naming a variable that exists. cmd substitutes it and then
+ re-parses the result, so a value carrying a metacharacter is command
+ execution, not just substitution. Undefined names pass through
+ untouched, which is what keeps ``git log --format=%h%n%s`` working.
+ - A newline or carriage return. cmd truncates the command line at a
+ newline and silently drops a bare CR, so the child would receive a
+ quietly different argv.
+ """
if len(tokens) == 1:
return tokens[0]
- if sys.platform == "win32":
- return subprocess.list2cmdline(tokens)
- import shlex
-
- return shlex.join(tokens)
+ if sys.platform != "win32":
+ import shlex
+
+ return shlex.join(tokens)
+
+ for token in tokens:
+ if "\n" in token or "\r" in token:
+ raise UnrenderableCommand(
+ "cmd.exe cannot carry a newline inside an argument; "
+ "quote the whole command as one argument to run it verbatim"
+ )
+ for name in _CMD_VAR_RE.findall(token):
+ if name in os.environ:
+ raise UnrenderableCommand(
+ f"cmd.exe would expand %{name}% and change this command; "
+ "quote the whole command as one argument to run it verbatim"
+ )
+
+ exe = tokens[0]
+ # Windows paths cannot contain `"`, so plain quoting is unambiguous.
+ if '"' not in exe and (
+ any(ch.isspace() for ch in exe) or any(ch in _CMD_METACHARS for ch in exe)
+ ):
+ head = f'"{exe}"'
+ else:
+ head = _caret_escape(subprocess.list2cmdline([exe]))
+ rest = _caret_escape(subprocess.list2cmdline(tokens[1:]))
+ return f"{head} {rest}" if rest else head
+
+
+def _caret_escape(rendered: str) -> str:
+ return "".join("^" + ch if ch in _CMD_METACHARS else ch for ch in rendered)
def _distill_or_raw(output: str, command_str: str, exit_code: int, source: str = "cli") -> str:
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index dd1257053..e46747901 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -102,14 +102,16 @@ def rewrite_group() -> None:
When installed, noisy commands an agent runs (tests, builds, git
status/log/diff, searches, listings) are rewritten to
- ``repowise distill <command>`` — pending your approval — so the agent
- sees a compact, errors-first rendering. Raw output stays recoverable
- via ``repowise expand <ref>``.
-
- Claude Code gets the full ask-posture rewrite. Codex hooks cannot show
- a rewritten command for approval, so there rewrites apply only to
- command families set to ``permission: allow``; every Codex install also
- maintains an AGENTS.md awareness section that works without any hook.
+ ``repowise distill <command>`` so the agent sees a compact, errors-first
+ rendering. Raw output stays recoverable via ``repowise expand <ref>``.
+
+ The default posture is ``allow``: rewrites run without a prompt, and only
+ ever wrap a command already recognized as one of the distill families.
+ Set ``permission: ask`` under ``distill.commands`` in
+ ``.repowise/config.yaml`` to approve each one instead. Codex hooks cannot
+ show a rewritten command for approval at all, so a family set to ``ask``
+ simply passes through there; every Codex install also maintains an
+ AGENTS.md awareness section that works without any hook.
"""
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
index 519845a37..f44b40589 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
@@ -65,8 +65,9 @@ def offer_distill_rewrite_hook(
)
scope = f"Applies to all {len(repo_paths)} selected repos. " if len(repo_paths) > 1 else ""
console_obj.print(
- f" [dim]{scope}Each rewrite is shown for approval; raw output stays "
- "recoverable via `repowise expand`.[/dim]"
+ f" [dim]{scope}Rewrites run without a prompt and only ever wrap a "
+ "recognized command; set `permission: ask` in .repowise/config.yaml to "
+ "approve each one. Raw output stays recoverable via `repowise expand`.[/dim]"
)
try:
flag = click.confirm(" Install the Claude Code rewrite hook?", default=True)
diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.py
index 898dd719d..b980cc176 100644
--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py
@@ -222,12 +222,14 @@ def _print_missed_report(start: Path, days: float, pricing_model: str) -> None:
return
if has_missed:
- _render_missed_distill_table(missed, days, pricing_model)
+ _render_missed_distill_table(missed, days, pricing_model, start)
if has_reread:
_render_reread_table(reread, days, pricing_model)
-def _render_missed_distill_table(report: dict, days: float, pricing_model: str) -> None:
+def _render_missed_distill_table(
+ report: dict, days: float, pricing_model: str, repo_root: Path | None = None
+) -> None:
usd, rate = _estimate_usd(report["est_saved_tokens"], pricing_model)
table = Table(
title=f"Missed distill savings - last {days:g} days",
@@ -262,13 +264,73 @@ def _render_missed_distill_table(report: dict, days: float, pricing_model: str)
f"[dim](at ${rate:.2f}/M input tokens, {pricing_model}; "
f"tokens are chars/4 estimates)[/dim]"
)
- console.print(
- " [dim]Tip: install the rewrite hook ('repowise hook rewrite install') "
- "to catch these automatically.[/dim]"
- )
+ console.print(f" [dim]{_missed_tip(repo_root)}[/dim]")
console.print()
+def _rewrite_hook_installed() -> bool:
+ """True when any agent surface has the rewrite hook wired up.
+
+ Mirrors the doctor check: Claude Code is always considered, Codex only
+ when it is actually present on the machine.
+ """
+ try:
+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+
+ if ClaudeCodeAdapter().rewrite_hook_installed():
+ return True
+ codex = CodexAdapter()
+ return codex.detect() and codex.rewrite_hook_installed()
+ except Exception:
+ return False
+
+
+def _distill_opted_out(repo_root: Path | None) -> bool:
+ """True when this repo turned the command path off in its own config."""
+ if repo_root is None:
+ return False
+ try:
+ from repowise.core.repo_config import load_repo_config
+
+ cfg = load_repo_config(repo_root).get("distill")
+ if not isinstance(cfg, dict):
+ return False
+ if cfg.get("enabled") is False:
+ return True
+ commands = cfg.get("commands")
+ return isinstance(commands, dict) and commands.get("enabled") is False
+ except Exception:
+ return False
+
+
+def _missed_tip(repo_root: Path | None = None) -> str:
+ """The one next step that is actually true for this machine.
+
+ Telling someone to install a hook they already installed hides the real
+ reason the rows are still there: the hook only rewrites a single
+ recognized command, so chained (``a && b``) and piped commands pass
+ through by design and have to be distilled explicitly. A repo that opted
+ out has a third, different reason again.
+ """
+ if not _rewrite_hook_installed():
+ return (
+ "Tip: install the rewrite hook ('repowise hook rewrite install') "
+ "to catch these automatically."
+ )
+ if _distill_opted_out(repo_root):
+ return (
+ "Tip: the rewrite hook is installed but this repo opted out "
+ "(distill.commands.enabled: false in .repowise/config.yaml), so nothing "
+ "here was rewritten. Set it back to true to catch these automatically."
+ )
+ return (
+ "Tip: the hook is installed. What is left is mostly commands it will not "
+ "rewrite - it only wraps a single recognized command, so chained and piped "
+ "ones pass through. Run those through 'repowise distill <cmd>' yourself."
+ )
+
+
def _render_reread_table(report: dict, days: float, pricing_model: str) -> None:
usd, rate = _estimate_usd(report["est_saved_tokens"], pricing_model)
table = Table(
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index a6a543b78..62b460e5b 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -405,7 +405,7 @@ def _inherit_distill_verdict(repo_path: Path, primary_cfg: dict) -> None:
``repowise init`` records ``distill.commands.enabled`` in every repo it
asks about; a repo added later would otherwise default to enabled (with
- the ``ask`` posture) the moment ``.repowise/`` exists — even after a
+ the ``allow`` posture) the moment ``.repowise/`` exists — even after a
workspace-wide decline. No explicit verdict on the primary → leave the
new repo's config untouched.
"""
diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.py
index bb4c3385c..d701030d3 100644
--- a/packages/cli/src/repowise/cli/rewrite_hook.py
+++ b/packages/cli/src/repowise/cli/rewrite_hook.py
@@ -215,16 +215,16 @@ _PIPE_UNSAFE_CHARS = ('"', "'", "$", "\\")
# POSIX-hosts-only. Module constant so tests can pin both platforms.
_POSIX_HOST = os.name == "posix"
-# Windows keeps the blunt character bail, quoted or not. Two reasons, both
-# downstream of this module:
+# Windows keeps the blunt character bail, quoted or not. Two reasons:
#
-# - distill rejoins its argv with ``subprocess.list2cmdline``, which quotes
-# for the C runtime's argv parser and not for cmd.exe. A token like
-# ``--grep=a&whoami`` holds no space, so it is emitted unquoted and
-# cmd.exe reads the ``&`` as a command separator. The lexer knows that
-# ``&`` was quoted text; the renderer downstream does not.
# - PowerShell has no backslash escape, so a Windows path ending in ``\``
-# does not extend a quoted run the way the POSIX rules here assume.
+# does not extend a quoted run the way the POSIX rules here assume, and
+# the lexer would split the command in a place PowerShell would not.
+# - Defense in depth on the renderer. ``distill_cmd._render_command`` now
+# caret-escapes what it hands cmd.exe, but it still has to refuse a
+# couple of shapes outright (a ``%NAME%`` cmd would expand, an embedded
+# newline). A rewrite is auto-allowed, so this side stays conservative
+# rather than depending on the far side getting every case right.
#
# So the lexer's false-bail win is a POSIX win. On Windows it still buys the
# structural bailouts, just not the widening.
diff --git a/tests/unit/distill/test_cli.py b/tests/unit/distill/test_cli.py
index 570f5fb6c..dfe2f1b81 100644
--- a/tests/unit/distill/test_cli.py
+++ b/tests/unit/distill/test_cli.py
@@ -2,8 +2,10 @@
from __future__ import annotations
+import json
import os
import shlex
+import subprocess
import sys
from pathlib import Path
@@ -96,15 +98,126 @@ def test_render_command_quotes_shell_metacharacters() -> None:
pipeline. POSIX ``shlex.join`` gets it right. Windows
``list2cmdline`` quotes for the C runtime's argv parser rather than for
cmd.exe, so a metacharacter with no surrounding space rides through
- unquoted — which is exactly why the hook refuses those commands outright
- on non-POSIX hosts (see
- ``test_rewrite_hook.py::test_quoted_metacharacters_still_bail_on_windows``).
+ unquoted; ``_render_command`` caret-escapes the rendered line to close
+ that.
"""
rendered = _render_command(("git", "log", "--grep=a&&b"))
if os.name == "posix":
assert rendered == "git log '--grep=a&&b'"
else:
- assert rendered == "git log --grep=a&&b"
+ assert rendered == "git log --grep=a^&^&b"
+
+
+def test_render_command_passes_a_single_token_through() -> None:
+ """One token means the user quoted the command themselves; that is intent."""
+ assert _render_command(("pytest -x | head -5",)) == "pytest -x | head -5"
+
+
+ "payload",
+ [
+ "--grep=a&whoami",
+ "--grep=a|whoami",
+ "--grep=a>rendered_should_not_write.txt",
+ "--grep=a;b",
+ "plain",
+ "has space",
+ 'say "hi" now',
+ 'a"b&c',
+ "a^b",
+ "a(b)c",
+ "trailing\\back\\slash\\",
+ "--format=%H",
+ "--format=%h%n%s",
+ "a!USERNAME!b",
+ "café中文",
+ "",
+ "^",
+ "a\tb",
+ ],
+)
+def test_render_command_roundtrips_argv_through_the_shell(payload: str, tmp_path: Path) -> None:
+ """The rendered string must hand the child exactly the token we started with.
+
+ This is the real contract: ``_render_command`` output goes straight to
+ ``subprocess.run(..., shell=True)``, so anything the shell reinterprets
+ is a command the user never typed. Asserting on the rendered string
+ alone did not catch the cmd.exe metacharacter hole, so this one runs the
+ render and reads the child's ``sys.argv`` back.
+ """
+ tokens = (sys.executable, "-c", "import sys,json;print(json.dumps(sys.argv[1:]))", payload)
+ proc = subprocess.run(
+ _render_command(tokens),
+ shell=True,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ cwd=tmp_path,
+ timeout=60,
+ )
+
+ assert proc.returncode == 0, proc.stderr
+ assert json.loads(proc.stdout.strip().splitlines()[-1]) == [payload]
+ # A redirect that reached the shell would have written a file instead.
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_render_command_keeps_an_executable_path_with_spaces_intact(tmp_path: Path) -> None:
+ """The program name needs real grouping quotes, not caret-escaped ones.
+
+ cmd.exe resolves the executable before caret processing, so escaping the
+ quotes around ``C:\\Program Files\\...`` splits the path at its first
+ space and the command does not run at all. This is the ``.cmd``-shim case
+ that ``shell=True`` exists to support.
+ """
+ shim_dir = tmp_path / "with space"
+ shim_dir.mkdir()
+ shim = shim_dir / "my shim.cmd"
+ # Echoes a fixed marker rather than %*: a batch file re-parses whatever %*
+ # expands to, which is the shim's own hazard and would not be testing the
+ # renderer. Argument fidelity is covered by the parametrized test above.
+ shim.write_text("@echo SHIM_OK\n", encoding="utf-8")
+
+ proc = subprocess.run(
+ _render_command((str(shim), "arg one", "a&b")),
+ shell=True,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ cwd=tmp_path,
+ timeout=60,
+ )
+
+ assert proc.returncode == 0, proc.stderr or proc.stdout
+ assert "SHIM_OK" in proc.stdout
+
+
[email protected](sys.platform != "win32", reason="cmd.exe rendering rules")
+def test_render_command_refuses_a_defined_env_var_expansion(monkeypatch) -> None:
+ """cmd expands %VAR% and re-parses the result, so a metacharacter in the
+ value is command execution. There is no escape for it, so refuse."""
+ monkeypatch.setenv("REPOWISE_TEST_EVIL", "x&echo pwned")
+ with pytest.raises(Exception, match="REPOWISE_TEST_EVIL"):
+ _render_command(("git", "log", "--grep=%REPOWISE_TEST_EVIL%"))
+
+
[email protected](sys.platform != "win32", reason="cmd.exe rendering rules")
+def test_render_command_allows_an_undefined_percent_pair(monkeypatch) -> None:
+ """`git log --format=%h%n%s` reads as %h% to cmd but expands to nothing."""
+ monkeypatch.delenv("h", raising=False)
+ monkeypatch.delenv("n", raising=False)
+ assert "%h%n%s" in _render_command(("git", "log", "--format=%h%n%s"))
+
+
[email protected](sys.platform != "win32", reason="cmd.exe rendering rules")
[email protected]("payload", ["a\nb", "a\r\nb", "a\rb"])
+def test_render_command_refuses_newlines(payload: str) -> None:
+ """cmd truncates the command line at a newline and drops a bare CR, both
+ silently, so the child would get a quietly different argv."""
+ with pytest.raises(Exception, match="newline"):
+ _render_command(("git", "log", f"--grep={payload}"))
def test_distill_and_expand_roundtrip(repo_cwd: Path, fixtures_dir: Path) -> None:
diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.py
index 716ee7966..46dea6cb9 100644
--- a/tests/unit/distill/test_rewrite_hook.py
+++ b/tests/unit/distill/test_rewrite_hook.py
@@ -252,13 +252,13 @@ class TestSafeTails:
],
)
def test_quoted_metacharacters_still_bail_on_windows(self, command, windows_host) -> None:
- """Quoting does not protect these once distill re-renders the argv.
+ """Windows gives up the false-bail win to stay conservative here.
- ``subprocess.list2cmdline`` quotes an argument only when it holds a
- space, so ``--grep=a&whoami`` reaches cmd.exe unquoted and the ``&``
- separates two commands. The rewrite is auto-allowed, so a wrong
- answer here runs something the user never typed — Windows keeps the
- blunt character bail and gives up the false-bail win.
+ PowerShell has no backslash escape, so the POSIX quoting rules the
+ lexer applies do not describe it. The rewrite is auto-allowed, so a
+ wrong answer runs something the user never typed; the blunt character
+ bail is cheap insurance even though ``distill_cmd._render_command``
+ now escapes what it passes to cmd.exe.
"""
assert classify(command) is None
diff --git a/tests/unit/distill/test_saved_cmd.py b/tests/unit/distill/test_saved_cmd.py
index 2239aafdc..bd16da064 100644
--- a/tests/unit/distill/test_saved_cmd.py
+++ b/tests/unit/distill/test_saved_cmd.py
@@ -8,6 +8,7 @@ from pathlib import Path
import pytest
from click.testing import CliRunner
+from repowise.cli.commands import saved_cmd
from repowise.cli.commands.saved_cmd import saved_command
from repowise.core.distill import tracking
from repowise.core.distill.store import OmissionStore
@@ -198,3 +199,38 @@ def test_saved_explicit_path_argument(tmp_path: Path) -> None:
result = CliRunner().invoke(saved_command, [str(repo)])
assert result.exit_code == 0
assert "test_output" in result.output
+
+
+def test_missed_tip_offers_install_when_hook_is_absent(monkeypatch) -> None:
+ monkeypatch.setattr(saved_cmd, "_rewrite_hook_installed", lambda: False)
+ assert "repowise hook rewrite install" in saved_cmd._missed_tip()
+
+
+def test_missed_tip_does_not_nag_when_hook_is_already_installed(monkeypatch) -> None:
+ """The old tip claimed installing would catch these rows even when the
+ hook was already installed, which hid the real reason they are there."""
+ monkeypatch.setattr(saved_cmd, "_rewrite_hook_installed", lambda: True)
+ tip = saved_cmd._missed_tip()
+ assert "repowise hook rewrite install" not in tip
+ assert "repowise distill" in tip
+
+
+def test_missed_tip_names_the_opt_out_when_the_repo_declined(monkeypatch, tmp_path: Path) -> None:
+ """An opted-out repo has a different reason again, and doctor says so too."""
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "distill:\n commands:\n enabled: false\n", encoding="utf-8"
+ )
+ monkeypatch.setattr(saved_cmd, "_rewrite_hook_installed", lambda: True)
+ assert "opted out" in saved_cmd._missed_tip(tmp_path)
+
+
+def test_rewrite_hook_installed_degrades_to_false(monkeypatch) -> None:
+ """A broken or absent adapter must not break `saved --missed`."""
+ import repowise.cli.agent_adapters.claude_code as cc
+
+ def boom(self):
+ raise RuntimeError("no adapter here")
+
+ monkeypatch.setattr(cc.ClaudeCodeAdapter, "rewrite_hook_installed", boom)
+ assert saved_cmd._rewrite_hook_installed() is False