Files
holocron/scripts/check-rtk-prefix.sh
Defame1297 ed8c99efbd fix(git): stop prefixing rtk where it rewrites the output skills parse
The #113 sweep rested on CLAUDE.md's premise that rtk either filters or passes through unchanged,
so prefixing is always safe. Measured against rtk 0.42.4, that premise is false for several of the
commands the sweep prefixed, and two skills were left giving wrong answers silently.

Why:
- `rtk git worktree list --porcelain -z` discards both flags and renders its own format. The
  `locked`/`lock_reason` fields git-worktrees Step 2 must emit are absent entirely, and paths under
  $HOME are abbreviated to `~/`.
- `rtk git branch --list <name>` prints a phantom `* ` line even when nothing matches, so
  git-branches' stated ambiguity test — "output from both means the name is ambiguous" — reported
  every name as ambiguous. `tag --list` is a clean passthrough, so only one half broke.
- `rtk git diff --name-only`/`--name-status` append a `Changes:` trailer to output documented as
  "one per line"; `--word-diff` emits none of the `[-removed-] {+added+}` markers its table
  describes; `rtk git log -L` truncates each line at ~72 chars, on the one command whose purpose is
  showing line content.
- `rtk git stash pop` prints only `FAILED: git stash pop`, swallowing the conflict diagnostic and
  retained-entry message the surrounding prose tells the agent to rely on.

Implementation notes:
- Eleven sites reverted to bare `git`, each carrying its reason inline so the next sweep does not
  undo it. `mergetool` and `rebase -i` are reverted on clause 3's interactive limb only: the TTY
  defect does not reproduce — rtk filters exactly twelve subcommands and execs the rest — and
  ADR-0023 records that measurement rather than a convenient one.
- ADR-0023 states the rule repo-wide with a third clause: a command whose output the skill parses,
  or which is interactive, stays bare. `plugins/git/README.md` is reduced to a pointer; its claim
  that gitea skills "contain no git/rtk mentions at all" was false, and its citation of
  `hard-rules.md` pointed at a file containing no occurrence of "rtk".
- Eight gitea sites swept, all verified byte-identical passthroughs first.
- `scripts/check-rtk-prefix.sh` gates clause 1. Run against main's pre-sweep corpus it reports 99
  findings including every gitea site, so it would have caught the drift #113 was filed about.

Impact: the gate covers clause 1 only, in shell-tagged fences and the opening span of Run cells.
Clause 2 is not gateable — "Run `git switch`" and "`git switch` refuses" are the same tokens — and
prose bullets are invisible to it. Both limits are recorded in gates.md rather than left implied.

Refs: #113
ADR: 0023
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EeH8SCbcrCAQrtymkNuhKP
2026-09-09 05:14:54 +00:00

