Skip to content
Security
Hook

Hooks

What vestige runs automatically, and when. A hook is a command Claude Code fires at a fixed moment, without you asking for it.

From plugin
vestige
6623 agents14 hooks

Claude Code

> /plugin marketplace add samvallad33/vestige
> /plugin install vestige@vestige

Where it lives

  • hooks/cwd-state-injector.shGitHub
    Read the script
    #!/bin/bash
    # cwd-state-injector.sh — SessionStart + UserPromptSubmit hook
    #
    # Injects live git + CI + Operator + rule state as additionalContext on the
    # active hook event so agents start every turn grounded in actual repo state.
    # Cached in ${TMPDIR:-/tmp}/cwd-state-{hash}.json for 60s. Fails open.
    
    set -u
    
    PY_BIN=""
    for _cand in python3 python; do
      if command -v "$_cand" >/dev/null 2>&1 && "$_cand" -I -c "import sys" >/dev/null 2>&1; then
        PY_BIN="$_cand"
        break
      fi
    done
    GIT_BIN="$(command -v git 2>/dev/null || true)"
    [ -n "$PY_BIN" ] && [ -n "$GIT_BIN" ] || exit 0
    
    INPUT="$(cat)"
    PARSED="$(VESTIGE_HOOK_INPUT="$INPUT" "$PY_BIN" -I -c '
    import json, os
    try:
        d = json.loads(os.environ.get("VESTIGE_HOOK_INPUT", "") or "{}")
    except Exception:
        d = {}
    cwd = d.get("cwd") or ""
    ev = d.get("hook_event_name") or "UserPromptSubmit"
    if ev not in ("SessionStart", "UserPromptSubmit"):
        ev = "UserPromptSubmit"
    print(ev + "\t" + cwd)
    ' 2>/dev/null || printf 'UserPromptSubmit\t')"
    
    EVENT_NAME="${PARSED%%	*}"
    CWD="${PARSED#*	}"
    [ -n "$EVENT_NAME" ] || EVENT_NAME="UserPromptSubmit"
    
    if [ -z "$CWD" ] || [ ! -d "$CWD" ]; then
      CWD="$(pwd 2>/dev/null || true)"
    fi
    
    cd "$CWD" 2>/dev/null || exit 0
    if ! "$GIT_BIN" rev-parse --is-inside-work-tree > /dev/null 2>&1; then
      exit 0
    fi
    
    CACHE_KEY="$(VESTIGE_CWD_RAW="$CWD:$EVENT_NAME" "$PY_BIN" -I -c '
    import hashlib, os
    print(hashlib.sha256(os.environ.get("VESTIGE_CWD_RAW","").encode()).hexdigest()[:16])
    ' 2>/dev/null || echo "default")"
    CACHE_DIR="${TMPDIR:-/tmp}"
    CACHE_FILE="${CACHE_DIR%/}/cwd-state-${CACHE_KEY}.json"
    if [ -f "$CACHE_FILE" ]; then
      MTIME=$(stat -c %Y "$CACHE_FILE" 2>/dev/null || stat -f %m "$CACHE_FILE" 2>/dev/null || echo 0)
      case "$MTIME" in ''|*[!0-9]*) MTIME=0 ;; esac
      NOW=$(date +%s 2>/dev/null || echo 0)
      AGE=$((NOW - MTIME))
      if [ "$AGE" -ge 0 ] && [ "$AGE" -lt 60 ] && [ -s "$CACHE_FILE" ]; then
        cat "$CACHE_FILE"
        exit 0
      fi
    fi
    
    BRANCH="$("$GIT_BIN" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
    HEAD_SHA="$("$GIT_BIN" rev-parse --short HEAD 2>/dev/null || true)"
    HEAD_SUBJECT="$("$GIT_BIN" log -1 --format='%s' 2>/dev/null | head -c 100 || true)"
    HEAD_AUTHOR="$("$GIT_BIN" log -1 --format='%an' 2>/dev/null || true)"
    STAGED_COUNT="$("$GIT_BIN" diff --cached --name-only 2>/dev/null | wc -l | awk '{print $1}')"
    UNSTAGED_COUNT="$("$GIT_BIN" diff --name-only 2>/dev/null | wc -l | awk '{print $1}')"
    UNTRACKED_COUNT="$("$GIT_BIN" ls-files --others --exclude-standard 2>/dev/null | wc -l | awk '{print $1}')"
    CONFLICT_COUNT="$("$GIT_BIN" diff --name-only --diff-filter=U 2>/dev/null | wc -l | awk '{print $1}')"
    AHEAD_BEHIND="$("$GIT_BIN" rev-list --left-right --count HEAD...@{upstream} 2>/dev/null | awk '{printf "ahead=%s behind=%s", $1, $2}')"
    [ -n "$AHEAD_BEHIND" ] || AHEAD_BEHIND="no-upstream"
    
    GIT_DIR="$("$GIT_BIN" rev-parse --git-dir 2>/dev/null || true)"
    OP_MODE="normal"
    if [ -n "$GIT_DIR" ]; then
      if [ -d "$GIT_DIR/rebase-merge" ] || [ -d "$GIT_DIR/rebase-apply" ]; then
        OP_MODE="rebase"
      elif [ -f "$GIT_DIR/MERGE_HEAD" ]; then
        OP_MODE="merge"
      elif [ -f "$GIT_DIR/BISECT_LOG" ]; then
        OP_MODE="bisect"
      fi
    fi
    
    WORKTREE_COUNT="$("$GIT_BIN" worktree list --porcelain 2>/dev/null | grep -c '^worktree ' || echo 1)"
    
    RULE_TAGS="0"
    if [ -f ".vestige-rules" ]; then
      RULE_TAGS="$(grep -cve '^[[:space:]]*\(#\|$\)' .vestige-rules 2>/dev/null || echo 0)"
    fi
    
    OP_HOME="${OPERATOR_HOME:-$HOME/.operator}"
    TODAY_UTC="$(date -u +%Y-%m-%d 2>/dev/null || true)"
    TODAY_STOPS="0"
    if [ -n "$TODAY_UTC" ] && [ -f "$OP_HOME/receipts/$TODAY_UTC.jsonl" ]; then
      TODAY_STOPS="$(grep -c '"decision":[[:space:]]*"STOP"' "$OP_HOME/receipts/$TODAY_UTC.jsonl" 2>/dev/null || echo 0)"
    fi
    
    CI_STATE=""
    PR_COUNT=""
    ISSUE_COUNT=""
    if [ "${VESTIGE_CWD_GH:-0}" = "1" ] && command -v gh > /dev/null 2>&1 && "$GIT_BIN" config --get remote.origin.url > /dev/null 2>&1; then
      GH_PARSED="$(VESTIGE_GH_BRANCH="$BRANCH" "$PY_BIN" -I -c '
    import json, os, subprocess
    branch = os.environ.get("VESTIGE_GH_BRANCH", "")
    def run_gh(args):
        try:
            r = subprocess.run(
                ["gh"] + args,
                stdin=subprocess.DEVNULL,
                capture_output=True,
                text=True,
                timeout=2.5,
            )
            return json.loads(r.stdout) if r.returncode == 0 and r.stdout.strip() else None
        except Exception:
            return None
    ci = run_gh(["run", "list", "--branch", branch, "--limit", "1", "--json", "status,conclusion,name"])
    prs = run_gh(["pr", "list", "--state", "open", "--limit", "100", "--json", "number"])
    iss = run_gh(["issue", "list", "--state", "open", "--limit", "100", "--json", "number"])
    ci_str = ""
    if isinstance(ci, list) and ci:
        r = ci[0]
        ci_str = "%s:%s:%s" % (r.get("name", "?"), r.get("status", "?"), r.get("conclusion") or "...")
    pr_str = str(len(prs)) if isinstance(prs, list) else ""
    is_str = str(len(iss)) if isinstance(iss, list) else ""
    print(ci_str + "\t" + pr_str + "\t" + is_str)
    ' 2>/dev/null || printf '\t\t')"
      CI_STATE="${GH_PARSED%%	*}"
      _GH_REST="${GH_PARSED#*	}"
      PR_COUNT="${_GH_REST%%	*}"
      ISSUE_COUNT="${_GH_REST#*	}"
    fi
    
    REPO_NAME="$(basename "$CWD")"
    CONTEXT_LINES=()
    CONTEXT_LINES+=("[CWD STATE — auto-injected, 60s cache]")
    CONTEXT_LINES+=("  repo: $REPO_NAME  branch: $BRANCH  HEAD: $HEAD_SHA  mode: $OP_MODE  worktrees: $WORKTREE_COUNT")
    if [ -n "$HEAD_SUBJECT" ]; then
      CONTEXT_LINES+=("  last commit: \"$HEAD_SUBJECT\" by $HEAD_AUTHOR")
    fi
    CONTEXT_LINES+=("  working tree: staged=$STAGED_COUNT unstaged=$UNSTAGED_COUNT untracked=$UNTRACKED_COUNT conflicts=$CONFLICT_COUNT")
    if [ "$AHEAD_BEHIND" != "no-upstream" ]; then
      CONTEXT_LINES+=("  vs upstream: $AHEAD_BEHIND")
    fi
    if [ -n "$CI_STATE" ]; then
      CONTEXT_LINES+=("  last CI run: $CI_STATE")
    fi
    if [ -n "$PR_COUNT" ] && [ -n "$ISSUE_COUNT" ]; then
      CONTEXT_LINES+=("  open: PRs=$PR_COUNT issues=$ISSUE_COUNT")
    fi
    CONTEXT_LINES+=("  vestige: rules_tags=$RULE_TAGS operator_stops_today=$TODAY_STOPS")
    
    JSON_OUT="$(VESTIGE_CWD_EVENT="$EVENT_NAME" V
  • hooks/load-all-memory.shGitHub
    Read the script
    #!/bin/bash
    # Load ALL memory MD files on every UserPromptSubmit.
    # This legacy opt-in hook cats every file in the memory directory into prompt
    # context. It is intentionally not enabled by default.
    
    # Resolve per-user Claude Code project memory dir from $HOME.
    # Claude Code encodes home path as `-Users-<name>`; allow override via env.
    if [ -n "${VESTIGE_MEMORY_DIR:-}" ]; then
      MEM_DIR="$VESTIGE_MEMORY_DIR"
    else
      MEM_DIR="$HOME/.claude/projects/$(printf '%s' "$HOME" | tr '/' '-')/memory"
    fi
    
    if [ ! -d "$MEM_DIR" ]; then
      exit 0
    fi
    
    echo "═══════════════════════════════════════════════════════════════"
    echo "[FULL MEMORY DUMP — EVERY FILE LOADED]"
    echo "═══════════════════════════════════════════════════════════════"
    echo ""
    
    # Iterate every .md file in the memory directory (not archive)
    for f in "$MEM_DIR"/*.md; do
      if [ -f "$f" ]; then
        filename=$(basename "$f")
        echo ""
        echo "┌─────────────────────────────────────────────────────────────"
        echo "│ FILE: $filename"
        echo "└─────────────────────────────────────────────────────────────"
        cat "$f"
        echo ""
      fi
    done
    
    echo ""
    echo "═══════════════════════════════════════════════════════════════"
    echo "[END FULL MEMORY DUMP — $(ls "$MEM_DIR"/*.md 2>/dev/null | wc -l | tr -d ' ') files loaded]"
    echo "═══════════════════════════════════════════════════════════════"
    
  • hooks/operator-stop-memory.pyGitHub
    Read the script
    #!/usr/bin/env python3
    """operator-stop-memory: every Operator stop becomes a Vestige memory. A Claude Code hook that
    `npx @vestige/init` registers once a gate is installed.
    
    The Operator gate (Lite or paid) writes a hash-chained receipt for every verdict to
    ~/.operator/receipts/<UTC date>.jsonl. This hook reads the STOP receipts it has not recorded yet and
    saves each one into Vestige through the MCP server's remember, so any agent on the same store can
    recall it later by exact handle:
    
      stop memory   node_type event; tags <rule>, op-receipt-<first 16 hex of the receipt digest>,
                    operator, operator-stop; its text quotes that digest; derived_from its rule memory
      rule memory   node_type pattern; tags <rule>, op-rule-<rule>, operator, operator-rule; written the
                    first time that rule stops a call
    
    These are the handles `recall` and the PRECEDENT journey (`npx @vestige/init`) look up. A stop already
    in memory under its op-receipt tag, from this hook or any other writer, is not written again.
    
    Write path: the hook starts `vestige-mcp` (the --mcp <path> argument, else VESTIGE_MCP_BIN, else the one on
    PATH; `npx @vestige/init` registers it with --mcp so no PATH is needed). It attaches to the
    server that already owns the store, or opens the store when none does, and the hook speaks MCP over its
    stdin: initialize, notifications/initialized, then tools/call. A write from here passes the same gate and
    gets the same receipt as an agent's own remember.
    
    The hook never blocks a tool call. It works within a time budget, logs any failure to
    ~/.operator/state/stop-memory.log, tries that stop again on a later call, and always exits 0. On
    PostToolUse and UserPromptSubmit it tells the agent, as additional context, which stops of its own
    session it just recorded and the handle that recalls each one. On SessionStart it hands the new session
    the most recent stops it recorded on this machine (the last RECENT_DAYS days, at most RECENT_SHOWN), each
    with its handle, so the next session knows what was stopped and why before it tries the same thing.
    
    Wire it after the gate's own PreToolUse hook: hooks/settings.stop-memory.fragment.json, or let
    `npx @vestige/init` do it, which copies this file to ~/.vestige/hooks/ once Operator Lite is installed.
    Env: OPERATOR_HOME (default ~/.operator), VESTIGE_MCP_BIN, OPERATOR_STOP_MEMORY_BUDGET (seconds, default 20).
    
    The server can record these stops itself through `session(action="reflex")` on the v6.2 surface. While
    that server is active it touches <data dir>/reflex/heartbeat, and this hook steps aside so a stop is never
    handled twice. With an older server, or none, this hook works exactly as before.
    Env for that check: VESTIGE_DATA_DIR, else the platform's default Vestige data directory.
    Stdlib only, Python 3.9 and later.
    """
    import calendar
    import json
    import os
    import queue
    import re
    import shutil
    import socket
    import subprocess
    import sys
    import threading
    import time
    
    try:
        import fcntl
    except ImportError:                                   # Windows: fallback to msvcrt lock
        fcntl = None
    try:
        import msvcrt
    except ImportError:
        msvcrt = None
    
    VERSION = "0.2.0"
    HOME = os.environ.get("HOME") or os.path.expanduser("~")
    OP_HOME = os.environ.get("OPERATOR_HOME") or os.path.join(HOME, ".operator")
    RECEIPTS = os.path.join(OP_HOME, "receipts")
    STATE_DIR = os.path.join(OP_HOME, "state")
    STATE = os.path.join(STATE_DIR, "stop-memory.json")
    LOG = os.path.join(STATE_DIR, "stop-memory.log")
    LOCK = os.path.join(STATE_DIR, "stop-memory.lock")
    MAX_PER_RUN = 8                                       # stops written per hook call; the rest wait for the next
    MAX_PENDING = 500
    MAX_DONE = 5000
    FIRST_RUN_FILES = 30                                  # day files read the first time, newest first
    RECENT_KEEP = 20                                      # recorded stops remembered for SessionStart
    RECENT_SHOWN = 5                                      # stops a new session is told about
    RECENT_DAYS = 7
    DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
    RULE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
    NODE_RE = re.compile(r"^(mem-[0-9a-f]{16}|[0-9a-f-]{36})$")
    REFLEX_FRESH_SECS = 900                               # a reflex heartbeat younger than this means reflex owns stops
    
    
    def log(msg):
        try:
            os.makedirs(STATE_DIR, exist_ok=True)
            if os.path.exists(LOG) and os.path.getsize(LOG) > 262144:
                os.replace(LOG, LOG + ".1")
            with open(LOG, "a", encoding="utf-8") as f:
                f.write("%s %s\n" % (time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), msg))
        except Exception:
            pass
    
    
    def data_dirs():
        """Where a Vestige server keeps its data directory on this machine, most specific first."""
        dirs = []
        custom = (os.environ.get("VESTIGE_DATA_DIR") or "").strip()
        if custom:
            dirs.append(os.path.expanduser(custom))
        if sys.platform == "darwin":
            dirs.append(os.path.join(HOME, "Library", "Application Support", "com.vestige.core"))
        elif sys.platform.startswith("win"):
            dirs.append(os.path.join(os.environ.get("APPDATA") or os.path.join(HOME, "AppData", "Roaming"), "vestige", "core", "data"))
        else:
            base = os.environ.get("XDG_DATA_HOME") or os.path.join(HOME, ".local", "share")
            dirs += [os.path.join(base, "vestige"), os.path.join(base, "core")]
        return dirs
    
    
    def reflex_active(now=None):
        """True while the native Reflex service records gate stops itself."""
        now = time.time() if now is None else now
        for d in data_dirs():
            try:
                if now - os.path.getmtime(os.path.join(d, "reflex", "heartbeat")) <= REFLEX_FRESH_SECS:
                    return True
            except OSError:
                pass
        return False
    
    
    def load_state():
        try:
            with open(STATE, encoding="utf-8") as f:
                st = json.load(f)
            if isinstance(st, dict):
                st.setdefault("offsets", {})
                st.setdefault("pending", [])
                st.setdef
  • hooks/preflight-swarm.shGitHub
    Read the script
    #!/bin/bash
    # preflight-swarm.sh — retired.
    #
    # This hook used to spawn a Lateral Thinker subagent and inject a
    # <subconscious_preflight> block that claimed a Haiku model had already run
    # and told the main agent not to mention it. That block is not a memory,
    # it is not a recorded edge, and it is not injected.
    #
    # The file remains so an older settings.json that still points at it fails
    # open instead of erroring. It never calls a model.
    
    exit 0
    
  • hooks/sanhedrin-local.pyGitHub
    Read the script
    #!/usr/bin/env python3
    # sanhedrin-local.py — OpenAI-compatible Sanhedrin Executioner bridge.
    # Drop-in replacement for the Haiku 4.5 subagent that sanhedrin.sh used to spawn.
    #
    # Reads draft from stdin, prints single-line verdict to stdout:
    #   yes
    #   no - [Sanhedrin Veto] [CLASS]: <reason under 120 chars>
    #
    # Architecture:
    #   stdin (draft) -> Vestige /api/deep_reference (single semantic query)
    #                 -> OpenAI-compatible chat endpoint (one-shot judgment)
    #                 -> stdout (single-line verdict)
    #
    # Fail-open: if the endpoint is unreachable, print "yes" and exit 0 (don't break
    # the Cognitive Sandwich on infra errors). The wrapping sanhedrin.sh maps
    # "yes" to exit 0, so this preserves existing fail-open semantics.
    
    from __future__ import annotations
    
    import json
    import os
    import re
    import sys
    import unicodedata
    import urllib.error
    import urllib.parse
    import urllib.request
    from dataclasses import asdict, dataclass, field, replace
    from pathlib import Path
    from typing import Any
    
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    try:
        import sanhedrin_core
    except Exception:
        sanhedrin_core = None
    
    
    def env_int(name: str, default: int) -> int:
        try:
            return int(os.environ.get(name, "") or default)
        except ValueError:
            return default
    
    
    DASHBOARD_PORT = os.environ.get("VESTIGE_DASHBOARD_PORT") or "3927"
    VESTIGE_BASE_URL = (
        os.environ.get("VESTIGE_BASE_URL") or f"http://127.0.0.1:{DASHBOARD_PORT}"
    ).rstrip("/")
    
    SANHEDRIN_ENDPOINT = (
        os.environ.get("VESTIGE_SANHEDRIN_ENDPOINT")
        or os.environ.get("MLX_ENDPOINT")
        or ""
    )
    VESTIGE_ENDPOINT = (
        os.environ.get("VESTIGE_DEEP_REFERENCE_ENDPOINT")
        or f"{VESTIGE_BASE_URL}/api/deep_reference"
    )
    VESTIGE_HEALTH = (
        os.environ.get("VESTIGE_HEALTH_ENDPOINT") or f"{VESTIGE_BASE_URL}/api/health"
    )
    MODEL = (
        os.environ.get("VESTIGE_SANHEDRIN_MODEL")
        or os.environ.get("VESTIGE_SANDWICH_MODEL")
        or ""
    )
    SANHEDRIN_TIMEOUT = env_int("VESTIGE_SANHEDRIN_TIMEOUT", env_int("MLX_TIMEOUT", 45))
    VESTIGE_TIMEOUT = env_int("VESTIGE_TIMEOUT", 5)
    SANHEDRIN_BACKEND = (os.environ.get("VESTIGE_SANHEDRIN_BACKEND") or "").strip().lower()
    THINK_RE = re.compile(
        r"<(?:think|thinking|reasoning)>.*?</(?:think|thinking|reasoning)>",
        re.DOTALL | re.IGNORECASE,
    )
    
    
    def post_json(url: str, body: dict, timeout: int):
        if not url:
            return None
        data = json.dumps(body).encode("utf-8")
        headers = {"Content-Type": "application/json"}
        api_key = os.environ.get("VESTIGE_SANHEDRIN_API_KEY")
        if api_key and same_endpoint_origin(url, SANHEDRIN_ENDPOINT):
            headers["Authorization"] = f"Bearer {api_key}"
        req = urllib.request.Request(
            url, data=data, headers=headers
        )
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read())
        except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
            return None
    
    
    def same_endpoint_origin(url: str, endpoint: str) -> bool:
        try:
            target = urllib.parse.urlsplit(url)
            expected = urllib.parse.urlsplit(endpoint)
        except ValueError:
            return False
        return (
            target.scheme == expected.scheme
            and target.netloc == expected.netloc
            and target.path == expected.path
        )
    
    
    def use_backend_extensions() -> bool:
        if SANHEDRIN_BACKEND in {"mlx", "vllm"}:
            return True
        if SANHEDRIN_BACKEND in {"openai", "ollama", "llama.cpp", "llamacpp", "litellm"}:
            return False
        return MODEL.startswith("mlx-community/")
    
    
    def sanhedrin_model_configured() -> bool:
        return bool(SANHEDRIN_ENDPOINT and MODEL)
    
    
    def sanhedrin_body(
        messages: list[dict[str, str]],
        max_tokens: int,
        stop: list[str] | None = None,
    ) -> dict[str, Any]:
        body: dict[str, Any] = {
            "model": MODEL,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": 0.0,
            "top_p": 1.0,
            "stream": False,
        }
        if stop:
            body["stop"] = stop
        if use_backend_extensions():
            body["top_k"] = 1
            body["seed"] = 42
            body["chat_template_kwargs"] = {"enable_thinking": False}
        return body
    
    
    TRUST_FLOOR = 0.55  # filter out low-trust memories that drive false-positive vetoes
    
    CLAIM_MODE_ENV = "VESTIGE_SANHEDRIN_CLAIM_MODE"
    OUTPUT_ENV = "VESTIGE_SANHEDRIN_OUTPUT"
    STAGE_FILE_ENV = "VESTIGE_SANHEDRIN_STAGE_FILE"
    MAX_CLAIMS = env_int("VESTIGE_SANHEDRIN_MAX_CLAIMS", 8)
    MAX_CLAIM_CHARS = env_int("VESTIGE_SANHEDRIN_MAX_CLAIM_CHARS", 500)
    MAX_EVIDENCE_CHARS = env_int("VESTIGE_SANHEDRIN_MAX_EVIDENCE_CHARS", 420)
    
    CLAIM_CLASSES = {
        "TECHNICAL",
        "BIOGRAPHICAL",
        "FINANCIAL",
        "ACHIEVEMENT",
        "TIMELINE",
        "QUANTITATIVE",
        "ATTRIBUTION",
        "CAUSAL",
        "COMPARATIVE",
        "EXISTENTIAL",
        "VAGUE-QUANTIFIER",
        "UNVERIFIED-POSITIVE",
    }
    CRITICAL_ABSENCE_CLASSES = {
        "BIOGRAPHICAL",
        "FINANCIAL",
        "ACHIEVEMENT",
        "TIMELINE",
        "QUANTITATIVE",
        "ATTRIBUTION",
        "VAGUE-QUANTIFIER",
    }
    STRUCTURED_VERDICTS = {"SUPPORTED", "REFUTED", "REFUTED_BY_ABSENCE", "NEI"}
    SEVERITY_ORDER = {
        "BIOGRAPHICAL": 0,
        "FINANCIAL": 1,
        "ACHIEVEMENT": 2,
        "ATTRIBUTION": 3,
        "TIMELINE": 4,
        "QUANTITATIVE": 5,
        "VAGUE-QUANTIFIER": 6,
        "UNVERIFIED-POSITIVE": 7,
        "TECHNICAL": 8,
        "EXISTENTIAL": 9,
        "CAUSAL": 10,
        "COMPARATIVE": 11,
    }
    USER_TERMS_RE = re.compile(
        r"\b(sam|sam's|the user|user's|you|your|yours|yourself)\b", re.IGNORECASE
    )
    HYPOTHETICAL_PREFIX_RE = re.compile(
        r"^\s*(if|suppose|imagine|hypothetically|assume|what if)\b",
        re.IGNORECASE,
    )
    SUBJECT_MODAL_PREFIX_RE = re.compile(
        r"^\s*(sam|sam's|the user|user's|you|your)\b\s+(would|could)\b",
        re.IGNORECASE,
    )
    TRAILING_MODAL_COMMENT_RE = re.compile(
        r"\s*,?\s+(which|that)\s+(would|could)\b.*$",
        re.IGNORECASE,
    )
    CURRENT_TURN_PREFIXES = [
        re.compile(r"^\s*(per your request|as requested)\s*,?\s*", re.IGNORECASE),
        re.co
  • hooks/sanhedrin.shGitHub
    Read the script
    #!/bin/bash
    # sanhedrin.sh — Stop hook (Post-Cognitive Sanhedrin / Full Agent-Type Guillotine)
    #
    # Spawns the Executioner subagent (Haiku 4.5, fresh context, Vestige MCP
    # tools) to run mcp__vestige__deep_reference 8-stage contradiction analysis
    # on the last assistant draft. If any technical claim contradicts a
    # high-trust memory, exit 2 with the veto reason — forces Main Claude to
    # rewrite.
    #
    # Runs AFTER veto-detector.sh (fast regex against veto-tagged memories).
    # Sanhedrin is the deeper semantic check: it reads the draft as a real
    # reasoning agent, extracts claims, runs deep_reference on each.
    #
    # Architecture:
    #   Main Claude finishes draft → Stop hook chain fires →
    #   veto-detector.sh (50ms regex, may block) →
    #   sanhedrin.sh (2-8s Haiku subagent, may block) →
    #   synthesis-stop-validator.sh (existing regex hedge check, may block)
    #
    # Opt-in: set VESTIGE_SANHEDRIN_ENABLED=1 in parent shell, or install with
    # scripts/install-sandwich.sh --enable-sanhedrin.
    # Re-entrancy lock: VESTIGE_EXECUTIONER_ACTIVE=1 inside the subagent.
    #
    # Ship date 2026-04-20.
    
    set -u
    
    load_vestige_sanhedrin_env() {
      [ -f "$1" ] || return 0
      command -v python3 >/dev/null 2>&1 || return 0
      while IFS="$(printf '\t')" read -r key value; do
        case "$key" in
          VESTIGE_SANHEDRIN_ENABLED|VESTIGE_SANHEDRIN_MODEL|VESTIGE_SANHEDRIN_ENDPOINT|VESTIGE_SANHEDRIN_API_KEY|VESTIGE_SANHEDRIN_BACKEND|VESTIGE_SANHEDRIN_CLAIM_MODE|VESTIGE_SANHEDRIN_OUTPUT|VESTIGE_SANHEDRIN_PYTHON|VESTIGE_SANHEDRIN_STATE_DIR|VESTIGE_SANHEDRIN_ALLOW_COMMAND_LEDGER|VESTIGE_SANHEDRIN_ALLOW_LOOSE_LEDGER|VESTIGE_DASHBOARD_PORT)
            export "$key=$value"
            ;;
        esac
      done < <(python3 -I - "$1" <<'PY'
    import shlex
    import sys
    
    allowed = {
        "VESTIGE_SANHEDRIN_ENABLED",
        "VESTIGE_SANHEDRIN_MODEL",
        "VESTIGE_SANHEDRIN_ENDPOINT",
        "VESTIGE_SANHEDRIN_API_KEY",
        "VESTIGE_SANHEDRIN_BACKEND",
        "VESTIGE_SANHEDRIN_CLAIM_MODE",
        "VESTIGE_SANHEDRIN_OUTPUT",
        "VESTIGE_SANHEDRIN_PYTHON",
        "VESTIGE_SANHEDRIN_STATE_DIR",
        "VESTIGE_SANHEDRIN_ALLOW_COMMAND_LEDGER",
        "VESTIGE_SANHEDRIN_ALLOW_LOOSE_LEDGER",
        "VESTIGE_DASHBOARD_PORT",
    }
    
    try:
        lines = open(sys.argv[1], encoding="utf-8").read().splitlines()
    except OSError:
        sys.exit(0)
    
    for raw in lines:
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        try:
            parts = shlex.split(line, posix=True)
        except ValueError:
            continue
        if len(parts) != 1 or "=" not in parts[0]:
            continue
        key, value = parts[0].split("=", 1)
        if key in allowed and "\t" not in value and "\0" not in value:
            print(f"{key}\t{value}")
    PY
      )
    }
    
    # === OPT-IN GATE ===
    # Sanhedrin is opt-in and model-agnostic. It never guesses a large verifier
    # model; if endpoint/model are unset, the bridge fails open with telemetry.
    # The installer writes this env file only for --enable-sanhedrin.
    SANHEDRIN_ENV="${VESTIGE_SANHEDRIN_ENV:-$HOME/.claude/hooks/vestige-sanhedrin.env}"
    if [ -f "$SANHEDRIN_ENV" ]; then
      load_vestige_sanhedrin_env "$SANHEDRIN_ENV" || exit 0
    fi
    
    case "${VESTIGE_SANHEDRIN_ENABLED:-0}" in
      1|true|TRUE|yes|YES|on|ON) ;;
      *) exit 0 ;;
    esac
    
    # === RE-ENTRANCY GUARD ===
    # The Executioner's own Stop hook will fire when it returns — prevent
    # recursive spawns that would fork-bomb the quota.
    if [ "${VESTIGE_EXECUTIONER_ACTIVE:-0}" = "1" ]; then
      exit 0
    fi
    
    PYTHON_BIN="${VESTIGE_SANHEDRIN_PYTHON:-}"
    if [ -z "$PYTHON_BIN" ]; then
      PYTHON_BIN="$(command -v python3 2>/dev/null || printf '')"
    fi
    if [ -z "$PYTHON_BIN" ]; then
      PYTHON_BIN="/usr/bin/python3"
    fi
    if ! "$PYTHON_BIN" -I -c 'import sys' >/dev/null 2>&1; then
      exit 0
    fi
    
    record_sanhedrin_fail_open() {
      REASON="$1"
      DETAIL="${2:-}"
      "$PYTHON_BIN" -I - "$REASON" "$DETAIL" <<'PY' 2>/dev/null || true
    import json
    import os
    import sys
    from datetime import datetime, timezone
    from pathlib import Path
    
    reason = sys.argv[1] if len(sys.argv) > 1 else "unknown"
    detail = sys.argv[2] if len(sys.argv) > 2 else ""
    state_dir = Path(os.environ.get("VESTIGE_SANHEDRIN_STATE_DIR") or Path.home() / ".vestige" / "sanhedrin")
    try:
        state_dir.mkdir(parents=True, exist_ok=True)
        with (state_dir / "fail-open.jsonl").open("a", encoding="utf-8") as f:
            f.write(json.dumps({
                "timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"),
                "runId": os.environ.get("VESTIGE_SANHEDRIN_RUN_ID"),
                "reason": reason,
                "detail": detail[:500],
                "transcript": os.environ.get("TRANSCRIPT_PATH") or os.environ.get("VESTIGE_SANHEDRIN_TRANSCRIPT"),
            }) + "\n")
    except OSError:
        pass
    PY
    }
    
    # === READ STOP HOOK INPUT ===
    INPUT="$(cat)"
    TRANSCRIPT_PATH="$(printf '%s' "$INPUT" | "$PYTHON_BIN" -I -c 'import sys,json;d=json.load(sys.stdin);print(d.get("transcript_path",""))' 2>/dev/null || printf '')"
    
    if [ -z "$TRANSCRIPT_PATH" ] || [ ! -f "$TRANSCRIPT_PATH" ]; then
      exit 0
    fi
    
    # === EXTRACT LAST ASSISTANT DRAFT ===
    # Read the transcript JSONL, pull the last assistant message text.
    export TRANSCRIPT_PATH
    DRAFT_SCRIPT="$(mktemp -t vestige-sanhedrin-draft.XXXXXX)"
    trap 'rm -f "$DRAFT_SCRIPT"' EXIT
    
    cat > "$DRAFT_SCRIPT" <<'DRAFT_PYEOF'
    import json, os, re, sys
    
    transcript = os.environ.get("TRANSCRIPT_PATH", "")
    last_assistant = ""
    
    try:
        with open(transcript) as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    obj = json.loads(line)
                except Exception:
                    continue
                role = obj.get("role") or obj.get("type", "")
                content = obj.get("message", {}).get("content", obj.get("content", ""))
                text = ""
                if isinstance(content, list):
                    for block in content:
                        if isinstance(block, dict) and block.get("type") == "text":
                            text += block.get("text", "") + "\n"
                elif isinstance(content, str):
                    text = con
  • hooks/sanhedrin_core.pyGitHub
  • hooks/save-gate.pyGitHub
  • hooks/synthesis-gate.shGitHub
  • hooks/synthesis-preflight.shGitHub
  • hooks/synthesis-stop-validator.shGitHub
  • hooks/test_save_gate.pyGitHub
  • hooks/vestige-pulse-daemon.shGitHub
  • hooks/veto-detector.shGitHub

All 14 scripts are listed above. The source is inlined for 6 of them, starting with whatever hooks.json actually runs. See all of them in the repo.

Read the script before you install anything that runs on your machine. This is the one part of a plugin that acts without being asked.

@samvallad33
Ships withvestige

Vestige is a local-first deterministic operating system, execution safety kernel, and zero-vector causal memory engine for autonomous AI agents built in Rust.

Stars on GitHub

Momentum

stars in total
662
Star history of samvallad33/vestige on GitHub, a chart by star-history.com

More plugins that ship hooks.

watermarks-remover

watermarks-remover

Agent skill + stdlib Python service to strip multi-vendor AI provenance marks from text and files, for privacy and hygiene on content you own. The skill is a thin client: it drives the machinery over HTTP, so the agent host needs no Python.

2 skills1 hook28k
@guillaumemeyer@guillaumemeyer
Install Plugin
agentic-bug-hunter

agentic-bug-hunter

Runs recon on a target, tests it for real, reportable vulnerabilities, checks each finding against a strict validation gate, and writes a report ready to submit to bug bounty platforms. It also remembers patterns across targets and resumes unfinished sessions.

25 skills+36k
@awarexone@awarexone
Install Plugin
agentic-bug-hunter

agentic-bug-hunter

A Claude Code plugin for bug bounty hunters, bundling skills for reconnaissance, vulnerability hunting such as IDOR, SSRF and XSS, black-box audits of deployed AI agents, and CI/CD pipeline security.

25 skills+36k
@shuvonsec@shuvonsec
Install Plugin
cc-safety-net

cc-safety-net

A pre-execution guard that blocks destructive Git and file system commands, plus common attempts to read sensitive files, before an AI coding agent runs a tool call. Works with Claude Code and several other agent CLIs.

2 skills1 hook2.1k
@kenryu42@kenryu42
Install Plugin
cc-safety-net

cc-safety-net

A pre-execution guard that blocks destructive Git and file system commands, and common attempts to read sensitive files, before a tool call runs. Works with several AI coding agents, including Claude Code.

2 skills1 hook2.1k
@kenryu42@kenryu42
Install Plugin
pentest-agents

pentest-agents

A bug bounty agent framework for Claude Code that automates reconnaissance, vulnerability hunting and exploit chaining, with skills for analyzing recon output, running autonomous hunt loops and correlating findings into attack chains.

39 skills+31.3k
@h-mmer@h-mmer
Install Plugin
cti-expert

cti-expert

A cyber threat intelligence and OSINT analysis toolkit that runs structured investigations and produces analyst-style reports with sourced, trust-scored findings. Built for security analysts working OSINT and CTI cases in Claude Code.

1 skill+2626
@7onez@7onez
Install Plugin
offensive-claude

offensive-claude

A Claude Code plugin for offensive security work, offering structured red-team engagement workflows based on the Cyber Kill Chain. It covers attacks on Active Directory, AI and LLM systems, command and control infrastructure, and browser exploitation.

38 skills+3423
@hypnguyen1209@hypnguyen1209
Install Plugin

Questions about the hooks in vestige.

Which coding agents can use the hooks in vestige?
The hooks in vestige install in Claude Code and Cursor: each runs Claude Code hooks from .claude/settings.json, so copy the hooks there.