Create a structured implementation plan for: the current task

Follow this format:
1. **Goal** — one-sentence objective
2. **Constraints** — existing code, dependencies, tests, or assumptions to respect
3. **Approach** — high-level strategy and rationale
4. **Steps** — numbered, actionable tasks small enough to verify one at a time
5. **Verification** — how to confirm each step works (tests, logs, manual checks)
6. **Risks & Rollbacks** — what could go wrong and how to undo safely
7. **Open Questions** — anything that needs clarification before starting

Use the codebase context as needed. Do not write implementation code yet; only produce the plan.


Let me analyze this request. The user is asking me to create a structured implementation plan for "the current task" - but there is no current task described. They want me to follow a specific format but don't specify what to implement.

I need to look at the codebase context to understand what the current task might be. The current working directory is `/home/liph/dotfiles/pi/.pi/agent/prompts`.

Since the user said "the current task" without defining it, I need to either:
1. Ask for clarification
2. Investigate the


Create a structured implementation plan for: is there a way to combine some of these prompt into a chain?

Follow this format:
1. **Goal** — one-sentence objective
2. **Constraints** — existing code, dependencies, tests, or assumptions to respect
3. **Approach** — high-level strategy and rationale
4. **Steps** — numbered, actionable tasks small enough to verify one at a time
5. **Verification** — how to confirm each step works (tests, logs, manual checks)
6. **Risks & Rollbacks** — what could go wrong and how to undo safely
7. **Open Questions** — anything that needs clarification before starting

Use the codebase context as needed. Do not write implementation code yet; only produce the plan.


We need answer: user asked: Create a structured implementation plan for: the current task. Then second message: "Create a structured implementation plan for: is there a way to combine some of these prompt into a chain?" They probably want plan about combining prompts into a chain. Need inspect codebase context. Current working directory: /home/liph/dotfiles/pi/.pi/agent/prompts. We should explore files in this directory to understand prompts. Use context-mode active; for file exploration and codebase stats use ctx_execute or ctx_execute_file. We need structured implementation plan only, no code.

Need understand: "is there a way to combine some of these prompt into a chain?" Maybe they have multiple prompt files and want chain them. Need look at prompts directory. Use bash or fffind. Since investigate. Use ctx_execute perhaps. Let's list directory.


total 60
drwxr-xr-x  3 liph liph 4096 Jul 24 16:47 .
drwxr-xr-x 12 liph liph 4096 Jul 24 17:15 ..
drwxr-xr-x  2 liph liph 4096 Jul 24 16:47 Doc
-rw-r--r--  1 liph liph 1285 Jul 24 16:42 p-brainstorm.md
-rw-r--r--  1 liph liph 1164 Jul 24 16:42 p-commit.md
-rw-r--r--  1 liph liph  845 Jul 24 16:41 p-debug.md
-rw-r--r--  1 liph liph 1158 Jul 24 16:41 p-diagnose.md
-rw-r--r--  1 liph liph 1205 Jul 24 16:42 p-doc.md
-rw-r--r--  1 liph liph  708 Jul 24 16:31 p-explain.md
-rw-r--r--  1 liph liph  787 Jul 24 16:31 p-plan.md
-rw-r--r--  1 liph liph 1140 Jul 24 16:42 p-refactor.md
-rw-r--r--  1 liph liph  892 Jul 24 16:31 p-review.md
-rw-r--r--  1 liph liph 1407 Jul 24 16:42 p-secaudit.md
-rw-r--r--  1 liph liph 1184 Jul 24 16:42 p-summarize.md
-rw-r--r--  1 liph liph 1103 Jul 24 16:41 p-test.md


There are prompt files p-*.md, plus Doc folder. Need inspect contents to understand them. Need create plan about combine some of these prompts into a chain. Likely user wants a chaining prompt that calls multiple subprompts sequentially? We should read the files, understand their purposes, identify overlaps and possible chain composition. Also maybe there is a doc folder with instructions. Let's read them. Could use cat. Let's read all p-*.md. Use bash for concatenation maybe but better read each with read tool for exact context. Use multiple read calls. Also list Doc.


total 16
drwxr-xr-x 2 liph liph 4096 Jul 24 16:47 .
drwxr-xr-x 3 liph liph 4096 Jul 24 16:47 ..
-rw-r--r-- 1 liph liph 4413 Jul 24 16:45 README.md


---
description: Generate 3–5 design alternatives with trade-offs before committing to an approach
argument-hint: "[problem or feature to design]"
---
Brainstorm approaches for: ${@:-the current problem or feature}

Structure your answer as:
1. **Problem restatement** — one paragraph; what we're solving, what constraints matter, what "done" looks like
2. **Alternatives** — 3 to 5 distinct approaches. For each:
   - **Summary** — one or two sentences
   - **How it works** — the key mechanism
   - **Pros** — what it gets right
   - **Cons** — what it costs, risks, or breaks
   - **Best when** — the conditions that would make this the right pick
3. **Comparison table** — across the alternatives, score or rank on: complexity, time-to-ship, reversibility, performance, fit-with-existing-code
4. **Recommendation** — which one to pick *given the current codebase*, with the second choice as a fallback
5. **Unknowns** — questions that, if answered, would change the recommendation

Be opinionated. Surface real trade-offs, not strawmen. If the obvious approach wins decisively, say so and only enumerate 2 alternatives — don't manufacture options for the sake of a full set. If the problem is under-specified, ask clarifying questions before brainstorming.


---
description: Generate a conventional commit message and optional PR description from current changes
argument-hint: "[diff, file list, or 'auto' to use git status]"
---
Generate a commit message for: ${@:-the current uncommitted changes (run git status / git diff first)}

Structure your answer as:
1. **Type & scope** — one of: feat, fix, refactor, perf, test, docs, build, ci, chore, style; scope is the affected module/subsystem
2. **Subject** — imperative mood, ≤72 chars, no trailing period, no emoji
3. **Body** — wrapped at 72 cols, explain *why* not *what*. Use bullet points for multiple distinct changes.
4. **Footer** — `BREAKING CHANGE: …` if applicable; `Refs: #123` for linked issues
5. **PR description** (if the change is non-trivial) — Summary, Motivation, Changes, Test plan, Risks

Format the final message in a single fenced block ready to copy. If the change spans multiple logical commits, propose a split with one subject per commit and the file groups that belong in each.

Read the diff before writing — never invent files, symbols, or behavior. If `git status` is empty or the diff is unclear, ask before fabricating.


---
description: Diagnose a failing test, build, or runtime error
argument-hint: "[error message, test name, or stack trace]"
---
Diagnose the following failure: ${@:-the current failing test or error}

Structure your answer as:
1. **What failed** — one-sentence summary; quote the exact error line
2. **Likely root cause** — ranked list, most probable first
3. **Minimal fix** — the smallest change that would resolve it
4. **How to verify** — the exact command or test to confirm the fix
5. **How to prevent** — a regression test, invariant, or guard to add

Be specific. If multiple causes are plausible, name each and give a quick disambiguation check (a log line, a flag, a one-line probe) to tell them apart. Do not speculate beyond what the error message and the code actually show — if you need more data, say so explicitly.


---
description: Diagnose unexpected behavior, not just failures (race conditions, perf regressions, weird output)
argument-hint: "[symptom or observed behavior]"
---
Diagnose the following unexpected behavior: ${@:-the current code or recent change}

Structure your answer as:
1. **What's wrong** — restate the observed behavior vs the expected behavior in one sentence each
2. **Where in the code** — point at the specific functions, lines, or modules most likely responsible
3. **Hypotheses** — 2–4 ranked explanations with the evidence for and against each
4. **Disambiguation** — the cheapest experiment (log, flag, breakpoint, minimal repro) that would confirm or rule out each hypothesis
5. **Likely fix** — once a hypothesis is confirmed, the smallest change that would correct it
6. **Why it wasn't caught** — what test, type, or invariant would have caught this earlier

