/**
 * Prompt-template commands — slash commands that inject detailed prompts
 * into the agent loop. Each command maps to a full prompt the agent executes.
 */
export const PROMPT_COMMANDS = [
    {
        name: "goal",
        aliases: ["g"],
        description: "Plan as needed, then create a programmatic goal loop",
        // Contract anchors for the audit verifier: /goal setup is setup-only.
        // Do not implement; plan/research as needed first, then define success criteria, evidence_plan, verifier, and goals metadata, then stop.
        prompt: "Create a Goal run for the following objective. First plan/research only if needed; Goal setup will consume that plan and create durable Goal state.",
    },
    {
        name: "expand",
        aliases: [],
        description: "Find exciting new features to add",
        prompt: `# Expand: Exciting Feature Discovery

Find the most exciting new features this project should add by comparing it to similar, adjacent, and best-in-class repositories/tools/products/services. This command is project-agnostic: infer what THIS project is before choosing comparisons. This command is report-first and feature-first — the only deliverable is a single ranked table of exciting, user-facing features. Do not edit, install, or implement anything until the user chooses an option at the end.

Focus on what users actually get excited about: the new, killer, user-facing capabilities that make a product stand out. Security audits, refactors, code-quality cleanups, tests, CI, and ops/DX hygiene are OUT OF SCOPE here — exclude them unless a specific item is itself an exciting user-facing feature.

## Phase 0: Profile this project first

Before external research, inspect the local project and write a private working profile:

- What the project does, who its users are, and how they use it.
- Core user-facing surfaces, workflows, commands/routes/screens, and the features that already exist.
- The feature categories most relevant to THIS project. Do not assume a stack or product type.

Use this profile to decide which features are relevant and genuinely missing. If the user passed arguments to /expand, treat them as a focus area and prioritize that lens while still validating relevance.

## Phase 1: Parallel feature research

Spawn exactly 5 sub-agents in parallel using the subagent tool (call the subagent tool 5 times in a single response). Give each sub-agent the project profile and a different feature-hunting lens:

**Agent 1 - Direct competitor killer features**: The standout, most-loved user-facing features in the closest peer projects/tools/products that this project lacks.

**Agent 2 - Adjacent & emerging tools**: Exciting user-facing features from adjacent products that would translate well to this project.

**Agent 3 - User demand signals**: Highly requested or trending features — top-voted issues, roadmap items, community asks, reviews, discussions — that point at what users want next.

**Agent 4 - Platform & ecosystem trends**: New user-facing capabilities unlocked by recent framework/API/model/platform releases that this project has not adopted yet.

**Agent 5 - Differentiators & wow-factor**: Novel or innovative features that would make this project stand out, even if no single peer has shipped them yet.

Each sub-agent must:

1. Use current sources: prefer repos/releases/changelogs/docs/articles updated within the last 6 months. Drop old or stale sources unless they are canonical and still actively maintained.
2. Return only user-facing FEATURES that appear absent in this project — not refactors, hardening, tooling, tests, or internal cleanup.
3. Include source names/URLs, freshness date (commit/release/article/doc date), and the local search anchors they used or recommend to verify the feature is absent.
4. Rank its own candidates by how exciting and valuable they would be to users, and state why each is exciting.
5. Avoid generic wishlist items. Every feature must be grounded in an external comparison or a real user-demand signal and relevant to this project profile.

## Phase 2: Main-agent validation against this repo

For every candidate from the sub-agents, validate it yourself before reporting:

1. Confirm the external source is relevant to this project and fresh enough (normally within 6 months).
2. Search this repo with grep/find and language-aware anchors to confirm the feature is not already present under another name.
3. Check routes, CLI commands, UI surfaces, package exports, config, docs, and examples before calling a feature missing.
4. If the mcp__kencode-search__searchCode tool is available, use it when a code-level look clarifies how peers actually ship the feature (literal imports, functions, config keys, CLI flags, route names, or package names — not conceptual phrases). Skip this step if the tool isn't connected.
5. Drop anything already present, irrelevant, too vague, too stale, or that is not a real user-facing feature.
6. Merge duplicates and keep only the most exciting 5–10 features.

## Final output

Output ONLY a single table, ranked most exciting (rank 1) to least exciting. No prose before or after the table except the options below. Include 5–10 rows. The table must have exactly 3 columns:

| Rank | Feature | Why it's exciting + evidence |
|---|---|---|
| 1 | concise feature name + what it does | why users would love it, which peers/tools have it, source + fresh date, and local proof it is missing |

Rules:

- 5–10 rows, ordered most exciting first (rank 1 = most exciting).
- Only user-facing features. No security, refactor, ops, tooling, or test rows.
- The table must have exactly 3 columns. Put source URL/date/evidence and local absence proof inside the cells, not extra columns.
- Keep each cell concise but specific enough to be actionable.
- If no exciting validated features are found, output one row saying no fresh validated features were found.

After the table, ask exactly:

What should I do?
A) Build all of these features in plan mode
B) Build only the top priority ones in plan mode
C) Other

Do not start implementing until the user chooses.

If the user chooses A or B, do not implement directly. First call the enter_plan tool, then research and design an implementation plan for the selected features (all of them for A; the top 3 most exciting — ranks 1-3 — for B). The plan must cover, per feature: the user-facing behavior, the local files/anchors it touches, the implementation approach (compared against real-world examples via kencode search using literal code tokens), and how it will be verified. Write the plan to .ezcoder/plans/<name>.md, then call exit_plan with the plan path so the user can review and approve it. Do not begin implementing until the user approves the plan.

If the user chooses C, ask what they would like — pick specific features by rank, refine or re-scope the list, or skip — and do not implement anything until they say so.`,
    },
    {
        name: "raise-floor",
        aliases: ["floor"],
        description: "Make existing features just work — raise the floor",
        prompt: `# Raise the Floor: Make Existing Features Just Work

This is the inward counterpart to /expand. /expand raises the CEILING with net-new features; /raise-floor raises the FLOOR on features that ALREADY exist. The goal is to make the project too good to fail — results-focused. A feature is not done when it can technically do something; it is done when a real user gets the result without having to learn it, configure it, or babysit it. Hunt the gap between what a feature CAN do (ceiling) and how easily a real user gets value from it on first use (floor), and close that gap.

This command is **app-wide first, specific features second**, and project-agnostic — profile THIS project before judging it. It is report-first: the only deliverable is a ranked report, after which you hand the fixes off as tasks. Do not edit, install, or implement anything until the user chooses an option at the end.

If the user passed arguments to /raise-floor, treat them as a focus area: narrow the audit to that feature/surface, but still run the app-wide lens within it and apply the full rubric.

**Out of scope** — exclude these unless an item is the direct reason a user can't get value from an existing feature: net-new capabilities (that's /expand), security audits (that's /bullet-proof), and pure refactors / code-quality cleanup / test coverage / CI / ops/DX hygiene.

## The floor rubric

Score every surface against these. A low score on any dimension is a "sagging floor" finding:

- **Zero-config** — works on first run with sensible defaults; no required setup, flags, or tuning to get value.
- **Discoverability** — a user can find and trigger it without reading source or docs.
- **End-to-end completeness** — it finishes the job instead of stopping halfway and leaving manual steps for the human.
- **Failure & edges** — empty / missing / error / slow / offline states are handled with a clear message and a recovery path, not crashes, silence, or confusion.
- **Results visible** — the user can see it worked and receives the payoff, with feedback/progress — not left guessing.
- **Time-to-first-value** — few steps between invoking it and the payoff; no hidden prerequisites.
- **Self-explaining** — empty states, inline hints, and defaults teach the feature in place, so the human doesn't have to learn it elsewhere.

## Phase 0: Profile + inventory (main agent)

Inspect the local project and write a short private working profile: what it is, who its users are, how they actually use it. Then inventory the real user-facing surfaces — commands, routes, screens, flows, exported APIs — and the features that already exist. Derive this from actual code and config, not from README claims.

## Phase 1: Parallel floor audit — app-wide first

Spawn subagents in parallel using the subagent tool (call the subagent tool multiple times in a single response).

**Agent 1 — App-wide floor (always include this one; it is the priority lens).** Audit the whole-product basics that gate every feature: first-run / onboarding / empty-project state, global defaults and required configuration, cross-cutting empty / loading / error states, global discoverability (can users find what already exists?), consistency of feedback and results across the app, and the path from install to first real result.

**Then one subagent per major feature area** from the inventory (cap the total at 6 subagents). Each audits its feature against the full rubric, walking the real code path.

Each subagent must:

1. Walk the actual code path for its surface — entry point through to the result the user gets.
2. Return only **floor findings**: existing capability that works but is hard to use, incomplete, hidden, silent on failure, or that needs the human to do the system's job.
3. For EVERY finding, give a concrete **first-run scenario** grounded in the code: a real user does X, expects Y, but instead gets Z or must manually do W. No scenario, no finding.
4. Cite the local file:line anchors that prove the floor sags (the missing default, the unhandled state, the manual step, the absent feedback).
5. Score the finding on the rubric and estimate fix cost (small / medium / large).

## Phase 2: Validate against the repo (main agent)

For every candidate:

1. Open the cited code and confirm the floor sag is real and not already handled elsewhere (a default, fallback, or empty state the subagent missed).
2. Confirm it is an existing-feature floor issue — not a net-new feature, security finding, or pure refactor. Drop out-of-scope items.
3. Confirm the first-run scenario actually holds against the code. Drop anything you can't ground.
4. Merge duplicates. Rank by **leverage = (users affected × how badly the floor sags) ÷ fix cost**.

## Phase 3: Report

Output the report. **App-wide findings first**, then per-feature, each ranked by leverage. Start with one line: project name + a one-sentence summary of where the floor sags most. Then a single table:

| ID | Scope | Floor gap + first-run scenario | Fix (what "just works" looks like) + file anchors | Leverage |
|---|---|---|---|---|
| RF-001 | app-wide | what sags + user does X, expects Y, gets Z | the default/empty-state/feedback/completion to add + path:line | high |

Use IDs like RF-001. App-wide rows lead, then features.

After the table, ask exactly:

What should I do?
A) Add tasks for all floor-raising fixes
B) Add tasks for the app-wide fixes only
C) Add tasks for specific findings (give IDs, e.g. "RF-001, RF-004")
D) None — report only

Do not start implementing until the user chooses.

## Phase 4: Hand off as tasks

If the user chooses A, B, or C, do not fix directly. Add one task per selected finding (or tightly coupled group) using the \`tasks\` tool (action=add), ordered by leverage and dependency, **app-wide first**. Each task needs a short title and a standalone prompt that includes:

- the finding ID and the first-run scenario it fixes,
- the affected local files/anchors,
- what "just works" looks like — the default / empty-state / feedback / completion the fix must deliver,
- the project's verification commands.

End EVERY task's standalone prompt with this exact line, verbatim, on its own line:

use kencode to reference working code. /commit when done.

After adding the tasks, tell the user exactly: "Tasks added. Press Ctrl+T to open the task list and run them." Do not begin executing them unless the user explicitly says so.

If the user chooses D, stop after the report.

## Rules

- **App-wide first, specific features second** — in both the audit and the report.
- **Existing features only.** Net-new capability is /expand; security is /bullet-proof; pure refactors/tooling are out of scope.
- **No finding without a concrete, code-grounded first-run scenario.** No "could be polished" nudges.
- **Report-first.** No edits, installs, or commits until the user picks an option.
- **Every generated task must end with the exact line:** use kencode to reference working code. /commit when done.`,
    },
    {
        name: "test-drive",
        aliases: ["qa", "td"],
        description: "Actually run the app, click around, screenshot, file bugs as tasks",
        prompt: `# /test-drive: Empirically Test the App and File Bugs as Tasks

You are a hands-on QA agent. Your job is to ACTUALLY RUN this app and use it like a real user — launch it, click around, type into it, navigate every reachable surface, and LOOK at the result with your own eyes (screenshots / captured output / logs). This is empirical, not a code review: you must drive the running app, not just read source. Every bug you find is recorded so it can be fixed later by another agent working through the task list — except bugs that block YOU from testing further, which you fix immediately so you can keep going.

This command is **project-agnostic**. Profile what THIS app is and how it runs before testing. If the user passed arguments to /test-drive, treat them as the area/flow to focus the test pass on, but still sanity-check the rest of the app.

## Phase 0: Figure out how to run it

Inspect the project (manifests, scripts, README, entry points) and determine how a user actually runs this app, then start it:

- **Web app / dev server** — find the dev/start script (e.g. \`pnpm dev\`, \`npm start\`, \`vite\`). Launch it with bash as a **background process** (\`run_in_background: true\`), wait for it to be ready, and read its output with task_output to learn the local URL (e.g. http://localhost:3000).
- **CLI / TUI** — run the binary/entry command. For interactive programs, launch as a background process and drive it with task_send (type input / answer prompts) + task_output (read what it printed). Use task_stop to end it.
- **Desktop app (Tauri/Electron/etc.)** — start it the way the project documents. If it exposes a local webview URL or dev server, point the screenshot tool at that; otherwise launch it and rely on captured logs/output for evidence.
- **Library / no runnable surface** — there's nothing to "click around." Run its examples/tests/demo instead, or report that there is no interactive surface to test and stop.

If you cannot get the app to start at all, that is itself the first blocking bug — fix it (Phase 2, blocking path) so you have something to test, then continue.

## Phase 1: Drive it and LOOK — use your eyes

Exercise the app like a real user, surface by surface. Use the real perception tools available to you:

- **screenshot tool** — your eyes for anything with a UI. Open each URL/screen, run \`actions\` (click / type / wait) to walk real flows, and CAPTURE the result so you actually see what rendered. Vary viewport for responsive surfaces and use \`full_page\` for long pages. Don't assume a screen works — look at it.
- **task_output / task_send** — your eyes and hands for CLIs, TUIs, and dev-server logs: read what the process emitted, type input to drive it, watch for errors/stack traces/warnings in the output.
- **bash** — hit health/API endpoints, trigger flows, and inspect logs the app writes.

Walk the real journeys, not just the happy path that's easy to reach. For each surface, exercise:

1. **Primary flows** — the main things a user comes here to do, start to finish.
2. **Inputs & forms** — submit valid input, empty input, and obviously wrong input; check validation and error messages.
3. **Navigation** — every reachable link/button/route/tab/command; look for dead ends, broken links, blank screens, 404s, console/stderr errors.
4. **States** — empty, loading, error, offline/slow, and "no data yet" states. These are where apps break most.
5. **Visual integrity** — overlapping/cut-off/misaligned elements, unstyled flashes, illegible text, broken images — things only visible by actually looking at a screenshot.

As you go, keep a running list of every bug with: what you did, what you expected, what actually happened, the evidence (screenshot path / captured output / log line), and the file/area it most likely lives in.

## Phase 2: Triage each bug — blocking vs deferrable

For every bug, decide one of two paths:

**A) BLOCKING — it stops you from testing further.** The app won't start, a screen crashes, a flow can't be completed, or a broken gate hides everything behind it. You cannot meaningfully continue the test pass until it's fixed. **Fix these immediately**, right now, so you can keep testing:

1. Reproduce it and find the root cause in the code.
2. Use the \`mcp__kencode-search__searchCode\` tool to reference how real projects implement the same pattern correctly, and base your fix on that working code. (If the kencode-search MCP tool isn't connected, note that and fix using project conventions + authoritative docs.)
3. Implement the fix, then re-run the app and CONFIRM with your eyes (re-screenshot / re-read output) that the bug is actually gone.
4. Commit the fix by running the \`/commit\` command, so each fix lands on working, committed code before you continue.
5. Resume the test pass from where you were blocked.

**B) DEFERRABLE — it's a real bug but you can keep testing around it.** Cosmetic issues, non-blocking errors, secondary-flow breakage, edge-case mishandling. **Do NOT fix these now.** Record them and move on — they'll be handed off as tasks for another agent to fix in a later session.

When unsure, prefer DEFER: only fix inline what genuinely blocks the test pass. The point is to keep driving the app and cataloguing bugs, not to stop and fix everything.

## Phase 3: File deferrable bugs as tasks

For every deferrable bug (or a tightly-coupled group), add one task with the \`tasks\` tool (action=add). Running /test-drive is the user's explicit request to populate the task list, so this is expected — but only file REAL, reproduced bugs, not speculation. **Before filing, trace each bug to its root cause and confirm it's an actual code defect — not bad seed/test/mock data, a misconfig, or expected behavior.** This app is full of synthetic data, so "these numbers look insane" is very often just the data, not a bug. Reading the code/data/DB to establish cause is REQUIRED here, not an "assumption" — the no-assumptions rule means don't claim a screen works without looking, it does not mean skip root-cause analysis. For any numeric/calculation bug, reproduce the arithmetic from the underlying inputs before filing. Order tasks by user impact and severity. Each task needs a short title and a standalone prompt (the next agent has NO context from this session) that includes:

- **The bug**: what you did, what you expected, what actually happened.
- **Reproduction steps**: the exact flow to trigger it (URL/screen/command + clicks/inputs).
- **Evidence**: the screenshot path / captured output / log line you saw.
- **Root cause**: the traced reason it's a code defect (not data/config/expected behavior) — for numeric bugs, the inputs and the arithmetic you reproduced.
- **Where to look**: the file(s)/area the bug most likely lives in.

End EVERY task's standalone prompt with this exact line, verbatim, on its own line:

use kencode to reference working code. /commit when done.

That line guarantees the next agent bases its fix on real working code (via the kencode MCP) and commits it.

## Phase 4: Report

When the test pass is done (or you've covered the focus area), summarize:

- What you ran and which surfaces/flows you actually drove (with screenshot/output evidence).
- **Blocking bugs you fixed inline** — each with its root cause and the commit.
- **Deferrable bugs filed as tasks** — a short list of titles.

Then tell the user exactly: "Tasks added. Press Ctrl+T to open the task list and run them." Do not start executing those deferred tasks unless the user explicitly says so.

## Rules

- **Actually run the app and look.** Don't claim a screen works without observing it — a screenshot, captured output, or log line. No "this should work." But observation alone is not a filed bug: confirming a defect requires tracing the cause, which means reading the code/data/inputs.
- **Trace cause before filing.** A symptom is not a bug until you've traced it to a code defect and ruled out bad seed/test/mock data, misconfig, and expected behavior. For numeric/calculation bugs, reproduce the arithmetic from the underlying inputs.
- **An AI/agent (or the model itself) noticing something looks wrong is NOT evidence** — a model flags "big number vs small position" the same way whether the cause is data or logic. Only reproduced behavior plus a traced cause counts.
- **Only fix what blocks you.** Blocking bugs get fixed inline (kencode-referenced + \`/commit\`); everything else becomes a task. When in doubt, defer.
- **Every fix is on working, committed code** — reference real code via kencode, verify the fix by re-running, then \`/commit\`.
- **Every filed task ends with the exact line:** use kencode to reference working code. /commit when done.
- **File only reproduced bugs with a traced root cause.** No speculative or "could be improved" tasks, and no symptoms with an unverified cause — this is a bug hunt, not a polish wishlist.`,
    },
    {
        name: "elon",
        aliases: ["delete"],
        description: "Delete dead weight until only what earns its place remains",
        prompt: `# /elon: The Deletion Algorithm

This is the SUBTRACTIVE sibling of /expand and /raise-floor. /expand raises the ceiling (net-new features); /raise-floor raises the floor (make existing features work); /elon SHRINKS THE SURFACE — it hunts the features, screens, flags, dependencies, abstraction layers, and half-built complexity that nobody uses, that make the product overwhelming, and that should be deleted so only what earns its place remains. The target is the user's real pain: "there's so much going on it's overwhelming and never gets used."

This applies Elon Musk's 5-step algorithm, IN ORDER, because the whole point is that people skip to step 3 and optimize things that should not exist:

1. **Make the requirement less dumb** — for every candidate, ask whose requirement this is and whether it is still real. Kill anonymous requirements ("it's here because someone added it once" → nobody remembers why).
2. **Delete the part or process** — remove the feature/screen/flag/dependency/layer entirely.
3. **Simplify** — only what survives deletion.
4. **Accelerate** — only what survived simplification.
5. **Automate** — last, never first.

/elon lives in steps 1-2. It NEVER recommends simplifying, accelerating, or automating something before asking whether it should be deleted outright. If a subagent proposes "optimize X", reframe it as "delete X — and if not, why does X earn its place?"

This command is **app-wide first, specific surfaces second**, and project-agnostic — profile THIS project before judging it. It is report-first: the only deliverable is a single ranked deletion ledger, after which you hand the deletions off as tasks. **Do not delete, edit, install, or implement anything until the user confirms by choosing an option at the end.**

If the user passed arguments to /elon, treat them as a focus area: narrow the hunt to that feature/surface, but still apply the full algorithm within it.

**Out of scope** — exclude these unless an item is the direct reason the product is bloated: net-new capabilities (that's /expand), making a kept feature work better (that's /raise-floor), and security findings (that's /bullet-proof). /elon only proposes REMOVAL.

## The required predicted add-back (the bullshit-detector)

Musk's rule: "if you're not adding ~10% back, you didn't delete enough" — and its inverse is the real safety mechanism. **Every single deletion row MUST carry a predicted add-back**: the small piece of the deleted thing that was doing real work and must return so dependents still function. State it BEFORE deleting, grounded in code. There are three flavors:

- **Zero add-back** — genuinely dead. Nothing reads it, no caller, no test references it. Cleanest, highest-leverage deletions.
- **Fold-in add-back** — the surface goes, but one essential behavior survives by merging into something simpler (e.g. delete a 12-toggle settings screen → add back ONE smart default at onboarding).
- **Seam add-back** — deleting a layer/dependency means re-implementing inline the one thing it actually did (e.g. drop a date library → add back a 4-line formatter).

**The add-back is the bullshit-detector:** if a candidate's predicted add-back is large, vague, or "we'd basically rebuild it", that is the signal the requirement was REAL — do NOT recommend deletion; mark it KEEP and move on. Only a zero/small/well-scoped add-back confirms dead weight. A row with no predicted add-back is invalid and must be dropped. This is what stops /elon from recommending reckless deletions: every row must prove that what comes back is smaller than what leaves.

## Phase 0: Profile + inventory (main agent)

Inspect the local project and write a short private working profile: what it is, who its users are, how they actually use it. Then inventory the real surface — user-facing surfaces (commands, routes, screens, flows, exported APIs) AND internal complexity (dependencies, config flags, feature toggles, abstraction layers, half-built or dead features). Derive this from actual code and config, not from README claims. The job is to find what to remove, so map breadth.

## Phase 1: Parallel deletion hunt — app-wide first

Spawn subagents in parallel using the subagent tool (call the subagent tool multiple times in a single response).

**Agent 1 — App-wide bloat (always include this one; it is the priority lens).** Audit the whole-product overwhelm: too many entry points / menu items / screens competing for attention, features that exist but are effectively never reached, redundant ways to do the same thing, configuration surface a user must wade through, and the gap between what the product offers and the small core users actually use. This lens directly answers "so much going on, never gets used."

**Then one subagent per major area** from the inventory (cap the total at 6 subagents). Split between user-facing surfaces and internal complexity (dead deps, config flags, abstraction layers, unfinished features).

Each subagent must:

1. Walk the actual code path for its area and find DELETION CANDIDATES — capability, screen, flag, dependency, layer, or dead/unfinished feature that is unused, rarely used, redundant, or pure overwhelm.
2. For EVERY candidate, gather **deletion evidence** grounded in code: who calls it, what imports it, what tests reference it, whether it's reachable, how often it's plausibly used. Cite file:line anchors that prove it's dead weight (no callers, write-only state, unreachable branch, duplicate path).
3. For EVERY candidate, predict **what breaks if removed** and the **required predicted add-back** (zero / fold-in / seam) — see the rubric above. If the add-back is large or vague, mark the candidate KEEP with the reason, do not propose deletion.
4. Apply step 1 of the algorithm: name whose requirement the thing served and whether it's still real. Flag anonymous/forgotten requirements as strong deletion candidates.
5. Estimate **removal risk** (low / medium / high) from blast radius (call sites, public API exposure, data/migration implications) and **surface removed** (how much complexity/overwhelm leaves).

## Phase 2: Validate against the repo (main agent)

For every candidate:

1. Open the cited code and confirm it is genuinely dead weight — not something reached by a path the subagent missed (a dynamic import, a route table, a public export, a config-driven call, a test).
2. Confirm the predicted add-back is honest and small. If validating reveals the add-back is actually large or load-bearing, drop the row to KEEP — the requirement was real.
3. Confirm it is a REMOVAL candidate — not a net-new feature (/expand), a make-it-work fix (/raise-floor), or a security issue (/bullet-proof). Drop out-of-scope items.
4. Merge duplicates. Rank by **simplification leverage = (surface removed × how rarely used) ÷ removal risk**.

## Phase 3: The deletion ledger (report)

Output the report. **App-wide deletions first**, then per-area, each ranked by leverage. Start with one line: project name + a one-sentence summary of where the product is most bloated. Then a single table:

| ID | Delete candidate | Why it's dead weight (evidence + file:line) | What breaks + required predicted add-back | Removal risk | Leverage |
|---|---|---|---|---|---|
| EL-001 | app-wide: settings screen w/ 12 toggles | 9 toggles write-only, never read after save (path:line) | nothing user-visible; fold-in: keep 1 default applied at onboarding | low | high |

Use IDs like EL-001. App-wide rows lead, then areas. **Every row's add-back cell is mandatory** and must say zero / fold-in / seam with the specific behavior that returns. Rows whose validation showed a large add-back are NOT listed as deletions — optionally list them in a short "Kept — requirement is real" note below the table so the user sees what you deliberately did not cut.

The ledger rows are structured so a later empirical mode can run them: each row implies a delete action and a verify (the project's own build/check/test as the "does it break?" oracle), with the predicted add-back as the minimal fix to reach for first. Do not run that loop now — this is report-only.

After the table, ask exactly:

What should I do?
A) Add tasks for all confirmed deletions
B) Add tasks for the app-wide deletions only
C) Add tasks for specific deletions (give IDs, e.g. "EL-001, EL-004")
D) None — report only

Do not delete or start implementing until the user chooses.

## Phase 4: Hand off as tasks

If the user chooses A, B, or C, do not delete directly. Add one task per selected deletion (or tightly coupled group) using the \`tasks\` tool (action=add), ordered by leverage and dependency, **app-wide first**. Each task needs a short title and a standalone prompt that includes:

- the deletion ID and exactly what to remove (files/symbols/flags/deps + anchors),
- the required add-back to implement so dependents still function (the zero/fold-in/seam from the ledger),
- the blast radius to clean up (call sites, imports, tests, docs, config),
- the project's verification commands to prove nothing broke after removal.

End EVERY task's standalone prompt with this exact line, verbatim, on its own line:

use kencode to reference working code. /commit when done.

After adding the tasks, tell the user exactly: "Tasks added. Press Ctrl+T to open the task list and run them." Do not begin executing them unless the user explicitly says so.

If the user chooses D, stop after the report.

## Rules

- **Removal only.** /elon proposes deletions, never additions or fixes. Net-new is /expand; make-it-work is /raise-floor; security is /bullet-proof.
- **Algorithm order is law.** Requirement → delete → (later) simplify/accelerate/automate. Never recommend optimizing something before asking whether to delete it.
- **Every row carries a required predicted add-back.** A large or vague add-back means KEEP — do not propose the deletion. No add-back = invalid row, drop it.
- **App-wide first, specific areas second** — in both the hunt and the ledger.
- **No deletion without code-grounded evidence** that the thing is dead weight (no callers / write-only / unreachable / redundant). No "feels bloated" nudges.
- **Report-first. No deletions, edits, installs, or commits until the user picks an option.**
- **Every generated task must end with the exact line:** use kencode to reference working code. /commit when done.`,
    },
    {
        name: "elon-2",
        aliases: ["step-2", "add-back"],
        description: "Finish the Elon algorithm: add back the ~10%, then simplify/accelerate/automate",
        prompt: `# /elon-2: The Add-Back & Optimize Pass

This is the SECOND HALF of /elon, and it only makes sense AFTER deletions have landed. /elon runs steps 1–2 of Elon Musk's algorithm — make the requirement less dumb, then delete the part/process — and it deletes aggressively, on purpose, until things break. /elon-2 runs the rest of the same algorithm, IN ORDER:

1. ~~Make the requirement less dumb~~ — done by /elon.
2. ~~Delete the part or process~~ — done by /elon.
3. **Simplify** — only what survived deletion.
4. **Accelerate** — only what survived simplification.
5. **Automate** — last, never first.

Before step 3, this command does the move /elon deliberately leaves undone — the famous Musk rule: **"if you're not adding ~10% back, you didn't delete enough."** Aggressive deletion overshoots; some small piece you cut was actually load-bearing and has to come back. **Phase 1 recovers that ~10%.** Only then do steps 3–5 run, on what survived.

This command is **project-agnostic** and **report-first**: the only deliverable is a single ranked ledger, after which you hand the work off as tasks. **Do not edit, install, or implement anything until the user confirms by choosing an option at the end.**

If the user passed arguments to /elon-2, treat them as a focus area: narrow the pass to that feature/surface, but still run the full algorithm within it.

**Hard scope rules:**
- **Add-backs are strictly the minimal load-bearing piece that broke.** Restoring functionality the deletions removed is NOT re-adding scope. If an "add-back" is really a net-new capability or a scope re-expansion, that is /expand — drop it here.
- **Steps 3–5 operate ONLY on survivors.** Never simplify, accelerate, or automate something that should have been deleted — /elon already made those calls. Do not re-litigate deletions (revert-the-whole-deletion is the one exception, see Phase 1).
- **Order is law.** Add-back → simplify → accelerate → automate. Never accelerate or automate something before it has been simplified.

## Phase 0: Establish what changed + a baseline oracle (main agent)

You cannot add back what broke without knowing what was cut. Build two maps from real evidence, not memory:

- **Deletion map** — what /elon actually removed. Derive it from \`git log\`/\`git diff\` over the relevant range, completed deletion tasks, and removed files/symbols/flags/dependencies. For each deletion, note its predicted add-back (zero / fold-in / seam) from the /elon ledger if available.
- **Survivor map** — the user-facing surfaces, flows, and internal pieces that remain after the deletions.

Then run the project's own **build / typecheck / test / lint** (whatever it has) to capture a baseline oracle: what is broken right now, after the deletions. Note dangling imports, broken routes, failing tests, dead references, and any flow that no longer completes.

## Phase 1: Add-back recovery (the ~10%)

Empirically find what the deletions broke or over-cut. Spawn subagents in parallel using the subagent tool (call the subagent tool multiple times in a single response), one per high-risk deletion cluster from the deletion map (cap at 6).

Each subagent must:

1. Walk the deletion and find **breakage evidence** grounded in code: failing build/typecheck/test output, dangling references to removed symbols, routes/commands that no longer resolve, a real user flow that now dead-ends, behavior that callers still expect.
2. For every breakage, identify the **minimal add-back** — the smallest piece of the deleted thing that must return so dependents work again (mirror the zero / fold-in / seam shapes from /elon). Cite the file:line that proves the breakage and what the restore touches.
3. **Right-size the add-back.** If the minimal restore is large, vague, or "we'd basically rebuild the deleted thing," that is the signal the deletion itself was wrong — flag it as **REVERT** (undo the whole deletion) rather than a partial add-back. A small, well-scoped add-back is a true ~10%; a large one means the cut went too far.

A deletion that broke nothing needs no add-back — that is a clean cut, leave it. The goal is to restore the minimum, not to undo the diet.

## Phase 2: Steps 3–5 on survivors (in order)

For the survivor map only, spawn subagents in parallel (cap at 6 total across the three steps) to find optimization candidates, strictly in algorithm order:

- **Step 3 — Simplify.** Indirection, layers, branches, or config that only existed to serve now-deleted things and can be collapsed or inlined; survivors that can be merged; flows that can be flattened. This is where most leverage lives post-deletion.
- **Step 4 — Accelerate.** Only what survived simplification: hot paths, redundant work, slow startup, repeated computation that can be sped up. A candidate may not be accelerated until it has been simplified first.
- **Step 5 — Automate.** Last: manual steps in surviving flows that the system should do for the user. Never propose automating something that should instead be simplified away.

Each subagent must cite file:line anchors, name which step it belongs to, and estimate effort (small / medium / large) and leverage.

## Phase 3: Validate against the repo (main agent)

For every candidate:

1. **Add-backs:** confirm the breakage is real against the baseline oracle and that the restore is genuinely minimal. If the restore turns out large, reclassify as REVERT or drop it.
2. **Simplify/accelerate/automate:** confirm the candidate is a survivor (not something that should have been deleted), and that the step order holds (nothing accelerated/automated before being simplified).
3. Confirm scope: add-backs restore removed behavior only — anything that is net-new capability is /expand, make-it-work polish is /raise-floor, security is /bullet-proof. Drop out-of-scope items.
4. Merge duplicates. Rank by **completion leverage = (breakage severity or surface improved) ÷ effort**, with all add-backs ahead of all step 3–5 work.

## Phase 4: The completion ledger (report)

Output the report. **Add-back (recover) rows first, then simplify, then accelerate, then automate** — algorithm order. Start with one line: project name + a one-sentence summary of how far the deletions overshot and where the biggest post-deletion wins are. Then a single table:

| ID | Step | Candidate | Evidence (file:line) | What it restores / improves | Effort | Leverage |
|---|---|---|---|---|---|---|
| E2-001 | add-back | re-add the one default the deleted settings screen applied | flow X dead-ends after delete (path:line) | onboarding applies the default inline; nothing else returns | small | high |
| E2-002 | simplify | inline the adapter layer that only wrapped the deleted backend | single caller left (path:line) | one fewer indirection; survivors merge | small | high |

Use IDs like E2-001. Add-back rows lead, then step 3, then 4, then 5. Mark any deletion that overshot as **REVERT** with the reason. The ledger is structured so a later empirical mode can run each row against the project's build/check/test as the "is it fixed / still green?" oracle. Do not run that loop now — this is report-only.

After the table, ask exactly:

What should I do?
A) Add tasks for everything (add-backs first, then simplify/accelerate/automate)
B) Add tasks for the add-backs only (just recover what broke)
C) Add tasks for specific rows (give IDs, e.g. "E2-001, E2-004")
D) None — report only

Do not start implementing until the user chooses.

## Phase 5: Hand off as tasks

If the user chooses A, B, or C, do not implement directly. Add one task per selected row (or tightly coupled group) using the \`tasks\` tool (action=add), ordered by algorithm step then leverage — **add-backs first, then simplify, then accelerate, then automate**. Each task needs a short title and a standalone prompt that includes:

- the row ID, its step, and exactly what to restore or change (files/symbols/flags + anchors),
- for add-backs: the breakage it fixes and the minimal restore (never re-expand scope),
- the blast radius to touch (call sites, imports, tests, docs, config),
- the project's verification commands to prove the build/tests are green again after the change.

End EVERY task's standalone prompt with this exact line, verbatim, on its own line:

use kencode to reference working code. /commit when done.

After adding the tasks, tell the user exactly: "Tasks added. Press Ctrl+T to open the task list and run them." Do not begin executing them unless the user explicitly says so.

If the user chooses D, stop after the report.

## Rules

- **Runs after /elon.** This pass assumes deletions already landed; Phase 0 derives them from git history and completed tasks.
- **Add back the ~10%, no more.** Restore only the minimal load-bearing piece that broke. A large add-back means the deletion overshot — mark it REVERT, don't quietly rebuild.
- **Algorithm order is law.** Add-back → simplify → accelerate → automate. Never accelerate or automate before simplifying.
- **Survivors only for steps 3–5.** Don't optimize something that should have been deleted; don't re-add scope (that's /expand).
- **Report-first. No edits, installs, or commits until the user picks an option.**
- **Every generated task must end with the exact line:** use kencode to reference working code. /commit when done.`,
    },
    {
        name: "bullet-proof",
        aliases: ["bp"],
        description: "Audit exploitable weaknesses",
        prompt: `# Bullet-Proof: Defensive Security Review

You are a defensive security auditor reviewing this codebase to identify exploitable weaknesses so they can be patched before the project ships. Think rigorously about realistic threat scenarios — boundary checks, edge cases, race conditions, trust assumptions, supply-chain risks, agent-mediated paths.

Goal: harden this project against realistic threats. **Report only HIGH CONFIDENCE findings (≥0.8) with a concrete data-flow path that demonstrates exposure.** Better to miss theoretical issues than flood the report with noise.

This command is **dynamic and project-agnostic**. Recon drives everything. Do not assume the stack, the language, the deploy target, or that there is an LLM/agent layer. Read first, decide second.

## Phase 1: Recon — Understand THIS project before auditing anything

Spawn **FOUR recon subagents in parallel** using the subagent tool (call the subagent tool 4 times in a single response). Each has a narrow, independent slice so they can all run at once. **No vulnerabilities flagged in this phase.**

**Recon Agent A — Stack & Deployment.** Read manifests, lockfiles, CI/CD configs, Dockerfile/Helm/Terraform, deploy scripts. Produce:
- Primary language(s), framework(s), runtimes
- Deploy target (browser / server / CLI / mobile / desktop / embedded / cloud function / container / serverless / smart contract / firmware / ML pipeline / library / SaaS / self-hosted)
- How it ships (npm/PyPI/cargo/go modules/app store/binary/Docker image/Helm chart/Terraform)
- Where it runs (which cloud/host, multi-tenant or single-tenant, network topology if discernible)

**Recon Agent B — Trust Boundaries & Sources.** Walk entry-point code (route handlers, CLI argparse, queue consumers, WebSocket handlers, IPC receivers, MCP server handlers, file/env readers, deserialization entry, plugin loaders). Produce:
- **Trust boundaries table** — every place untrusted data crosses into the system
- **Sources table** — for each entry point: location (file:line), input shape, who controls it (anonymous / authenticated user / admin / other service / build-time / env)

**Recon Agent C — Sinks.** Walk dangerous-operation code. Produce a **Sinks table** with location (file:line) and sink type for: shell exec, SQL / NoSQL / LDAP / XPath queries, eval / Function / exec / pickle / yaml.load / Marshal / ObjectInputStream, file write, file include / require with dynamic path, network egress (fetch / requests / http.Get), auth decisions, secret reads, native deserializers, dynamic code load, smart-contract external calls, child_process spawns.

**Recon Agent D — Assets.** Scan for what is worth stealing or destroying. Produce an **Assets table** with location and asset type for: credentials / tokens (config files, env files, KMS, OAuth flows, ~/.{app}/auth.json-style stores), customer/PII data stores, source code with IP value, build/CI secrets, signing keys, model API tokens, on-chain funds / wallets, session state, MCP config files, license keys.

**After all four return, the main agent synthesizes:**
1. Assemble the four tables (Stack/Deploy, Sources, Sinks, Assets) into the recon report
2. Add the **Threat model** — concrete to THIS project, derived from the four agents' outputs. Who would realistically target it and what for? (Examples: supply-chain risks affecting downstream users of a library; multi-tenant abuse on a SaaS; untrusted user input on a CLI/mobile app; insider risk with repo access; phishing-based account takeover; coding-agent risks from injected web content; on-chain reentrancy risks for a smart contract.) Be specific.
3. Note any obvious gaps the four recon agents flagged (areas that need a deeper look in Phase 3)

## Phase 2: Plan the audit — recon drives this

From the recon output, decide which vulnerability classes apply to THIS project. **Skip audits with no entry surface.** A static documentation site does not get a SQLi audit. A Rust embedded firmware project does not get a prompt-injection audit. A Python ML pipeline does get pickle/yaml audits. A library that ships to others gets supply-chain weighted heavily.

Default catalog — pick what applies, drop what doesn't, add stack-specific audits where recon shows a unique surface:

| Audit | Fires when | Audits for |
|---|---|---|
| **Injection** | unsanitized input reaches an interpreter | SQLi, command injection, template injection, eval/Function/exec, pickle/yaml.load, NoSQL/LDAP/XPath injection, prompt injection |
| **AuthN/AuthZ/Session** | any auth, session, or access-control logic exists | broken access control (IDOR, BOLA), JWT alg confusion / alg:none, OAuth state/PKCE/redirect-uri abuse, session fixation, missing rate limit on credential checks, MFA bypass, TOCTOU races |
| **Secrets & exposure paths** | any secret/credential/token exists | hardcoded keys, logs/errors/debug-file leakage, source maps in published artifacts, telemetry leakage, prototype pollution exposing secrets, \`JSON.stringify(err)\` shapes, env dump in error pages, exposed \`.git\`/\`.env\`/\`.map\` |
| **Supply chain** | any dependency manager or external code | unpinned deps/actions, postinstall scripts, typosquats, **slopsquats (AI-hallucinated package names registered by malicious parties)**, dependency confusion, lockfile drift, install-time \`curl \\| sh\`, unsigned releases, unverified maintainer takeovers, self-spreading worms (Shai-Hulud family) |
| **CI/CD & build integrity** | any CI workflow, release pipeline | \`pull_request_target\` + checkout of PR HEAD (Pwn Request), Actions cache poisoning, OIDC token theft from \`/proc\`, self-hosted runner reuse, secret echoes, missing \`permissions:\` block |
| **SSRF, path traversal, file ops** | any URL/path/file built from input | SSRF to metadata endpoints (IMDSv1), path traversal, zip-slip, symlink races, unrestricted upload, archive extraction outside target dir |
| **Cloud/infra & misconfig** | any IaC, container, cloud SDK use | overpermissive IAM (\`Action:*\`, \`iam:PassRole:*\`), public buckets, IMDSv1, exposed K8s API/kubelet, presigned URLs without expiry, default creds, debug endpoints in prod, CORS \`origin:*\` + \`credentials:true\` |
| **Crypto** | any crypto/hashing/signing | weak algos (MD5/SHA1 for auth), missing IV, ECB mode, hardcoded keys, JWT \`alg:none\`, non-constant-time compare on secrets, predictable PRNG for tokens |
| **Agent surface** | only if recon detected LLM/AI/MCP/coding-agent/tool-calling code | indirect prompt injection via fetched content, MCP tool poisoning, tool-description injection (ToolLeak), system-prompt exposure via tool args, **Rules-File Backdoor (Unicode bidi / zero-width chars hiding instructions in CLAUDE.md / .cursorrules / AGENTS.md)**, malicious CLAUDE.md walking up parent dirs, DNS-exfil via coerced tool calls, RAG / memory / context poisoning, vector-store embedding risks |
| **Dangerous-sink dataflow (taint)** | Sources × Sinks tables are non-empty | trace each Source through the codebase to every reachable Sink; flag reachable paths with no sanitization between |

**Add stack-specific audits when recon surfaces them**: smart-contract reentrancy/oracle manipulation; mobile IPC / deep links / pasteboard / WebView \`addJavascriptInterface\`; embedded firmware update integrity, debug interfaces left enabled; ML model deserialization, training-data poisoning, MLflow/Triton config exposure.

## Phase 3: Parallel audits

Spawn one subagent per active audit **in a single response** (call the subagent tool N times **with \`agent: "auditor"\`**, where N is whatever Phase 2 picked — do not pad to a fixed number, do not drop audits Phase 2 selected). The \`auditor\` agent has the defensive-review persona and exclusion list baked in, so your task description only needs the vulnerability-class scope. Each auditor receives:
- The full recon output (Sources, Sinks, Assets, Threat model)
- Its specific vulnerability-class scope
- The 2026 threat reference at the bottom of this prompt

Each auditor must:
1. **Trace data flow** from Sources to Sinks for its class. Not pattern matching.
2. For every candidate, apply the **untrusted-input vs trusted-input** decision: is the input *actually reachable* by an untrusted source, or is it a settings constant / build-time string / hard-coded value?
3. Construct a concrete **vulnerability scenario** — describe how the weakness would be triggered (input → system response → resulting exposure). If you can't describe the steps, don't flag it.
4. Assign **confidence 0.0–1.0**. Drop anything <0.8 before returning.
5. Be framework-aware: ORM parameterization, auto-escape, memory-safe languages, JSX/template escaping all eliminate entire vuln classes. Don't flag what the framework already handles.

## Phase 4: False-positive filter

After auditors complete, spawn one verification subagent per surviving finding **in parallel with \`agent: "skeptic"\`** (call the subagent tool once per finding in a single response). The \`skeptic\` agent starts from "this is a false positive" and tries to disprove the finding — only confirmed findings survive. Pass each verifier the full audit finding (location, source/sink, vulnerability scenario, claimed confidence). Drop anything the skeptic returns as DROP; lower severity for DOWNGRADE.

**Hard exclusions — do NOT report these, even if real:**
- DOS / rate-limiting / memory exhaustion without a clear amplification primitive
- Theoretical race conditions without a demonstrable trigger window
- Regex-DOS without untrusted-supplied regex
- Log spoofing / log injection (cosmetic)
- SSRF where the URL is a settings constant or build-time string
- Env-var trust (env is server-controlled by definition)
- Client-side authentication theatre on a server-validated endpoint
- React/Angular/Vue XSS in non-unsafe-sink paths (\`dangerouslySetInnerHTML\`, \`v-html\`, \`bypassSecurityTrust*\` are the only real ones)
- Shell-script command injection without an untrusted input path
- Findings in documentation files, example code, or test fixtures
- Insecure-by-design dev tooling that doesn't ship to users
- "Could be improved" style preferences or hardening-best-practice nudges with no demonstrable path

## Phase 5: Report

Output one report. No code edits in this phase.

\`\`\`
# Bullet-Proof Report — [Project name from recon]
Date: [today's date]
Threat model: [from recon]

## Exposure Surface Summary
[1-paragraph summary of the project's realistic exposure profile and where untrusted data enters]

## Sources / Sinks / Assets
[Compact tables from recon]

## Risk Matrix
| Severity | Count | Definition |
|---|---|---|
| Critical | N | RCE, full auth bypass, credential theft, fund loss |
| High     | N | privilege escalation, data exposure with auth, supply-chain compromise |
| Medium   | N | limited-scope info disclosure, weakened crypto, partial bypass |

## Findings

### [BP-001] <title> — Critical
- Location: path:line
- Category: <slug>   CWE: CWE-XXX   Confidence: 0.95
- Exposure surface: <entry point from Sources>
- Source → Sink: <e.g. \`POST /api/foo body.userId\` → \`subprocess.run(..., shell=True)\`>
- Vulnerability scenario:
  1. Untrusted input <specific payload> reaches <source>
  2. Server processes it as <what>
  3. Result: <RCE / data exposure / auth bypass>
- Impact: <blast radius — what is exposed, how far it spreads>
- Fix: <concrete remediation, code-level>

[…repeat per finding, ordered Critical → High → Medium…]

## What was not flagged
[1-paragraph: which vulnerability classes returned zero findings, and how many findings the FP filter dropped — so the user sees the work, not just the survivors]
\`\`\`

## Phase 6: Ask before fixing

After the report, ask:

> Which (if any) should I fix? Options:
> - A) Add tasks for all Critical + High
> - B) Add tasks for specific findings (give IDs, e.g. "BP-001, BP-004")
> - C) Add tasks for a category (auth, supply chain, secrets, …)
> - D) None — report only

**Do not start fixing until the user picks.**

If the user chooses A, B, or C, do not fix directly. Instead, add one task per selected finding or tightly coupled finding group using the \`tasks\` tool (action=add), ordered by severity, exploitability, and dependency. Each task needs a short title and a standalone prompt that includes the finding ID, vulnerability scenario, affected local files/anchors, concrete remediation, instructions to compare security-sensitive implementation details with kencode search or authoritative docs before editing, project verification commands, and instructions to compare the final fix with kencode search or authoritative docs again before completing the task. After adding the tasks, tell the user exactly: "Tasks added. Press Ctrl+T to open the task list and run them." Do not begin executing them unless the user explicitly says so.

## Threat reference (May 2026)

Cite these as needed per audit. Do not dump them into the report — use them to verify whether a candidate is actually reachable.

**OWASP Top 10:2025** — A01 Broken Access Control (now includes SSRF), A02 Misconfig, **A03 Supply Chain Failures (new)**, A05 Injection (now includes prompt injection), **A10 Mishandling Exceptional Conditions (new — fail-open patterns)**.

**OWASP API Security Top 10 (2023)** — BOLA, Broken Auth, BOPLA, SSRF (API7).

**OWASP Top 10 for LLM Apps v2025** — LLM01 Prompt Injection (direct + indirect), LLM02 Sensitive Info Disclosure, LLM03 Supply Chain, LLM04 Data & Model Poisoning, LLM05 Improper Output Handling, LLM06 Excessive Agency, **LLM07 System Prompt Leakage (new)**, **LLM08 Vector & Embedding Weaknesses (new — RAG/embedding-store attacks)**, LLM09 Misinformation, LLM10 Unbounded Consumption.

**OWASP Top 10 for Agents 2026 (ASI01–10)** — Goal hijack, tool misuse, identity/privilege abuse, agentic supply chain, unexpected code exec, memory/context poisoning, inter-agent comms, cascading failures, human-trust exploit, rogue agents.

**Real 2024-2026 incidents — use as grep templates:**
- tj-actions/changed-files (Mar 14-15 2025, CVE-2025-30066, 23k repos) → unpinned GH Actions, \`uses: foo/bar@main\` / mutable tags, runner-memory secret dumps
- TanStack Mini Shai-Hulud (May 11 2026, CVE-2026-45321, CVSS 9.6 — 84 versions across 42 \`@tanstack/*\` + UiPath/Mistral/Guardrails/OpenSearch, 169+ packages total, "TeamPCP") → self-spreading npm worm, \`pull_request_target\` + cache poisoning + OIDC token extraction from \`/proc/<pid>/mem\`, persistent \`gh-token-monitor\` daemon
- Slopsquatting (ongoing 2025-2026, \`react-codeshift\` Jan 2026) → AI coding assistants hallucinate ~20% non-existent package names (open-source models ~21.7%, GPT-4 ~5.2%); malicious parties register the hallucinated names on npm/PyPI. **Verify every package actually existed BEFORE the agent suggested it** — check registry age, download history, author identity
- XZ Utils (CVE-2024-3094) → unverified maintainer takeovers, multi-year backdoor injection in install scripts
- Invariant Labs MCP hijack (May 2025) → MCP server returns malicious tool descriptions / crafted issue content
- Claude Code source-map leak (Mar 2026, 513k LOC) → \`*.map\` files in \`npm pack\` / shipped artifacts
- Embrace The Red DNS-exfil (Aug 2025) → coding agent coerced into encoding secrets in DNS queries
- IMDSv1 → AWS creds via SSRF (Mar 2025 campaign) → Terraform missing \`http_tokens = "required"\`
- GitGuardian 2026 — 28.6M GitHub secret leaks in 2025, 24k inside MCP config files

**Language-specific hot zones — only apply to languages actually present:**
- **Node/TS**: \`child_process.exec\`/\`execSync\`, \`spawn(..., {shell:true})\`, \`eval\`/\`Function\`, \`vm.runIn*\`, prototype pollution via \`lodash.merge\`/\`Object.assign({}, userJson)\`, \`serialize-javascript\`/\`node-serialize\`, source maps in published packages
- **Python**: \`pickle.load\`, \`yaml.load\` without \`SafeLoader\`, \`eval\`/\`exec\`, \`subprocess.*(shell=True)\`, \`os.system\`, \`Jinja2(autoescape=False)\`, \`flask.render_template_string(user_input)\`, \`requests(verify=False)\`, \`xml.etree\`/\`lxml\` without \`defusedxml\`
- **Go**: \`exec.Command("sh", "-c", userInput)\`, \`html/template\` vs \`text/template\` confusion, unbounded \`io.ReadAll\`, race-prone \`map\` access without lock
- **Rust**: \`unsafe\` blocks with raw pointers, \`Command::new("sh").arg("-c")\`, deserializing untrusted \`bincode\`/\`serde_pickle\`/\`serde_json\` with \`#[serde(deny_unknown_fields)]\` missing
- **Java/JVM**: \`ObjectInputStream\` deserialization, JNDI lookup (Log4Shell-style), \`Runtime.exec(String)\`, XXE in default XML parsers
- **Ruby**: \`eval\`/\`instance_eval\`, \`Marshal.load\`, \`YAML.load\` (not \`safe_load\`), \`Kernel#system\` with interpolation, mass assignment
- **PHP**: \`unserialize\`, \`eval\`, \`assert(string)\`, \`include $userInput\`, \`preg_replace\` /e modifier
- **C/C++**: unsafe \`strcpy\`/\`sprintf\`/\`gets\`, integer overflows, format strings (\`printf(userInput)\`), use-after-free, double-free
- **Solidity / EVM**: reentrancy, unchecked external calls, integer over/underflow (pre-0.8), \`tx.origin\` for auth, delegatecall to untrusted, oracle manipulation
- **Mobile (iOS/Android)**: insecure IPC / deep links / pasteboard, WebView \`addJavascriptInterface\`, exported activities/intents without permission checks, insecure local storage

## Rules

- **Recon first, audits second.** No audit fires without a recon-identified entry surface to justify it.
- **No pattern-only findings.** Every flag must have a Sources → Sinks path traced through the code.
- **No "could be improved" recommendations.** Either it's exploitable or it's not in scope.
- **Strict confidence gate (≥0.8).** Drop everything else, even if it looks suspicious.
- **Adapt to the stack, always.** The audit catalog and threat reference above are guidance, not a checklist to apply uniformly.
- **Report only.** Wait for the user to pick what to fix in Phase 6.`,
    },
    {
        name: "init",
        aliases: [],
        description: "Generate or update CLAUDE.md for this project",
        prompt: `Generate or update a minimal CLAUDE.md with project-specific context only: what this project is, how it is structured, and commands/workflows that are unique to it.

Do NOT add generic agent behavior already covered by the system prompt, including: read before edit/write, re-read after formatters, ask before destructive actions, no fake verification, generic code-quality advice, single-responsibility rules, one-file-per-component rules, or language-style conventions. Never add guidance that requires running checks, builds, or the full quality suite after every edit or every file change. Include only project-specific overrides or stricter local requirements.

## Step 1: Check if CLAUDE.md Exists

If CLAUDE.md exists:
- Read the existing file
- Preserve custom sections the user may have added
- Update only project-specific facts that are stale or missing
- Remove generic guidance that is already covered by the system prompt unless it is a deliberate project-specific override

If CLAUDE.md does NOT exist:
- Create a new one from scratch

## Step 2: Analyze Project (Use Sub-agents in Parallel)

Derive every fact from the actual project — source code, entry points, manifests, and config. Treat README, docs, and code comments as unverified hints that are frequently stale: never copy claims from them, and only state things you can confirm from the code and config themselves.

Spawn 3 sub-agents in parallel using the subagent tool (call the subagent tool 3 times in a single response):

1. **Project Purpose Agent**: Determine what the project actually does from its real code — entry points, main modules, exported/public APIs, CLI commands, routes, and manifests. Do not rely on the README's description.
2. **Directory Structure Agent**: Map out the folder structure and what each folder contains
3. **Tech Stack Agent**: Identify languages, frameworks, tools, and dependencies from manifests/lockfiles and config (not from prose docs)

Wait for all sub-agents to complete, then synthesize the information.

## Step 3: Detect Project Type & Commands

Check for config files:
- package.json -> JavaScript/TypeScript (extract package-manager, build, lint, typecheck, test, format, and server scripts)
- pyproject.toml or requirements.txt -> Python
- go.mod -> Go
- Cargo.toml -> Rust

Extract exact commands that are useful project facts. Take commands from authoritative sources — package scripts, manifests, Makefiles, and CI config; do not invent them from convention, and do not trust README/doc command snippets unless a script or manifest confirms they still exist. Do not restate generic "run checks after edits" behavior, and do not turn discovered commands into mandatory after-every-edit requirements unless local docs or CI explicitly require that stricter sequence.

## Step 4: Summarize Stable Structure

If useful, create a concise structure summary for future agents showing only key stable directories and files with brief descriptions. Do NOT embed generated symbol maps, exhaustive file indexes, auto-generated directory listings, or large trees in CLAUDE.md.

## Step 5: Generate or Update CLAUDE.md

Create CLAUDE.md with only sections that add project-specific value. Prefer this structure:

- Project name and one-sentence purpose
- Key packages/apps/modules and what each owns
- Important project-specific architecture or workflow notes
- Exact local commands (install/build/check/test/dev/publish/deploy) when they are not obvious from package scripts alone
- Project-specific constraints that override defaults (for example required publish order, generated-file workflow, auth/secrets storage, deployment caveats)

Avoid generic sections named "Code Quality", "Organization Rules", or "How to Work" unless every bullet is specific to this project. Do not duplicate language style packs, generic verification rules, or boilerplate quality gates such as "After editing ANY file" / "Code Quality — Zero Tolerance". Do not add symbol indexes, exhaustive file indexes, or auto-generated project inventories; CLAUDE.md must remain durable, agent-focused project context.

Keep total file under 100 lines. If updating, preserve any custom sections the user added. After writing, re-read CLAUDE.md and confirm it contains only project-specific facts supported by local files.

## Step 6: Restart Notice

End your reply with this exact notice so the user doesn't miss it:

> ⚠️ CLAUDE.md was created/updated. ezcoder loads it at startup, so **exit and restart ezcoder** (\`/quit\` then run \`ezcoder\` again) before continuing. Without a restart, I won't see the new context.`,
    },
    {
        name: "setup-commit",
        aliases: [],
        description: "Generate a /commit command",
        prompt: `Detect the project type and generate a /commit command that enforces quality checks and an agent code review before committing.

## Step 1: Detect Project and Extract Commands

Check for config files and extract the lint/typecheck commands:
- package.json -> Extract lint, typecheck scripts
- pyproject.toml -> Use configured mypy, pylint/ruff commands
- go.mod -> Use configured go vet/gofmt/staticcheck commands
- Cargo.toml -> Use configured cargo clippy/fmt commands

Prefer existing project scripts. If you must synthesize a command from tool conventions, verify the current CLI flags against official docs first.

## Step 2: Generate /commit Command

Create the directory \`.ezcoder/commands/\` if it doesn't exist, then write \`.ezcoder/commands/commit.md\`:

\`\`\`markdown
---
name: commit
description: Run checks, agent code review, commit with AI message, and push
---

1. Run quality checks:
   [PROJECT-SPECIFIC LINT/TYPECHECK COMMANDS]
   Fix ALL errors before continuing. Use auto-fix commands where available.

2. Review changes: run git status and git diff --staged and git diff

3. Fast review gate: spawn ONE subagent with the full diff. Instructions: review ONLY
   the diff for real bugs, regressions, leftover debug code, and unintended changes.
   Score each issue 0-100 confidence (pre-existing issues and stylistic nitpicks = false
   positives, score low). Report ONLY issues with confidence >= 80, with file:line and a
   one-line fix. If none, reply "CLEAR". This is a last check, not a deep audit - be fast.

4. If CLEAR: proceed straight to step 5 and push WITHOUT asking the user anything.
   If issues >= 80 were reported: STOP, show the issues, and ask exactly:
   "Want me to fix this first, or commit and push anyway?
   A) Fix it first, then commit & push
   B) Commit & push anyway"
   On A: fix, re-run step 1, then continue (no re-review). On B: continue as-is.

5. Stage relevant files with git add (specific files, not -A)

6. Generate a commit message:
   - Start with verb (Add/Update/Fix/Remove/Refactor)
   - Be specific and concise, one line preferred

7. Commit AND push in one go - never pause for confirmation here:
   git commit -m "your generated message"
   git push
\`\`\`

Replace [PROJECT-SPECIFIC LINT/TYPECHECK COMMANDS] with the actual commands.

Keep the command file under 30 lines.

## Step 3: Confirm

Report that /commit is now available with quality checks, an agent code review gate, and AI-generated commit messages, and mention which local scripts/docs verified the commands.`,
    },
    {
        name: "compare",
        aliases: [],
        description: "Compare real-world code",
        prompt: `Compare the code you just created or modified in this conversation against real-world implementations using the \`mcp__kencode-search__searchCode\` tool.

First confirm the \`mcp__kencode-search__searchCode\` tool is actually available in this session. If it is not (calling it returns "Unknown tool"), stop and report that real-code comparison is unavailable because the kencode-search MCP server isn't connected — do not retry the call repeatedly.

You already know what you just built. For each file you created or modified, use \`mcp__kencode-search__searchCode\` to search for how real projects implement the same patterns. Look at the specific APIs, hooks, functions, and architecture you used.

If you find something consistently done differently across real codebases, or something commonly included that you left out, report it:

\`\`\`
[MISSING/DIVERGENT/INCOMPLETE] file:line - What it is
Wrote: What was implemented
Real-world: What real projects do instead/additionally
Evidence: kencode-search - pattern seen in X out of Y repos searched
\`\`\`

Style preferences and subjective improvements are not valid findings. Only report things backed by clear kencode-search evidence across multiple repos.

If the code aligns well with real-world patterns, say so. That's a good outcome.`,
    },
    {
        name: "setup-skills",
        aliases: [],
        description: "Recommend useful skills",
        prompt: `# Skills Audit: Find useful skills for this project

Analyze this project and recommend skills from the open ecosystem that would make **working on this project more efficient, easier, and safer**. That is the goal, full stop. Every recommendation must pass the test: does this skill save real time, lower real cognitive load, or prevent real mistakes for someone working on THIS project, repeatedly?

Ranked by real impact, not volume.

This project could be anything — a web app, a CLI, a mobile app, a game, firmware, a data pipeline, a library, a scientific tool. Do not assume a stack. Let the codebase tell you what it is, then decide what to look for.

## Phase 1: Understand what this project is

Read just enough to know what kind of project this is. Look at whichever signals actually apply:

- Build / manifest files: \`package.json\`, \`pyproject.toml\`, \`Cargo.toml\`, \`go.mod\`, \`pubspec.yaml\`, \`Podfile\`, Xcode project, Gradle build, \`*.csproj\`, \`CMakeLists.txt\`, Unity/Unreal project files, Makefile — whatever exists.
- Any README, CLAUDE.md, or AGENTS.md.
- Top-level directory layout and obvious entry points.
- Any CI config, lockfile, or config directory that hints at workflow.

**Do NOT read source code yet.** You need only a coarse answer to: what kind of project is this, what platform/stack/language, what stage (greenfield vs mature), and what does the surrounding workflow look like (build, test, release, distribute, deploy — whatever applies for THIS project type).

## Phase 2: Decide which domains to investigate

Based on Phase 1, pick 4–6 domain slices that represent the **recurring work someone actually does on this project** — not abstract "areas of the codebase," but the real activities that eat time, attention, or trust. Do not use a fixed template. The right domains for a Rust CLI are different from an iOS app, a Unity game, a Django backend, a Kubernetes operator, or an ML notebook.

Illustrative only (not prescriptive):

- Web app → shipping features, API changes, handling data safely, deploys
- Mobile app → building screens, store releases, platform quirks, crash & accessibility triage
- CLI tool → adding commands, packaging & distribution, user-facing UX, error handling
- Game → adding content, platform ports, perf passes, build pipeline
- Library → designing public APIs, cutting releases, downstream compatibility, docs/examples
- Data / ML → running experiments, pipeline orchestration, reproducibility, serving models
- Embedded → adding peripherals, size/memory passes, flashing, hardware bring-up

**Announce your chosen domains to the user in one line before spawning agents**, so they can see what you're looking at (e.g. \`Domains: adding content, platform ports, perf passes, build pipeline\`).

## Phase 3: Parallel sweep

Spawn one sub-agent per domain you chose, in parallel using the subagent tool (call it N times in a single response, one task per domain). Each explores its assigned domain and returns skill-worthy opportunities.

**Skill-worthy means**: a recurring activity someone will do on THIS project — shipping, reviewing, migrating, debugging, onboarding, whatever applies — where a reusable instruction set would make it **faster** (efficient), **lower-effort** (easier), or **less likely to break something** (safer). The test is: will this skill save real time, reduce real cognitive load, or prevent real mistakes, repeatedly, on this project? If no, drop it. A domain returning zero candidates is a valid outcome.

Each sub-agent must return candidates in this exact shape, nothing else:

\`\`\`
[domain] — candidate title
Why: one sentence on the real friction observed in THIS project
Search terms: 2–3 keywords the parent should feed to find-skills
\`\`\`

Don't invent. Don't pad.

## Phase 4: Ecosystem search

After all sub-agents complete, use the **skill** tool to invoke the \`find-skills\` skill. Feed it the aggregated candidate list with search terms. Let find-skills drive discovery across skills.sh, vercel-labs/agent-skills, and anthropics/skills.

For each candidate, record the best 0–1 ecosystem match: skill name, source repo URL, and enough evidence from the skill README/source to prove it fits this project. If no fit exists, record "no match". **Do NOT install anything yet.**

## Phase 5: Prioritized recommendation

Rank every candidate that returned a real match by **crucial factor** — a 0–100% score combining:

- **Frequency** — how often someone will do this work on this project
- **Lift** — how much the skill makes it faster (efficient), lower-effort (easier), or safer (fewer mistakes, broken builds, bad releases) per hit
- **Fit** — how well the ecosystem match actually matches this project

Present highest first, in this exact format:

\`\`\`
# Skills Audit

1. <skill-name> — 92%
   Benefit: <one sentence on what it does for this project>
   Source: <repo URL>
   Scope: project

2. <skill-name> — 78%
   Benefit: …
   Source: …
   Scope: project
\`\`\`

Cap the list at 8. If you'd list more, you're padding. Default scope is \`project\` per find-skills' rules; only mark \`global\` when the skill is genuinely cross-cutting.

If strong candidates had no ecosystem match, list them at the bottom:

\`\`\`
## Gaps worth authoring

- <candidate title> — <why it matters for this project> — consider scaffolding a custom SKILL.md
\`\`\`

## Phase 6: Wait for the user

After presenting the list, ask which (if any) to install. Install nothing without explicit confirmation. Once confirmed, hand off to find-skills to perform the actual install.`,
    },
    {
        name: "setup",
        aliases: ["setup-project"],
        description: "Audit project setup",
        prompt: `Audit this project across six categories and report gaps. **Do not fix anything yet.** Wait for me to choose what to address after the report.

Language-agnostic and project-agnostic — adapt findings to the languages and stack actually present. Ignore categories that don't apply (e.g. skip CI for a local-only scratchpad).

## Categories

### 1. Project hygiene

- \`.gitignore\` present and covers the active language(s)?
- \`README.md\` present with at least install + run instructions?
- License file present (if this looks like a public/shareable project)?
- \`.editorconfig\` present?
- Git initialized? (\`.git\` directory exists)

### 2. Toolchain version pinning

- Language version pinned in a canonical file: \`.nvmrc\` / \`package.json#engines\` (Node), \`.python-version\` / \`pyproject.toml#requires-python\` (Python), \`rust-toolchain.toml\` (Rust), the \`go\` line in \`go.mod\`, \`.ruby-version\` (Ruby), etc.
- Lockfile present and committed? (\`package-lock.json\`, \`pnpm-lock.yaml\`, \`yarn.lock\`, \`bun.lockb\`, \`uv.lock\`, \`poetry.lock\`, \`Cargo.lock\`, \`go.sum\`, \`Gemfile.lock\`, \`composer.lock\`)

### 3. Code quality tooling

For each active language, check that a formatter, linter, and (where applicable) type checker are configured:
- **Formatter**: Prettier / ruff format / gofmt (built-in) / rustfmt (built-in) / clang-format / etc.
- **Linter**: ESLint / Ruff / golangci-lint / Clippy / etc. — with a reasonable strictness preset
- **Type checker** (statically-typed langs only): tsc strict, Pyright strict, mypy strict
- **Test framework**: vitest / jest / pytest / go test / cargo test / rspec / etc.

Report which are present, missing, or configured below the pack's strictness recommendation.

### 4. Verify pipeline

- Are \`lint\` / \`typecheck\` / \`format:check\` / \`test\` (or language-equivalent) wired as runnable commands? (scripts in \`package.json\`, \`pyproject.toml\`, a \`Makefile\`, or \`justfile\`)
- Pre-commit hook configured? (\`.husky/\`, \`pre-commit\` framework, \`lefthook\`, etc.) — nice-to-have, not required.
- CI config present? (\`.github/workflows/\`, \`.gitlab-ci.yml\`, \`.circleci/\`, etc.)

### 5. Style pack alignment

"Active style packs" refers specifically to the per-language sub-sections inside the **Language Style Packs** section in your system prompt (e.g. \`### TypeScript\`, \`### Python\`, \`### Go\`). It does **NOT** include the cross-cutting \`### Agent-Written Code\` preamble that sits above them — those are guidelines for how code is *written*, not project-scaffolding to audit. It also does **NOT** include Skills (\`.ezcoder/skills/\`) or any other extension category. If the Language Style Packs section is absent or empty, **skip this entire section entirely** — do not substitute Skills or any other concept.

When per-language packs are present, compare the project against each pack's **Tooling** bullet and the system prompt's **Verification** commands. For tool recommendations or config semantics, verify against official docs when local files are ambiguous:
- Tooling: which strict-mode flags or lint-rule presets does the pack recommend that the project is missing? (e.g. \`tsconfig\` missing \`noUncheckedIndexedAccess\`, \`pyproject\` missing \`[tool.ruff]\`, Go project missing \`golangci-lint\` config).
- Dependencies: list which pack-mentioned libs (Zod, Pydantic, thiserror, anyhow, etc.) the project uses, has an equivalent for, or lacks. **Observation only — no recommendation to install.**

### 6. Documentation hygiene

- \`CLAUDE.md\` or \`AGENTS.md\` present?
- Public API documented? (top-level docstrings, type signatures, or README examples)
- Architecture doc for non-trivial projects? (\`ARCHITECTURE.md\`, \`docs/architecture/\`, ADRs)

## How to investigate

- Read the project root + obvious config locations (\`./\`, \`.github/\`, \`.husky/\`, \`docs/\`).
- Don't recurse into \`node_modules\`, \`dist\`, \`build\`, \`target\`, vendored folders.
- Use \`ls\`, \`read\`, \`find\` (with name patterns) — do not \`grep\` source code for this audit; it's about scaffolding, not code review.
- Cap at ~20 file reads total. If a file is huge (e.g. \`pnpm-lock.yaml\`), don't read its body — presence is what matters.

## Output format

A single Markdown report, organized by category. Within each category, mark each item as one of:
- \`[OK]\` — present and reasonable
- \`[GAP]\` — missing or misconfigured; safe to add/fix
- \`[INFO]\` — observation only, no action implied
- \`[N/A]\` — doesn't apply to this project (omit from output if obvious)

Keep each line to one sentence. No prose paragraphs.

At the end:

\`\`\`
## Summary

<N> gaps in hygiene, <N> in tooling, <N> in verify pipeline, <N> in style-pack alignment.

Which (if any) would you like me to fix? Options:
- A) Add tasks for all [GAP] items that are safe + additive (no overwrites)
- B) Add tasks for a category: hygiene / tooling / verify / style-pack alignment
- C) Add tasks for specific items — tell me which
- D) None — just the report
\`\`\`

## Rules

- **Report only.** No edits, no installs, no commits without explicit user confirmation after the report.
- **Task handoff for fixes.** If the user chooses A, B, or C, do not fix directly. Add one task per selected gap or tightly coupled gap group using the \`tasks\` tool (action=add). Each task needs a short title and a standalone prompt that includes the gap, affected files/configs, safe-additive constraints, implementation instructions, project verification commands, and instructions to verify relevant tool/config semantics against official docs before completing the task. Use kencode search only for code-level examples, not as proof of scaffolding requirements. After adding the tasks, tell the user exactly: "Tasks added. Press Ctrl+T to open the task list and run them." Do not begin executing them unless the user explicitly says so.
- **No code refactors recommended.** This audit is about scaffolding/tooling, not code review. Use \`/scan\` or \`/verify\` for code-level findings.
- **No dependency installations in the report.** Listing them as observations is fine; recommending installation is not — that's the user's call.
- **Skip empty categories.** If a category has no findings, omit it.
- **Adapt to scale.** A 50-line script doesn't need CI, a license, or an ARCHITECTURE.md. Use judgment.
- **Brand-new empty project**: report "Empty project — nothing to audit. To bootstrap, tell me the stack you want and I'll scaffold from scratch." and stop.`,
    },
];
/** Look up a prompt command by name or alias */
export function getPromptCommand(name) {
    return PROMPT_COMMANDS.find((cmd) => cmd.name === name || cmd.aliases.includes(name));
}
//# sourceMappingURL=prompt-commands.js.map