#!/usr/bin/env bash set -euo pipefail # Clause 1, and ONLY clause 1, of the rtk-prefix rule: an executable, instructed # local git command in plugin skill or agent content is written `rtk git`, never # bare `git`. The rule and its rationale are in # docs/adr/0023-rtk-prefix-marks-executable-commands-only.md. # # WHY THIS IS NARROW ON PURPOSE. The rule 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 `" 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 ` 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 marker `rtk-bare:` on the SAME LINE, followed by the reason # — in a shell comment for a code line, in the cell text for a table row. The # marker is neutral on purpose: plugin content is consumed by other repos, so it # must not cite this repo's ADRs. 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* # `rtk-bare:` 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 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 = "rtk-bare:" SHELL_INFO = {"bash", "sh", "shell", "zsh", "console", "shell-session"} FENCE_OPEN = re.compile(r"^\s*(?P`{3,}|~{3,})\s*(?P[^\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"check-rtk-prefix: {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 `. If this command must stay bare because rtk rewrites\n" "output the skill parses, or because it is interactive, record the opt-out on the same\n" "line as `rtk-bare: ` (e.g. `# rtk-bare: the output is parsed`).", file=sys.stderr, ) sys.exit(1) PY