Use this when nothing is "failing" but behavior is wrong: a value drifts, a UI flashes, a query is slow, two users see different results. Distinguish carefully between "the test fails" (use `p-debug`) and "the test passes but production is broken" (this prompt).


---
description: Write or improve documentation (README, docstrings, JSDoc, godoc, ADRs)
argument-hint: "[file path, symbol, or topic to document]"
---
Write documentation for: ${@:-the current code or topic}

Structure your answer as:
1. **Audience** — who is reading this (new contributor, end user, API consumer, future self) and what they already know
2. **One-paragraph summary** — what it is and when to use it
3. **Minimal example** — the smallest runnable/usable snippet that demonstrates the primary path
4. **API or interface** — for code: every public symbol with one line of purpose and a signature. For prose: headings and key terms.
5. **Gotchas** — non-obvious behavior, common mistakes, sharp edges, things that look like bugs but aren't
6. **How to verify** — for code docs, a command or test the reader can run; for prose, a cross-link to source

Match the existing style of the project's docs. Do not invent APIs, parameters, or behavior — if something is unclear from the code, say "behavior unclear, needs verification" rather than guessing. If the project has no docs yet, propose a minimal README structure and call it out so the user can approve before you scaffold.


---
description: Explain code, concepts, or errors in plain terms
argument-hint: "[topic: code, concept, or error]"
---
Explain the following in clear, plain language: ${@:-the current code or context}

Structure your answer as:
1. **What it is** — one-sentence summary
2. **How it works** — walk through the key parts step by step
3. **Why it matters** — purpose, trade-offs, or design intent
4. **Connections** — how it relates to the surrounding system or codebase
5. **Key details to know** — important gotchas, assumptions, or common pitfalls

Avoid unnecessary jargon. If showing code, keep snippets short and annotate them. If explaining an error, include the likely cause and how to fix it.


---
description: Create a structured implementation plan before coding
argument-hint: "[task or feature]"
---
Create a structured implementation plan for: ${@:-the current task}

Follow this format:
1. **Goal** — one-sentence objective
2. **Constraints** — existing code, dependencies, tests, or assumptions to respect
3. **Approach** — high-level strategy and rationale
4. **Steps** — numbered, actionable tasks small enough to verify one at a time
5. **Verification** — how to confirm each step works (tests, logs, manual checks)
6. **Risks & Rollbacks** — what could go wrong and how to undo safely
7. **Open Questions** — anything that needs clarification before starting

Use the codebase context as needed. Do not write implementation code yet; only produce the plan.


---
description: Safely restructure code without changing behavior
argument-hint: "[file path or symbol to refactor]"
---
Refactor: ${@:-the current code or context}

Structure your answer as:
1. **Current shape** — what this code does today, in terms of responsibilities (not lines)
2. **Target shape** — what the refactor preserves externally (behavior, API, output) and what it improves internally (readability, coupling, testability, reuse)
3. **Why this is safe** — the test/contract that proves the refactor doesn't change behavior. If none exists, STOP and recommend `p-test` first.
4. **Step-by-step mechanical changes** — numbered, each one individually committable and runnable
5. **After each step** — the command to run (test, type-check, lint) to confirm green
6. **Final verification** — full test suite, plus any manual smoke check
7. **Rollback** — how to revert each step in isolation (e.g. one commit = one rollback unit)

Do not combine refactor with new features. Do not change behavior "while you're in there." If you spot a bug or a missing test, call it out separately at the end, do not fix it inline.


---
description: Review code, diffs, or changes with actionable feedback
argument-hint: "[target: file path, diff, or PR]"
---
Review the following code or changes: ${@:-the current file / diff / staged changes}

Provide feedback in these categories:
- **Correctness** — bugs, logic errors, edge cases, race conditions
- **Security** — injection, unsafe defaults, secrets, auth/z issues
- **Performance** — unnecessary work, memory leaks, hot-path inefficiencies
- **Maintainability** — naming, complexity, duplication, testability
- **Style & Idioms** — consistency with the surrounding codebase
- **Error Handling** — missing or misleading failure modes

For each issue, include:
- The specific location (file, line, function)
- A clear description of the problem
- A concrete suggestion or example fix

Also call out anything done well. Keep the review concise and prioritized.


---
description: Security-focused review covering OWASP-style categories
argument-hint: "[file path, diff, or feature to audit]"
---
Security-audit: ${@:-the current code, diff, or feature}

Structure your answer as:
1. **Trust boundary** — where untrusted input enters, where sensitive data leaves; map the attack surface in one paragraph
2. **Findings** — grouped by severity (Critical / High / Medium / Low / Info). For each:
   - **Category** — one of: Injection, AuthN/AuthZ, Secrets, Crypto, Input validation, Output encoding, Deserialization, SSRF, Path traversal, Race/TOC-TOU, Dependency, Logging/PII, Configuration, Supply chain
   - **Location** — file, line, function
   - **Description** — the vulnerability, with a concrete exploit scenario
   - **Fix** — the minimal secure change, with a code snippet
3. **Missing controls** — auth, rate limiting, audit logging, CSRF/CORS, headers, etc. that should exist but don't
4. **Dependencies** — any third-party packages with known CVEs in this surface (if you can determine versions)
5. **Threat model gaps** — what's out of scope for this audit but worth a separate pass

Be concrete and adversarial — describe a real attack, not "consider validating input." If the code is sound, say so explicitly and explain what you'd look for if it weren't. Do not pad with general security advice that doesn't apply to the specific code.


---
description: Summarize a long file, log, diff, or document into structured notes
argument-hint: "[file path, log, or topic to summarize]"
---
Summarize: ${@:-the current file or context}

Structure your answer as:
1. **One-paragraph gist** — what this is, in plain terms, at the level a smart non-expert would understand
2. **Key points** — 5 to 10 bullets, ordered by importance, each ≤2 lines
3. **Structure** — how the content is organized: sections, layers, time periods, components
4. **Important details** — names, numbers, paths, error codes, dates, anything concrete that a later reader will need verbatim
5. **What's missing or unclear** — gaps, assumptions, things that need a follow-up read
6. **Pointer to deep-dive sections** — if a reader only has 5 minutes, which 2–3 sections cover 80% of the value

Be ruthless about compression. If the source is long, the summary should be short — that's the whole point. Prefer concrete over abstract. Quote exact strings (paths, error messages, identifiers) rather than paraphrasing them, because the reader will likely need to grep for them later. Do not editorialize or add recommendations; just compress.


---
description: Write or expand unit / integration tests for the given code
argument-hint: "[file path, function, or feature to test]"
---
Write tests for: ${@:-the current code or context}

Structure your answer as:
1. **Existing conventions** — name patterns, framework, assertion style, fixtures; match what's already there
2. **Test cases to add** — grouped as:
   - **Happy path** — the primary expected behavior
   - **Edge cases** — empty, zero, max, boundary, off-by-one
   - **Error cases** — invalid input, missing deps, timeouts, permission failures
3. **Test code** — minimal, runnable, following the project's framework (jest, pytest, go test, etc.)
4. **How to run** — the exact command, plus how to run just the new tests
5. **Coverage gaps** — anything still untestable without a refactor; flag it but do not refactor in this pass

Keep tests independent, deterministic, and fast. Prefer many small tests over one large one. If the codebase has no test setup yet, propose the smallest viable setup and call it out clearly so the user can approve before you scaffold it.


# Prompts

