diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index ce0e017..165546c 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -14,6 +14,11 @@ "name": "security-tools", "source": "./plugins/security-tools", "description": "Harden GitHub Actions workflows against supply-chain and injection attacks." + }, + { + "name": "pr-tools", + "source": "./plugins/pr-tools", + "description": "Open well-formed GitHub pull requests from Claude Code and attach screenshots and recordings to them." } ] } diff --git a/README.md b/README.md index afdfd23..9ce4dee 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Add the marketplace, then install the plugin you want: - **[skill-tools](./plugins/skill-tools/)** — Tools for authoring and reviewing Claude Code skills. Includes the `skill-review` skill, which reviews skills against a closed 7-category quality rubric (Structural Discipline, Integrity, Test Coverage, Security, Content Quality, Convention, Cost) with structured JSON output and a determinism contract. - **[security-tools](./plugins/security-tools/)** — Harden GitHub Actions workflows against supply-chain and injection attacks. Includes the `secure-github-actions` skill (a 14-rule review checklist plus audit commands) and a hook that auto-loads it when you edit a workflow file. +- **[pr-tools](./plugins/pr-tools/)** — Open well-formed GitHub pull requests from Claude Code and attach screenshots and recordings to them. Includes `create-pr` (intent-gathering, diff validation, public-repo safeguards) and `attach-github-assets` (upload local images/recordings to GitHub for use in PR and issue markdown). ## License diff --git a/plugins/pr-tools/.claude-plugin/plugin.json b/plugins/pr-tools/.claude-plugin/plugin.json new file mode 100644 index 0000000..86707d1 --- /dev/null +++ b/plugins/pr-tools/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "pr-tools", + "version": "0.1.0", + "description": "Open well-formed GitHub pull requests from Claude Code and attach screenshots and recordings to them.", + "author": { + "name": "Fin 2x" + }, + "keywords": [ + "github", + "pull-request", + "pr", + "workflow" + ], + "license": "MIT" +} diff --git a/plugins/pr-tools/CHANGELOG.md b/plugins/pr-tools/CHANGELOG.md new file mode 100644 index 0000000..4994fd4 --- /dev/null +++ b/plugins/pr-tools/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to the `pr-tools` plugin are documented here. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.0] - 2026-07-07 + +### Added + +- Initial release of the `pr-tools` plugin. +- `create-pr` skill — opens or updates a well-formed GitHub pull request for the current branch, with intent-gathering, diff validation, and public-repo safeguards. +- `attach-github-assets` skill — uploads local screenshots and recordings to GitHub and returns markdown-ready URLs. diff --git a/plugins/pr-tools/LICENSE b/plugins/pr-tools/LICENSE new file mode 100644 index 0000000..3970429 --- /dev/null +++ b/plugins/pr-tools/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Intercom + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/pr-tools/README.md b/plugins/pr-tools/README.md new file mode 100644 index 0000000..c76459d --- /dev/null +++ b/plugins/pr-tools/README.md @@ -0,0 +1,25 @@ +# pr-tools + +Open well-formed GitHub pull requests from Claude Code and attach screenshots and recordings to them. + +Part of the [`fin-2x`](../../README.md) marketplace. + +## Install + +``` +/plugin marketplace add intercom/2x-skills +/plugin install pr-tools@fin-2x +``` + +## Skills + +- **[attach-github-assets](./skills/attach-github-assets/)** — Upload local files (screenshots, screen recordings, images, videos) to GitHub as user-attachment assets and return markdown-ready URLs for PR descriptions, issue bodies, or PR/issue comments. +- **[create-pr](./skills/create-pr/)** — Open or update a well-formed GitHub pull request for the current branch: gathers intent, validates the diff against it, applies public-repo safeguards, and writes a clean Why/How description. + +## Hooks + +`pr-tools` installs a `PreToolUse` hook that intercepts direct `gh pr create` calls and redirects you to the `create-pr` skill, so PRs go through its intent-gathering and public-repo safeguards. Once `create-pr` is loaded in the session, `gh pr create` runs normally. The hook only matches real invocations (not `gh pr create` mentioned inside a quoted string or heredoc), fails open on any ambiguity, and clears its per-session state on context compaction. + +## License + +MIT diff --git a/plugins/pr-tools/hooks/clear-skill-markers-on-compact.sh b/plugins/pr-tools/hooks/clear-skill-markers-on-compact.sh new file mode 100755 index 0000000..ef84c6b --- /dev/null +++ b/plugins/pr-tools/hooks/clear-skill-markers-on-compact.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# PreCompact hook that clears skill activation markers. +# +# After context compaction, the agent loses awareness of previously loaded +# skills. Without clearing markers, the intercept-gh-pr-create hook would +# still find a stale marker and allow gh pr create through — even though +# the agent no longer has the create-pr skill instructions in context. + +hook_data=$(cat) + +if [[ "$hook_data" =~ \"session_id\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + session_id="${BASH_REMATCH[1]}" +else + exit 0 +fi + +# Clear both session-scoped and agent-scoped markers +marker_dir="/tmp/activated-skills/${session_id}" +if [[ -d "$marker_dir" ]]; then + rm -rf "$marker_dir" +fi + +exit 0 diff --git a/plugins/pr-tools/hooks/hooks.json b/plugins/pr-tools/hooks/hooks.json new file mode 100644 index 0000000..0c8a4ef --- /dev/null +++ b/plugins/pr-tools/hooks/hooks.json @@ -0,0 +1,25 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Skill", + "hooks": [ + { "type": "command", "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/track-skill-activation.sh\"" } + ] + }, + { + "matcher": "Bash", + "hooks": [ + { "type": "command", "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/intercept-gh-pr-create.sh\"" } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { "type": "command", "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/clear-skill-markers-on-compact.sh\"" } + ] + } + ] + } +} diff --git a/plugins/pr-tools/hooks/intercept-gh-pr-create.sh b/plugins/pr-tools/hooks/intercept-gh-pr-create.sh new file mode 100755 index 0000000..58448de --- /dev/null +++ b/plugins/pr-tools/hooks/intercept-gh-pr-create.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# PreToolUse hook that intercepts gh pr create and redirects to create-pr skill +# +# Blocks direct `gh pr create` unless the create-pr skill has already been +# activated in this session. Activation is tracked via marker files written +# by track-skill-activation.sh (deterministic, no transcript grepping). +# +# Markers are cleared on context compaction (by clear-skill-markers-on-compact.sh) +# so the agent must re-invoke the skill after compaction. +# +# `/rewind`, however, fires NO hook, so a marker is NOT cleared when the user +# rewinds the conversation back past the create-pr load — leaving the guard +# permanently satisfied even though the skill is no longer in context. To close +# that gap, when a session-scoped marker is found we re-validate it against the +# current branch of the transcript (skill-active-in-transcript.py): the marker +# only counts if the create-pr Skill tool_use is still an ancestor of the latest +# leaf. We fail OPEN (honour the marker) whenever validation is inconclusive, so +# this can only ever re-block a load that was provably rewound away — never a +# legitimate in-context activation. + +# Read hook event data from stdin +hook_data=$(cat) + +# Extract tool name and command from the JSON +tool_name=$(echo "$hook_data" | jq -r '.tool_name // empty' 2>/dev/null) +command=$(echo "$hook_data" | jq -r '.tool_input.command // empty' 2>/dev/null) + +# Only intercept Bash tool calls +if [[ "$tool_name" != "Bash" ]]; then + exit 0 +fi + +# Strip single-quoted, double-quoted, and heredoc-delimited content before +# matching so that the phrase inside a quoted flag value or heredoc body +# isn't treated as a real invocation. Logic lives in a sibling helper so +# it can be tested (and reused) on its own. +HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +STRIP_HELPER="${HOOK_DIR}/../scripts/strip-quoted-and-heredocs.py" +SKILL_ACTIVE_HELPER="${HOOK_DIR}/../scripts/skill-active-in-transcript.py" + +cleaned_command=$(printf '%s' "$command" | python3 "$STRIP_HELPER") + +# Check if the cleaned command contains "gh pr create" +if [[ "$cleaned_command" =~ gh[[:space:]]+pr[[:space:]]+create ]]; then + # Allow if the create-pr skill has been activated in this session + # Pure bash JSON extraction — matches track-skill-activation.sh approach + # Regex handles both minified and pretty-printed JSON + if [[ "$hook_data" =~ \"session_id\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + session_id="${BASH_REMATCH[1]}" + else + # Can't determine session — don't block + exit 0 + fi + + # Check agent-scoped markers first (subagent context), then session-scoped + if [[ "$hook_data" =~ \"agent_id\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + agent_marker_dir="/tmp/activated-skills/${session_id}/${BASH_REMATCH[1]}" + if [[ -f "${agent_marker_dir}/create-pr" || -f "${agent_marker_dir}/pr-tools:create-pr" ]]; then + exit 0 + fi + else + marker_dir="/tmp/activated-skills/${session_id}" + if [[ -f "${marker_dir}/create-pr" || -f "${marker_dir}/pr-tools:create-pr" ]]; then + # Marker present. Re-validate it against the current transcript branch + # so a marker left behind by a /rewind (which fires no hook, so it is + # never cleared) doesn't keep the guard satisfied after the create-pr + # load was rewound out of context. Fail OPEN unless the load is + # provably absent from the active branch (helper exit code 1). + if [[ "$hook_data" =~ \"transcript_path\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + transcript_path="${BASH_REMATCH[1]}" + else + transcript_path="" + fi + + if [[ -n "$transcript_path" && -f "$transcript_path" ]] && command -v python3 >/dev/null 2>&1; then + python3 "$SKILL_ACTIVE_HELPER" "$transcript_path" create-pr + if [[ "$?" -ne 1 ]]; then + # 0 = create-pr still active in this branch; 2 = undetermined. + # Either way, honour the marker. + exit 0 + fi + # Exit 1: create-pr was rewound away — fall through and re-block. + else + # No transcript available to validate — preserve prior behaviour. + exit 0 + fi + fi + fi + + echo "❌ Direct gh pr create detected - use the create-pr skill instead. + +Use: Skill(skill: \"pr-tools:create-pr\") + +The create-pr skill ensures proper PR descriptions by: +- Extracting intent from the session (asks if missing) +- Following the Why?/How? format standard +- Creating meaningful documentation" >&2 + exit 2 +fi + +# Command is allowed +exit 0 diff --git a/plugins/pr-tools/hooks/track-skill-activation.sh b/plugins/pr-tools/hooks/track-skill-activation.sh new file mode 100755 index 0000000..6baa146 --- /dev/null +++ b/plugins/pr-tools/hooks/track-skill-activation.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Synchronous PreToolUse:Skill hook that records skill activations. +# +# Writes a marker file per session+skill so other hooks can deterministically +# check whether a given skill has been loaded in this session. +# +# Marker location: /tmp/activated-skills/{session_id}/{skill_name} +# /tmp/activated-skills/{session_id}/{agent_id}/{skill_name} (inside subagents) +# +# Markers are cleared on context compaction (by clear-skill-markers-on-compact.sh) +# so the agent must re-invoke skills after compaction. +# +# This replaces the old approach of grepping the transcript for skill names, +# which caused false positives when file contents happened to mention a skill. + +hook_data=$(cat) + +# Pure bash JSON extraction — avoids jq overhead on every Skill call +# Regex handles both minified ("key":"val") and pretty-printed ("key": "val") JSON +if [[ "$hook_data" =~ \"session_id\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + session_id="${BASH_REMATCH[1]}" +else + exit 0 +fi + +if [[ "$hook_data" =~ \"skill\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + skill_name="${BASH_REMATCH[1]}" +else + exit 0 +fi + +# Scope markers to agent_id when running inside a subagent, so that a skill +# activated in one agent doesn't unlock guarded commands for other agents. +if [[ "$hook_data" =~ \"agent_id\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + marker_dir="/tmp/activated-skills/${session_id}/${BASH_REMATCH[1]}" +else + marker_dir="/tmp/activated-skills/${session_id}" +fi +mkdir -p "$marker_dir" +touch "${marker_dir}/${skill_name}" + +# Clean up stale session dirs older than 24h +find /tmp/activated-skills -mindepth 1 -maxdepth 1 -type d -mtime +1 -exec rm -rf {} + 2>/dev/null & + +exit 0 diff --git a/plugins/pr-tools/scripts/skill-active-in-transcript.py b/plugins/pr-tools/scripts/skill-active-in-transcript.py new file mode 100755 index 0000000..7867db1 --- /dev/null +++ b/plugins/pr-tools/scripts/skill-active-in-transcript.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Check whether a skill is still active on the CURRENT branch of a transcript. + +Claude Code transcripts are an append-only DAG: every event carries a ``uuid`` +and ``parentUuid``. A ``/rewind`` (or an edited/retried turn) starts a new branch +from an earlier node — the abandoned branch's events physically REMAIN in the +.jsonl file. ``/rewind`` fires no hook, so the skill-activation marker written by +track-skill-activation.sh is never cleared when the user rewinds past a skill load. + +This helper lets intercept-gh-pr-create.sh re-validate a marker: a skill counts as +active only if its activation sits in the ancestry of the current (latest) +main-conversation leaf. A load that was rewound away lives on an abandoned branch +and is therefore NOT an ancestor, so the guard can correctly re-engage. + +A skill can be activated two ways, both of which write the same marker: + * the ``Skill`` tool (PreToolUse:Skill -> track-skill-activation.sh) — appears as + an assistant ``tool_use`` block named "Skill"; + * a ``/skill`` slash command (UserPromptSubmit -> track-skill-slash-command.sh) — + expanded inline, so it appears as a user message whose text begins with the raw + slash command (e.g. ``/create-pr`` or ``/pr-tools:create-pr``) or carries + a synthesized ```` tag. Both forms are recognised here. + +Matching these structured signals (not a bare substring) avoids the false positives +that originally motivated replacing transcript grepping with markers. + +SAFETY: this helper must FAIL OPEN. It returns 1 ("block") only on a confident, +fully-parsed "absent" determination. Any ambiguity — unreadable/undecodable file, +any line that failed to parse, a dangling parent chain, or an unexpected error — +returns 2 so the caller honours the marker. An uncaught exception would exit 1 and +be misread as "absent", so everything runs under a guard that converts errors to 2. + +Usage: skill-active-in-transcript.py + +Exit codes (consumed by the caller, which fails OPEN on anything but 1): + 0 skill IS active in the current branch -> allow + 1 skill is POSITIVELY absent (rewound away) -> let the caller block + 2 undetermined (missing/empty/unreadable/parse error/ambiguous) -> caller fails open +""" +import re +import sys + +UNDETERMINED = 2 + +# Matches the raw slash-command form at the start of a prompt, mirroring +# base/hooks/track-skill-slash-command.sh (which writes the marker). +_SLASH_RE = re.compile(r"^\s*/([A-Za-z0-9_:.-]+)") +# Matches a synthesized /skill tag anywhere. +_CMD_NAME_RE = re.compile(r"\s*/?([A-Za-z0-9_:.-]+)") + + +def _skill_component(value): + """Normalise 'pr-tools:create-pr' / 'create-pr' -> 'create-pr'.""" + if not isinstance(value, str): + return None + return value.split(":")[-1].strip() + + +def _text_of(content): + """Best-effort plain text for a message's content (string or block list).""" + if isinstance(content, str): + return content + if isinstance(content, list): + parts = [] + for block in content: + if isinstance(block, dict) and isinstance(block.get("text"), str): + parts.append(block["text"]) + return "\n".join(parts) + return "" + + +def _is_skill_tool_load(entry, skill_name): + """True if entry is a main-conversation assistant Skill tool_use for skill_name.""" + if entry.get("isSidechain") is True or entry.get("isVisibleInTranscriptOnly") is True: + return False + msg = entry.get("message") + if not isinstance(msg, dict): + return False + content = msg.get("content") + if not isinstance(content, list): + return False + for block in content: + if not isinstance(block, dict): + continue + if block.get("type") != "tool_use" or block.get("name") != "Skill": + continue + tool_input = block.get("input") + if not isinstance(tool_input, dict): + continue # wrong-shaped input: ignore this block, never crash + for key in ("command", "skill", "skill_name"): + if _skill_component(tool_input.get(key)) == skill_name: + return True + return False + + +def _is_slash_load(entry, skill_name): + """True if entry is a user message that activated skill_name via slash command. + + Claude Code stores a slash invocation as a synthesized command block — the + message text begins with / tags (verified + against real transcripts). We only trust a tag when the message + actually IS such a block (text starts with the tag), so user-authored prose + that merely quotes `/create-pr` cannot spoof an + activation and bypass the guard. The raw `/skill` form is also accepted, but + only anchored at the very start of the message. + + KNOWN LIMITATION: Claude Code stores no field distinguishing a synthesized + slash block from user-typed text, so a user who already holds a stale marker + could in principle bypass the guard by sending a message that begins with a + literal `/create-pr`. This is accepted: the guard + is a workflow nudge, not a boundary against the operator themselves (who can + disable the hook or call `gh api` directly), and recognising genuine slash + activations avoids false-blocking the common `/create-pr` path — a strictly + better trade than refusing to honour slash loads at all.""" + if entry.get("isSidechain") is True or entry.get("isVisibleInTranscriptOnly") is True: + return False + if entry.get("type") != "user": + return False + msg = entry.get("message") + text = _text_of(msg.get("content")) if isinstance(msg, dict) else "" + if not text: + return False + + # Raw form: the message is exactly the slash command (anchored at start). + m = _SLASH_RE.match(text) + if m and _skill_component(m.group(1)) == skill_name: + return True + + # Synthesized form: only trust it when the message is genuinely a command + # block, i.e. it opens with the command tags rather than merely mentioning one. + stripped = text.lstrip() + if stripped.startswith("") or stripped.startswith(""): + for name in _CMD_NAME_RE.findall(text): + if _skill_component(name) == skill_name: + return True + return False + + +def _evaluate(path, skill_name): + try: + # errors="replace" so undecodable bytes never raise (fail-open intent). + with open(path, "r", errors="replace") as fh: + raw_lines = fh.read().splitlines() + except OSError: + return UNDETERMINED + + import json # local import keeps a stray import error inside the guard + + parent_of = {} # uuid -> parentUuid + load_uuids = set() # uuids that activated skill_name (tool or slash) + last_main_uuid = None # latest main-conversation leaf (file order) + parse_failures = 0 + + for line in raw_lines: + line = line.strip() + if not line: + continue + try: + entry = json.loads(line) + except (ValueError, TypeError): + parse_failures += 1 + continue + if not isinstance(entry, dict): + parse_failures += 1 + continue + uuid = entry.get("uuid") + if not uuid: + # A conversation message with no uuid is anomalous — bias to ambiguity + # rather than silently dropping it from the DAG. + if entry.get("type") in ("user", "assistant"): + parse_failures += 1 + continue + # Keep every uuid-bearing record in the parent map so the ancestry chain + # stays connected through interleaved attachment/system nodes... + parent_of[uuid] = entry.get("parentUuid") + # ...but only a real, user-visible conversation message may anchor the + # walk. Transcripts end on trailing records (attachment/system/snapshot) + # that carry uuids, and transcript-only nodes aren't on the live branch; + # starting the walk from any of those could miss an active ancestor. + if ( + entry.get("type") in ("user", "assistant") + and entry.get("isSidechain") is not True + and entry.get("isVisibleInTranscriptOnly") is not True + ): + last_main_uuid = uuid + if _is_skill_tool_load(entry, skill_name) or _is_slash_load(entry, skill_name): + load_uuids.add(uuid) + + if not parent_of or last_main_uuid is None: + return UNDETERMINED # nothing usable -> caller falls back to prior behaviour + + # Walk parentUuid from the current leaf to the root, collecting ancestors. + ancestors = set() + cursor = last_main_uuid + dangling = False + cyclic = False + while cursor is not None: + if cursor in ancestors: + cyclic = True # parent loop -> malformed/ambiguous, not a clean root + break + if cursor not in parent_of: + # Chain references a node we never parsed -> transcript is incomplete. + dangling = True + break + ancestors.add(cursor) + cursor = parent_of[cursor] + + if load_uuids & ancestors: + return 0 # active on the current branch + + # Not found among ancestors. Only re-block if we are confident the transcript + # was complete, fully parsed, and acyclic; any ambiguity stays undetermined + # (fail open) per the safety contract. + if dangling or cyclic or parse_failures: + return UNDETERMINED + return 1 + + +def main(): + if len(sys.argv) < 3: + return UNDETERMINED + try: + return _evaluate(sys.argv[1], sys.argv[2]) + except Exception: + # Never let an unexpected error become exit 1 (which the caller reads as + # "skill absent" and would wrongly block). Any crash fails open. + return UNDETERMINED + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plugins/pr-tools/scripts/strip-quoted-and-heredocs.py b/plugins/pr-tools/scripts/strip-quoted-and-heredocs.py new file mode 100755 index 0000000..ec284f9 --- /dev/null +++ b/plugins/pr-tools/scripts/strip-quoted-and-heredocs.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Strip single-quoted, double-quoted, and heredoc-delimited content from +a shell command read on stdin, writing the stripped result to stdout. + +Pragmatic — not a full bash parser. Intended for hooks that want to check +whether a specific command phrase appears as a real invocation rather than +as text inside a quoted flag value or heredoc body. + +Handled forms: +- Single-quoted segments: '...' (no escape handling — sh semantics) +- Double-quoted segments: "..." (\\" treated as escaped quote) +- Heredocs: <['\"]?)(?P[A-Za-z_][A-Za-z0-9_]*)(?P=q)" +) + + +def strip_heredocs(text: str) -> str: + out: list[str] = [] + pos = 0 + while pos < len(text): + m = HEREDOC_OPEN.search(text, pos) + if not m: + out.append(text[pos:]) + break + out.append(text[pos:m.start()]) + delim = m.group("delim") + after = text[m.end():] + nl = after.find("\n") + if nl < 0: + pos = m.end() + continue + rest = after[nl + 1:] + close = re.search(r"(?m)^[ \t]*" + re.escape(delim) + r"[ \t]*$", rest) + if not close: + pos = m.end() + continue + pos = m.end() + nl + 1 + close.end() + return "".join(out) + + +def strip(text: str) -> str: + text = strip_heredocs(text) + text = re.sub(r'"(?:[^"\\]|\\.)*"', "", text) + text = re.sub(r"'[^']*'", "", text) + return text + + +def main() -> None: + sys.stdout.write(strip(sys.stdin.read())) + + +if __name__ == "__main__": + main() diff --git a/plugins/pr-tools/scripts/tests/intercept-gh-pr-create.bats b/plugins/pr-tools/scripts/tests/intercept-gh-pr-create.bats new file mode 100644 index 0000000..537d630 --- /dev/null +++ b/plugins/pr-tools/scripts/tests/intercept-gh-pr-create.bats @@ -0,0 +1,440 @@ +#!/usr/bin/env bats +# Tests for intercept-gh-pr-create.sh PreToolUse hook + +setup() { + SCRIPT_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/../.." && pwd)" + HOOK_SCRIPT="$SCRIPT_DIR/hooks/intercept-gh-pr-create.sh" + + # Unique per-test session id so marker-file tests stay hermetic + TEST_SESSION="intercept-gh-pr-create-test-${BATS_TEST_NUMBER}-$$" + TEST_MARKER_DIR="/tmp/activated-skills/${TEST_SESSION}" +} + +teardown() { + rm -rf "$TEST_MARKER_DIR" +} + +# Helper: pipe JSON stdin into the hook script, capture exit + output +run_hook() { + echo "$1" | "$HOOK_SCRIPT" 2>&1 +} + +# ============================================================ +# Fast path — non-Bash tools pass through +# ============================================================ + +@test "allows non-Bash tools (Read)" { + run run_hook '{"tool_name":"Read","tool_input":{"file_path":"/etc/hosts"}}' + [ "$status" -eq 0 ] +} + +@test "allows non-Bash tools (Edit)" { + run run_hook '{"tool_name":"Edit","tool_input":{"file_path":"/tmp/test"}}' + [ "$status" -eq 0 ] +} + +# ============================================================ +# True positives — direct invocation still blocked +# ============================================================ + +@test "blocks bare gh pr create" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"gh pr create\"}}" + [ "$status" -eq 2 ] + [[ "$output" == *"create-pr"* ]] +} + +@test "blocks gh pr create with flags (unquoted values)" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"gh pr create --title foo --body bar\"}}" + [ "$status" -eq 2 ] + [[ "$output" == *"create-pr"* ]] +} + +@test "blocks gh pr create with stderr redirect" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"gh pr create 2>&1\"}}" + [ "$status" -eq 2 ] +} + +@test "blocks gh pr create in chained command (cd && ...)" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"cd /tmp && gh pr create\"}}" + [ "$status" -eq 2 ] +} + +@test "blocks gh pr create in chained command (; )" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"cd /tmp ; gh pr create || true\"}}" + [ "$status" -eq 2 ] +} + +@test "blocks gh pr create with title passed via quoted flag (flag is quoted, command is not)" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"gh pr create --title 'My PR'\"}}" + [ "$status" -eq 2 ] +} + +# ============================================================ +# False positives — phrase inside a quoted value or heredoc is allowed +# ============================================================ + +@test "allows phrase inside single-quoted flag value" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"git commit -m 'note about gh pr create behaviour'\"}}" + [ "$status" -eq 0 ] +} + +@test "allows phrase inside double-quoted flag value" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"curl -d \\\"note about gh pr create behaviour\\\" https://example.com\"}}" + [ "$status" -eq 0 ] +} + +@test "allows phrase inside echoed double-quoted string" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"echo \\\"gh pr create\\\"\"}}" + [ "$status" -eq 0 ] +} + +@test "allows phrase inside echoed single-quoted string" { + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"tool_input\":{\"command\":\"echo 'gh pr create'\"}}" + [ "$status" -eq 0 ] +} + +@test "allows phrase inside plain heredoc body (cat < "$tf" + echo "$tf" +} + +@test "rewind: marker + create-pr load IS an ancestor of the leaf -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript \ + '{"uuid":"a1","parentUuid":null,"type":"user"}' \ + '{"uuid":"a2","parentUuid":"a1","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":{"command":"pr-tools:create-pr"}}]}}' \ + '{"uuid":"a3","parentUuid":"a2","type":"user"}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: marker but create-pr load is on an ABANDONED branch -> block" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # b2 (the create-pr load) branches off b1; the user then rewound to b1 and + # continued with b3. b3 is the active leaf; b2 is not its ancestor. + tf="$(make_transcript \ + '{"uuid":"b1","parentUuid":null,"type":"user"}' \ + '{"uuid":"b2","parentUuid":"b1","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":{"command":"create-pr"}}]}}' \ + '{"uuid":"b3","parentUuid":"b1","type":"user"}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 2 ] + [[ "$output" == *"create-pr"* ]] +} + +@test "rewind: marker but transcript has no create-pr load at all -> block" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript \ + '{"uuid":"c1","parentUuid":null,"type":"user"}' \ + '{"uuid":"c2","parentUuid":"c1","type":"user"}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 2 ] +} + +@test "rewind: marker + transcript_path points to a missing file -> fail open (allow)" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"/tmp/does-not-exist-$$.jsonl\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: marker + unparseable transcript -> fail open (allow)" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript 'not json at all' '{also bad')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +# ---- slash-command activations (marker written by track-skill-slash-command.sh) ---- + +@test "rewind: marker + /create-pr slash activation IS an ancestor -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript \ + '{"uuid":"s1","parentUuid":null,"type":"user","message":{"role":"user","content":"/create-pr open the PR"}}' \ + '{"uuid":"s2","parentUuid":"s1","type":"assistant","message":{"content":[{"type":"text","text":"ok"}]}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: marker + plugin-qualified /pr-tools:create-pr slash activation -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript \ + '{"uuid":"q1","parentUuid":null,"type":"user","message":{"role":"user","content":"/pr-tools:create-pr"}}' \ + '{"uuid":"q2","parentUuid":"q1","type":"user","message":{"role":"user","content":"go"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: slash activation on an ABANDONED branch -> block" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript \ + '{"uuid":"x1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{"uuid":"x2","parentUuid":"x1","type":"user","message":{"role":"user","content":"/create-pr"}}' \ + '{"uuid":"x3","parentUuid":"x1","type":"user","message":{"role":"user","content":"use the gh cli"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 2 ] +} + +# ---- fail-open hardening: ambiguity must never re-block ---- + +@test "rewind: partial parse failure + load absent from branch -> fail open (allow)" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # A malformed line means the transcript is not fully parseable; absence is no + # longer trustworthy, so the helper must stay undetermined (allow). + tf="$(make_transcript \ + '{"uuid":"p1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{ this line is broken' \ + '{"uuid":"p2","parentUuid":"p1","type":"user","message":{"role":"user","content":"go"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: dangling parent chain (incomplete transcript) -> fail open (allow)" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # d2's parent (d1) was never written to this slice; the chain is incomplete. + tf="$(make_transcript \ + '{"uuid":"d2","parentUuid":"d1","type":"user","message":{"role":"user","content":"go"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: wrong-shaped Skill input does not crash; valid load still found -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # w2 has a non-dict "input" (must be ignored, not crash); w3 is a valid load. + tf="$(make_transcript \ + '{"uuid":"w1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{"uuid":"w2","parentUuid":"w1","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":"not-a-dict"}]}}' \ + '{"uuid":"w3","parentUuid":"w2","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":{"skill":"pr-tools:create-pr"}}]}}' \ + '{"uuid":"w4","parentUuid":"w3","type":"user","message":{"role":"user","content":"go"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: non-UTF-8 bytes in transcript do not crash; valid load found -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(mktemp "${BATS_TEST_TMPDIR:-/tmp}/transcript.XXXXXX.jsonl")" + printf '{"uuid":"u1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}\n' > "$tf" + printf '\xff\xfe invalid utf8 bytes here\n' >> "$tf" + printf '{"uuid":"u2","parentUuid":"u1","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":{"skill":"create-pr"}}]}}\n' >> "$tf" + printf '{"uuid":"u3","parentUuid":"u2","type":"user","message":{"role":"user","content":"go"}}\n' >> "$tf" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +# ---- leaf selection must anchor on a conversation message, not a trailing record ---- + +@test "rewind: trailing system/attachment record does not become the leaf -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # create-pr is loaded on the active branch (t1->t2->t3). t9 is a trailing + # system record (has a uuid, parentUuid null) — it must NOT anchor the walk. + tf="$(make_transcript \ + '{"uuid":"t1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{"uuid":"t2","parentUuid":"t1","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":{"skill":"create-pr"}}]}}' \ + '{"uuid":"t3","parentUuid":"t2","type":"user","message":{"role":"user","content":"go"}}' \ + '{"uuid":"t9","parentUuid":null,"type":"system","content":"post-turn system note"}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +# ---- slash-command synthesized form vs spoofed mention ---- + +@test "rewind: genuine synthesized command block -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + tf="$(make_transcript \ + '{"uuid":"g1","parentUuid":null,"type":"user","message":{"role":"user","content":"/create-pr\ncreate-pr\n"}}' \ + '{"uuid":"g2","parentUuid":"g1","type":"assistant","message":{"content":[{"type":"text","text":"ok"}]}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: command-name tag merely quoted mid-message is NOT an activation -> block" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # No genuine load on the active branch; a later message just quotes the tag. + tf="$(make_transcript \ + '{"uuid":"z1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{"uuid":"z2","parentUuid":"z1","type":"user","message":{"role":"user","content":"earlier I ran /create-pr but rewound"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 2 ] +} + +@test "rewind: cyclic parent chain -> fail open (allow)" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # c1 <-> c2 form a parent loop; no create-pr load. A cycle is malformed, so + # the result must be undetermined rather than a confident "absent" block. + tf="$(make_transcript \ + '{"uuid":"c1","parentUuid":"c2","type":"user","message":{"role":"user","content":"a"}}' \ + '{"uuid":"c2","parentUuid":"c1","type":"user","message":{"role":"user","content":"b"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: trailing isVisibleInTranscriptOnly node does not become the leaf -> allow" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # create-pr is active on v1->v2->v3; v9 is a transcript-only node appended + # after, with a null parent — it must not anchor the walk. + tf="$(make_transcript \ + '{"uuid":"v1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{"uuid":"v2","parentUuid":"v1","type":"assistant","message":{"content":[{"type":"tool_use","name":"Skill","input":{"skill":"create-pr"}}]}}' \ + '{"uuid":"v3","parentUuid":"v2","type":"user","message":{"role":"user","content":"go"}}' \ + '{"uuid":"v9","parentUuid":null,"type":"user","isVisibleInTranscriptOnly":true,"message":{"role":"user","content":"transcript-only note"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} + +@test "rewind: uuid-less conversation record makes result undetermined -> fail open (allow)" { + mkdir -p "$TEST_MARKER_DIR" + touch "$TEST_MARKER_DIR/create-pr" + # No create-pr load on the branch, but a user record is missing its uuid — + # the DAG is incomplete, so the helper must stay undetermined (allow). + tf="$(make_transcript \ + '{"uuid":"m1","parentUuid":null,"type":"user","message":{"role":"user","content":"hi"}}' \ + '{"parentUuid":"m1","type":"user","message":{"role":"user","content":"no uuid here"}}' \ + '{"uuid":"m2","parentUuid":"m1","type":"user","message":{"role":"user","content":"go"}}')" + + run run_hook "{\"tool_name\":\"Bash\",\"session_id\":\"${TEST_SESSION}\",\"transcript_path\":\"${tf}\",\"tool_input\":{\"command\":\"gh pr create --title foo\"}}" + [ "$status" -eq 0 ] +} diff --git a/plugins/pr-tools/scripts/tests/strip-quoted-and-heredocs.bats b/plugins/pr-tools/scripts/tests/strip-quoted-and-heredocs.bats new file mode 100644 index 0000000..f6c2b88 --- /dev/null +++ b/plugins/pr-tools/scripts/tests/strip-quoted-and-heredocs.bats @@ -0,0 +1,141 @@ +#!/usr/bin/env bats +# Tests for strip-quoted-and-heredocs.py +# +# Verifies the helper strips quoted segments and heredoc bodies so callers +# can match command-phrase patterns against the cleaned text. + +setup() { + SCRIPTS_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)" + HELPER="$SCRIPTS_DIR/strip-quoted-and-heredocs.py" +} + +# Pipe stdin into the helper, capture stdout +run_helper() { + printf '%s' "$1" | python3 "$HELPER" +} + +# ============================================================ +# Unquoted content passes through unchanged +# ============================================================ + +@test "passes through a bare command unchanged" { + result=$(run_helper "foo bar baz") + [ "$result" = "foo bar baz" ] +} + +@test "passes through multi-line unquoted content unchanged" { + input=$'cd /tmp\nls -la\necho done' + result=$(run_helper "$input") + [ "$result" = "$input" ] +} + +# ============================================================ +# Single-quoted segments are stripped +# ============================================================ + +@test "strips single-quoted segment" { + result=$(run_helper "echo 'hidden phrase'") + [ "$result" = "echo " ] +} + +@test "strips multiple single-quoted segments" { + result=$(run_helper "foo 'a' bar 'b'") + [ "$result" = "foo bar " ] +} + +# ============================================================ +# Double-quoted segments are stripped (with escape handling) +# ============================================================ + +@test "strips double-quoted segment" { + result=$(run_helper 'echo "hidden phrase"') + [ "$result" = "echo " ] +} + +@test "strips double-quoted segment containing escaped quotes" { + # `echo "he said \"hi\""` — whole quoted span (with inner \") strips out + result=$(run_helper 'echo "he said \"hi\""') + [ "$result" = "echo " ] +} + +# ============================================================ +# Heredoc bodies are stripped +# ============================================================ + +@test "strips plain heredoc body" { + input=$'cat < [additional-file-paths...]" + keywords: + - pr-image +allowed-tools: Bash Read Glob +--- + +# Attach GitHub Assets + +Upload local files to GitHub via `uploads.github.com/user-attachments/assets`. + +## Contract: if loaded, run the script + +**This skill exists to call `upload.sh`. If it is loaded with a local file path in context, you MUST run the script — do not describe the flow, do not propose markdown without uploading, do not stop after acknowledging the request.** The only correct trajectory ends with a `gh`/`curl`-backed upload and a returned asset URL. + +If no local file path is present and none can be inferred from conversation, output `no-op: no local file path` and exit — do NOT call `upload.sh` with a placeholder, a remote URL, or a guessed path. + +## When to Self-Invoke + +Self-invoke ONLY when **all** of the following hold: + +1. The user (or a calling skill) references a concrete **local** file path — absolute (`/tmp/...`, `~/Desktop/...`) or relative to cwd — for an image (png, jpg, jpeg, gif, webp, svg) or video (mov, mp4, webm). +2. The destination is GitHub — a PR body, issue body, PR/issue comment, or `/create-sub-issues` flow. + +Canonical triggers: +- User pastes a local screenshot/recording path and asks to put it on a PR/issue. +- A PR-creation flow is producing a body and the conversation already contains visual context (e.g. QA screenshots, extracted video frames). + +## When NOT to invoke + +- The change is backend/logic only and no images or recordings have been mentioned. *Most PR-creation prompts in this category never need this skill — do not load it speculatively.* +- The user references a remote URL (already on GitHub, Slack, S3, etc.). The script only handles local files. +- No file path appears in the conversation. "Should I add a screenshot?" is a question, not an invocation. +- The file is not a supported type (see `upload.sh` for the list — only image/video formats are accepted). + +If you have been loaded but none of the "When to Self-Invoke" conditions are met, emit `no-op: ` and return control. This is the script-first path; staying loaded without uploading is the failure mode. + +## Flow + +### Step 1: Resolve file path(s) + +- If `$ARGUMENTS` is set, use those file path(s) verbatim — one per upload. +- Otherwise, scan the recent conversation for local image/video paths. Use only paths the user actually referenced; do not invent paths. + +`upload.sh` itself errors on missing files (`File not found: `), so do not pre-gate on existence — pass the user's path through and surface the script's error verbatim if it fails. + +### Step 2: Run the upload script — once per file + +```bash +${CLAUDE_PLUGIN_ROOT}/skills/attach-github-assets/scripts/upload.sh "" +``` + +The script auto-detects the repo ID from `git remote` and MIME type from extension. Returns the asset URL on stdout, exits non-zero on failure. + +To override repo ID (e.g. uploading from a worktree whose remote isn't the target repo): + +```bash +${CLAUDE_PLUGIN_ROOT}/skills/attach-github-assets/scripts/upload.sh "" +``` + +Run the script **once per file** — never batch into a single invocation, never substitute `curl` or a different upload mechanism. + +### Step 3: Return markdown for the returned URL(s) + +- **Images** (png, jpg, jpeg, gif, webp, svg) → `![{filename}]({url})` +- **Videos** (mov, mp4, webm) → paste the URL on its own line; GitHub auto-renders video URLs and `![]()` would break that. + +## Examples + +- `/attach-github-assets ~/Desktop/screenshot.png` +- `/attach-github-assets /tmp/before.png /tmp/after.png` diff --git a/plugins/pr-tools/skills/attach-github-assets/scripts/upload.sh b/plugins/pr-tools/skills/attach-github-assets/scripts/upload.sh new file mode 100755 index 0000000..bb2e978 --- /dev/null +++ b/plugins/pr-tools/skills/attach-github-assets/scripts/upload.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# Usage: ./upload.sh [repository_id] +# Requires: gh, curl, jq +set -euo pipefail + +FILE_PATH="${1:-}" +REPO_ID="${2:-}" + +if [[ -z "$FILE_PATH" ]]; then + echo "Usage: upload.sh [repository_id]" >&2 + exit 1 +fi + +if [[ ! -f "$FILE_PATH" ]]; then + echo "Error: File not found: $FILE_PATH" >&2 + exit 1 +fi + +# Get auth token +TOKEN=$(gh auth token 2>/dev/null) || { + echo "Error: gh auth token failed. Run 'gh auth login' first." >&2 + exit 1 +} + +# Auto-detect repo ID if not provided +if [[ -z "$REPO_ID" ]]; then + # Try to get owner/repo from git remote + REMOTE_URL=$(git remote get-url origin 2>/dev/null || echo "") + if [[ -n "$REMOTE_URL" ]]; then + # Extract owner/repo from SSH or HTTPS remote URL + OWNER_REPO=$(echo "$REMOTE_URL" | sed -E 's#(git@github\.com:|https://github\.com/)##; s#\.git$##') + REPO_ID=$(gh api "repos/$OWNER_REPO" --jq '.id' 2>/dev/null || echo "") + fi + + if [[ -z "$REPO_ID" ]]; then + echo "Error: Could not detect repository ID. Pass it as second argument." >&2 + exit 1 + fi +fi + +# Determine MIME type from extension +FILENAME=$(basename "$FILE_PATH") +EXT="${FILENAME##*.}" +EXT_LOWER=$(echo "$EXT" | tr '[:upper:]' '[:lower:]') + +case "$EXT_LOWER" in + png) MIME="image/png" ;; + jpg|jpeg) MIME="image/jpeg" ;; + gif) MIME="image/gif" ;; + webp) MIME="image/webp" ;; + svg) MIME="image/svg+xml" ;; + mov) MIME="video/quicktime" ;; + mp4) MIME="video/mp4" ;; + webm) MIME="video/webm" ;; + *) + echo "Error: Unsupported file type '.$EXT_LOWER'. Supported: png, jpg, jpeg, gif, webp, svg, mov, mp4, webm" >&2 + exit 1 + ;; +esac + +# URL-encode filename and mime type +ENCODED_NAME=$(printf '%s' "$FILENAME" | jq -sRr @uri) +ENCODED_MIME=$(printf '%s' "$MIME" | jq -sRr @uri) + +# Upload +RESPONSE=$(curl -s -w "\n%{http_code}" \ + "https://uploads.github.com/user-attachments/assets?name=${ENCODED_NAME}&content_type=${ENCODED_MIME}&repository_id=${REPO_ID}" \ + -X POST \ + -H "Content-Type: application/octet-stream" \ + -H "Accept: application/json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + -H "Authorization: Bearer $TOKEN" \ + --data-binary "@$FILE_PATH") + +# Split response body and HTTP status +HTTP_CODE=$(echo "$RESPONSE" | tail -1) +BODY=$(echo "$RESPONSE" | sed '$d') + +if [[ "$HTTP_CODE" != "201" ]]; then + echo "Error: Upload failed with HTTP $HTTP_CODE" >&2 + echo "$BODY" >&2 + exit 1 +fi + +# Extract URL from response +URL=$(echo "$BODY" | jq -r '.url // empty') +if [[ -z "$URL" ]]; then + echo "Error: No URL in response: $BODY" >&2 + exit 1 +fi + +# Output the URL +echo "$URL" diff --git a/plugins/pr-tools/skills/create-pr/SKILL.md b/plugins/pr-tools/skills/create-pr/SKILL.md new file mode 100644 index 0000000..1a1dc4b --- /dev/null +++ b/plugins/pr-tools/skills/create-pr/SKILL.md @@ -0,0 +1,228 @@ +--- +name: create-pr +description: Open or update a GitHub pull request for the current branch — use when asked to create a PR, open a pull request, push and PR, or submit a PR. +allowed-tools: Bash Read Write Grep Glob AskUserQuestion +--- + +# Pull Request Creation + +## Core Rules + +1. **NEVER dispatch a sub-agent.** Run every step of this workflow directly in the main session — the `Task`/`Agent` tool is deliberately not in this skill's `allowed-tools`. Dispatching to a sub-agent is a common failure mode: subagents lose the session's intent, can't see the diff in context, and re-ask intent questions you already answered. If you find yourself reaching for `Task(...)` — even to "run this in parallel", "off-load the boring parts", or "delegate the gh pr create" — stop and run the next step inline instead. This rule overrides any general preference for parallelism, delegation, or context-window savings. + +2. **NEVER push past an explicit user rejection.** Before running any step, scan the recent session for signals like "don't push anything yet", "don't make a PR", "hold off on the PR", "not ready for a PR", "wait before opening a PR". If you see one, STOP — do not run `gh pr create`, do not push. Surface what the user said and ask whether they have changed their mind, then wait. A user rejection in the same session is a hard halt, not a hint. + +3. **NEVER fabricate intent.** Most users say "do X" without explaining why. When intent is missing (which is usually the case), ASK before creating the PR. + +4. **NEVER list files.** No "Files Updated" or "Files Changed" sections. GitHub shows this already. + +5. **NEVER narrate code changes.** Don't explain what the code does in human language. The diff shows the implementation. + +6. **NEVER speculate on risks.** Only include risks if the user explicitly mentioned them. + +7. **NEVER include a "Test plan" section.** Omit any test plan, test checklist, or testing instructions from PR descriptions. + +8. **NEVER call `gh pr create` without first running `check-pr-context.sh`.** Step 1.5 (`check-pr-context.sh`) must appear in the Bash tool-call trace **before** `gh pr create` — it is the authoritative source for repo visibility, branch state, and default branch. Never infer its output from prompt text, prior turns, session context, or your own judgement — the script is cheap, deterministic, and non-substitutable. "The user said the repo is private" / "I already know the branch name" / "the intent is obvious" are NOT reasons to skip. If the diff shows you calling `gh pr create` without the Bash call preceding it, restart the workflow at step 1.5. + +## Workflow + +Execute all steps below directly in this session. Per Core Rules 1 and 8, no sub-agent / `Task` dispatch, and the context script runs inline before any `gh pr create`. + +### 1. Look for intent in session history + +Did the user explicitly state: +- What problem they're solving? +- Why they need this change? + +**"Do X" is not intent.** "Add button to page" describes WHAT, not WHY. + +### 1.5. Check repo context (once, reuse everywhere) + +**Always run this script** — even if the user mentions visibility or branch name in their message. The script is the authoritative source; never infer from prompt text. + +Run it once early and reuse the results for steps 2, 2.5, 3, and 3.6: + +```bash +bash "${CLAUDE_PLUGIN_ROOT}/skills/create-pr/scripts/check-pr-context.sh" +``` + +Returns JSON: + +```json +{ + "repo": "your-org/your-repo", + "visibility": "PUBLIC", + "branch": "fix/typo", + "already_pushed": false, + "default_branch": "main" +} +``` + +Use these values throughout the workflow: +- `visibility` is `PUBLIC`, `PRIVATE`, or `INTERNAL` +- `PUBLIC` → apply public-repo safeguards in steps 2, 2.5, and 3.6 +- `PRIVATE` or `INTERNAL` → skip public-repo safeguards +- `already_pushed` → if `true`, skip branch rename in step 2 (renaming after push is disruptive) +- `default_branch` → starting point for base branch in step 3 (adjust if upstream tracking differs) + +Do NOT query `isPrivate` — its polarity inverts the natural-language framing and has caused repeat misreads where `isPrivate=true` was treated as "public". + +### 2. Ask for intent (usually needed) + +Most sessions won't have intent. Ask: + +``` +Before creating this PR, I need to understand the intent behind this change. + +What problem does this solve, and why is this change needed? +``` + +### 2.5. Check for auto-generated branch names + +Using `branch` from step 1.5: if it looks meaningless, random, or unrelated to the intent, suggest a descriptive rename and ask the user to confirm. Skip if `already_pushed` is `true` — renaming after push is disruptive. + +Prefix the new name with your GitHub login (`gh api user -q .login`) if that succeeds; otherwise omit the prefix. Rename with `git branch -m `. + +**Public repo branch names:** If `visibility` is `PUBLIC` (from step 1.5), also verify the branch name doesn't contain internal identifiers — internal IDs, customer names, private project codenames, or team-specific references. If it does, suggest a sanitized rename. + +### 3. Commit and push if needed + +If changes aren't committed and pushed, do that first. Always push with `-u` to set upstream tracking: `git push -u origin `. + +**Public repo commit messages:** If the repo is public (per step 1.5), before pushing review all commit messages on the branch (`git log --oneline ..HEAD`). If any commit message contains internal identifiers, customer data, internal URLs, or team-specific references, warn the user and suggest amending or squashing before pushing — once pushed to a public repo, commit messages are permanently visible even if force-pushed later (cached by bots, mirrored, or already fetched). + +### 3.5. Determine the base branch + +Start with `default_branch` from step 1.5. Override it if the current branch has an upstream tracking branch that differs: `git rev-parse --abbrev-ref @{upstream} 2>/dev/null`. If the upstream tracks a different remote branch (e.g., `develop` instead of `main`), use that as the base. If uncertain, ask the user. Always pass `--base ` to `gh pr create`. + +### 3.55. Validate diff matches intent + +Before writing the PR description, review the actual diff to ensure it matches the user's intent: + +1. Run `git diff ...HEAD --stat` to see all files changed +2. Compare the changed files against what the user discussed in this session +3. If there are **unexpected files** — files changed that weren't part of the conversation — STOP and warn the user: + +``` +I notice the diff includes changes to files we didn't discuss: +- +- + +These may be leftover changes from a previous session. Should I: +1. Proceed with all changes in one PR +2. Help you split these into separate commits/PRs +3. Exclude them (you'll need to stash or reset those files) +``` + +4. Only proceed once the user has confirmed the diff is intentional +5. When writing the PR description, base the "How?" section on the **actual diff alone** — the conversation context informs Why, never How + +### 3.6. Public repo description and title safeguards + +If the repo is **public** (per step 1.5), the PR description will be visible to anyone on the internet without authentication. Apply these rules: + +- **No internal URLs** — internal dashboards (observability, error tracking, metrics), private wikis, internal docs, admin tools, or any company-internal domains +- **No internal identifiers** — team names, group names, employee names, internal IDs, private project codenames +- **No internal process details** — references to internal tools, deployment pipelines, feature flag names, or issue links from private repos +- **No customer data** — customer names, account IDs, user IDs, or anything that could identify a customer +- **Keep it general** — describe the *what* and *why* in terms any external contributor could understand + +These rules apply to the **PR title as well** — the title is even more visible than the description (it appears in search engine results, GitHub notification emails, and RSS feeds). Keep titles generic and free of internal context. + +If the user's stated intent contains sensitive details, rephrase it in generic terms. Ask the user to confirm the sanitized description and title before creating the PR. + +**Always print this warning to the user before creating the PR on a public repo:** + +``` +WARNING: This repository is PUBLIC. The PR title, description, comments, +commits, and full diff will be permanently visible to anyone on the internet +— even if the PR is later closed or the branch is deleted, the history remains. + +Please review the PR description above and confirm you're comfortable with +everything in it being public. +``` + +Wait for the user to explicitly confirm before proceeding with `gh pr create`. + +### 4. Create or update PR + +Use `gh` CLI for all PR operations: + +**Create new PR:** +```bash +gh pr create --base "" --title "" --body "$(cat <<'EOF' +<description body here> +EOF +)" +``` + +If the user explicitly requested a draft PR, add `--draft`. + +**Update existing PR:** +```bash +gh pr edit --body "$(cat <<'EOF' +<description body here> +EOF +)" +``` + +**Check if PR exists:** `gh pr view --json number 2>/dev/null` + +If PR already exists for branch, update its description. Otherwise create new PR. + +**Description format:** +```markdown +### Why? + +[The problem we're solving - from user's explanation, NOT fabricated] + +### How? + +[High-level approach - 1-2 sentences. Do NOT list changes or files. The diff shows the implementation.] + +<details> +<summary>Implementation Plan</summary> + +[PLAN_CONTENT — see "Finding the plan file" below. If no plan file found, omit this entire <details> section.] + +</details> + +<sub>Generated with Claude Code</sub> +``` + +**Issue/PR references:** When referencing related issues or PRs, use bulleted lists (`- #123`) so GitHub renders them as rich linked cards. + +**Avoid accidental issue links:** On GitHub, `#` followed by a number (e.g., `#1`, `#42`) automatically creates a hyperlink to the issue/PR with that number. Only use `#NUMBER` when intentionally linking to an issue or PR. Never use it in prose like "the #1 cause" or "#3 priority" — rephrase instead (e.g., "the top cause", "third priority"). If a literal `#` before a number is unavoidable, escape it with a backslash (`\#1`). + +**Finding the plan file:** + +1. **Check conversation history first.** Look in this conversation for a system message containing a path like `~/.claude/plans/<name>.md`. When plan mode was used, the system always injects the full path. Use it directly with the Read tool. +2. **If not in history**, run `ls -t ~/.claude/plans/*.md | head -5` via Bash to get the 5 most recently modified plan files. Read the first few lines of each to identify which one matches the current task. If no plan clearly matches, or the match is ambiguous, omit the plan section. (Do NOT use Glob for this — Glob sorts alphabetically by filename, not by modification time, and plan filenames are random.) +3. Paste the plan file's full markdown contents into the `<details>` block. Do NOT include the file path — plan files are gitignored and won't exist in the PR. +4. If no plan file is found by either method, omit the entire `<details>` block. + +**Optional sections** (only if user explicitly discussed): +- `### Decisions` - if user explained trade-offs or choices made +- `### Risks` - ONLY if user mentioned specific concerns + +## Response Style + +Output only what the user needs to act: +- **Step 2:** the intent question (only if intent is missing from session history) +- **Step 3.6:** the PUBLIC repo warning block (only on public repos) +- **PR URL** on success +- **Error messages** when something goes wrong + +All other steps run silently. No step narration ("Now I'll run...", "Let me check...", "The script returned..."), no script output recap, no announcing each phase. This skill creates a PR — it does not narrate creating a PR. + +## Anti-Patterns + +| Don't | Why | +|-------|-----| +| Dispatch a sub-agent / `Task` for this workflow | Core Rule 1 — subagents lose session intent, re-ask questions, and can't see the diff context. Every step runs inline. | +| Skip `check-pr-context.sh` (step 1.5) | Core Rule 8 — the script is mandatory before `gh pr create`; its output cannot be inferred from prompt text or prior turns. | +| Open a PR after the user said "don't" | Core Rule 2 — "don't push yet" / "don't make a PR" in the session is a hard halt. Ask, don't override. | +| Base How? on conversation, not diff | PR description must reflect the ACTUAL changes, not just what was discussed | +| Use `#NUMBER` in prose | `#42` links to issue 42 — only use for intentional references, rephrase otherwise | +| Include internal details in public repos | Internal URLs, team names, customer data, and tool references are visible to anyone — check repo visibility first | +| Add "Files Updated", "Test plan", or risk sections | Core Rules 4, 6, 7 — these sections are always omitted; GitHub shows the diff, testing is implicit, risks belong in the user's own judgment | diff --git a/plugins/pr-tools/skills/create-pr/scripts/check-pr-context.sh b/plugins/pr-tools/skills/create-pr/scripts/check-pr-context.sh new file mode 100755 index 0000000..0041693 --- /dev/null +++ b/plugins/pr-tools/skills/create-pr/scripts/check-pr-context.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Returns JSON with repo context needed for PR creation in a single call. +# Usage: bash "${CLAUDE_PLUGIN_ROOT}/skills/create-pr/scripts/check-pr-context.sh" +# Output: {"repo":"...","visibility":"PUBLIC|PRIVATE|INTERNAL|UNKNOWN","branch":"...","already_pushed":bool,"default_branch":"..."} + +# `git config --get remote.origin.url` is read-only — it reads the remote without +# any chance of mutating it (unlike `git remote ...`, which can rewrite remotes). +REPO_FULL=$(git config --get remote.origin.url 2>/dev/null | sed -E 's|^.*github\.com[:/]||; s|\.git$||') || REPO_FULL="" + +VISIBILITY=$(gh repo view --json visibility -q '.visibility' 2>/dev/null || echo "UNKNOWN") + +BRANCH=$(git branch --show-current 2>/dev/null || echo "") + +ALREADY_PUSHED="false" +if [ -n "$BRANCH" ] && git ls-remote --heads origin "$BRANCH" 2>/dev/null | grep -q .; then + ALREADY_PUSHED="true" +fi + +DEFAULT_BRANCH=$(gh repo view --json defaultBranchRef -q '.defaultBranchRef.name' 2>/dev/null || echo "main") + +jq -nc \ + --arg repo "$REPO_FULL" \ + --arg visibility "$VISIBILITY" \ + --arg branch "$BRANCH" \ + --argjson already_pushed "$ALREADY_PUSHED" \ + --arg default_branch "$DEFAULT_BRANCH" \ + '{repo:$repo,visibility:$visibility,branch:$branch,already_pushed:$already_pushed,default_branch:$default_branch}'