Skip to content

Hooks

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

From plugin
ponytail
188k6 skills10 hooks

Claude Code

> /plugin marketplace add DietrichGebert/ponytail
> /plugin install ponytail@ponytail

Where it lives

  • hooks/ponytail-activate.jsGitHub
    Read the script
    #!/usr/bin/env node
    // ponytail — Claude Code SessionStart activation hook (also Codex, Copilot,
    // Grok, CodeBuddy and Cursor sessionStart)
    //
    // Runs on every session start:
    //   1. Writes flag file at $CLAUDE_CONFIG_DIR/.ponytail-active (defaults to ~/.claude; statusline reads this)
    //   2. Emits ponytail ruleset as hidden SessionStart context
    //   3. Detects missing statusline config and emits setup nudge
    
    const fs = require('fs');
    const path = require('path');
    const { execFileSync } = require('child_process');
    const { getDefaultMode, getClaudeDir, isShellSafe } = require('./ponytail-config');
    const { getPonytailInstructions } = require('./ponytail-instructions');
    const {
      clearMode,
      cursorRuleNotice,
      cursorRulePath,
      isCodeBuddy,
      isCodex,
      isCopilot,
      isCursor,
      readMode,
      setMode,
      writeHookOutput,
    } = require('./ponytail-runtime');
    
    const claudeDir = getClaudeDir();
    const settingsPath = path.join(claudeDir, 'settings.json');
    
    function activate(mode) {
      // "off" mode — skip activation entirely, don't write flag or emit rules
      if (mode === 'off') {
        clearMode();
        process.exit(0);
      }
    
      // Cursor with the always-on rule in the workspace: the rule already carries the
      // ruleset and would contradict any other level, so leave the flag alone and
      // hand the model a one-line notice instead of a second copy (#817).
      if (isCursor) {
        const rule = cursorRulePath();
        if (rule) {
          try {
            writeHookOutput('SessionStart', mode, cursorRuleNotice(rule));
          } catch (e) {
            // Silent fail — stdout closed/EPIPE at hook exit must not surface as a hook failure
          }
          process.exit(0);
        }
      }
    
      // 1. Write flag file
      try {
        setMode(mode);
      } catch (e) {
        // Silent fail -- flag is best-effort, don't block the hook
      }
    
      // 2. Emit the ponytail ruleset, filtered to the active intensity level.
      let output = getPonytailInstructions(mode);
    
      // 2b. Codebase map: what already exists, so "reuse first" costs no search. Fail open: the map
      // gets 3 s, well inside the 15 s hook limit, so a stalled map never costs the rules (#1079, #1157).
      // shortcut: a map slower than 3 s is still dropped; a cached per-repo map would lift that if it shows up.
      if (mode !== 'review' && process.env.PONYTAIL_MAP !== '0') try {
        const map = execFileSync(process.execPath, [path.join(__dirname, 'ponytail-map.js')], {
          encoding: 'utf8', timeout: 3000, maxBuffer: 64 * 1024, stdio: ['ignore', 'pipe', 'ignore'],
        }).trimEnd();
        if (map) output += '\n\n' + map;
      } catch (e) { /* no map */ }
    
      // 3. Detect missing statusline config — nudge Claude to help set it up
      if (!isCodex && !isCopilot && !isCursor && !isCodeBuddy) try {
        const isWindows = process.platform === 'win32';
        let statusCommand = null;
        if (fs.existsSync(settingsPath)) {
          // Strip UTF-8 BOM some editors prepend on Windows (breaks JSON.parse)
          const raw = fs.readFileSync(settingsPath, 'utf8').replace(/^\uFEFF/, '');
          const settings = JSON.parse(raw);
          if (settings.statusLine) {
            statusCommand = String(settings.statusLine.command || '');
          }
        }
    
        // A statusLine already set up before #1032 can still run a script from a
        // plugin version that has since been deleted. Only absolute paths are checked,
        // so ~ or $HOME forms are never mistaken for missing files.
        const ref = statusCommand &&
          statusCommand.match(/"([^"]*ponytail-statusline\.(?:sh|ps1))"|(\S*ponytail-statusline\.(?:sh|ps1))/);
        const refPath = ref ? (ref[1] || ref[2]) : null;
        // isShellSafe keeps quotes, newlines and shell metacharacters from
        // settings.json out of the model context.
        // On Windows only drive-letter or UNC paths count: a Git Bash path such as
        // /c/Users/... is absolute to Node but does not resolve, so it would be
        // flagged as broken while it works.
        const checkable = refPath && isShellSafe(refPath) && path.isAbsolute(refPath) &&
          (!isWindows || /^([A-Za-z]:[\\/]|\\\\)/.test(refPath));
        const stalePath = checkable && !fs.existsSync(refPath) ? refPath : null;
    
        // The plugin root is a versioned cache dir (.../ponytail/4.12.0/) that Claude
        // Code deletes on update, so a statusLine pointing into it goes blank after the
        // next update (#1032). Point it at a copy in the config dir instead. A statusLine
        // that already runs ponytail keeps its script type, so its copy stays fresh.
        const usePs1 = refPath ? refPath.endsWith('.ps1') : isWindows;
        const scriptName = usePs1 ? 'ponytail-statusline.ps1' : 'ponytail-statusline.sh';
        const scriptPath = path.join(claudeDir, scriptName);
    
        // Nudge at most once — the flag file marks that the user has already seen
        // (and implicitly declined) the statusline setup offer. Repeating it every
        // session start turns a helpful hint into a nag. A broken path is nudged once
        // per path: the flag records it.
        const nudgeFlagPath = path.join(claudeDir, '.ponytail-statusline-nudged');
        let nudged = null;
        try { nudged = fs.readFileSync(nudgeFlagPath, 'utf8'); } catch (e) { /* not nudged yet */ }
        const nudge = stalePath ? nudged !== stalePath : statusCommand === null && nudged === null;
    
        // Refresh the copy every session so script fixes ship with plugin updates.
        // Copy to a new temp file, then rename: the rename replaces a symlink at
        // scriptPath instead of writing through it, and a concurrent session never
        // runs a half-written script.
        if (nudge || fs.existsSync(scriptPath)) {
          const tmpPath = scriptPath + '.' + process.pid + '.tmp';
          try {
            fs.copyFileSync(path.join(__dirname, scriptName), tmpPath, fs.constants.COPYFILE_EXCL);
            fs.chmodSync(tmpPath, 0o644);
            fs.renameSync(tmpPath, scriptPath);
          } finally {
            try { fs.unlinkSync(tmpPath); } catch (e) { /* renamed */ }
          }
        }
    
        if (nudge) {
          try { fs.writeFileSync(nudgeFlagPath, stalePath || ''); } catch (e)
  • hooks/ponytail-band-import.jsGitHub
    Read the script
    #!/usr/bin/env node
    // ponytail — imports past Claude Code sessions into the band's task ledger, so the board can
    // compare them: cost, agent time, tokens, turns, name and model. Started in the background by
    // `/ponytail band import`; also runs by hand. Sessions already in the ledger are left alone.
    
    const fs = require('fs');
    const os = require('os');
    const path = require('path');
    const { spawnSync } = require('child_process');
    const { StringDecoder } = require('string_decoder');
    const { getClaudeDir } = require('./ponytail-config');
    
    // The band's columns (CSV_HEADER in hooks/band/metrics.ts; a test keeps the two equal).
    const CSV_HEADER = 'key,started,project,name,cost_usd,turns,agent_minutes,tokens_total,tokens_output,reuse_pct,reused,new,callers_open,tests,level,model';
    
    // USD per million tokens from https://platform.claude.com/docs/en/about-claude/pricing, checked
    // 2026-10-17: [input, 5-minute cache write, 1-hour cache write, cache read, output]. Opus 5.5 and
    // Fable 5.1 also match Claude Code's own totals in real transcripts. A model missing here, or a
    // fast-mode reply, gets no estimate: an empty cost beats a guessed one.
    const OPUS = [5, 6.25, 10, 0.5, 25];
    const PRICES = {
      'claude-fable-5-1': [10, 12.5, 20, 0.25, 50],
      'claude-fable-5': [10, 12.5, 20, 1, 50],
      'claude-opus-5-5': [4, 5, 8, 0.2, 20],
      'claude-opus-5': OPUS,
      'claude-opus-4-8': OPUS,
      'claude-opus-4-7': OPUS,
      'claude-opus-4-6': OPUS,
      'claude-opus-4-5': OPUS,
      'claude-sonnet-5-5': [2, 2.5, 4, 0.1, 10],
      'claude-sonnet-5': [2, 2.5, 4, 0.2, 10],
      'claude-sonnet-4-6': [3, 3.75, 6, 0.3, 15],
      'claude-sonnet-4-5': [3, 3.75, 6, 0.3, 15],
      'claude-haiku-5-5': [0.1, 0.125, 0.2, 0.01, 0.5],
      'claude-haiku-4-5': [1, 1.25, 2, 0.1, 5],
    };
    // Haiku 5.5 bills a request whose prompt (input, cache reads and writes) is over 100,000 tokens higher.
    const HAIKU_55_LONG = [0.5, 0.625, 1, 0.05, 2.5];
    const WEB_SEARCH = 10 / 1000;
    const IDLE_MS = 30 * 60000;
    const modelId = m => m.replace(/\[.*\]$/, '').replace(/-\d{8}$/, '');
    
    // One reply's price from its usage, or null when the price is not known.
    function replyCost(model, u) {
      let p = PRICES[modelId(model)];
      if (!p || u.speed === 'fast') return null;
      const cc = u.cache_creation || {};
      const split = cc.ephemeral_5m_input_tokens !== undefined || cc.ephemeral_1h_input_tokens !== undefined;
      const w5 = split ? cc.ephemeral_5m_input_tokens || 0 : u.cache_creation_input_tokens || 0;
      const w1 = split ? cc.ephemeral_1h_input_tokens || 0 : 0;
      const input = u.input_tokens || 0;
      const read = u.cache_read_input_tokens || 0;
      if (modelId(model) === 'claude-haiku-5-5' && input + read + w5 + w1 > 100000) p = HAIKU_55_LONG;
      const searches = (u.server_tool_use && u.server_tool_use.web_search_requests) || 0;
      return (input * p[0] + w5 * p[1] + w1 * p[2] + read * p[3] + (u.output_tokens || 0) * p[4]) / 1e6 + searches * WEB_SEARCH;
    }
    
    const human = r => r.type === 'user' && (r.turnOrigin === 'human' || (r.origin && r.origin.kind === 'human'));
    const promptText = r => {
      const c = r.message && r.message.content;
      const t = typeof c === 'string' ? c : Array.isArray(c) ? (c.find(b => b && b.type === 'text') || {}).text || '' : '';
      return t.trim();
    };
    const ms = r => (r.timestamp ? Date.parse(r.timestamp) : NaN);
    const toolResult = r => (r.toolResult !== undefined ? r.toolResult
      : Array.isArray(r.message && r.message.content) && r.message.content.some(b => b && b.type === 'tool_result'));
    
    // Only what the numbers need from one record: a long session's transcript can pass 500 MB.
    function slim(r) {
      const m = r.message || {};
      const c = human(r) ? m.content : undefined;
      const text = typeof c === 'string' ? c.slice(0, 500)
        : Array.isArray(c) ? c.filter(b => b && b.type === 'text').slice(0, 1).map(b => ({ type: 'text', text: String(b.text).slice(0, 500) })) : undefined;
      return {
        type: r.type, timestamp: r.timestamp, turnOrigin: r.turnOrigin, origin: r.origin && { kind: r.origin.kind },
        isMeta: r.isMeta, toolResult: toolResult(r),
        sessionId: r.sessionId, customTitle: r.customTitle, totalCostUSD: r.totalCostUSD,
        message: { id: m.id, model: m.model, usage: m.usage, content: text },
      };
    }
    
    // A JSONL file line by line, so no transcript is too big to read (one string stops at 512 MB).
    function readRecords(file) {
      const out = [];
      const take = l => { if (l.startsWith('{')) try { out.push(slim(JSON.parse(l))); } catch (e) {} };
      const fd = fs.openSync(file, 'r');
      const buf = Buffer.alloc(1 << 20);
      const dec = new StringDecoder('utf8');
      let rest = '';
      try {
        for (let n; (n = fs.readSync(fd, buf, 0, buf.length, null)) > 0;) {
          const parts = (rest + dec.write(buf.subarray(0, n))).split('\n');
          rest = parts.pop();
          parts.forEach(take);
        }
        take(rest + dec.end());
      } finally {
        fs.closeSync(fd);
      }
      return out;
    }
    
    // One session's numbers from its transcript records and its subagents' records. Null for a session
    // nobody typed into (benchmarks, `claude -p`, scripts) or one without a model reply.
    function sessionStats(records, subagentRecords = [], sessionId = '') {
      const prompts = records.filter(human);
      if (prompts.length === 0) return null;
    
      // Usage repeats on every record of one message: count each message id once, subagents included.
      const seen = new Set();
      const replies = {};
      let tokens = 0;
      let output = 0;
      let estimate = 0;
      const reply = r => r.type === 'assistant' && r.message && r.message.model && r.message.model !== '<synthetic>';
      for (const r of records) if (reply(r)) replies[r.message.model] = (replies[r.message.model] || 0) + 1;
      for (const r of [...records, ...subagentRecords]) {
        if (!reply(r)) continue;
        const { id, model, usage } = r.message;
        if (!usage || !id || seen.has(id)) continue;
        seen.add(id);
        tokens += (usage.input_tokens || 0) + (usage.output_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0);
        o
  • hooks/ponytail-config.jsGitHub
    Read the script
    #!/usr/bin/env node
    // ponytail — shared configuration resolver
    //
    // Resolution order for default mode:
    //   1. PONYTAIL_DEFAULT_MODE environment variable
    //   2. Config file defaultMode field:
    //      - $XDG_CONFIG_HOME/ponytail/config.json (any platform, if set)
    //      - ~/.config/ponytail/config.json (macOS / Linux fallback)
    //      - %APPDATA%\ponytail\config.json (Windows fallback)
    //   3. 'full'
    
    const fs = require('fs');
    const path = require('path');
    const os = require('os');
    
    const DEFAULT_MODE = 'full';
    const VALID_MODES = ['off', 'lite', 'full', 'ultra', 'review'];
    const RUNTIME_MODES = ['off', 'lite', 'full', 'ultra'];
    
    function normalizeMode(mode) {
      if (typeof mode !== 'string') return null;
      const normalized = mode.trim().toLowerCase();
      return RUNTIME_MODES.includes(normalized) ? normalized : null;
    }
    
    function normalizeConfigMode(mode) {
      if (typeof mode !== 'string') return null;
      const normalized = mode.trim().toLowerCase();
      return VALID_MODES.includes(normalized) ? normalized : null;
    }
    
    function normalizePersistedMode(mode) {
      return normalizeMode(mode) || normalizeConfigMode(mode);
    }
    
    // "stop ponytail" / "normal mode" turn ponytail off, but only as a standalone
    // command. Matching the phrase anywhere in the message turned it off mid-task
    // for ordinary requests like "add a normal mode toggle" — so require the whole
    // message to be the command, ignoring case and trailing punctuation.
    function isDeactivationCommand(text) {
      const t = String(text || '').trim().toLowerCase().replace(/[.!?\s]+$/, '');
      return t === 'stop ponytail' || t === 'normal mode';
    }
    
    // ponytail: only embed the plugin install path in a statusline shell command when
    // it's made of ordinary path characters. An allowlist beats escaping every shell's
    // metacharacters; a hostile clone path (quotes, &, $, backtick, ;, etc.) falls back
    // to manual setup instead. Allows : \ / for normal Windows and POSIX paths. Full
    // per-shell escaper only if a real need appears.
    function isShellSafe(p) {
      return typeof p === 'string' && /^[A-Za-z0-9 _.\-:/\\~]+$/.test(p);
    }
    
    function getConfigDir() {
      if (process.env.XDG_CONFIG_HOME) {
        return path.join(process.env.XDG_CONFIG_HOME, 'ponytail');
      }
      if (process.platform === 'win32') {
        return path.join(
          process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'),
          'ponytail'
        );
      }
      return path.join(os.homedir(), '.config', 'ponytail');
    }
    
    function getConfigPath() {
      return path.join(getConfigDir(), 'config.json');
    }
    
    function getClaudeDir() {
      // ponytail: CLAUDE_CONFIG_DIR overrides ~/.claude, matching Claude Code.
      return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
    }
    
    function getQoderDir() {
      return process.env.QODER_CONFIG_DIR || path.join(os.homedir(), '.qoder');
    }
    
    function getDefaultMode() {
      // 1. Environment variable (highest priority)
      // ponytail: a default must be a runtime level (off/lite/full/ultra); review is
      // a session-only mode, never a valid default (#377). Normalize here so values
      // with whitespace or mixed casing still resolve correctly.
      const envMode = normalizeMode(process.env.PONYTAIL_DEFAULT_MODE);
      if (envMode) {
        return envMode;
      }
    
      // 2. Config file
      try {
        const configPath = getConfigPath();
        // Strip UTF-8 BOM (common on Windows-saved files) so JSON.parse doesn't choke
        const config = JSON.parse(fs.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));
        const configMode = normalizeMode(config.defaultMode);
        if (configMode) {
          return configMode;
        }
      } catch (e) {
        // Config file doesn't exist or is invalid — fall through
      }
    
      // 3. Default
      return DEFAULT_MODE;
    }
    
    // Silence the pi "Ponytail loaded" startup toast while keeping ponytail active.
    // PONYTAIL_QUIET_STARTUP=1 (or any truthy value; 0/false/empty mean "show it")
    // takes precedence, else config.quietStartup === true. Mirrors getHideStatus.
    function getQuietStartup() {
      const env = process.env.PONYTAIL_QUIET_STARTUP;
      if (env !== undefined) {
        const v = env.trim().toLowerCase();
        return v !== '' && v !== '0' && v !== 'false' && v !== 'no';
      }
      try {
        const config = JSON.parse(fs.readFileSync(getConfigPath(), 'utf8').replace(/^\uFEFF/, ''));
        return config.quietStartup === true;
      } catch (_) {
        return false;
      }
    }
    
    // Hide the status-bar indicator while keeping ponytail active (#324).
    // PONYTAIL_HIDE_STATUS=1 (or any truthy value; 0/false/empty mean "don't hide")
    // takes precedence, else config.hideStatus === true.
    function getHideStatus() {
      const env = process.env.PONYTAIL_HIDE_STATUS;
      if (env !== undefined) {
        const v = env.trim().toLowerCase();
        return v !== '' && v !== '0' && v !== 'false' && v !== 'no';
      }
      try {
        const config = JSON.parse(fs.readFileSync(getConfigPath(), 'utf8').replace(/^\uFEFF/, ''));
        return config.hideStatus === true;
      } catch (_) {
        return false;
      }
    }
    
    function writeDefaultMode(mode) {
      // ponytail: only a runtime level can be a default; review is session-only (#377).
      const normalized = normalizeMode(mode);
      if (!normalized) return null;
    
      const configPath = getConfigPath();
      fs.mkdirSync(path.dirname(configPath), { recursive: true });
      let config = {};
      try {
        config = JSON.parse(fs.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));
        if (!config || typeof config !== 'object' || Array.isArray(config)) config = {};
      } catch (_) {}
      config.defaultMode = normalized;
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
      return normalized;
    }
    
    module.exports = {
      DEFAULT_MODE,
      VALID_MODES,
      RUNTIME_MODES,
      getDefaultMode,
      getConfigDir,
      getConfigPath,
      getClaudeDir,
      getQoderDir,
      getHideStatus,
      getQuietStartup,
      isShellSafe,
      normalizeMode,
      normalizeConfigMode,
      normalizePersistedMode,
      isDeactivationCommand,
      writeDefaultMode,
    };
    
  • hooks/ponytail-instructions.jsGitHub
    Read the script
    #!/usr/bin/env node
    // Shared Ponytail instruction builder for Claude hooks and Pi extension.
    
    const fs = require('fs');
    const path = require('path');
    const { DEFAULT_MODE, normalizeMode, normalizePersistedMode } = require('./ponytail-config');
    
    const INDEPENDENT_MODES = new Set(['review']);
    const SKILL_PATH = path.join(__dirname, '..', 'skills', 'ponytail', 'SKILL.md');
    
    function filterSkillBodyForMode(body, mode) {
      const effectiveMode = normalizeMode(mode) || DEFAULT_MODE;
      const withoutFrontmatter = String(body || '').replace(/^---[\s\S]*?---\s*/, '');
    
      // Only the intensity table rows and worked examples are mode-specific, and
      // both are keyed by a mode name (lite/full/ultra). A bullet whose label is
      // not a mode — e.g. "No unrequested abstractions: ..." — is a normal rule
      // and must be kept verbatim.
      return withoutFrontmatter
        .split(/\r?\n/)
        .filter((line) => {
          const tableLabel = line.match(/^\|\s*\*\*(.+?)\*\*\s*\|/);
          if (tableLabel) {
            const labelMode = normalizeMode(tableLabel[1].trim());
            if (labelMode) return labelMode === effectiveMode;
          }
    
          // Require a quoted value: every worked example is `- lite: "..."`. Without
          // this, an ordinary rule bullet that happens to start with a mode word
          // (e.g. "- Full: ...") is silently dropped in every other mode — it looks
          // like a worked example but is really prose meant to survive verbatim.
          const exampleLabel = line.match(/^-\s*([^:]+):\s*"/);
          if (exampleLabel) {
            const labelMode = normalizeMode(exampleLabel[1].trim());
            if (labelMode) return labelMode === effectiveMode;
          }
    
          return true;
        })
        .join('\n');
    }
    
    function getFallbackInstructions(mode) {
      // Used only when SKILL.md cannot be read: the same rules as AGENTS.md.
      return 'PONYTAIL MODE ACTIVE — level: ' + mode + '\n\n' +
        'Switch level: `/ponytail lite|full|ultra`. Off: "stop ponytail" or "normal mode".\n\n' +
        "You are a lazy senior developer. The best code is the code never written. You solve the whole problem with the least new code. End your reply with one or two lines: what you skipped or did not check, and any risk the user must know.\n" +
        "\n" +
        "## Before you write\n" +
        "\n" +
        "Read the task and the code it touches. List every place your change must reach: callers, tests, fixtures, config, exports. Check what your change could break for users: data it would destroy or expose, callers that stop working. That is scope. Extra features are not.\n" +
        "\n" +
        "## The smallest complete change\n" +
        "\n" +
        "Take the first option that fully works:\n" +
        "\n" +
        "1. Does it need to exist? Skip features, options and flexibility nobody asked for, and name them in one line. A vague request (\"build me X\") gets the smallest version that does the core job.\n" +
        "2. Already in this codebase (a helper, component, service, pattern)? Use it the way the surrounding code does.\n" +
        "3. Standard library or a platform feature? Use it, unless the project has its own. A house component beats a native widget.\n" +
        "4. An installed dependency? Use it. Never add a dependency for a few lines.\n" +
        "5. Can it be one line a reader gets at a glance? One line.\n" +
        "6. Otherwise: the minimum code that works.\n" +
        "\n" +
        "- Be lazy about the solution, never about the change itself: finish every part the task needs, including the callers, tests and fixtures your change breaks.\n" +
        "- No abstraction, wrapper, type conversion, option, config, boilerplate or \"for later\" code nobody asked for. Keep values in the form the platform already gives you. Deletion beats addition. Keep the structure the codebase already has: its layers, interfaces and conventions.\n" +
        "- The shortest working diff wins, once you know everything it must touch. A one-liner that needs decoding is not short.\n" +
        "- Comment only the why the code cannot show, in one line.\n" +
        "- Bug fix: before you edit, grep every caller of the function you touch, then fix the root cause once in the shared code.\n" +
        "- Code you move or merge keeps its error handling and validation.\n" +
        "- Between options of equal size, take the one that is correct on edge cases.\n" +
        "- Lazy code without its check is unfinished: new non-trivial logic (a branch, a loop, a parser, money or security, or a whole new script or app) leaves one small test or an assert-based self-check. Trivial changes need none.\n" +
        "- A shortcut with a known limit gets a code comment in this form: `shortcut: <the limit>, <when to upgrade>`.\n" +
        "\n" +
        "Never cut: validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs, anything the user asked for.\n";
    }
    
    function getPonytailInstructions(mode) {
      const configuredMode = normalizePersistedMode(mode) || DEFAULT_MODE;
    
      if (INDEPENDENT_MODES.has(configuredMode)) {
        return 'PONYTAIL MODE ACTIVE — level: ' + configuredMode + '. Behavior defined by /ponytail-' + configuredMode + ' skill.';
      }
    
      const effectiveMode = normalizeMode(configuredMode) || DEFAULT_MODE;
    
      try {
        return 'PONYTAIL MODE ACTIVE — level: ' + effectiveMode + '\n\n' +
          filterSkillBodyForMode(fs.readFileSync(SKILL_PATH, 'utf8'), effectiveMode);
      } catch (e) {
        return getFallbackInstructions(effectiveMode);
      }
    }
    
    module.exports = {
      filterSkillBodyForMode,
      getFallbackInstructions,
      getPonytailInstructions,
    };
    
  • hooks/ponytail-map.jsGitHub
    Read the script
    #!/usr/bin/env node
    // ponytail — codebase map: what already exists, so "reuse first" costs no search.
    //
    // Lists the top-level functions, classes and exports of the project's source files, one line
    // per folder, inside a character budget. No model, no dependencies: `git ls-files` (or a short
    // directory walk) plus a regex per language. Tests, generated and vendored files are skipped;
    // shared code (utils, lib, services, components, hooks) is listed first when the budget is tight.
    //
    // ponytail: regex, not a parser. Misses nested or dynamic definitions; a tree-sitter index is the
    // upgrade if the map ever needs to be exact.
    
    const fs = require('fs');
    const path = require('path');
    const { execFileSync } = require('child_process');
    
    const BUDGET = Number(process.env.PONYTAIL_MAP_CHARS || 2000);
    const MAX_FILES = 4000;
    const SRC = /\.(py|js|jsx|mjs|cjs|ts|tsx|go|rs|rb|java|kt|php|swift|cs)$/;
    const SKIP_DIR = /(^|\/)(node_modules|\.git|dist|build|out|vendor|venv|\.venv|__pycache__|coverage|\.next|target|migrations|versions|fixtures|tests?|__tests__|spec)(\/|$)/;
    const SKIP_FILE = /(^|\/)(test_[^/]*|[^/]*(_test|\.test|\.spec|\.gen|\.min|\.d)\.[a-z]+)$/;
    const NAME = /^(?:type\s+)?(?:[\w$]+\s+as\s+)?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)$/;
    const SAFE_PATH = /^[\w.@+$()[\]\/-]+$/;
    const SHARED = /(util|helper|lib|common|shared|service|component|hook|core|model|schema|api)/i;
    
    const PATTERNS = {
      py: [/^(?:async\s+)?def\s+([A-Za-z]\w*)/gm, /^class\s+([A-Za-z]\w*)/gm],
      js: [/^export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|var|interface|type|enum)\s+([A-Za-z_$][\w$]*)/gm,
           /^export\s*\{([^}]*)\}/gm],
      go: [/^func\s+(?:\([^)]*\)\s*)?([A-Z]\w*)/gm, /^type\s+([A-Z]\w*)/gm],
      rs: [/^pub\s+(?:async\s+)?(?:fn|struct|enum|trait|type)\s+(\w+)/gm],
      rb: [/^\s*(?:def|class|module)\s+([A-Za-z][\w.]*)/gm],
      jvm: [/^\s*(?:public\s+)?(?:static\s+)?(?:final\s+)?(?:class|interface|enum|record)\s+(\w+)/gm],
    };
    const LANG = { py: 'py', js: 'js', jsx: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', go: 'go', rs: 'rs',
                   rb: 'rb', java: 'jvm', kt: 'jvm', swift: 'jvm', cs: 'jvm', php: 'jvm' };
    
    function listFiles(root) {
      try {
        // 64 MiB: in repos with many tracked files `git ls-files` overflows Node's 1 MiB
        // default, and the catch below reads that as "not a git repo" and falls back to a
        // walk that ignores .gitignore. The list is capped at MAX_FILES * 5 lines anyway.
        const tracked = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000, maxBuffer: 64 * 1024 * 1024 })
          .split('\n').filter(Boolean).slice(0, MAX_FILES * 5);
        if (tracked.length) return tracked;
      } catch (e) { /* not a git repo: walk below */ }
      {
        // No git, or an untracked folder inside a parent repo (git ls-files is then empty, not an error).
        const out = [];
        (function walk(dir, depth) {
          if (depth > 6 || out.length > MAX_FILES * 5) return;
          for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
            if (ent.name.startsWith('.')) continue;
            const rel = path.relative(root, path.join(dir, ent.name)).replace(/\\/g, '/');
            if (ent.isDirectory()) { if (!SKIP_DIR.test(rel + '/')) walk(path.join(dir, ent.name), depth + 1); }
            else out.push(rel);
          }
        })(root, 0);
        return out;
      }
    }
    
    function namesIn(file, text) {
      const lang = LANG[path.extname(file).slice(1)];
      const names = [];
      for (const re of PATTERNS[lang] || []) {
        for (const m of text.matchAll(re)) {
          for (const n of m[1].split(',').map((s) => (s.trim().match(NAME) || [])[1]).filter(Boolean)) {
            if (!n.startsWith('_') && !names.includes(n)) names.push(n);
          }
        }
      }
      return names;
    }
    
    function buildMap(root = process.cwd()) {
      const files = listFiles(root)
        .filter((f) => SAFE_PATH.test(f) && SRC.test(f) && !SKIP_DIR.test(f) && !SKIP_FILE.test(f))
        .slice(0, MAX_FILES)
        .sort((a, b) => (SHARED.test(b) - SHARED.test(a)) || a.localeCompare(b));
      // One line per directory: names are enough to know something exists; grep finds the file.
      const dirs = new Map();
      for (const f of files) {
        let text;
        try {
          if (!fs.lstatSync(path.join(root, f)).isFile()) continue;
          text = fs.readFileSync(path.join(root, f), 'utf8').slice(0, 65536);
        } catch (e) { continue; }
        const names = namesIn(f, text);
        if (!names.length) continue;
        const dir = path.dirname(f) === '.' ? '.' : path.dirname(f);
        dirs.set(dir, [...(dirs.get(dir) || []), names]);
      }
      const lines = [];
      let used = 0;
      let skipped = 0;
      for (const [dir, perFile] of dirs) {
        // The first exports say what a file is; in a folder of many files (a UI kit) one name each.
        const names = [...new Set(perFile.flatMap((n) => n.slice(0, perFile.length > 8 ? 1 : 3)))];
        const line = `${dir}/: ${names.slice(0, 30).join(', ')}${names.length > 30 ? ', ...' : ''}`;
        if (used + line.length > BUDGET) { skipped++; continue; }
        lines.push(line);
        used += line.length + 1;
      }
      if (!lines.length) return '';
      return 'Codebase map (what already exists; reuse it, read a file only when you need its details):\n' +
        lines.join('\n') + (skipped ? `\n(${skipped} more folders not listed)` : '');
    }
    
    module.exports = { buildMap };
    
    if (require.main === module) process.stdout.write(buildMap(process.argv[2] || process.cwd()) + '\n');
    
  • hooks/ponytail-mode-tracker.jsGitHub
    Read the script
    #!/usr/bin/env node
    // ponytail — UserPromptSubmit hook to track which ponytail mode is active
    // Inspects user input for /ponytail commands and writes mode to flag file
    
    const fs = require('fs');
    const path = require('path');
    const { spawn } = require('child_process');
    const { getClaudeDir, getDefaultMode, isDeactivationCommand, writeDefaultMode } = require('./ponytail-config');
    const {
      clearMode,
      cursorRuleNotice,
      cursorRulePath,
      isCodeBuddy,
      isCodex,
      isCopilot,
      isCursor,
      isQoder,
      readMode,
      setMode,
      writeHookOutput,
    } = require('./ponytail-runtime');
    const { getPonytailInstructions } = require('./ponytail-instructions');
    
    let input = '';
    let done = false;
    
    function finish() {
      if (done) return;
      done = true;
      try {
        // Strip UTF-8 BOM some shells prepend when piping (breaks JSON.parse)
        const data = JSON.parse(input.replace(/^\uFEFF/, ''));
        const prompt = (data.prompt || '').trim().toLowerCase();
    
        // Cursor with the always-on rule in the workspace: no hook can change or
        // switch off a rule, so answer the command with the notice instead of
        // writing a mode the rule would contradict (#817). Ordinary prompts
        // stay silent as usual.
        if (isCursor && (/^[/@$]ponytail/.test(prompt) || isDeactivationCommand(prompt))) {
          const rule = cursorRulePath();
          if (rule) {
            writeHookOutput('UserPromptSubmit', readMode() || 'off', cursorRuleNotice(rule));
            return;
          }
        }
    
        // Match /ponytail commands
        let modeSwitched = false;
        let deactivated = false;
        let defaultNotice = '';
        if (/^[/@$]ponytail/.test(prompt)) {
          const parts = prompt.split(/\s+/);
          const cmd = parts[0].replace(/^[@$]/, '/');
          const arg = parts[1] || '';
    
          let mode = null;
          let isReportOnly = false;
    
          // /ponytail-review is a one-shot skill, not a session level (#736).
          // Matching it here used to setMode('review'), which latched
          // INDEPENDENT_MODES for the rest of the session.
          if (cmd === '/ponytail' || cmd === '/ponytail:ponytail') {
            // `/ponytail default <mode>` persists the default to config (survives
            // restarts). Plain switches stay session-scoped ("sticks until session
            // end"), so this is the only path that writes config. review is not a
            // valid default (#377), so only off/lite/full/ultra are accepted.
            if (arg === 'default') {
              const dmode = parts[2];
              if (dmode === 'off' || dmode === 'lite' || dmode === 'full' || dmode === 'ultra') {
                writeDefaultMode(dmode);
                defaultNotice = 'PONYTAIL DEFAULT SET — new sessions start in ' + dmode + '.';
                if (!isQoder) writeHookOutput('UserPromptSubmit', dmode, defaultNotice);
              }
              // Qoder still needs this turn's ruleset: the block below folds the
              // notice into it. mode stays null, so the session level is untouched.
              if (!isQoder) return; // don't fall through to the session-mode switch
            }
            // `/ponytail band [on|off]` shows or hides the band above the Claude Code
            // prompt (hooks/band reads this flag). It outlives the session; absent = shown.
            // Other hosts have no band, so there the word stays an unknown argument.
            if (arg === 'band' && !isCopilot && !isCodex && !isQoder && !isCodeBuddy && !isCursor) {
              // `/ponytail band import`: past sessions into the board, in the background, so the prompt
              // is answered right away while the transcripts are read. Detached, it outlives this hook's
              // process.exit below.
              if (parts[2] === 'import') {
                spawn(process.execPath, [path.join(__dirname, 'ponytail-band-import.js')], { detached: true, stdio: 'ignore' });
                writeHookOutput('UserPromptSubmit', readMode() || 'off', 'PONYTAIL BAND IMPORT: past Claude Code sessions (cost, agent time, tokens) are being added to the board in the background. Open the board in a minute. Confirm in one short line.');
                return;
              }
              const flag = path.join(getClaudeDir(), '.ponytail-band');
              let hidden = false;
              try { hidden = fs.readFileSync(flag, 'utf8').trim() === 'off'; } catch (e) {}
              const show = parts[2] === 'on' ? true : parts[2] === 'off' ? false : hidden;
              if (show) {
                try { fs.unlinkSync(flag); } catch (e) {}
              } else {
                fs.mkdirSync(path.dirname(flag), { recursive: true });
                fs.writeFileSync(flag, 'off');
              }
              writeHookOutput('UserPromptSubmit', readMode() || 'off', show
                ? 'PONYTAIL BAND ON: the band shows above the prompt again. The ponytail level is unchanged. Confirm in one short line.'
                : 'PONYTAIL BAND OFF: the band above the prompt is hidden, `/ponytail band` brings it back. The ponytail level is unchanged. Confirm in one short line.');
              return;
            }
            if (arg === 'lite') mode = 'lite';
            else if (arg === 'full') mode = 'full';
            else if (arg === 'ultra') mode = 'ultra';
            else if (arg === 'off') mode = 'off';
            else if (arg === '') {
              // Bare /ponytail switches ponytail on: off → the default level (full if
              // the default is off too); already on → keep the level, report it (#639).
              const live = readMode();
              if (live && live !== 'off') {
                isReportOnly = true;
                mode = live;
              } else {
                mode = getDefaultMode() === 'off' ? 'full' : getDefaultMode();
              }
            }
          }
    
          if (isReportOnly) {
            // On Qoder the ruleset block below already reports; a second write
            // here would put two JSON objects on stdout.
            if (!isQoder) {
              writeHookOutput(
                'UserPromptSubmit',
                mode,
                'PONYTAIL MODE ACTIVE — level: ' + mode,
              );
            }
          } else if (mode && mode !== 'off') {
            setMode(mode);
            mode
  • hooks/ponytail-runtime.jsGitHub
  • hooks/ponytail-statusline.ps1GitHub
  • hooks/ponytail-statusline.shGitHub
  • hooks/ponytail-subagent.jsGitHub

All 10 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.

@dietrichgebert
Ships withponytail

Makes your AI agent think like the laziest senior dev in the room. The best code is the code you never wrote.

Stars on GitHub

Momentum

stars in total
187.9k
Star history of DietrichGebert/ponytail on GitHub, a chart by star-history.com

More plugins that ship hooks.

superpowers

superpowers

A development methodology for coding agents that makes the agent brainstorm before building, follow plans, run parallel work and finish branches in a disciplined way. You get fewer skipped steps and more consistent results from your coding assistant.

15 skills1 hook311k
@obra@obra
Install Plugin
agent-skills

agent-skills

Walks a software change from a written spec through design, testing, code review, CI/CD, and release, applying the matching engineering skill at each stage. Useful for developers using Claude Code on full development workflows.

25 skills+3112k
@addyosmani@addyosmani
Install Plugin
planning-with-files

planning-with-files

Persistent file-based planning for AI coding agents on long-running, multi-step tasks. It keeps task_plan.md, findings.md and progress.md on disk, so work can resume after /clear or context compaction.

6 skills+228k
@othmanadi@othmanadi
Install Plugin
gsd-core

gsd-core

A spec-driven development workflow for Claude Code that guides a project through planning, phases, milestone audits and fixes. Includes skills to generate tests from UAT criteria and to audit completed work.

72 skills+311k
@open-gsd@open-gsd
Install Plugin
superpowers-zh

superpowers-zh

Chinese-language skill pack for Claude Code that adds workflow guidance for brainstorming, TDD, debugging, and code review, plus Chinese conventions for commits, documentation, and domestic Git platforms like Gitee and Coding.net.

21 skills1 hook8.5k
@jnmetacode@jnmetacode
Install Plugin
socraticode

socraticode

Gives Claude Code semantic search, dependency graph and architecture context over a codebase, so an AI assistant can explore and understand a project's code. Includes skills for indexing a project and managing its file watching.

2 skills+33.4k
@giancarloerra@giancarloerra
Install Plugin
cocoindex-code

cocoindex-code

A lightweight code search engine that uses AST-based semantic search with local embeddings and incremental indexing. It helps Claude Code users find code faster and more efficiently.

1 skill1 MCP+13k
@cocoindex-io@cocoindex-io
Install Plugin
myclaude

myclaude

Bundles skills for developers using Claude Code to run AI coding tasks across Codex, Claude, Gemini, and OpenCode backends. It also covers structured feature development, multi-session agent work with checkpoints, and browser automation via Chrome DevTools.

11 skills+32.8k
@cexll@cexll
Install Plugin

Questions about the hooks in ponytail.

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