Slash-style prompts for the interactive pi session. Each file is a `p-<verb>.md` template with a frontmatter `description` + `argument-hint` and a structured body. Invoke with `:p-<verb> [arg]` or via the `:prompts` TUI picker.

## When to use which

| Prompt             | Use it when…                                                                                | Pairs well with                                         |
| ------------------ | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| **`p-plan`**       | You're about to start a non-trivial change and want a structured plan before coding.                            | `p-brainstorm` (first), then `p-refactor` / `p-test`    |
| **`p-brainstorm`** | You have a problem but no chosen approach yet; want 3–5 alternatives with trade-offs.                           | `p-plan` (after picking one)                            |
| **`p-explain`**    | You don't understand a piece of code, a concept, or an error message.                                           | `p-debug` / `p-diagnose` (if it's a problem)            |
| **`p-debug`**      | A test, build, or command is failing with a clear error. You have the error in hand.                            | `p-test` (add a regression test after the fix)          |
| **`p-diagnose`**   | Nothing is "failing" but behavior is wrong — wrong values, races, perf drift, "passes locally, broken in prod." | `p-debug` (if you find a hard failure)                  |
| **`p-review`**     | You want a code review of a diff, file, or staged change. General quality feedback.                             | `p-secaudit` (security subset)                          |
| **`p-secaudit`**   | Touching auth, input handling, secrets, network, deserialization, or any trust boundary.                        | `p-review` (broader quality), `p-test`                  |
| **`p-refactor`**   | Restructuring code without changing behavior. Safety-first, mechanical steps.                                   | `p-test` (first, as the safety net), `p-review` (after) |
| **`p-test`**       | You need to write or expand tests for existing or new code.                                                     | `p-debug` (after a failure), `p-refactor` (before)      |
| **`p-doc`**        | Writing or improving README, docstrings, JSDoc, godoc, or ADRs.                                                 | `p-summarize` (skim the code first)                     |
| **`p-commit`**     | About to commit. You want a conventional message and (optionally) a PR description.                             | `p-review` (final check before committing)              |
| **`p-summarize`**  | A file, log, diff, or document is too long to read in full. You need the gist + key details.                    | `p-plan` / `p-debug` (then dive into specifics)         |

## Decision flow

```
Got an idea or vague problem?
└─ Yes → p-brainstorm  →  pick an approach  →  p-plan  →  implement
                                                          └─ p-test  →  p-commit
Touching existing code that needs to change?
└─ p-refactor (after p-test confirms a safety net)  →  p-review  →  p-commit
Something is broken?
├─ Hard failure (error message, failing test)  →  p-debug
└─ Soft failure (wrong output, race, perf)      →  p-diagnose
                                       →  fix  →  p-test (regression)  →  p-commit
Touching a trust boundary, auth, secrets, or untrusted input?
└─ p-secaudit  (then p-review for general quality)
Need to understand a long file/log/diff quickly?
└─ p-summarize
Need to write or update docs?
└─ p-doc
Don't know what something does or what an error means?
└─ p-explain
```

## Conventions

- Every prompt uses `${@:-<default>}` so it works with or without an argument.
- Output is structured (numbered sections, fixed categories) so the result is diff-friendly and skim-friendly.
- Prompts intentionally do **not** overlap with subagent workflows (`agents/`, `chains/`, `skills/`) — those are for orchestration; these are for interactive turns.
- Prefer one prompt per turn. Chain them yourself (`p-brainstorm` → `p-plan` → `p-refactor`) rather than asking one prompt to do everything.


We have prompt library. The user's question: "is there a way to combine some of these prompt into a chain?" They want implementation plan for creating chains of prompts. We need produce structured implementation plan for building chain prompt(s). We need use codebase context. Could be within pi harness: there are subagent chains and skills maybe. Current directory is prompts; Doc/README says prompts intentionally do not overlap with subagent workflows (agents/, chains/, skills/) — those are for orchestration; these are for interactive turns. It says prefer one prompt per turn. Chain them yourself rather than asking one prompt to do everything. So maybe user is asking to create a chain prompt that automates sequence e.g. p-brainstorm -> p-plan -> ... But Doc/README says prompts are interactive; chain them yourself. Yet user asks if there is a way to combine some of these prompt into a chain. We should plan for enabling chain invocation, maybe a new meta-prompt `p-chain.md` or a script that runs multiple prompts sequentially. Need inspect pi environment? Maybe there are pi-specific mechanisms: `:prompts` TUI picker, slash-style prompts. The plan could propose a chain definition file (chain config or TUI feature). Need understand how pi uses prompts. There might be pi docs about prompts and chains. Current working directory is .pi/agent/prompts under dotfiles. The README in Doc describes usage: invoke with `:p-<verb> [arg]` or via `:prompts` TUI picker. The user likely wants to know if they can combine some prompts into a chain. There are subagent workflow directories agents/, chains/, skills/ mentioned. The project at dotfiles/pi likely has pi config. Need inspect dotfiles/pi structure. Let's explore. Use bash.

bash

find /home/liph/dotfiles/pi -maxdepth 4 -type f | head -100


total 16
drwxr-xr-x  4 liph liph 4096 Jul 23 20:35 .
drwxr-xr-x 30 liph liph 4096 Jul 23 16:54 ..
drwxr-xr-x  6 liph liph 4096 Jul 23 20:54 .pi
drwxr-xr-x  6 liph liph 4096 Jul 23 20:35 .pi_1


find /home/liph/dotfiles/pi -maxdepth 4 -type f \( -path '*context-mode*' -prune \) -o -type f -print | head -100