199 lines
7.7 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# ADR-0023 clause 1, and ONLY clause 1: an executable, instructed local git
# command in plugin skill or agent content is written `rtk git`, never bare
# `git`.
#
# WHY THIS IS NARROW ON PURPOSE. ADR-0023 has three clauses, and only the first
# is machine-decidable:
#
# 1. executable + instructed -> `rtk git` <- this hook
# 2. illustrative/referential -> bare `git` <- undecidable, not gated
# 3. machine-parsed or interactive -> bare `git`, marked <- opt-out, below
#
# Clause 2 is a judgement about what a sentence is doing, not a pattern. "`git
# switch` refuses rather than clobbering conflicting local edits" and "run `git
# switch <branch>`" are the same token sequence in prose. A gate that guessed
# would fire on every doc paragraph in the corpus, and a gate that fires on
# correct content gets disabled. So this hook looks only at the two places where
# a `git` mention is unambiguously an instruction to execute:
#
# (a) a line inside a fenced code block whose info string names a shell
# (bash / sh / shell / zsh / console);
# (b) the OPENING backticked span of a "Run" column cell in a markdown
# dispatch table -- and only the opening span.
#
# (b) is that narrow because a Run cell routinely carries a command followed by
# prose about it, and that prose is clause 2. git-worktrees/SKILL.md has both
# shapes on adjacent rows: a cell reading `rtk git worktree add --track ...` --
# always correct. `git worktree add <path> <branch>` expands to exactly this
# (instruction first, reference second), and a `**Never** ...` row whose Run cell
# is entirely explanatory prose containing a bare `git push`. Checking every span
# flags both; checking only a leading span flags neither, and still catches the
# ordinary `| List | `git worktree list -v` |` case this gate exists for.
#
# Prose bullets, prose-leading Run cells, table cells outside a Run column, and
# fences tagged `text`, `yaml`, `json` etc. are NOT checked. That is a real
# coverage gap, recorded in docs/spec/gates.md rather than papered over.
#
# CLAUSE-3 OPT-OUT. A site that is deliberately bare because rtk rewrites the
# output the skill parses, or because the command is interactive, is exempted by
# putting the literal string `ADR-0023` on the SAME LINE — in a shell comment for
# a code line, in the cell text for a table row. Per-line, never per-block: a
# fenced block routinely mixes `rtk git` steps with one deliberately-bare
# command (references/push.md does exactly that), and a block-level marker would
# silently disarm the checked lines around the marked one.
#
# The marker is a bare substring match, so a line that merely *mentions*
# ADR-0023 for an unrelated reason is also exempt. That is accepted: the marker
# is an author's deliberate opt-out, not a security boundary, and a stricter
# form would only move the same trust to a different string.
if [[ $# -eq 0 ]]; then
exit 0
fi
if ! command -v python3 > /dev/null 2>&1; then
echo "ERROR: python3 is required for the ADR-0023 rtk-prefix gate but was not found on PATH." >&2
echo " Fix: install python3 (pre-commit itself is a Python application, so it is almost certainly already present)." >&2
exit 1
fi
# No PyYAML here, unlike skill-size-check.sh: this gate never reads frontmatter,
# only the markdown body, so it has no folded scalar to measure.
exec python3 -u - "$@" <<'PY'
import re
import sys
MARKER = "ADR-0023"
SHELL_INFO = {"bash", "sh", "shell", "zsh", "console", "shell-session"}
FENCE_OPEN = re.compile(r"^\s*(?P<f>`{3,}|~{3,})\s*(?P<info>[^\s`]*)")
ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=\S*\s+")
# Shell separators that begin a fresh command word.
SPLIT = re.compile(r"(?:\|\||&&|[;|&\n]|\$\(|`|\()")
BACKTICKED = re.compile(r"`([^`]+)`")
def strip_shell_comment(line: str) -> str:
"""Drop a trailing `#` comment, ignoring `#` inside single/double quotes."""
out = []
quote = None
prev = ""
for ch in line:
if quote:
if ch == quote and prev != "\\":
quote = None
elif ch in "'\"":
quote = ch
elif ch == "#" and (not out or out[-1].isspace()):
break
out.append(ch)
prev = ch
return "".join(out)
def bare_git_in_shell(code: str) -> bool:
for segment in SPLIT.split(code):
seg = segment.lstrip()
if seg.startswith("$ "): # a copied prompt
seg = seg[2:].lstrip()
while True: # VAR=x VAR2=y git ...
m = ASSIGNMENT.match(seg)
if not m:
break
seg = seg[m.end():]
if re.match(r"git(\s|$)", seg):
return True
return False
def run_column(header: str):
"""Index of the 'Run' column in a markdown header row, or None."""
cells = [c.strip().strip("`*_ ").lower() for c in header.strip().strip("|").split("|")]
return cells.index("run") if "run" in cells else None
def check(path: str):
problems = []
try:
lines = open(path, encoding="utf-8").read().splitlines()
except (OSError, UnicodeDecodeError) as exc:
# Unreadable is an error, never a silent pass.
return [(0, f"could not read file: {exc}")]
fence = None # closing marker of the open fence, or None
fence_is_shell = False
run_col = None # active Run-column index, or None
pending_header = None
for n, raw in enumerate(lines, start=1):
if fence is not None:
if re.match(r"^\s*" + re.escape(fence) + r"\s*$", raw):
fence, fence_is_shell = None, False
continue
if fence_is_shell and MARKER not in raw:
if bare_git_in_shell(strip_shell_comment(raw)):
problems.append((n, raw.strip()))
continue
m = FENCE_OPEN.match(raw)
if m:
fence = m.group("f")
fence_is_shell = m.group("info").lower() in SHELL_INFO
run_col, pending_header = None, None
continue
stripped = raw.strip()
if not stripped.startswith("|"):
run_col, pending_header = None, None
continue
# A markdown table: header row, delimiter row, then data rows.
if run_col is None:
if pending_header is not None and set(stripped) <= set("|-: "):
run_col = run_column(pending_header)
pending_header = None
else:
pending_header = stripped
run_col = None
continue
if MARKER in raw:
continue
cells = stripped.strip("|").split("|")
if run_col >= len(cells):
continue
cell = cells[run_col].strip()
# Only a cell that OPENS with a backticked command is a dispatch entry.
# A cell opening with prose is explanation, and explanation is clause 2.
if not cell.startswith("`"):
continue
opening = BACKTICKED.match(cell)
if opening and re.match(r"git(\s|$)", opening.group(1).strip()):
problems.append((n, opening.group(1).strip()))
return problems
failed = False
for path in sys.argv[1:]:
for line_no, text in check(path):
failed = True
print(
f"ADR-0023: {path}:{line_no}: executable git command is not prefixed with `rtk`: {text}",
file=sys.stderr,
)
if failed:
print("", file=sys.stderr)
print(
"Fix: write `rtk git <subcommand>` (ADR-0023 clause 1). If this command must stay bare\n"
"because rtk rewrites output the skill parses, or because it is interactive (clause 3),\n"
"say so inline and put the literal string ADR-0023 on the same line to record the opt-out.",
file=sys.stderr,
)
sys.exit(1)
PY