diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 000000000000..02f4ffebb15b --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,19 @@ +{ + "name": "llama-cpp-local", + "interface": { + "displayName": "llama.cpp local plugins" + }, + "plugins": [ + { + "name": "ponytail", + "source": { + "source": "local", + "path": "./third_party/ponytail" + }, + "category": "Productivity", + "policy": { + "installation": "AVAILABLE" + } + } + ] +} diff --git a/.agents/skills/README.md b/.agents/skills/README.md index f7093656b036..47ba32fecda7 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -52,3 +52,9 @@ The lock file generated by the updater becomes the ongoing record of installed c ## Repository setup After installing or materially updating the bundle, run `/setup-matt-pocock-skills` when repository-specific tracker, triage-label, or documentation configuration needs to be initialized or refreshed. + +## Ponytail + +Ponytail is **not** part of this vendored skill directory. It is installed as the official Codex plugin because its standard behavior depends on lifecycle hooks and runtime mode state, not only its six skills. See [docs/agents/ponytail.md](../../docs/agents/ponytail.md). + +Do not add Ponytail skill names to the Matt Pocock update allowlist; that would create duplicate skill installations. diff --git a/docs/agents/ponytail.md b/docs/agents/ponytail.md new file mode 100644 index 000000000000..f15c5aef23c1 --- /dev/null +++ b/docs/agents/ponytail.md @@ -0,0 +1,118 @@ +# Ponytail integration + +This repository carries a reviewable copy of the **official Ponytail Codex plugin** +from [DietrichGebert/ponytail](https://github.com/DietrichGebert/ponytail). + +The canonical project copy lives at: + +`third_party/ponytail/` + +Codex sees it through the repository marketplace: + +`.agents/plugins/marketplace.json` + +This keeps Ponytail's standard architecture intact while making the exact hooks and +skills used by this project part of the repository history. + +## What is vendored + +The project copy includes Ponytail's Codex runtime payload: + +- native `.codex-plugin/plugin.json` +- lifecycle hooks +- all six Ponytail skills +- package metadata +- upstream `AGENTS.md` +- MIT license +- uninstall helper +- upstream logo asset + +The executable hook and skill files are copied from upstream unchanged. + +There is one packaging-only difference: the local manifest points its cosmetic icon +fields at Ponytail's upstream `assets/logo-dark.svg` instead of the much larger PNG. +This does not change Ponytail behavior. + +The exact upstream commit is recorded in: + +`third_party/ponytail/UPSTREAM_REVISION` + +## Install + +Windows: + +```powershell +./scripts/setup-ponytail.ps1 +``` + +POSIX: + +```bash +./scripts/setup-ponytail.sh +``` + +The setup registers this repository as a local Codex marketplace when needed and +installs: + +`ponytail@llama-cpp-local` + +Codex supports repository marketplaces at `.agents/plugins/marketplace.json` and +local plugin entries that point at another path in the same repository. + +## Hook trust + +After installation, start Codex and open: + +`/hooks` + +Review and trust Ponytail's hooks. Do not bypass this approval boundary. + +The standard plugin then provides: + +- `SessionStart`: activates Ponytail and injects the active ruleset. +- `UserPromptSubmit`: tracks `lite`, `full`, `ultra`, and `off` mode changes. +- `SubagentStart`: propagates the active ruleset to subagents. + +Node.js must be available on `PATH`. + +## Default mode + +Ponytail's upstream default remains **full**. This repository does not override it. + +## Updating + +Refresh the project copy from upstream with: + +Windows: + +```powershell +./scripts/update-ponytail.ps1 +``` + +POSIX: + +```bash +./scripts/update-ponytail.sh +``` + +The updater shallow-clones current upstream `main`, replaces only the vendored +Ponytail runtime payload, records the new upstream commit, and reapplies the single +cosmetic SVG icon-path adaptation. + +Always inspect the resulting hook and skill diff before committing. Ponytail updates +can change executable lifecycle code, not just prompts. + +After accepting an update, restart Codex/ChatGPT so the local plugin cache refreshes +from the updated repository source. + +## Relationship to Matt Pocock skills + +The systems intentionally remain separate: + +- Matt Pocock skills: project-local skill copies under `.agents/skills/`, managed by + the `skills` CLI and `skills-lock.json`. +- Ponytail: a complete local Codex plugin under `third_party/ponytail/`, exposed + through the repository marketplace. + +Do not separately install Ponytail's six skills with the `skills` CLI; the plugin is +their authoritative source and also supplies their lifecycle behavior. diff --git a/scripts/setup-ponytail.ps1 b/scripts/setup-ponytail.ps1 new file mode 100644 index 000000000000..3042a24e4086 --- /dev/null +++ b/scripts/setup-ponytail.ps1 @@ -0,0 +1,37 @@ +$ErrorActionPreference = "Stop" + +function Require-Command([string]$Name) { + if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) { + throw "'$Name' is required but was not found on PATH." + } +} + +Require-Command "node" +Require-Command "codex" + +$RepoRoot = Split-Path -Parent $PSScriptRoot +Push-Location $RepoRoot +try { + $marketplaces = (& codex plugin marketplace list 2>&1 | Out-String) + if ($marketplaces -notmatch "llama-cpp-local") { + Write-Host "Registering the repository-local plugin marketplace..." + & codex plugin marketplace add . + if ($LASTEXITCODE -ne 0) { + throw "Failed to register the repository-local marketplace." + } + } + + Write-Host "Installing Ponytail from the repository-local marketplace..." + & codex plugin add ponytail@llama-cpp-local + if ($LASTEXITCODE -ne 0) { + throw "Failed to install the local Ponytail plugin." + } +} +finally { + Pop-Location +} + +Write-Host "" +Write-Host "Ponytail is installed from third_party/ponytail." +Write-Host "Start Codex, open /hooks, review Ponytail's hooks, and trust them." +Write-Host "Ponytail's upstream default mode is full." diff --git a/scripts/setup-ponytail.sh b/scripts/setup-ponytail.sh new file mode 100755 index 000000000000..7486bb70cb82 --- /dev/null +++ b/scripts/setup-ponytail.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +command -v node >/dev/null 2>&1 || { echo "node is required but was not found on PATH." >&2; exit 1; } +command -v codex >/dev/null 2>&1 || { echo "codex is required but was not found on PATH." >&2; exit 1; } + +repo_root="$(cd "$(dirname "$0")/.." && pwd)" +cd "$repo_root" + +if ! codex plugin marketplace list 2>&1 | grep -q 'llama-cpp-local'; then + echo "Registering the repository-local plugin marketplace..." + codex plugin marketplace add . +fi + +echo "Installing Ponytail from the repository-local marketplace..." +codex plugin add ponytail@llama-cpp-local + +cat <<'EOF' + +Ponytail is installed from third_party/ponytail. +Start Codex, open /hooks, review Ponytail's hooks, and trust them. +Ponytail's upstream default mode is full. +EOF diff --git a/scripts/update-ponytail.ps1 b/scripts/update-ponytail.ps1 new file mode 100644 index 000000000000..ffd145102733 --- /dev/null +++ b/scripts/update-ponytail.ps1 @@ -0,0 +1,83 @@ +$ErrorActionPreference = "Stop" + +function Require-Command([string]$Name) { + if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) { + throw "'$Name' is required but was not found on PATH." + } +} + +Require-Command "git" + +$RepoRoot = Split-Path -Parent $PSScriptRoot +$Dest = Join-Path $RepoRoot "third_party/ponytail" +$Temp = Join-Path ([System.IO.Path]::GetTempPath()) ("ponytail-" + [guid]::NewGuid().ToString("N")) + +try { + & git clone --depth 1 https://github.com/DietrichGebert/ponytail.git $Temp + if ($LASTEXITCODE -ne 0) { + throw "Failed to clone DietrichGebert/ponytail." + } + + $Revision = (& git -C $Temp rev-parse HEAD).Trim() + + if (Test-Path $Dest) { + Remove-Item -Recurse -Force $Dest + } + New-Item -ItemType Directory -Force -Path $Dest | Out-Null + New-Item -ItemType Directory -Force -Path (Join-Path $Dest "assets") | Out-Null + New-Item -ItemType Directory -Force -Path (Join-Path $Dest "scripts") | Out-Null + + Copy-Item -Recurse (Join-Path $Temp ".codex-plugin") $Dest + Copy-Item -Recurse (Join-Path $Temp "hooks") $Dest + Copy-Item -Recurse (Join-Path $Temp "skills") $Dest + Copy-Item (Join-Path $Temp "AGENTS.md") $Dest + Copy-Item (Join-Path $Temp "LICENSE") $Dest + Copy-Item (Join-Path $Temp "package.json") $Dest + Copy-Item (Join-Path $Temp "scripts/uninstall.js") (Join-Path $Dest "scripts/uninstall.js") + Copy-Item (Join-Path $Temp "assets/logo-dark.svg") (Join-Path $Dest "assets/logo-dark.svg") + + $ManifestPath = Join-Path $Dest ".codex-plugin/plugin.json" + $Manifest = [System.IO.File]::ReadAllText($ManifestPath) + $Manifest = $Manifest.Replace("./assets/logo.png", "./assets/logo-dark.svg") + [System.IO.File]::WriteAllText($ManifestPath, $Manifest, [System.Text.UTF8Encoding]::new($false)) + + [System.IO.File]::WriteAllText( + (Join-Path $Dest "UPSTREAM_REVISION"), + $Revision + [Environment]::NewLine, + [System.Text.UTF8Encoding]::new($false) + ) + + $VendorNote = @" +# Vendored Ponytail plugin + +Source: https://github.com/DietrichGebert/ponytail + +Upstream revision: `$Revision` + +This directory contains Ponytail's Codex runtime payload: its native plugin manifest, +lifecycle hooks, six skills, package metadata, license, upstream AGENTS.md, uninstall +helper, and logo asset. + +The runtime files are copied from upstream unchanged except for one packaging-only +manifest adjustment: the icon paths use the upstream `assets/logo-dark.svg` instead +of `assets/logo.png`. This avoids carrying a large binary asset while leaving all +skills and executable hook behavior unchanged. + +Refresh with `scripts/update-ponytail.ps1` or `scripts/update-ponytail.sh`, then +review the full diff before committing. +"@ + [System.IO.File]::WriteAllText( + (Join-Path $Dest "VENDORED.md"), + $VendorNote, + [System.Text.UTF8Encoding]::new($false) + ) + + Write-Host "Ponytail vendored at upstream revision $Revision" + Write-Host "Review: git diff -- third_party/ponytail" + Write-Host "Restart Codex/ChatGPT after accepting the update so the local plugin cache refreshes." +} +finally { + if (Test-Path $Temp) { + Remove-Item -Recurse -Force $Temp + } +} diff --git a/scripts/update-ponytail.sh b/scripts/update-ponytail.sh new file mode 100755 index 000000000000..fb35e90add39 --- /dev/null +++ b/scripts/update-ponytail.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail + +command -v git >/dev/null 2>&1 || { echo "git is required but was not found on PATH." >&2; exit 1; } + +repo_root="$(cd "$(dirname "$0")/.." && pwd)" +dest="$repo_root/third_party/ponytail" +tmp="$(mktemp -d)" + +cleanup() { + rm -rf "$tmp" +} +trap cleanup EXIT + +git clone --depth 1 https://github.com/DietrichGebert/ponytail.git "$tmp/src" +revision="$(git -C "$tmp/src" rev-parse HEAD)" + +rm -rf "$dest" +mkdir -p "$dest/assets" "$dest/scripts" + +cp -R "$tmp/src/.codex-plugin" "$dest/" +cp -R "$tmp/src/hooks" "$dest/" +cp -R "$tmp/src/skills" "$dest/" +cp "$tmp/src/AGENTS.md" "$dest/" +cp "$tmp/src/LICENSE" "$dest/" +cp "$tmp/src/package.json" "$dest/" +cp "$tmp/src/scripts/uninstall.js" "$dest/scripts/" +cp "$tmp/src/assets/logo-dark.svg" "$dest/assets/" + +python3 - "$dest/.codex-plugin/plugin.json" <<'PY' +from pathlib import Path +import sys +p = Path(sys.argv[1]) +s = p.read_text(encoding="utf-8") +p.write_text(s.replace("./assets/logo.png", "./assets/logo-dark.svg"), encoding="utf-8") +PY + +printf '%s\n' "$revision" > "$dest/UPSTREAM_REVISION" + +cat > "$dest/VENDORED.md" < + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/ponytail/hooks/claude-codex-hooks.json b/third_party/ponytail/hooks/claude-codex-hooks.json new file mode 100644 index 000000000000..0cd2fbafd597 --- /dev/null +++ b/third_party/ponytail/hooks/claude-codex-hooks.json @@ -0,0 +1,41 @@ +{ + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|clear|compact", + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/ponytail-activate.js\"", + "timeout": 5, + "statusMessage": "Loading ponytail mode..." + } + ] + } + ], + "SubagentStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/ponytail-subagent.js\"", + "timeout": 5, + "statusMessage": "Loading ponytail mode..." + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/ponytail-mode-tracker.js\"", + "timeout": 5, + "statusMessage": "Tracking ponytail mode..." + } + ] + } + ] + } +} diff --git a/third_party/ponytail/hooks/copilot-hooks.json b/third_party/ponytail/hooks/copilot-hooks.json new file mode 100644 index 000000000000..1210c35a4546 --- /dev/null +++ b/third_party/ponytail/hooks/copilot-hooks.json @@ -0,0 +1,21 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "bash": "node \"${PLUGIN_ROOT}/hooks/ponytail-activate.js\"", + "powershell": "node \"${PLUGIN_ROOT}\\hooks\\ponytail-activate.js\"", + "timeoutSec": 5 + } + ], + "userPromptSubmitted": [ + { + "type": "command", + "bash": "node \"${PLUGIN_ROOT}/hooks/ponytail-mode-tracker.js\"", + "powershell": "node \"${PLUGIN_ROOT}\\hooks\\ponytail-mode-tracker.js\"", + "timeoutSec": 5 + } + ] + } +} diff --git a/third_party/ponytail/hooks/cursor-hooks.json b/third_party/ponytail/hooks/cursor-hooks.json new file mode 100644 index 000000000000..0eb3cf746ede --- /dev/null +++ b/third_party/ponytail/hooks/cursor-hooks.json @@ -0,0 +1,17 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "command": "node \"PONYTAIL_DIR/hooks/ponytail-activate.js\"", + "timeout": 5 + } + ], + "beforeSubmitPrompt": [ + { + "command": "node \"PONYTAIL_DIR/hooks/ponytail-mode-tracker.js\"", + "timeout": 5 + } + ] + } +} diff --git a/third_party/ponytail/hooks/ponytail-activate.js b/third_party/ponytail/hooks/ponytail-activate.js new file mode 100755 index 000000000000..35d741ede3b4 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-activate.js @@ -0,0 +1,115 @@ +#!/usr/bin/env node +// ponytail — Claude Code SessionStart activation hook (also Codex, Copilot, +// Grok 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 { getDefaultMode, getClaudeDir, isShellSafe } = require('./ponytail-config'); +const { getPonytailInstructions } = require('./ponytail-instructions'); +const { + clearMode, + cursorRuleNotice, + cursorRulePath, + isCodex, + isCopilot, + isCursor, + setMode, + writeHookOutput, +} = require('./ponytail-runtime'); + +const claudeDir = getClaudeDir(); +const settingsPath = path.join(claudeDir, 'settings.json'); + +const mode = getDefaultMode(); + +// "off" mode — skip activation entirely, don't write flag or emit rules +if (mode === 'off') { + clearMode(); + const hookOutput = (isCodex || isCopilot || isCursor) ? '' : 'OK'; + writeHookOutput('SessionStart', 'off', hookOutput); + 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); + +// 3. Detect missing statusline config — nudge Claude to help set it up +if (!isCodex && !isCopilot && !isCursor) try { + let hasStatusline = false; + 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) { + hasStatusline = true; + } + } + + // 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. + const nudgeFlagPath = path.join(claudeDir, '.ponytail-statusline-nudged'); + if (!hasStatusline && !fs.existsSync(nudgeFlagPath)) { + try { fs.writeFileSync(nudgeFlagPath, ''); } catch (e) { /* best-effort */ } + const isWindows = process.platform === 'win32'; + const scriptName = isWindows ? 'ponytail-statusline.ps1' : 'ponytail-statusline.sh'; + const scriptPath = path.join(__dirname, scriptName); + if (isShellSafe(scriptPath)) { + const command = isWindows + ? `powershell -ExecutionPolicy Bypass -File "${scriptPath}"` + : `bash "${scriptPath}"`; + const statusLineSnippet = + '"statusLine": { "type": "command", "command": ' + JSON.stringify(command) + ' }'; + output += "\n\n" + + "STATUSLINE SETUP NEEDED: The ponytail plugin includes a statusline badge showing active mode " + + "(e.g. [PONYTAIL], [PONYTAIL:ULTRA]). It is not configured yet. " + + "To enable, add this to " + settingsPath + ": " + + statusLineSnippet + " " + + "Proactively offer to set this up for the user on first interaction."; + } else { + // ponytail: install path has shell metacharacters — don't embed it in a + // command snippet; have the agent wire it up by hand instead. + output += "\n\n" + + "STATUSLINE SETUP NEEDED: The ponytail plugin includes a statusline badge showing active mode. " + + "Its install path contains characters unsafe to embed in a shell command, so configure it manually: " + + "add a statusLine command of type \"command\" that runs " + scriptName + + " from the plugin's hooks directory to " + settingsPath + ", quoting/escaping the path for your shell. " + + "Proactively offer to set this up for the user on first interaction."; + } + } +} catch (e) { + // Silent fail — don't block session start over statusline detection +} + +try { + writeHookOutput('SessionStart', mode, output); +} catch (e) { + // Silent fail — stdout closed/EPIPE at hook exit must not surface as a hook failure +} diff --git a/third_party/ponytail/hooks/ponytail-config.js b/third_party/ponytail/hooks/ponytail-config.js new file mode 100755 index 000000000000..9ba7fdc2e785 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-config.js @@ -0,0 +1,169 @@ +#!/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 getDefaultMode() { + // 1. Environment variable (highest priority) + const envMode = process.env.PONYTAIL_DEFAULT_MODE; + // ponytail: a default must be a runtime level (off/lite/full/ultra); review is + // a session-only mode, never a valid default (#377). Validate against + // RUNTIME_MODES so a stray env var or config can't make review the default. + if (envMode && RUNTIME_MODES.includes(envMode.toLowerCase())) { + return envMode.toLowerCase(); + } + + // 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/, '')); + if (config.defaultMode && RUNTIME_MODES.includes(config.defaultMode.toLowerCase())) { + return config.defaultMode.toLowerCase(); + } + } 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, + getHideStatus, + getQuietStartup, + isShellSafe, + normalizeMode, + normalizeConfigMode, + normalizePersistedMode, + isDeactivationCommand, + writeDefaultMode, +}; diff --git a/third_party/ponytail/hooks/ponytail-instructions.js b/third_party/ponytail/hooks/ponytail-instructions.js new file mode 100755 index 000000000000..3ec3980a08d9 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-instructions.js @@ -0,0 +1,98 @@ +#!/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) { + return 'PONYTAIL MODE ACTIVE — level: ' + mode + '\n\n' + + 'You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.\n\n' + + '## Persistence\n\n' + + 'ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if unsure. Off only: "stop ponytail" / "normal mode".\n\n' + + 'Current level: **' + mode + '**. Switch: `/ponytail lite|full|ultra`.\n\n' + + '## The ladder\n\n' + + 'Before any code, stop at the first rung that holds (the ladder runs after you understand the problem, not instead of it — read the code it touches and trace the real flow first):\n' + + '1. Does this need to be built at all? (YAGNI)\n' + + '2. Does it already exist in this codebase? Reuse what is already here, do not re-write it.\n' + + '3. Does the standard library do this? Use it.\n' + + '4. Does a native platform feature cover it? Use it.\n' + + '5. Does an already-installed dependency solve it? Use it.\n' + + '6. Can this be one line? Make it one line.\n' + + '7. Only then: write the minimum code that works.\n\n' + + 'Bug fix = root cause, not symptom: grep every caller of the function you touch and fix the shared function once (a smaller diff than one guard per caller); patching only the path the ticket names leaves a sibling caller broken.\n\n' + + '## Rules\n\n' + + 'No abstractions that were not requested. No avoidable dependencies. No boilerplate nobody asked for. ' + + 'Deletion over addition. Boring over clever. Fewest files possible. ' + + 'Ship the lazy version and question the complex request in the same response — never stall. ' + + 'Between two same-size stdlib options, pick the one correct on edge cases. ' + + 'Mark deliberate simplifications that cut a real corner with a known ceiling, using a `ponytail:` comment that names the ceiling and upgrade path.\n\n' + + '## Output\n\n' + + 'Code first. Then at most three short lines: what was skipped, when to add it. ' + + 'If the explanation is longer than the code, delete the explanation. ' + + 'Explanation the user explicitly asked for is not debt, give it in full.\n\n' + + '## When NOT to be lazy\n\n' + + 'Never simplify away: understanding the problem (read it fully and trace the real flow before picking a rung — a small diff you do not understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, ' + + 'security measures, accessibility basics, the calibration real hardware needs (the platform is never the spec ideal), anything the user explicitly asked to keep. ' + + 'Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind (assert-based demo/self-check or one small test file; no frameworks). Trivial one-liners need no test.\n\n' + + '## Boundaries\n\n' + + 'Ponytail governs what you build, not how you talk. "stop ponytail" or "normal mode": revert. Level persists until changed or session end.'; +} + +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, +}; diff --git a/third_party/ponytail/hooks/ponytail-mode-tracker.js b/third_party/ponytail/hooks/ponytail-mode-tracker.js new file mode 100755 index 000000000000..59877fe19af3 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-mode-tracker.js @@ -0,0 +1,155 @@ +#!/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 { getDefaultMode, isDeactivationCommand, writeDefaultMode } = require('./ponytail-config'); +const { + clearMode, + cursorRuleNotice, + cursorRulePath, + 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; + if (/^[/@$]ponytail/.test(prompt)) { + const parts = prompt.split(/\s+/); + const cmd = parts[0].replace(/^[@$]/, '/'); + const arg = parts[1] || ''; + + let mode = null; + let isReportOnly = false; + + if (cmd === '/ponytail-review' || cmd === '/ponytail:ponytail-review') { + mode = 'review'; + } else if (cmd === '/ponytail' || cmd === '/ponytail:ponytail') { + // `/ponytail default ` 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); + writeHookOutput('UserPromptSubmit', dmode, 'PONYTAIL DEFAULT SET — new sessions start in ' + dmode + '.'); + } + return; // don't fall through to the session-mode switch + } + 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 === '') { + isReportOnly = true; + mode = readMode() || getDefaultMode(); + } else { + mode = getDefaultMode(); + } + } + + if (isReportOnly) { + writeHookOutput( + 'UserPromptSubmit', + mode, + 'PONYTAIL MODE ACTIVE — level: ' + mode, + ); + } else if (mode && mode !== 'off') { + setMode(mode); + modeSwitched = true; + // ponytail: Qoder needs the full ruleset every turn, so when a mode + // switch happens we fold the confirmation into the ruleset output + // below (one JSON on stdout) instead of emitting two separate writes. + if (!isQoder) { + // Cursor has no /ponytail command that would load the skill body + // for the new level, so the tracker delivers that level's ruleset + // along with the confirmation (#817). + const header = 'PONYTAIL MODE CHANGED — level: ' + mode; + writeHookOutput( + 'UserPromptSubmit', + mode, + isCursor ? header + '\n\n' + getPonytailInstructions(mode) : header, + ); + } + } else if (mode === 'off') { + clearMode(); + deactivated = true; + writeHookOutput('UserPromptSubmit', 'off', 'PONYTAIL MODE OFF'); + } + } + + // Detect deactivation + if (!modeSwitched && !deactivated && isDeactivationCommand(prompt)) { + clearMode(); + deactivated = true; + writeHookOutput('UserPromptSubmit', 'off', 'PONYTAIL MODE OFF'); + } + + // Qoder has no SessionStart event, so UserPromptSubmit does double duty: + // activate the default mode on first prompt (if no flag exists yet), then + // inject the ruleset on every prompt. Claude Code/Codex do this in + // SessionStart via ponytail-activate.js; Qoder can't, so we do it here. + // Skip when deactivated — user just turned ponytail off. + if (isQoder && !deactivated) { + let currentMode = readMode(); + if (!currentMode) { + // First prompt in session — initialize from config/env default + currentMode = getDefaultMode(); + if (currentMode !== 'off') { + try { setMode(currentMode); } catch (e) {} + } + } + if (currentMode && currentMode !== 'off') { + // ponytail: one JSON per invocation — mode-switch confirmation is + // folded into the ruleset header so Qoder gets both in one write. + const header = modeSwitched + ? 'PONYTAIL MODE CHANGED — level: ' + currentMode + '\n\n' + : ''; + writeHookOutput('UserPromptSubmit', currentMode, header + getPonytailInstructions(currentMode)); + } + } + } catch (e) { + // Silent fail + } +} + +process.stdin.on('data', chunk => { input += chunk; }); +process.stdin.on('end', finish); + +// Never hang the session. On Windows, Claude Code runs this hook through a +// PowerShell `if {}` wrapper that can swallow the piped prompt JSON, so stdin +// 'end' never fires and the hook blocks forever — freezing the session (#443). +// On error, or after a short fallback, process whatever arrived (recovering the +// mode if data came without EOF) and exit. unref() keeps the timer from adding +// latency to the normal path, where 'end' fires first. Mirrors the best-effort, +// never-block contract the other lifecycle hooks already follow. +process.stdin.on('error', () => { finish(); process.exit(0); }); +setTimeout(() => { finish(); process.exit(0); }, 1000).unref(); diff --git a/third_party/ponytail/hooks/ponytail-runtime.js b/third_party/ponytail/hooks/ponytail-runtime.js new file mode 100755 index 000000000000..1e24c1822407 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-runtime.js @@ -0,0 +1,144 @@ +const fs = require('fs'); +const path = require('path'); +const os = require('os'); +const { getClaudeDir, getConfigDir } = require('./ponytail-config'); + +const STATE_FILE = '.ponytail-active'; + +// ponytail: VS Code Copilot never sets COPILOT_PLUGIN_DATA — it only injects +// CLAUDE_PLUGIN_ROOT, pointed at an install path under .vscode/agent-plugins/ +// (#528). Without this fallback isCopilot was false, so ponytail assumed +// native Claude Code and emitted the statusline nudge, which VS Code Copilot +// doesn't read. +function isVsCodeCopilotRoot(pluginRoot) { + if (!pluginRoot) return false; + return pluginRoot.split(/[\\/]+/).includes('agent-plugins') && + pluginRoot.toLowerCase().includes('.vscode'); +} + +const isCopilot = Boolean(process.env.COPILOT_PLUGIN_DATA) || + isVsCodeCopilotRoot(process.env.CLAUDE_PLUGIN_ROOT); +const isCodex = !isCopilot && Boolean(process.env.PLUGIN_DATA); +const isQoder = !isCopilot && !isCodex && Boolean(process.env.QODER_SESSION_ID); +// Cursor (#817): CURSOR_VERSION is set only in the environment Cursor builds +// for hook processes (Cursor 3.20.17 assigns it in exactly one place, the hook +// env builder), so it never leaks into a Claude Code session running inside +// Cursor's terminal. Cursor also sets it when it runs a Claude-format plugin's +// hooks next to CLAUDE_PLUGIN_ROOT, and it needs Cursor-shaped JSON either +// way, so this check comes after the hosts with their own data dirs. +const isCursor = !isCopilot && !isCodex && !isQoder && Boolean(process.env.CURSOR_VERSION); + +let stateDir = getClaudeDir(); +if (isCodex) stateDir = process.env.PLUGIN_DATA; +// COPILOT_PLUGIN_DATA is unset under VS Code Copilot, so fall back to +// getClaudeDir() rather than building a path from undefined. +if (isCopilot) stateDir = process.env.COPILOT_PLUGIN_DATA || getClaudeDir(); +if (isQoder) stateDir = path.join(os.homedir(), '.qoder'); +if (isCursor) stateDir = path.join(os.homedir(), '.cursor'); + +const statePath = path.join(stateDir, STATE_FILE); + +function setMode(mode) { + fs.mkdirSync(path.dirname(statePath), { recursive: true }); + fs.writeFileSync(statePath, mode); +} + +function clearMode() { + try { fs.unlinkSync(statePath); } catch (e) {} +} + +// Live mode written by activate/mode-tracker. Absent flag = ponytail off. +function readMode() { + try { + return fs.readFileSync(statePath, 'utf8').trim() || null; + } catch (e) { + return null; + } +} + +// Cursor's always-on project rule (.cursor/rules/ponytail.mdc) already puts the +// ruleset in front of every prompt and no hook can switch a rule off, so while +// it is in the workspace the hooks step back instead of injecting a second, +// possibly contradicting, copy (#817). Cursor hands every hook the workspace +// root as CURSOR_PROJECT_DIR; project hooks also run from that directory. +// ponytail: first workspace root only, a rule in a secondary folder of a +// multi-root workspace goes undetected. +function cursorRulePath() { + const root = process.env.CURSOR_PROJECT_DIR || process.cwd(); + const rule = path.join(root, '.cursor', 'rules', 'ponytail.mdc'); + return fs.existsSync(rule) ? rule : null; +} + +function cursorRuleNotice(rule) { + return 'PONYTAIL: the always-on Cursor rule ' + rule + ' is active in this workspace and ' + + 'already carries the ponytail ruleset, so the ponytail hooks injected nothing further. ' + + 'Mode switching (/ponytail lite|full|ultra|off, "stop ponytail") is unavailable while ' + + 'that rule exists. When the user tries to switch or turn off ponytail, tell them to ' + + 'delete that rule so hooks.json can manage the level.'; +} + +function writeHookOutput(event, mode, context = '') { + if (isCopilot) { + // Copilot reads additionalContext on SessionStart; ignores output elsewhere. + process.stdout.write(JSON.stringify( + event === 'SessionStart' && context ? { additionalContext: context } : {})); + return; + } + if (isCodex) { + const output = { systemMessage: `PONYTAIL:${mode.toUpperCase()}` }; + if (context) { + output.hookSpecificOutput = { + hookEventName: event, + additionalContext: context, + }; + } + process.stdout.write(JSON.stringify(output)); + return; + } + if (isQoder) { + // Qoder: hookSpecificOutput JSON, same shape as Codex minus systemMessage. + // UserPromptSubmit additionalContext is injected into the Agent's conversation. + const output = {}; + if (context) { + output.hookSpecificOutput = { + hookEventName: event, + additionalContext: context, + }; + } + process.stdout.write(JSON.stringify(output)); + return; + } + if (isCursor) { + // Cursor parses stdout as JSON and treats empty stdout as "nothing to + // say"; raw text would be logged as a parse error. sessionStart takes + // additional_context into the conversation's system context; + // beforeSubmitPrompt needs continue:true and, in Cursor 3.20.17, injects + // additional_context into that turn (docs/cursor-hooks.md). + if (!context) return; + const output = { additional_context: context }; + if (event === 'UserPromptSubmit') output.continue = true; + process.stdout.write(JSON.stringify(output)); + return; + } + // Native Claude: SessionStart accepts raw stdout, but SubagentStart needs the + // hookSpecificOutput JSON form or the context is dropped. + if (event === 'SubagentStart') { + process.stdout.write(JSON.stringify( + { hookSpecificOutput: { hookEventName: event, additionalContext: context } })); + return; + } + process.stdout.write(context); +} + +module.exports = { + clearMode, + cursorRuleNotice, + cursorRulePath, + isCodex, + isCopilot, + isCursor, + isQoder, + readMode, + setMode, + writeHookOutput, +}; diff --git a/third_party/ponytail/hooks/ponytail-statusline.ps1 b/third_party/ponytail/hooks/ponytail-statusline.ps1 new file mode 100644 index 000000000000..b75b142143b9 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-statusline.ps1 @@ -0,0 +1,24 @@ +# CLAUDE_CONFIG_DIR overrides ~/.claude, matching where the hooks write the flag (issue #34) +$ClaudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" } +$Flag = Join-Path $ClaudeDir ".ponytail-active" +if (-not (Test-Path $Flag)) { + exit 0 +} + +$Mode = "" +try { + $Mode = (Get-Content $Flag -ErrorAction Stop | Select-Object -First 1).Trim() +} catch { + exit 0 +} + +$Esc = [char]27 +# ultra is the high-intensity mode; flag it amber so it stands out from the +# default green. The level is still in the text, so color is a redundant cue. +$Color = if ($Mode -eq "ultra") { "173" } else { "108" } +if ([string]::IsNullOrEmpty($Mode) -or $Mode -eq "full") { + [Console]::Write("${Esc}[38;5;${Color}m[PONYTAIL]${Esc}[0m") +} else { + $Suffix = $Mode.ToUpperInvariant() + [Console]::Write("${Esc}[38;5;${Color}m[PONYTAIL:$Suffix]${Esc}[0m") +} diff --git a/third_party/ponytail/hooks/ponytail-statusline.sh b/third_party/ponytail/hooks/ponytail-statusline.sh new file mode 100755 index 000000000000..7d0616051b5a --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-statusline.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# CLAUDE_CONFIG_DIR overrides ~/.claude, matching where the hooks write the flag (issue #34) +flag="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.ponytail-active" +[ -f "$flag" ] || exit 0 + +mode=$(head -n1 "$flag" | tr -d '[:space:]') + +# ultra is the high-intensity mode; flag it amber so it stands out from the +# default green at a glance. The level is still in the text, so color is a +# redundant cue, not the only one. +color=108 +[ "$mode" = "ultra" ] && color=173 + +if [ -z "$mode" ] || [ "$mode" = "full" ]; then + printf '\033[38;5;%sm[PONYTAIL]\033[0m' "$color" +else + printf '\033[38;5;%sm[PONYTAIL:%s]\033[0m' "$color" "$(printf '%s' "$mode" | tr '[:lower:]' '[:upper:]')" +fi diff --git a/third_party/ponytail/hooks/ponytail-subagent.js b/third_party/ponytail/hooks/ponytail-subagent.js new file mode 100755 index 000000000000..f2a7c7763261 --- /dev/null +++ b/third_party/ponytail/hooks/ponytail-subagent.js @@ -0,0 +1,77 @@ +#!/usr/bin/env node +// ponytail — Claude Code SubagentStart hook +// +// SessionStart context is parent-thread only and never reaches subagents, so +// without this every Task-spawned agent runs ponytail-unaware (issue #252). +// When ponytail mode is active, inject the same ruleset into each subagent. +// +// Scoping (opt-in, issue #506): set PONYTAIL_SUBAGENT_MATCHER to a regex and +// the ruleset is injected only into subagents whose agent_type matches. The +// regex is unanchored and case-insensitive — "explore|general" matches either, +// "^general$" is exact. Unset means inject into every subagent, as before. + +const { getPonytailInstructions } = require('./ponytail-instructions'); +const { readMode, writeHookOutput } = require('./ponytail-runtime'); + +const mode = readMode(); + +// Absent flag or off → ponytail isn't active; inject nothing. +if (!mode || mode === 'off') { + process.exit(0); +} + +function inject() { + try { + writeHookOutput('SubagentStart', mode, getPonytailInstructions(mode)); + } catch (e) { + // Silent fail — a stdout error at hook exit must not surface as a hook failure. + } +} + +// A bad regex must never crash the hook; treat it as "no matcher" and inject. +let matcherRe = null; +try { + if (process.env.PONYTAIL_SUBAGENT_MATCHER) { + matcherRe = new RegExp(process.env.PONYTAIL_SUBAGENT_MATCHER, 'i'); + } +} catch (e) { + matcherRe = null; +} + +// No matcher → keep the original synchronous, stdin-independent path. On Windows +// the PowerShell `if {}` wrapper can swallow the piped JSON so stdin 'end' never +// fires (#443); the default path must not wait on stdin or it would stall every +// subagent spawn. +if (!matcherRe) { + inject(); + process.exit(0); +} + +// Matcher set → read agent_type from stdin and skip only on a definite +// mismatch. Missing/unparseable agent_type, a stdin error, or the timeout all +// fail open (inject), so scoping never silently drops the persona. +let input = ''; +let done = false; + +function finish() { + if (done) return; + done = true; + + let agentType = ''; + try { + // Strip UTF-8 BOM some shells prepend when piping (breaks JSON.parse) + agentType = String(JSON.parse(input.replace(/^\uFEFF/, '')).agent_type || '').trim(); + } catch (e) { + // Unparseable payload — fall through and inject to be safe. + } + if (agentType && !matcherRe.test(agentType)) { + process.exit(0); + } + inject(); +} + +process.stdin.on('data', chunk => { input += chunk; }); +process.stdin.on('end', finish); +// Never block the session (#443): recover on stdin error or a short fallback. +process.stdin.on('error', () => { finish(); process.exit(0); }); +setTimeout(() => { finish(); process.exit(0); }, 1000).unref(); diff --git a/third_party/ponytail/hooks/qoder-hooks.json b/third_party/ponytail/hooks/qoder-hooks.json new file mode 100644 index 000000000000..8865abaa7bcd --- /dev/null +++ b/third_party/ponytail/hooks/qoder-hooks.json @@ -0,0 +1,26 @@ +{ + "_comment": "Reference template — copy the 'hooks' object into your .qoder/settings.json or ~/.qoder/settings.json. Replace PONYTAIL_DIR with the path to your ponytail checkout (e.g. ~/.qoder/plugins/ponytail or the npm global install path).", + "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node PONYTAIL_DIR/hooks/ponytail-mode-tracker.js" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "task|Task", + "hooks": [ + { + "type": "command", + "command": "node PONYTAIL_DIR/hooks/ponytail-subagent.js" + } + ] + } + ] + } +} diff --git a/third_party/ponytail/package.json b/third_party/ponytail/package.json new file mode 100644 index 000000000000..b17f2ba13038 --- /dev/null +++ b/third_party/ponytail/package.json @@ -0,0 +1,48 @@ +{ + "name": "@dietrichgebert/ponytail", + "version": "4.10.0", + "description": "Lazy senior dev mode for AI agents. The best code is the code you never wrote.", + "keywords": ["opencode-plugin", "opencode", "ponytail", "pi-package", "pi", "skills", "qoder"], + "license": "MIT", + "author": { + "name": "Dietrich Gebert", + "url": "https://github.com/DietrichGebert" + }, + "homepage": "https://github.com/DietrichGebert/ponytail", + "repository": { + "type": "git", + "url": "git+https://github.com/DietrichGebert/ponytail.git" + }, + "bugs": { + "url": "https://github.com/DietrichGebert/ponytail/issues" + }, + "main": "./.opencode/plugins/ponytail.mjs", + "exports": { + ".": "./.opencode/plugins/ponytail.mjs", + "./plugin": "./.opencode/plugins/ponytail.mjs" + }, + "files": [ + "AGENTS.md", + "hooks/", + "skills/", + ".opencode/", + ".qoder/", + ".qoder-plugin/", + "pi-extension/", + "scripts/uninstall.js", + "scripts/cursor-hooks.js", + "assets/", + "LICENSE" + ], + "scripts": { + "test": "node --test tests/*.test.js && npm test --prefix pi-extension && npm test --prefix ponytail-mcp" + }, + "pi": { + "extensions": ["./pi-extension/index.js"], + "skills": ["./skills"] + }, + "publishConfig": { + "access": "public" + } +} + diff --git a/third_party/ponytail/scripts/uninstall.js b/third_party/ponytail/scripts/uninstall.js new file mode 100755 index 000000000000..7bb8cc365883 --- /dev/null +++ b/third_party/ponytail/scripts/uninstall.js @@ -0,0 +1,77 @@ +#!/usr/bin/env node +// ponytail — removes state ponytail wrote outside the plugin's own files: +// the mode flag, the config file, the statusLine entry it added to +// settings.json, and its entries in ~/.cursor/hooks.json. Plugin files +// themselves are removed by each host's own uninstall command (see README); +// this only cleans up what those commands can't see. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { getConfigPath, getClaudeDir } = require('../hooks/ponytail-config'); +const cursorHooks = require('./cursor-hooks'); + +const STATUSLINE_SCRIPT = 'ponytail-statusline'; + +function removeIfExists(filePath, label) { + try { + fs.unlinkSync(filePath); + console.log(`Removed ${label}: ${filePath}`); + } catch (e) { + if (e.code !== 'ENOENT') throw e; + } +} + +removeIfExists(path.join(getClaudeDir(), '.ponytail-active'), 'mode flag'); +removeIfExists(path.join(os.homedir(), '.cursor', '.ponytail-active'), 'Cursor mode flag'); +removeIfExists(getConfigPath(), 'config file'); + +// Cursor hooks (#817): drop only ponytail's entries from ~/.cursor/hooks.json, +// keep every other hook the user configured there. +try { + const hooksFile = cursorHooks.uninstall('user'); + if (hooksFile) console.log(`Removed ponytail hooks from ${hooksFile}`); +} catch (e) { + if (e instanceof SyntaxError) { + // ponytail: malformed hooks.json — can't safely edit it; leave intact, warn + console.warn(`~/.cursor/hooks.json is malformed — could not remove the ponytail hook entries. Remove them manually from: ${cursorHooks.hooksPath('user')} (${e.message})`); + } else { + throw e; + } +} + +const settingsPath = path.join(getClaudeDir(), 'settings.json'); +try { + const raw = fs.readFileSync(settingsPath, 'utf8').replace(/^\uFEFF/, ''); + const settings = JSON.parse(raw); + const cmd = settings.statusLine && settings.statusLine.command; + // Only remove the parts ponytail owns. If the user combined statuslines + // (e.g. caveman && ponytail), keep the other plugin's command intact. + // ponytail: splits on && / ; to detect other segments — good enough; a user + // piping statuslines together is on their own. + if (typeof cmd === 'string' && cmd.includes(STATUSLINE_SCRIPT)) { + const parts = cmd + .split(/&&|;/) + .map((s) => s.trim()) + .filter(Boolean); + const others = parts.filter((s) => !s.includes(STATUSLINE_SCRIPT)); + if (others.length === 0) { + delete settings.statusLine; + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8'); + console.log(`Removed ponytail statusLine entry from ${settingsPath}`); + } else { + settings.statusLine.command = others.join(' && '); + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8'); + console.log(`Removed ponytail statusLine segment from ${settingsPath}`); + } + } +} catch (e) { + if (e.code === 'ENOENT') { + // no settings.json — nothing to clean + } else if (e instanceof SyntaxError) { + // ponytail: malformed settings.json — can't safely edit it; leave intact, warn + console.warn(`settings.json is malformed — could not remove the ponytail statusLine entry. Remove it manually from: ${settingsPath} (${e.message})`); + } else { + throw e; + } +} diff --git a/third_party/ponytail/skills/ponytail-audit/SKILL.md b/third_party/ponytail/skills/ponytail-audit/SKILL.md new file mode 100644 index 000000000000..5582d10335da --- /dev/null +++ b/third_party/ponytail/skills/ponytail-audit/SKILL.md @@ -0,0 +1,41 @@ +--- +name: ponytail-audit +description: > + Whole-repo audit for over-engineering. Like ponytail-review, but scans the + entire codebase instead of a diff: a ranked list of what to delete, simplify, + or replace with stdlib/native equivalents. Use when the user says "audit this + codebase", "audit for over-engineering", "what can I delete from this repo", + "find bloat", "ponytail-audit", or "/ponytail-audit". One-shot report, does + not apply fixes. +--- + +ponytail-review, repo-wide. Scan the whole tree instead of a diff. Rank +findings biggest cut first. + +## Tags + +Same as ponytail-review: + +- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing. +- `stdlib:` hand-rolled thing the standard library ships. Name the function. +- `native:` dependency or code doing what the platform already does. Name the feature. +- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller. +- `shrink:` same logic, fewer lines. Show the shorter form. + +## Hunt + +Deps the stdlib or platform already ships, single-implementation interfaces, +factories with one product, wrappers that only delegate, files exporting one +thing, dead flags and config, hand-rolled stdlib. + +## Output + +One line per finding, ranked: ` . . [path]`. +End with `net: - lines, - deps possible.` Nothing to cut: `Lean already. Ship.` + +## Boundaries + +Scope: over-engineering and complexity only. Correctness bugs, security holes, +and performance are explicitly out of scope. Route them to a normal review +pass. Lists findings, applies nothing. One-shot. +"stop ponytail-audit" or "normal mode" to revert. diff --git a/third_party/ponytail/skills/ponytail-debt/SKILL.md b/third_party/ponytail/skills/ponytail-debt/SKILL.md new file mode 100644 index 000000000000..ecbc0ca8161b --- /dev/null +++ b/third_party/ponytail/skills/ponytail-debt/SKILL.md @@ -0,0 +1,44 @@ +--- +name: ponytail-debt +description: > + Harvest every `ponytail:` comment in the codebase into a debt ledger, so the + deliberate shortcuts and deferrals ponytail leaves behind get tracked instead + of rotting into "later means never". Use when the user says "ponytail debt", + "/ponytail-debt", "what did ponytail defer", "list the shortcuts", "ponytail + ledger", or "what did we mark to do later". One-shot report, changes nothing. +--- + +Every deliberate ponytail shortcut is marked with a `ponytail:` comment naming +its ceiling and upgrade path. This collects them into one ledger so a deferral +can't quietly become permanent. + +## Scan + +Grep the repo for comment markers, skipping `node_modules`, `.git`, and build +output: + +`grep -rnE '(#|//) ?ponytail:' .` (add other comment prefixes if your stack uses them) + +Each hit is one ledger row. The comment prefix keeps prose that merely mentions +the convention out of the ledger. + +## Output + +One row per marker, grouped by file: + +`:, . ceiling: . upgrade: .` + +The convention is `ponytail: , `, so pull the ceiling +and the trigger straight from the comment. Want an owner per row too? add +`git blame -L,`. + +Flag the rot risk: any `ponytail:` comment that names no upgrade path or +trigger gets a `no-trigger` tag, those are the ones that silently rot. + +End with ` markers, with no trigger.` Nothing found: `No ponytail: debt. Clean ledger.` + +## Boundaries + +Reads and reports only, changes nothing. To persist it, ask and it writes the +ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot. "stop ponytail-debt" or +"normal mode" to revert. diff --git a/third_party/ponytail/skills/ponytail-gain/SKILL.md b/third_party/ponytail/skills/ponytail-gain/SKILL.md new file mode 100644 index 000000000000..012e37b6bf31 --- /dev/null +++ b/third_party/ponytail/skills/ponytail-gain/SKILL.md @@ -0,0 +1,50 @@ +--- +name: ponytail-gain +description: > + Show ponytail's measured impact as a compact scoreboard: less code, less + cost, more speed, from the benchmark medians. One-shot display, not a + persistent mode, and not a per-repo number. Trigger: /ponytail-gain, + "ponytail gain", "what does ponytail save", "show ponytail impact", + "ponytail scoreboard". +--- + +# Ponytail Gain + +Display this scoreboard when invoked. One-shot: do NOT change mode, write flag +files, or persist anything. + +The figures are the published benchmark medians (5 everyday tasks: email +validator, debounce, CSV sum, countdown timer, rate limiter; three models: +Haiku, Sonnet, Opus). They are measured, not computed from the current repo. +Source: `benchmarks/` and the README. + +## Scoreboard + +Render plain ASCII bars. The bar length shows the measured range; the label +carries the exact figure: + +``` + ponytail gain benchmark median · 5 tasks · 3 models + + Lines of code no-skill ████████████████████ 100% + ponytail ██▌················· 6–20% ▼ 80–94% + Cost no-skill ████████████████████ 100% + ponytail █████▌·············· 23–53% ▼ 47–77% + Speed ponytail ▸ 3–6× faster + + This repo: /ponytail-debt (shortcuts you deferred) + /ponytail-audit (what's still cuttable) +``` + +## Honesty boundary + +These are benchmark medians, not this repo. NEVER print a per-repo savings +number ("you saved X lines/tokens here"): the unbuilt version was never +written, so there is no real baseline to subtract from in a live repo. The +only real per-repo figures come from `/ponytail-debt` (a counted ledger), and +this card points there instead of inventing one. + +## Boundaries + +One-shot display. Edits nothing, changes no mode. +"stop ponytail" or "normal mode": revert. diff --git a/third_party/ponytail/skills/ponytail-help/SKILL.md b/third_party/ponytail/skills/ponytail-help/SKILL.md new file mode 100644 index 000000000000..ba145c0ebb7c --- /dev/null +++ b/third_party/ponytail/skills/ponytail-help/SKILL.md @@ -0,0 +1,71 @@ +--- +name: ponytail-help +description: > + Quick-reference card for all ponytail modes, skills, and commands. + One-shot display, not a persistent mode. Trigger: /ponytail-help, + "ponytail help", "what ponytail commands", "how do I use ponytail". +--- + +# Ponytail Help + +Display this reference card when invoked. One-shot, do NOT change mode, +write flag files, or persist anything. + +## Levels + +| Level | Trigger | What change | +|-------|---------|-------------| +| **Lite** | `/ponytail lite` | Build what's asked, name the lazier alternative in one line. | +| **Full** | `/ponytail` | The ladder enforced: YAGNI → stdlib → native → one line → minimum. Default. | +| **Ultra** | `/ponytail ultra` | YAGNI extremist. Deletion before addition. Challenges requirements before building. | + +Level sticks until changed or session end. + +## Skills + +| Skill | Trigger | What it does | +|-------|---------|--------------| +| **ponytail** | `/ponytail` | Lazy mode itself. Simplest solution that works. | +| **ponytail-review** | `/ponytail-review` | Over-engineering review: `L42: yagni: factory, one product. Inline.` | +| **ponytail-audit** | `/ponytail-audit` | Whole-repo over-engineering audit: ranked list of what to delete. | +| **ponytail-debt** | `/ponytail-debt` | Harvest `ponytail:` shortcut comments into a tracked ledger. | +| **ponytail-gain** | `/ponytail-gain` | Measured-impact scoreboard: less code, less cost, more speed. | +| **ponytail-help** | `/ponytail-help` | This card. | + +Codex uses `@ponytail`, `@ponytail-review`, and `@ponytail-help`; Claude Code +and OpenCode use the slash-command forms above (OpenCode ships all six as +slash commands). + +## Deactivate + +Say "stop ponytail" or "normal mode". Resume anytime with `/ponytail`. +`/ponytail off` also works. + +## Configure Default Mode + +Default mode = `full`, auto-active every session. Change it: + +**Environment variable** (highest priority): +```bash +export PONYTAIL_DEFAULT_MODE=ultra +``` + +**Config file** (`~/.config/ponytail/config.json`, Windows: `%APPDATA%\ponytail\config.json`): +```json +{ "defaultMode": "lite" } +``` + +Set `"off"` to disable auto-activation on session start, activate manually +with `/ponytail` when wanted. + +Resolution: env var > config file > `full`. + +## Update + +Enable auto-update once: open `/plugin`, go to Marketplaces, pick ponytail, Enable auto-update. Claude Code then pulls new versions at startup (run `/reload-plugins` when it prompts). Manual refresh: `/plugin marketplace update ponytail` then `/reload-plugins`. + +If `/plugin` is not recognized, your Claude Code is out of date. Update it (`npm install -g @anthropic-ai/claude-code@latest`, or `brew upgrade claude-code`) and restart. Other hosts use their own update flow. + +## More + +Full docs + examples: https://github.com/DietrichGebert/ponytail diff --git a/third_party/ponytail/skills/ponytail-review/SKILL.md b/third_party/ponytail/skills/ponytail-review/SKILL.md new file mode 100644 index 000000000000..e137a855bd87 --- /dev/null +++ b/third_party/ponytail/skills/ponytail-review/SKILL.md @@ -0,0 +1,57 @@ +--- +name: ponytail-review +description: > + Code review focused exclusively on over-engineering. Finds what to delete: + reinvented standard library, unneeded dependencies, speculative abstractions, + dead flexibility. One line per finding: location, what to cut, what replaces + it. Use when the user says "review for over-engineering", "what can we + delete", "is this over-engineered", "simplify review", or invokes + /ponytail-review. Complements correctness-focused review, this one only + hunts complexity. +--- + +Review diffs for unnecessary complexity. One line per finding: location, what +to cut, what replaces it. The diff's best outcome is getting shorter. + +## Format + +`L: . .`, or `:L: ...` for +multi-file diffs. + +Tags: + +- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing. +- `stdlib:` hand-rolled thing the standard library ships. Name the function. +- `native:` dependency or code doing what the platform already does. Name the feature. +- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller. +- `shrink:` same logic, fewer lines. Show the shorter form. + +## Examples + +❌ "This EmailValidator class might be more complex than necessary, have you +considered whether all these validation rules are needed at this stage?" + +✅ `L12-38: stdlib: 27-line validator class. "@" in email, 1 line, real validation is the confirmation mail.` + +✅ `L4: native: moment.js imported for one format call. Intl.DateTimeFormat, 0 deps.` + +✅ `repo.py:L88: yagni: AbstractRepository with one implementation. Inline it until a second one exists.` + +✅ `L52-71: delete: retry wrapper around an idempotent local call. Nothing replaces it.` + +✅ `L30-44: shrink: manual loop builds dict. dict(zip(keys, values)), 1 line.` + +## Scoring + +End with the only metric that matters: `net: - lines possible.` + +If there is nothing to cut, say `Lean already. Ship.` and stop. + +## Boundaries + +Scope: over-engineering and complexity only. Correctness bugs, security holes, +and performance are explicitly out of scope. Route them to a normal review +pass, not this one. A single smoke test or `assert`-based +self-check is the ponytail minimum, not bloat, never flag it for deletion. +Does not apply the fixes, only lists them. +"stop ponytail-review" or "normal mode": revert to verbose review style. diff --git a/third_party/ponytail/skills/ponytail/SKILL.md b/third_party/ponytail/skills/ponytail/SKILL.md new file mode 100644 index 000000000000..02c0712c8627 --- /dev/null +++ b/third_party/ponytail/skills/ponytail/SKILL.md @@ -0,0 +1,120 @@ +--- +name: ponytail +description: > + Forces the laziest solution that actually works, simplest, shortest, most + minimal. Channels a senior dev who has seen everything: question whether the + task needs to exist at all (YAGNI), reach for the standard library before + custom code, native platform features before dependencies, one line before + fifty. Supports intensity levels: lite, full (default), ultra. Use on ANY + coding task: writing, adding, refactoring, fixing, reviewing, or designing + code, and choosing libraries or dependencies. Also use whenever the user + says "ponytail", "be lazy", "lazy mode", "simplest solution", "minimal + solution", "yagni", "do less", or "shortest path", or complains about + over-engineering, bloat, boilerplate, or unnecessary dependencies. Do NOT + use for non-coding requests (general knowledge, prose, translation, + summaries, recipes). +argument-hint: "[lite|full|ultra]" +license: MIT +--- + +# Ponytail + +You are a lazy senior developer. Lazy means efficient, not careless. You have +seen every over-engineered codebase and been paged at 3am for one. The best +code is the code never written. + +## Persistence + +ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if +unsure. Off only: "stop ponytail" / "normal mode". Default: **full**. +Switch: `/ponytail lite|full|ultra`. + +## The ladder + +Stop at the first rung that holds: + +1. **Does this need to exist at all?** Speculative need = skip it, say so in one line. (YAGNI) +2. **Already in this codebase?** A helper, util, type, or pattern that already lives here → reuse it. Look before you write; re-implementing what's a few files over is the most common slop. +3. **Stdlib does it?** Use it. +4. **Native platform feature covers it?** `` over a picker lib, CSS over JS, DB constraint over app code. +5. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do. +6. **Can it be one line?** One line. +7. **Only then:** the minimum code that works. + +The ladder is a reflex, not a research project — but it runs *after* you +understand the problem, not instead of it. Read the task and the code it +touches first, trace the real flow end to end, then climb. Two rungs work → +take the higher one and move on. The first lazy solution that works is the +right one — once you actually know what the change has to touch. + +**Bug fix = root cause, not symptom.** A report names a symptom. Before you +edit, grep every caller of the function you're about to touch. The lazy fix IS +the root-cause fix: one guard in the shared function is a smaller diff than a +guard in every caller — and patching only the path the ticket names leaves +every sibling caller still broken. Fix it once, where all callers route through. + +## Rules + +- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes. +- No boilerplate, no scaffolding "for later", later can scaffold for itself. +- Deletion over addition. Boring over clever, clever is what someone decodes at 3am. +- Fewest files possible. Shortest working diff wins — but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug. +- Complex request? Ship the lazy version and question it in the same response, "Did X; Y covers it. Need full X? Say so." Never stall on an answer you can default. +- Two stdlib options, same size? Take the one that's correct on edge cases. Lazy means writing less code, not picking the flimsier algorithm. +- Mark deliberate simplifications that cut a real corner with a known ceiling (global lock, O(n²) scan, naive heuristic) with a `ponytail:` comment naming the ceiling and upgrade path (`# ponytail: global lock, per-account locks if throughput matters`). + +## Output + +Code first. Then at most three short lines: what was skipped, when to add it. +No essays, no feature tours, no design notes. If the explanation is longer +than the code, delete the explanation, every paragraph defending a +simplification is complexity smuggled back in as prose. Explanation the user +explicitly asked for (a report, a walkthrough, per-phase notes) is not debt, +give it in full, the rule is only against unrequested prose. + +Pattern: `[code] → skipped: [X], add when [Y].` + +## Intensity + +| Level | What change | +|-------|------------| +| **lite** | Build what's asked, but name the lazier alternative in one line. User picks. | +| **full** | The ladder enforced. Stdlib and native first. Shortest diff, shortest explanation. Default. | +| **ultra** | YAGNI extremist. Deletion before addition. Ship the one-liner and challenge the rest of the requirement in the same breath. | + +Example: "Add a cache for these API responses." +- lite: "Done, cache added. FYI: `functools.lru_cache` covers this in one line if you'd rather not own a cache class." +- full: "`@lru_cache(maxsize=1000)` on the fetch function. Skipped custom cache class, add when lru_cache measurably falls short." +- ultra: "No cache until a profiler says so. When it does: `@lru_cache`. A hand-rolled TTL cache class is a bug farm with a hit rate." + +## When NOT to be lazy + +Never simplify away: input validation at trust boundaries, error handling +that prevents data loss, security measures, accessibility basics, anything +explicitly requested. User insists on the full version → build it, no +re-arguing. + +Never lazy about understanding the problem. The ladder shortens the +solution, never the reading. Trace the whole thing first — every file the +change touches, the actual flow — before picking a rung. Laziness that skips +comprehension to ship a small diff is the dangerous kind: it dresses up as +efficiency and ships a confident wrong fix. Read fully, then be lazy. + +Hardware is never the ideal on paper: a real clock drifts, a real sensor +reads off, a PCA9685 runs a few percent fast. Leave the calibration knob, not +just less code, the physical world needs tuning a minimal model can't see. + +Lazy code without its check is unfinished. Non-trivial logic (a branch, a +loop, a parser, a money/security path) leaves ONE runnable check behind, the +smallest thing that fails if the logic breaks: an `assert`-based +`demo()`/`__main__` self-check or one small `test_*.py`. No frameworks, no +fixtures, no per-function suites unless asked. Trivial one-liners need no +test, YAGNI applies to tests too. + +## Boundaries + +Ponytail governs what you build, not how you talk (pair with Caveman for +terse prose). "stop ponytail" / "normal mode": revert. Level persists until +changed or session end. + +The shortest path to done is the right path.