/home/liph/dotfiles/pi/.pi/extensions/pi-web-agent/config.json
/home/liph/dotfiles/pi/.pi/agent/trust.json
/home/liph/dotfiles/pi/.pi/agent/models.json
/home/liph/dotfiles/pi/.pi/agent/npm/package.json
/home/liph/dotfiles/pi/.pi/agent/npm/package-lock.json
/home/liph/dotfiles/pi/.pi/agent/npm/.gitignore
/home/liph/dotfiles/pi/.pi/agent/prompts/p-commit.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-brainstorm.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-doc.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-explain.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-review.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-test.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-secaudit.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-plan.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-summarize.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-refactor.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-debug.md
/home/liph/dotfiles/pi/.pi/agent/prompts/p-diagnose.md
/home/liph/dotfiles/pi/.pi/agent/auth.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-solarized-light.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-dark.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-gruvbox-light.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-gruvbox-dark.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-solarized-dark.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-catppuccin-mocha.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-catppuccin-latte.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-tokyo-night.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-nord.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-one-dark.json
/home/liph/dotfiles/pi/.pi/agent/themes/rose-pine-beautiful.json
/home/liph/dotfiles/pi/.pi/agent/themes/crew-dracula.json
/home/liph/dotfiles/pi/.pi/agent/run-history.jsonl
/home/liph/dotfiles/pi/.pi/agent/agents/ollama-orchestrator.md
/home/liph/dotfiles/pi/.pi/agent/agents/ollama-explain.md
/home/liph/dotfiles/pi/.pi/agent/agents/ollama-planner.md
/home/liph/dotfiles/pi/.pi/agent/agents/ollama-researcher.md
/home/liph/dotfiles/pi/.pi/agent/agents/ollama-reviewer.md
/home/liph/dotfiles/pi/.pi/agent/agents/ollama-coder.md
/home/liph/dotfiles/pi/.pi/agent/settings.json
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/187b7128_ollama-orchestrator_0_transcript.jsonl
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/a22166b7_planner_0_transcript.jsonl
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/a22166b7_planner_0_output.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/4059014e_ollama-planner_0_input.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/a22166b7_planner_0_meta.json
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/187b7128_ollama-orchestrator_0_output.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/187b7128_ollama-orchestrator_0_input.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/4059014e_ollama-planner_0_output.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/a22166b7_planner_0_input.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/4059014e_ollama-planner_0_meta.json
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/4059014e_ollama-planner_0_transcript.jsonl
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/plan.md
/home/liph/dotfiles/pi/.pi/.pi-subagents/artifacts/187b7128_ollama-orchestrator_0_meta.json
/home/liph/dotfiles/pi/.pi_1/extensions/pi-web-agent/config.json
/home/liph/dotfiles/pi/.pi_1/teams/audit/prune.jsonl
/home/liph/dotfiles/pi/.pi_1/agent/trust.json
/home/liph/dotfiles/pi/.pi_1/agent/models.json
/home/liph/dotfiles/pi/.pi_1/agent/npm/package.json
/home/liph/dotfiles/pi/.pi_1/agent/npm/package-lock.json
/home/liph/dotfiles/pi/.pi_1/agent/npm/.gitignore
/home/liph/dotfiles/pi/.pi_1/agent/prompts/p-explain.md
/home/liph/dotfiles/pi/.pi_1/agent/prompts/p-review.md
/home/liph/dotfiles/pi/.pi_1/agent/prompts/p-plan.md
/home/liph/dotfiles/pi/.pi_1/agent/auth.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-solarized-light.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-dark.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-gruvbox-light.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-gruvbox-dark.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-solarized-dark.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-catppuccin-mocha.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-catppuccin-latte.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-tokyo-night.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-nord.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-one-dark.json
/home/liph/dotfiles/pi/.pi_1/agent/themes/crew-dracula.json
/home/liph/dotfiles/pi/.pi_1/agent/run-history.jsonl
/home/liph/dotfiles/pi/.pi_1/agent/chains/research-brief.chain.md
/home/liph/dotfiles/pi/.pi_1/agent/chains/feature-build.chain.md
/home/liph/dotfiles/pi/.pi_1/agent/agents/ollama-orchestrator.md
/home/liph/dotfiles/pi/.pi_1/agent/agents/ollama-planner.md
/home/liph/dotfiles/pi/.pi_1/agent/agents/ollama-researcher.md
/home/liph/dotfiles/pi/.pi_1/agent/agents/ollama-reviewer.md
/home/liph/dotfiles/pi/.pi_1/agent/agents/ollama-coder.md
/home/liph/dotfiles/pi/.pi_1/agent/settings.json


Interesting: `.pi_1/agent/chains/` has `research-brief.chain.md` and `feature-build.chain.md`. The current `.pi` has no chains directory. The user is in `.pi/agent/prompts`, but there is a backup `.pi_1` with chain examples. Maybe the current active profile is `.pi` and user wants to combine prompts into chains as in `.pi_1`? We need inspect those chain files and agent files to understand chain format. Also pi docs about chains? The system prompt says pi docs in /home/liph/.local/lib/node_modules/@earendil-works/pi-coding-agent/README.md and docs. There is docs about prompts and subagents. We need follow. But maybe we can use existing `.pi_1` as a model. Let's read chain files. Also check `.pi/agent` for settings, agents. Use read.


---
name: research-brief
description: Parallel web research + local code context → synthesis. Three-stage chain for well-sourced answers combining external evidence and local code.
---

## ollama-researcher
phase: External Research
label: Web research
as: web_research
output: research/web.md
progress: true

Research the external side of {task}. Search, evaluate sources, and produce a focused research brief with citations. Write to {output}.

## scout
phase: Local Context
label: Local code analysis
as: local_context
output: research/local.md
progress: true

Map the local codebase side of {task}. Identify relevant files, how they interact with the topic, and capture local patterns. Write to {output}.

## worker
phase: Synthesis
label: Combine and synthesize
as: synthesis
reads: research/web.md, research/local.md
output: research/brief.md
progress: true

Read {reads} and create a unified research brief. Include: direct answer, evidence from web, evidence from local code, contradictions, recommendation, and confidence level. Write to {output}.


---
name: feature-build
description: Recon → plan → implement → parallel review → synthesize. Five-stage workflow for shipping features end-to-end with Ollama Cloud subagents.
---

## scout
phase: Context
label: Map codebase
as: context
output: context.md
progress: true

Map the relevant code for {task}. List files to touch, capture conventions, identify risks, and write findings to {output}.

## ollama-planner
phase: Planning
label: Create implementation plan
as: plan
reads: context.md
output: plan.md
progress: true

Read {reads} and create a concrete implementation plan for {task}. Write ordered tasks with file paths, acceptance criteria, and risks to {output}.

## ollama-coder
phase: Implementation
label: Implement the feature
as: implementation
reads: plan.md
output: implementation.md
progress: true

Execute the plan from {reads}. Implement the smallest correct changes, run validation, and report changed files with evidence to {output}.

## reviewer
phase: Review
label: Correctness review
as: correctness_review
reads: plan.md, implementation.md
output: review-correctness.md
progress: true

Review the implementation against the plan. Focus on: correctness, regressions, edge cases, and whether the change does what it claims. Write findings to {output}.

## reviewer
phase: Review
label: Tests and validation review
as: test_review
reads: plan.md, implementation.md
output: review-tests.md
progress: true

Review test coverage and validation. Focus on: tests added/updated, do they exercise the new code, are they sufficient to catch regressions. Write findings to {output}.

## reviewer
phase: Review
label: Simplicity and security review
as: simplicity_review
reads: plan.md, implementation.md
output: review-simplicity.md
progress: true

Review for simplicity, maintainability, and security. Focus on: smallest correct change, readability, naming consistency, input validation, secrets, injection risks. Write findings to {output}.

## worker
phase: Synthesis
label: Synthesize and apply fixes
reads: review-correctness.md, review-tests.md, review-simplicity.md
output: synthesis.md
progress: true

Synthesize the three reviews from {reads}. Apply fixes worth doing now (small, safe changes). Report: what was fixed, what was deferred, and any blockers that need user decision.


---
name: ollama-orchestrator
description: Ollama-cloud orchestrator. Adaptive task decomposition and dispatch — has the subagent tool, so it can spawn and coordinate the other ollama-* and built-in subagents at runtime. Use for complex, open-ended, multi-step tasks where static chains (feature-build, research-brief) are too rigid. Powered by MiniMax M3, the deep-reasoning frontier model on Ollama Cloud.
model: ollama/minimax-m3:cloud
thinking: high
tools: read, grep, find, ls, write, subagent, intercom
systemPromptMode: replace
inheritProjectContext: true
inheritSkills: false
defaultContext: fresh
defaultReads: context.md, plan.md
defaultProgress: true
---

You are `ollama-orchestrator`: the adaptive orchestration subagent
powered by Ollama Cloud (MiniMax M3).

You are the **only** one of the `ollama-*` agents that has the
`subagent` tool. That is your defining capability. The other four
(`ollama-planner`, `ollama-coder`, `ollama-researcher`, `ollama-reviewer`)
are workers; you are the dispatcher.

## When you are invoked

You are called when a task is too complex, open-ended, or
ill-structured to be handled by a single worker or by a static chain
like `feature-build` or `research-brief`. Typical triggers:

- "Plan and implement adding a /healthz endpoint to this Express app,
  including tests, then review it."
- "Investigate why this flaky test fails, fix the root cause, and
  open a PR-ready diff."
- "Migrate this component from class to hooks, then run a code review."

If the task is *one* well-defined job, defer to the worker directly
(`ollama-coder` for code, `ollama-researcher` for research, etc.) and
do not invoke yourself.

## How to work

### 1. Decompose

Read the task. Break it into 2–5 sub-tasks. Each sub-task must:
- have a single owner agent
- be independently verifiable
- have a clear pass/fail signal

If the task has only one sub-task, return that you are not needed and
recommend the appropriate worker directly.

### 2. Map to agents

Pick the right agent for each sub-task:

| Sub-task kind | Agent |
|---|---|
| Map a codebase, list files, capture conventions | `scout` (built-in) |
| Write a step-by-step plan, read-only | `ollama-planner` |
| Implement code, run validation | `ollama-coder` |
| Critique a diff against a plan | `ollama-reviewer` |
| External/web research with citations | `ollama-researcher` |
| Cross-check, decision on a stuck call | `oracle` (built-in) |
| Build a compressed context file | `context-builder` (built-in) |
| A simple, well-defined worker task | `worker` (built-in, inherits) |

When in doubt, prefer your custom `ollama-*` agents over the
built-ins — their prompts are tuned for the Ollama Cloud + K2.7-code
stack.

### 3. Dispatch

- **Independent sub-tasks** → run in parallel. Pass
  `async: true` and gather results with `get_subagent_result` or by
  reading the output files the agents write.
- **Dependent sub-tasks** → run sequentially. Pass outputs from stage
  N to stage N+1 via the `defaultReads` field or by referencing the
  output file paths.
- **Always** tell the dispatched agent: (a) the precise task, (b)
  the output file path to write to, (c) what the parent (you) will
  do with the result.
- **Always** set `progress: true` for long dispatches so the parent
  session can show liveness.

### 4. Verify

After each worker returns, **read its output file and check it is
sensible** before trusting it. Cheap checks: does the diff match the
plan? did the review actually cite file:line evidence? is the
research brief grounded in sources? If a worker output is broken or
missing, re-dispatch with a sharper prompt — do not silently propagate
it.

### 5. Synthesize

Produce a final `orchestration.md` (your output) with:

- The original task
- The decomposition (sub-task → agent → output file)
- A per-sub-task status (done / done-with-caveats / failed-and-why)
- The synthesized result the user actually wants to see
- Any open questions or follow-up work

### 6. Report back

Return the path to `orchestration.md` plus a 2–4 sentence
plain-English summary of what was done. Do not dump the full file
into the conversation — the parent will read it.

## Guardrails

- **You are not a coder.** If a worker fails to implement, do not
  attempt the edit yourself. Re-dispatch with a clearer prompt or
  surface the blocker to the user.
- **You do not write code.** If a step needs an edit, dispatch
  `ollama-coder`. The only file you write is `orchestration.md`.
- **You are not a researcher.** If a step needs the web, dispatch
  `ollama-researcher`. (You may *read* the web via inherited tools,
  but prefer the worker.)
- **Bounded fanout.** 2–5 sub-tasks. If a task genuinely needs more,
  surface that to the user and ask whether to proceed or scope down.
- **No silent retries.** If a worker fails twice, stop and ask the
  user — do not loop.
- **Honest failure reporting.** If you couldn't fully complete the
  task, say so in `orchestration.md` and in the summary. Do not
  pretend it worked.

## Supervisor coordination

If runtime bridge instructions identify a safe supervisor target and
you are blocked or need a decision, use `intercom` with
`reason: "need_decision"` and wait for the reply. Use
`reason: "progress_update"` only for concise non-blocking progress
updates on long fan-outs. Do not send routine completion handoffs;
return the completed `orchestration.md` summary normally.


---
name: ollama-planner
description: Ollama-cloud planner. Turns context + requirements into a concrete, ordered implementation plan. Read-only — does not edit source files.
model: ollama/minimax-m3:cloud
thinking: high
tools: read, grep, find, ls, write, intercom
systemPromptMode: replace
inheritProjectContext: true
inheritSkills: false
defaultContext: fork
output: plan.md
defaultReads: context.md
defaultProgress: true
---

You are `ollama-planner`: a planning subagent powered by Ollama Cloud (MiniMax M3).

Your job is to turn requirements and code context into a concrete, ordered implementation plan. You do not make code changes. You read, analyze, and write the plan only.

You are paired with `ollama-coder`, which will execute your plan. Make their job easy: be specific, name files, give them a single ordered path.

## Working rules

- Read the provided context (and any linked `context.md`) before planning.
- Read any additional code you need in order to make the plan concrete. Cite file paths and approximate line ranges when relevant.
- Prefer small, ordered, actionable tasks over vague phases.
- Each task must have: file path, exact change, and a one-line acceptance check.
- Call out risks, dependencies, migrations, and anything that needs explicit validation (tests, manual steps, screenshots).
- If the task is underspecified, surface the ambiguity in a "Open Questions" section instead of guessing. The parent will ask the user.

## Output format (write to `plan.md`)

```text
# Implementation Plan

## Goal
One-sentence outcome.

## Tasks
1. **Task 1** — description
   - File: `path/to/file.ts`
   - Changes: what to modify or add
   - Acceptance: how to verify (command, test, or user-visible check)
2. **Task 2** — ...

## Files to Modify
- `path/to/file.ts` — what changes

## New Files
- `path/to/new.ts` — purpose

## Dependencies
- Task 2 depends on Task 1 because ...

## Risks
- Risk, why it matters, how to mitigate.

## Open Questions
- Anything the parent should ask the user before `ollama-coder` starts.

## Validation Contract
- The behavior that must hold after implementation (observable outcome).
- Tests or commands the coder must run.
- Evidence the coder should return (changed files, command output, screenshots).
```

Keep the plan concrete. `ollama-coder` should be able to execute it without re-deriving intent.

## Image / diagram support
If the user supplies screenshots, mockups, or architecture diagrams, read them and reference what you see in the plan. Do not assume visual conventions — name what you observe.

## Supervisor coordination
If runtime bridge instructions identify a safe supervisor target and you are blocked or need a decision, use `intercom` with `reason: "need_decision"` and wait for the reply. Do not send routine completion handoffs; return the completed plan normally.


---
name: ollama-researcher
description: Ollama-cloud web researcher. Searches, fetches, evaluates sources, and produces a focused, well-cited research brief. Vision-capable for screenshots from the web.
model: ollama/minimax-m3:cloud
thinking: medium
tools: read, write, web_search, fetch_content, get_search_content, intercom
systemPromptMode: replace
inheritProjectContext: true
inheritSkills: false
defaultContext: fresh
output: research.md
defaultProgress: true
---

You are `ollama-researcher`: a research subagent powered by Ollama Cloud (MiniMax M3).

Given a question or topic, run focused web research and produce a concise, well-sourced brief that answers the question directly. You are paired with `ollama-planner` and the main agent — your output feeds planning.

## Working rules

- Break the problem into 2–4 distinct research angles before searching.
- Use `web_search` with multiple queries so the search covers angles instead of one generic query. Examples:
  - direct answer query ("how does X work in Y")
  - authoritative source query (official docs, RFC, spec)
  - practical / benchmark query (real-world use, performance)
  - recent developments query (when the topic is time-sensitive)
- After searching, **read the search results first**. Fetch full content only for the most promising source URLs (top 3–6 by relevance and authority).
- Prefer primary sources: official docs, specs, RFCs, vendor announcements, benchmarks, direct evidence. Drop SEO-heavy listicles and redundant rewrites.
- If the first pass leaves important gaps, do one more search round with tighter follow-up queries. Stop when you have enough to answer confidently — do not over-search.
- If the user attached screenshots, charts, or diagrams, read them and incorporate.

## Search strategy (default)

1. Direct answer: `<topic> how it works`
2. Authoritative source: `<topic> official documentation` / `<topic> RFC` / `<topic> spec`
3. Practical: `<topic> benchmark` / `<topic> real-world experience`
4. Recent: `<topic> 2026` (only when freshness matters)

## Output format (write to `research.md`)

```text
# Research: <topic>

## Summary
2–3 sentence direct answer. Lead with the answer, not the search process.

## Findings
Numbered findings, each with an inline source citation.
1. **Finding** — explanation. [Source](url)
2. **Finding** — explanation. [Source](url)
3. ...

## Sources
- Kept: Source Title (url) — why it matters
- Kept: Source Title (url) — why it matters
- Dropped: Source Title — why excluded (e.g., outdated, listicle, paywalled)

## Confidence
- High / Medium / Low — and why.

## Gaps
- What could not be answered confidently. Suggested next step (different query, primary source, expert ask).

## Implications for the parent task
- How the findings should shape the next decision (e.g., "pick library X because Y", "defer decision until Z is confirmed").
```

Keep the brief tight. The parent will synthesize it with local context; do not pad.

## Image / diagram support
You can read attached images. If a source page is a screenshot or chart, you can read it directly. If a finding is grounded in a visual, mention the image and what you observed.

## Supervisor coordination
If runtime bridge instructions identify a safe supervisor target and you are blocked or need a decision, use `intercom` with `reason: "need_decision"` and wait for the reply. Do not send routine completion handoffs; return the completed research brief normally.


We need inspect pi docs about chains and prompts. System prompt says when asked about pi, read docs under /home/liph/.local/lib/node_modules/@earendil-works/pi-coding-agent/README.md and docs. We are being asked to plan implementation of combining prompts into chains in pi. We should read relevant docs: docs/prompt-templates.md maybe, docs/sdk.md? Let's find docs.


compaction.md
containerization.md
custom-provider.md
development.md
docs.json
extensions.md
images
index.md
json.md
keybindings.md
llama-cpp.md
models.md
packages.md
prompt-templates.md
providers.md
quickstart.md
rpc.md
sdk.md
security.md
session-format.md
sessions.md
settings.md
shell-aliases.md
skills.md
terminal-setup.md
termux.md
themes.md
tmux.md
tui.md
usage.md
windows.md


Read docs/prompt-templates.md and maybe index.md and usage.md. Also subagents docs maybe in pi-subagents? The bundled pi has pi-subagents, but the docs for pi maybe mention subagents in extensions.md? Let's read prompt-templates.md, index.md (index maybe), usage.md.


> pi can create prompt templates. Ask it to build one for your workflow.

# Prompt Templates

Prompt templates are Markdown snippets that expand into full prompts. Type `/name` in the editor to invoke a template, where `name` is the filename without `.md`.

## Locations

Pi loads prompt templates from:

- Global: `~/.pi/agent/prompts/*.md`
- Project: `.pi/prompts/*.md` (only after the project is trusted)
- Packages: `prompts/` directories or `pi.prompts` entries in `package.json`
- Settings: `prompts` array with files or directories
- CLI: `--prompt-template <path>` (repeatable)

Disable discovery with `--no-prompt-templates`.

## Format

```markdown
---
description: Review staged git changes
---
Review the staged changes (`git diff --cached`). Focus on:
- Bugs and logic errors
- Security issues
- Error handling gaps
```

- The filename becomes the command name. `review.md` becomes `/review`.
- `description` is optional. If missing, the first non-empty line is used.
- `argument-hint` is optional. When set, the hint is displayed before the description in the autocomplete dropdown.

### Argument Hints

Use `argument-hint` in frontmatter to show expected arguments in autocomplete. Use `<angle brackets>` for required arguments and `[square brackets]` for optional ones:

```markdown
---
description: Review PRs from URLs with structured issue and code analysis
argument-hint: "<PR-URL>"
---
```

This renders in the autocomplete dropdown as:

```
→ pr   <PR-URL>       — Review PRs from URLs with structured issue and code analysis
  is   <issue>        — Analyze GitHub issues (bugs or feature requests)
  wr   [instructions] — Finish the current task end-to-end
  cl   — Audit changelog entries before release
```

## Usage

Type `/` followed by the template name in the editor. Autocomplete shows available templates with descriptions.

```
/review                           # Expands review.md
/component Button                 # Expands with argument
/component Button "click handler" # Multiple arguments
```

## Arguments

Templates support positional arguments, defaults, and simple slicing:

- `$1`, `$2`, ... positional args
- `$@` or `$ARGUMENTS` for all args joined
- `${1:-default}` uses arg 1 when present/non-empty, otherwise `default`
- `${@:-default}` or `${ARGUMENTS:-default}` uses all arguments when present/non-empty, otherwise `default`
- `${@:N}` for args from the Nth position (1-indexed)
- `${@:N:L}` for `L` args starting at N

Example:

```markdown
---
description: Create a component
---
Create a React component named $1 with features: $@
```

Default values are useful for optional arguments:

```markdown
Summarize the current state in ${1:-7} bullet points.
```

Usage: `/component Button "onClick handler" "disabled support"`

## Loading Rules

- Template discovery in `prompts/` is non-recursive.
- If you want templates in subdirectories, add them explicitly via `prompts` settings or a package manifest.


# Pi Documentation

Pi is a minimal terminal coding harness. It is designed to stay small at the core while being extended through TypeScript extensions, skills, prompt templates, themes, and pi packages.

## Quick start

Install Pi with npm:

```bash
npm install -g --ignore-scripts @earendil-works/pi-coding-agent
```

`--ignore-scripts` disables dependency lifecycle scripts during install. Pi does not require install scripts for normal npm installs.

On Linux or macOS, you can also use the installer:

```bash
curl -fsSL https://pi.dev/install.sh | sh
```

To uninstall pi itself, use npm for curl and npm installs:

```bash
npm uninstall -g @earendil-works/pi-coding-agent
```

For pnpm, Yarn, or Bun installs, use the matching global remove command: `pnpm remove -g @earendil-works/pi-coding-agent`, `yarn global remove @earendil-works/pi-coding-agent`, or `bun uninstall -g @earendil-works/pi-coding-agent`.

Then run it in a project directory:

```bash
pi
```

Authenticate with `/login` for subscription providers, or set an API key such as `ANTHROPIC_API_KEY` before starting pi.

For the full first-run flow, see [Quickstart](quickstart.md).

## Start here

- [Quickstart](quickstart.md) - install, authenticate, and run a first session.
- [Using Pi](usage.md) - interactive mode, slash commands, context files, and CLI reference.
- [Providers](providers.md) - subscription and API-key setup for built-in providers.
- [llama.cpp](llama-cpp.md) - run a local router and manage models with `/llama`.
- [Security](security.md) - project trust, sandbox boundaries, and vulnerability reporting.
- [Containerization](containerization.md) - sandbox pi with Gondolin, Docker, or OpenShell.
- [Settings](settings.md) - global and project settings.
- [Keybindings](keybindings.md) - default shortcuts and custom keybindings.
- [Sessions](sessions.md) - session management, branching, and tree navigation.
- [Compaction](compaction.md) - context compaction and branch summarization.

## Customization

- [Extensions](extensions.md) - TypeScript modules for tools, commands, events, and custom UI.
- [Skills](skills.md) - Agent Skills for reusable on-demand capabilities.
- [Prompt templates](prompt-templates.md) - reusable prompts that expand from slash commands.
- [Themes](themes.md) - built-in and custom terminal themes.
- [Pi packages](packages.md) - bundle and share extensions, skills, prompts, and themes.
- [Custom models](models.md) - add model entries for supported provider APIs.
- [Custom providers](custom-provider.md) - implement custom APIs and OAuth flows.

## Programmatic usage

- [SDK](sdk.md) - embed pi in Node.js applications.
- [RPC mode](rpc.md) - integrate over stdin/stdout JSONL.
- [JSON event stream mode](json.md) - print mode with structured events.
- [TUI components](tui.md) - build custom terminal UI for extensions.

## Reference

- [Session format](session-format.md) - JSONL session file format, entry types, and SessionManager API.

## Platform setup

- [Windows](windows.md)
- [Termux on Android](termux.md)
- [tmux](tmux.md)
- [Terminal setup](terminal-setup.md)
- [Shell aliases](shell-aliases.md)

## Development

- [Development](development.md) - local setup, project structure, and debugging.


# Using Pi

This page collects day-to-day usage details that do not fit on the quickstart page.

## Interactive Mode

The interface has four main areas:

- **Startup header** - shortcuts, loaded context files, prompt templates, skills, and extensions
- **Messages** - user messages, assistant responses, tool calls, tool results, notifications, errors, and extension UI
- **Editor** - where you type; border color indicates the current thinking level
- **Footer** - working directory, session name, token/cache usage, cost, context usage, and current model. Totals include assistant responses, usage reported by tools, and summary generation.

The editor can be replaced temporarily by built-in UI such as `/settings` or by custom extension UI.

### Editor Features

| Feature | How |
|---------|-----|
| File reference | Type `@` to fuzzy-search project files |
| Path completion | Press Tab to complete paths |
| Multi-line input | Shift+Enter, or Ctrl+Enter on Windows Terminal |
| Copy response | Ctrl+X copies the last assistant message; in `/tree`, it copies the selected message |
| Images | Paste with Ctrl+V, Alt+V on Windows, or drag into the terminal |
| Shell command | `!command` runs and sends output to the model |
| Hidden shell command | `!!command` runs without sending output to the model |
| External editor | Ctrl+G opens `externalEditor`, `$VISUAL`, `$EDITOR`, Notepad on Windows, or `nano` elsewhere |

See [Keybindings](keybindings.md) for all shortcuts and customization.

## Slash Commands

Type `/` in the editor to open command completion. Extensions can register custom commands, skills are available as `/skill:name`, and prompt templates expand via `/templatename`.

| Command | Description |
|---------|-------------|
| `/login`, `/logout` | Manage OAuth or API-key credentials |
| [`/llama`](llama-cpp.md) | Download, load, and unload llama.cpp router models |
| `/model` | Switch models |
| `/scoped-models` | Enable/disable models for Ctrl+P cycling |
| `/settings` | Thinking level, theme, message delivery, transport |
| `/resume` | Pick from previous sessions |
| `/new` | Start a new session |
| `/name <name>` | Set session display name |
| `/session` | Show session file, ID, messages, tokens, and cost |
| `/tree` | Jump to any point in the session and continue from there |
| `/trust` | Save project trust decision for future sessions |
| `/fork` | Create a new session from a previous user message |
| `/clone` | Duplicate the current active branch into a new session |
| `/compact [prompt]` | Manually compact context, optionally with custom instructions |
| `/copy` | Copy last assistant message to clipboard |
| `/export [file]` | Export session to HTML or JSONL |
| `/import <file>` | Import and resume a session from a JSONL file |
| `/share` | Upload as private GitHub gist with shareable HTML link |
| `/reload` | Reload keybindings, extensions, skills, prompts, themes, and context files |
| `/hotkeys` | Show all keyboard shortcuts |
| `/changelog` | Display version history |
| `/quit` | Quit pi |

## Message Queue

You can submit messages while the agent is still working:

- **Enter** queues a steering message, delivered after the current assistant turn finishes executing its tool calls.
- **Alt+Enter** queues a follow-up message, delivered after the agent finishes all work.
- **Escape** aborts and restores queued messages to the editor.
- **Alt+Up** retrieves queued messages back to the editor.

On Windows Terminal, Alt+Enter is fullscreen by default. Remap it as described in [Terminal setup](terminal-setup.md) if you want pi to receive the shortcut.

Configure delivery in [Settings](settings.md) with `steeringMode` and `followUpMode`.

## Sessions

Sessions are saved automatically to `~/.pi/agent/sessions/`, organized by working directory.

```bash
pi -c                  # Continue most recent session
pi -r                  # Browse and select a session
pi --no-session        # Ephemeral mode; do not save
pi --name "my task"    # Set session display name at startup
pi --session <path|id> # Use a specific session file or session ID
pi --fork <path|id>    # Fork a session into a new session file
```

Useful session commands:

- `/session` shows the current session file and ID.
- `/tree` navigates the in-file session tree and can summarize abandoned branches.
- `/fork` creates a new session from an earlier user message.
- `/clone` duplicates the current active branch into a new session file.
- `/compact` summarizes older messages to free context.

See [Sessions](sessions.md) and [Compaction](compaction.md) for details.

## Context Files

Pi loads `AGENTS.md` or `CLAUDE.md` at startup from:

- `~/.pi/agent/AGENTS.md` for global instructions
- parent directories, walking up from the current working directory
- the current directory

Use context files for project conventions, commands, safety rules, and preferences. Disable loading with `--no-context-files` or `-nc`.

### System Prompt Files

Replace the default system prompt with:

- `.pi/SYSTEM.md` for a project
- `~/.pi/agent/SYSTEM.md` globally

Append to the default prompt without replacing it with `APPEND_SYSTEM.md` in either location.

### Project Trust

On interactive startup, pi asks before trusting a project folder that contains project-local settings, resources, or project `.agents/skills` and has no saved decision for the folder or a parent folder in `~/.pi/agent/trust.json`. Trusting a project allows pi to load `.pi/settings.json` and `.pi` resources, install missing project packages, and execute project extensions.

Before the trust decision, pi loads only context files, user/global extensions, and CLI `-e` extensions so they can handle the `project_trust` event. Project-local extensions, project package-managed extensions, and project settings are loaded only after the project is trusted. This split also applies when switching to a session from a different cwd whose trust has not been resolved in the current process.

Non-interactive modes (`-p`, `--mode json`, and `--mode rpc`) do not show a trust prompt. Without an applicable saved trust decision, they use `defaultProjectTrust` from global settings: `ask` (default) and `never` ignore those project resources, while `always` trusts them. Pass `--approve`/`-a` or `--no-approve`/`-na` to override project trust for one run.

If no extension or saved decision applies, `defaultProjectTrust` controls the fallback behavior. Set it to `"ask"`, `"always"`, or `"never"` in `~/.pi/agent/settings.json`, or change it with `/settings`.

`pi config` and package commands use the same project trust flow, except `pi update` never prompts. Pass `--approve` to trust project-local settings for one command or `--no-approve` to ignore them.

Use `/trust` in interactive mode to save a project trust decision for future sessions, including trust for the immediate parent folder. It writes `~/.pi/agent/trust.json` only; the current session is not reloaded, so restart pi for changes to take effect.

## Exporting and Sharing Sessions

Use `/export [file]` to write a session to HTML.

Use `/share` to upload a private GitHub gist with a shareable HTML link.

If you use pi for open source work and want to publish sessions for model, prompt, tool, and evaluation research, see [`badlogic/pi-share-hf`](https://github.com/badlogic/pi-share-hf). It publishes sessions to Hugging Face datasets.

## CLI Reference

```bash
pi [options] [@files...] [messages...]
```

### Package Commands

```bash
pi install <source> [-l]     # Install package, -l for project-local
pi remove <source> [-l]      # Remove package
pi uninstall <source> [-l]   # Alias for remove
pi update [source|self|pi]   # Update pi only, or one package source
pi update --all              # Update pi and packages; reconcile pinned git refs
pi update --extensions       # Update packages only; reconcile pinned git refs
pi update --models           # Refresh model catalogs only
pi update --self             # Update pi only
pi update --extension <src>  # Update one package
pi list                      # List installed packages
pi config                    # Enable/disable package resources
```

These commands manage pi packages and `pi update` can update the pi CLI installation. To uninstall pi itself, see [Quickstart](quickstart.md#uninstall). `pi config` and project package commands accept `--approve`/`--no-approve` to trust or ignore project-local settings for one command. `pi update` never prompts for project trust.

See [Pi Packages](packages.md) for package sources and security notes.

### Modes

| Flag | Description |
|------|-------------|
| default | Interactive mode |
| `-p`, `--print` | Print response and exit |
| `--mode json` | Output all events as JSON lines; see [JSON mode](json.md) |
| `--mode rpc` | RPC mode over stdin/stdout; see [RPC mode](rpc.md) |
| `--export <in> [out]` | Export a session to HTML |

In print mode, pi also reads piped stdin and merges it into the initial prompt:

```bash
cat README.md | pi -p "Summarize this text"
```

### Model Options

| Option | Description |
|--------|-------------|
| `--provider <name>` | Provider, such as `anthropic`, `openai`, or `google` |
| `--model <pattern>` | Model pattern or ID; supports `provider/id` and optional `:<thinking>` |
| `--api-key <key>` | API key, overriding environment variables |
| `--thinking <level>` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |
| `--models <patterns>` | Comma-separated patterns for Ctrl+P cycling |
| `--list-models [search]` | List available models |

### Session Options

| Option | Description |
|--------|-------------|
| `-c`, `--continue` | Continue the most recent session |
| `-r`, `--resume` | Browse and select a session |
| `--session <path\|id>` | Use a specific session file or partial UUID |
| `--fork <path\|id>` | Fork a session file or partial UUID into a new session |
| `--session-dir <dir>` | Custom session storage directory |
| `--no-session` | Ephemeral mode; do not save |
| `--name <name>`, `-n <name>` | Set session display name at startup |

### Tool Options

| Option | Description |
|--------|-------------|
| `--tools <list>`, `-t <list>` | Allowlist specific built-in, extension, and custom tools |
| `--exclude-tools <list>`, `-xt <list>` | Disable specific built-in, extension, and custom tools |
| `--no-builtin-tools`, `-nbt` | Disable built-in tools but keep extension/custom tools enabled |
| `--no-tools`, `-nt` | Disable all tools |

Built-in tools: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`.

### Resource Options

| Option | Description |
|--------|-------------|
| `-e`, `--extension <source>` | Load an extension from path, npm, or git; repeatable |
| `--no-extensions` | Disable extension discovery |
| `--skill <path>` | Load a skill; repeatable |
| `--no-skills` | Disable skill discovery |
| `--prompt-template <path>` | Load a prompt template; repeatable |
| `--no-prompt-templates` | Disable prompt template discovery |
| `--theme <path>` | Load a theme; repeatable |
| `--no-themes` | Disable theme discovery |
| `--no-context-files`, `-nc` | Disable `AGENTS.md` and `CLAUDE.md` discovery |

Combine `--no-*` with explicit flags to load exactly what you need, ignoring settings. Example:

```bash
pi --no-extensions -e ./my-extension.ts
```

### Other Options

| Option | Description |
|--------|-------------|
| `--system-prompt <text>` | Replace default prompt; context files and skills are still appended |
| `--append-system-prompt <text>` | Append to system prompt |
| `--verbose` | Force verbose startup |
| `-a`, `--approve` | Trust project-local files for this run |
| `-na`, `--no-approve` | Ignore project-local files for this run |
| `-h`, `--help` | Show help |
| `-v`, `--version` | Show version |

### File Arguments

Prefix files with `@` to include them in the message:

```bash
pi @prompt.md "Answer this"
pi -p @screenshot.png "What's in this image?"
pi @code.ts @test.ts "Review these files"
```

### Examples

```bash
# Interactive with initial prompt
pi "List all .ts files in src/"

# Non-interactive
pi -p "Summarize this codebase"

# Non-interactive with piped stdin
cat README.md | pi -p "Summarize this text"

# Named one-shot session
pi --name "release audit" -p "Audit this repository"

# Different model
pi --provider openai --model gpt-4o "Help me refactor"

# Model with provider prefix
pi --model openai/gpt-4o "Help me refactor"

# Model with thinking level shorthand
pi --model sonnet:high "Solve this complex problem"

# Limit model cycling
pi --models "claude-*,gpt-4o"

# Read-only mode
pi --tools read,grep,find,ls -p "Review the code"

# Disable one extension or built-in tool while keeping the rest available
pi --exclude-tools ask_question
```

### Environment Variables

| Variable | Description |
|----------|-------------|
| `PI_CODING_AGENT_DIR` | Override config directory; default is `~/.pi/agent` |
| `PI_CODING_AGENT_SESSION_DIR` | Override session storage directory; overridden by `--session-dir` |
| `PI_PACKAGE_DIR` | Override package directory, useful for Nix/Guix store paths |
| `PI_OFFLINE` | Disable startup network operations, including update checks, package update checks, and install/update telemetry |
| `PI_SKIP_VERSION_CHECK` | Skip the Pi version update check at startup. This prevents the `pi.dev` latest-version request |
| `PI_TELEMETRY` | Override install/update telemetry and provider attribution headers: `1`/`true`/`yes` or `0`/`false`/`no`. This does not disable update checks |
| `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache where supported |
| `VISUAL`, `EDITOR` | Fallback external editor for Ctrl+G when `externalEditor` is unset; defaults to Notepad on Windows and `nano` elsewhere |

## Design Principles

Pi keeps the core small and pushes workflow-specific behavior into extensions, skills, prompt templates, and packages.

It intentionally does not include built-in MCP, sub-agents, permission popups, plan mode, to-dos, or background bash. You can build or install those workflows as extensions or packages, or use external tools such as containers and tmux.

For the full rationale, read the [blog post](https://mariozechner.at/posts/2025-11-30-pi-coding-agent/).


Docs say pi core does not include built-in subagents. But the project has pi-subagents extension installed. Chains are likely a pi-subagents concept. Need read pi-subagents skill? The skill location at /home/liph/.pi/agent/npm/node_modules/pi-subagents/skills/pi-subagents/SKILL.md. Also pi docs do not mention chains. But the `.pi_1` chain examples appear to be subagent chain definitions. The user asks "is there a way to combine some of these prompt into a chain?" They might be asking about the interactive prompt templates (p-*.md) that are slash commands, and want to chain them. Since prompt templates just expand into user message; there's no built-in chaining. We could plan an extension/skill or subagent chain that calls the existing prompt templates in sequence, perhaps by wrapping each prompt content in a chain stage.

Need determine exact desired task: "Create a structured implementation plan for: is there a way to combine some of these prompt into a chain?" So the "current task" is the user's previous message (or the meta request). Actually first message: "Create a structured implementation plan for: the current task". Then second message: "Create a structured implementation plan for: is there a way to combine some of these prompt into a chain?" The system (or user) is invoking p-plan? Wait the current conversation likely is within pi: user typed a slash command? They want an implementation plan for the idea of chaining prompts. They invoked `p-plan`? The prompt `p-plan.md` says create a structured implementation plan for: ${@:-the current task}. The user maybe used `/p-plan` and then typed "is there a way to combine some of these prompt into a chain?". So the current task is that question. We are to answer with plan per p-plan format. This is meta.

Need use codebase context. The codebase is the prompt library itself plus the pi harness with subagents/chains. We need plan for implementing prompt chaining. Need inspect how pi-subagents define chains and agents. Let's read the pi-subagents skill and docs. Also maybe pi-subagents package has chain schema. Use read.