# Direct Pi authoring

Read this procedure after the user has clarified a direct Prompt, ordinary-Skill or project-Pi-guidance task. Before drafting or revising these agent instructions, read the complete bundled original [Writing for Agents](writing-for-agents/SKILL.md) by Matt Pocock and apply it as the primary writing method. Read it from this package even when no writing Skill is installed; an abridged installed variant is not its replacement. Resolve this path relative to this guide, not the conversation's cwd. This is authoring guidance, not a Skill catalog, invoker or permission grant.

## 1. Choose the purpose and owner

Select the destination from the confirmed need, not text length or a convenient existing file.

| Confirmed need | Responsible destination |
| --- | --- |
| Global behavior or safety, such as a rule governing all sessions | The actual system-prompt Append original |
| Simple explicit reusable Markdown slashprompt with arguments | A native prompt template at its configured original |
| Richer situational workflow with references, such as reviewing a particular document type | The responsible ordinary Skill |
| Pi-specific behavior or harness context for one project | That project's natively loaded context original, normally `AGENTS.md` |
| Already solved by available guidance or existing means | No new durable artifact |

Inspect the authorized actual source and applicable local guidance before proposing changes. Keep global rules out of project guidance and project-only rules out of the global Append. If the need is executable Pi integration, follow the separate [Extension workflow](extensions.md) instead of hiding an integration in a Skill; its code/project preparation ends at an explicit receiving owner.

**Done when** the purpose, scope and responsible destination are explicit, or the task is complete without a new artifact. Unresolved ownership or access stops the affected work.

## 2. Resolve one active original

- Existing artifact: identify/read the current responsible original and touched references. Preserve it in place; generated views, installed copies, Workbench guides and archives are not editable authorities.
- Global Append: establish actual agentDir, not assumed `~/.pi/agent`; native defaults can be changed by `PI_CODING_AGENT_DIR` or SDK `agentDir`. Inspect only authorized configuration/inputs. A trusted project's `.pi/APPEND_SYSTEM.md` takes precedence over `<agentDir>/APPEND_SYSTEM.md`; same-name files are not automatically combined. Explicit host prompt sources and overrides can replace discovery or transform inputs. Stored global text alone proves no active effect. Unverified inputs → report uncertainty before effect claims; no automatic merge or project-file edits.
- Project instructions: inspect the host's native context loading and existing authorized guidance. Normally use `AGENTS.md`; preserve an existing supported source such as `CLAUDE.md` rather than creating a competing original. Use `.pi/Pi.md` only with verified inclusion in loaded context. Workbench reload does not add inclusion. Missing inclusion: resolve the native destination with the owner before dependent edits; do not migrate or overwrite existing guidance without authorization.

For a new native prompt template or Skill, choose an already configured user, project or native-package resource location and identify its owner. Verify the actual configured source rather than assuming a conventional path is active. Creating files or configuring a location requires the applicable grant. For package placement details, consult the current host's `docs/packages.md`, “Create a package” and “Select package resources”; declared paths are package-root-relative.

**Done when** one concrete original (or new-file destination) and its relevant references are known and inspected within authorized read scope.

## 3. Establish permission and pre-edit backup

Confirm permission for the concrete target and intended change before writing. Knowing a path, approving an idea or reading this guide does not authorize modification, installation, activation, reload, publication or live-session actions.

Before the first write to an existing original:

1. Resolve the original and symlink targets. Automatic backups cover Pi-owned originals in the actual Pi agent directory, including Append, Skills and settings. Git-repository targets and files outside this directory require no Workbench backup. A Skill linked into Pi from a repository remains a repository file; Extension projects and surrounding files are not backup targets.
2. For an in-scope original outside Git, confirm archive and change permission; call `workbench_archive_original` with absolute `sourcePath` and optional inspected absolute `projectRoot`. Require successful `status: "archived"`, matching resolved source, actual `archivePath` and `timestamp` before editing.
3. The helper also checks the boundary if called on an excluded source. Successful `status: "skipped"` with `reason: "git-repository"` or `"outside-pi"` creates no archive and satisfies only the backup exemption. Continue solely under actual edit permission. Never report skipped as archived.

Archived results contain absolute `archivePath` and `sourcePath`, integer Unix-millisecond `timestamp`, and `status: "archived"`. Project results also contain `projectRoot` and `relativePath`; external results omit both. Skipped results contain only `status`, resolved `sourcePath` and `reason`. Results match `details` and `structuredContent` under the output schema. Paths resolve with filesystem `realpath`; an optional root must contain the resolved source. Repository detection checks ancestor `.git` directories or files, including linked-worktree markers, independently of tracking, commits or working-tree cleanliness. This exemption is not a claim that every file is committed or remotely backed up. The helper preserves the original and returns no original content.

Under `<getAgentDir()>/workbench/`, archives use `backups/v1/project/<base64url-absolute-root>/<base64url-relative-segment>/.../<base64url-file-name>/workbench--<epoch-ms>.gz`, or `backups/v1/external/<base64url-absolute-source>/workbench--<epoch-ms>.gz`. Decode each UTF-8 base64url component to recover the source hierarchy/origin; gunzip recovers the unchanged bytes. The filename records the UTC instant. An archive is recovery data, not another active authority.

For a backup-required Pi original, if the helper is absent, blocked, fails or does not identify the required source, **stop before editing** and report the unmet prerequisite. Consultation and a clearly labelled proposal may continue without changing the original. These are instructed gates, not universal technical enforcement over native or external file tools. For retention settings and explicit-start cleanup, follow the shared [backup retention guidance](#backup-retention-and-explicit-starts), including settings-write permission and automatic non-blocking cleanup with a notice, without extra confirmation.

For a genuinely new file, record that no prior original exists; there are no original bytes to archive. Still confirm creation permission and destination.

**Done when** change permission is established and the target has either successful required archival, a confirmed Git/outside-Pi exemption, or no prior original. Proposed or skipped backups are never archival evidence.

## 4. Author the selected native artifact

- Skill creation/revision/review → internal [Skill authoring](skill-authoring.md). It owns complete original writing references, native mechanics and Skill-specific completion criteria.
- System-Prompt/project-context only → skip artifact mechanics below; shared source/permission/backup/edit/check gates remain.
- Simple explicit reusable Markdown slashprompt → native prompt template. Read actual host `docs/prompt-templates.md` before authoring; use `docs/configuration.md` for agentDir/trust and `docs/packages.md` for package selection.

### Native prompt template

1. Confirm task, owner and actual configured personal/project/package original under steps 1–3. Conventional `<agentDir>/prompts/` and trusted project `.pi/prompts/` load direct `.md` children only. Explicit settings/package paths can select nested Markdown files. Package `pi.prompts` paths/globs are package-root-relative; filters only narrow declared resources. Use [native packages](packages.md#package-authoring-and-publication) when package selection matters. Do not change settings, create personal templates or convert/move/activate existing resources without matching authorization.
2. Use Markdown with optional frontmatter `description` and `argument-hint`. Filename supplies command name; absent description falls back to first non-empty line. Hint uses `<required>` / `[optional]`. Native argument syntax: `$1`, `$2`, … positional; `$@`/`$ARGUMENTS` all; `${1:-default}`/`${@:-default}` defaults; `${@:N}`/`${@:N:L}` slices. Arguments use shell-like quoting.
3. Keep prompt instruction-only; executable integration → [Extension handoff](extensions.md). Rich workflows/supporting references → Skill. Eleven shipped Skill examples remain Skills, not native prompt templates.

Illustrative syntax only; no creation, invocation or permission evidence. Selected configured `summarize.md` would expose `/summarize`:

```markdown
---
description: Summarize supplied material
argument-hint: "[focus]"
---
Summarize the supplied material, focusing on ${1:-key decisions}. Additional context: ${@:2}
```

Illustrative `/summarize "open questions" brief` substitutes first argument `open questions`, remaining argument `brief`. Pi expands templates before agent input; extensions see raw input first unless a same-name Extension command handles it. Verify actual discovery/name conflicts and intended expansion only under authorized runtime checks in step 6.

**Done when** selected artifact matches the confirmed purpose, native syntax/source selection is inspected and shared gates remain satisfied.

## 5. Edit the authorized original directly

After the gates above, apply the smallest complete change at the responsible original, preserving unrelated and independently owned material. Re-read the modified region, its incoming pointers and affected supporting references using the bundled writing method. For human prose, use an applicable writing Skill when available; otherwise write directly. No additional Skill installation is required.

Add a short representative example when it clarifies actual syntax or behavior. Use provided session variables directly when they already work; use descriptive `<placeholders>` for task-dependent or returned values, not apparently preexisting variables. Preserve required literal tokens. Mark non-executable schemas as text and distinguish illustrative examples from real grants or observed evidence. Omit examples that add no clarification.

**Done when** the intended change and its pointers agree, unrelated content remains intact and there is still one active source. Backup archives remain recovery data, not live instruction sources.

## 6. Check the claim and report its limits

### System-Prompt review lens

When creating or revising a System-Prompt, check the resulting target agent's instructions, not only the author's edit workflow:

- Keep permanently needed behavior in the prompt; place situational procedures behind pointers with the relevant reading conditions.
- Express the role's concrete domain decision criteria while preserving confirmed user decisions and persona.
- Make the target agent's actually needed tool/authority boundaries, output and completion criteria, and behavior when blocked explicit. Derive these from the real host and existing grants; writing them creates no new authority.

The target prompt is ready only when these checks hold; report concrete unresolved conflicts instead of declaring it complete. This is a supplemental [system-prompt lens](https://github.com/tjennychen/writing-system-prompts), not a replacement for the bundled writing method; Skill and Extension work keep their separate branches.

### Evidence and reporting

Choose evidence for what changed and report the actual target, checks, outcomes and omissions.

| Claim | Evidence needed |
| --- | --- |
| Correct source, frontmatter, diff and reachable references | Static/source inspection |
| Sensible routing, workflow or permission/stop sequence | Semantic review or explicitly labelled text simulations |
| Native prompt-template discovery/expansion or explicit `/skill:name` behavior | Actually executed native diagnostics/command checks |
| Model/session behavior | Genuinely observed runtime behavior, with any provider double disclosed |

After an authorized active prompt-template or Skill edit, native docs call for `/reload` before runtime validation. Append and natively loaded project-context changes likewise need an authorized fresh/reloaded context before claiming runtime effect; verify actual inclusion, especially for a custom source such as `.pi/Pi.md`. Full native reload may install missing/mismatched configured packages and update temporary sources. Reload alone supplies no install/update grant: before invoking, ensure actual authorization covers relevant possible package effects; otherwise stop/clarify without invoking. Explicit commissioned native installs/updates remain allowed. Do not change host settings or clone reload to evade this boundary.

For a needed, authorized Append basis check, use existing native `getSystemPromptOptions()` only where the host exposes it, such as Command context. Inspect relevant base construction inputs, not complete prompt dumps. These inputs do not certify later Extension transformations or model compliance. No new diagnostic tool or automatic Append merge. Obtain actual grants for checks; this authoring task supplies none. Editing a file or reviewing prose proves no discovery, reload, invocation, live-model compliance or user-visible E2E. State omitted checks and concrete reasons. No reload, original edit or backup execution is performed merely by delivering this guide.

**Done when** every reported result has its real evidence class and untested boundaries are explicit.

## Reviewed basis and targeted lookup

The archive connection was reviewed against Pi Coding Agent **1.3.0** and managed **1.2.0** complete `docs/extensions.md`, `docs/sdk.md`, `docs/configuration.md`, `docs/environment-variables.md`, `docs/custom-provider.md`, `docs/message-types.md`, `docs/packages.md` and `docs/skills.md`, plus public tool/output-schema and `withFileMutationQueue` declarations. Native Pi owns tool validation, restrictions, failed results, continuation and cooperative cancellation; Workbench uses its mutation queue and passes the operation signal to the actual stream pipeline.

- Pi Coding Agent **1.5.0**, complete installed public `docs/prompt-templates.md`, `docs/skills.md`, `docs/configuration.md`, `docs/packages.md`; targeted public resource-loader/package-manager and Command-context declarations for reload effects, Append discovery/overrides and `getSystemPromptOptions()`. Reviewed source version, not latest-release/runtime guarantee.
- Pi Coding Agent **1.2.0**, installed `docs/skills.md`: “Create a skill”, “Understand how skills load”, “Add it to Pi”, “Write portable frontmatter”, “Validate and share a skill”.
- Pi Coding Agent **1.2.0**, installed `docs/packages.md`: “Create a package” and “Select package resources”, for ordinary placement and package-resource reachability only.
- The same documents were also inspected on the project host, Pi Coding Agent **1.3.0**; their bytes match the reviewed 1.2.0 documents.
- Matt Pocock's complete original `writing-for-agents/SKILL.md` and `SKILL-MECHANICS.md`, bundled here as the primary Prompt/Skill writing method. [Source and license](writing-for-agents/SOURCE.md) identify the upstream downloads; Pi-specific mechanics remain governed by the host's native documentation.

These label the reviewed sources, not dependency pins or portable runtime paths. Native Pi and the original Skills retain their authority. For a concrete gap or version difference, locate the current host's installed `@earendil-works/pi-coding-agent` documentation and the current responsible Skill source, then read the relevant section. Resolve material contradictions before acting. Reuse this sequence without routinely re-researching or copying complete manuals.

## Backup retention and explicit starts

Both explicit entries, `/workbench` and the collaboration tool `workbench`, automatically start cleanup of expired own archives under `<getAgentDir()>/workbench/` as non-blocking background work. No additional confirmation or separate cleanup tool is needed. Guidance delivery and the ordinary PiQuickDoku version check do not wait for cleanup. A native UI notification reports the effective retention days and actual number of removed archives, including zero. Overlapping starts share any cleanup already running; after it finishes, a later start reads settings again. Session shutdown cooperatively aborts and awaits its own cleanup without a late notification in another session. Notifications use Pi's native UI, not an additional model turn; UI-less hosts have no visible notification.

For an authorized retention-setting change, call `workbench_set_backup_retention` with, for example, `{"days":7}`. Confirm permission to write `<getAgentDir()>/workbench/settings.json`; changing settings is separate from automatic background cleanup. `days` is a required nonnegative integer **number**; zero is valid, while missing arguments, strings, null, fractions, booleans, arrays and objects fail. The native input schema requires the field and rejects extra fields; its value is transported as unknown and strictly checked by the setter before settings access, without coercion. It deliberately does not advertise machine-readable integer input. Missing stored `backupRetentionDays` means **30 days**, not a missing-call default. A missing settings file need not be created to express that default. Pi's own settings are untouched.

Require a successful native result with absolute `settingsPath` and integer `backupRetentionDays`, matching `details` and `structuredContent`. A setting change writes the effective value while preserving other settings properties; it deletes no archives. Later explicit starts, including a new process, read it. Failed validation or persistence is a native tool error, not saved configuration. Malformed JSON, an invalid present setting or cleanup failure produces a native error notification without preventing guidance/index startup. No guessed setting is used. Cleanup is not transactional: earlier deletions are not rolled back. A background error is not a failed collaboration-tool result.

Cleanup uses the complete v1 project/external archive grammar described in [pre-edit backup](pi-authoring.md#3-establish-permission-and-pre-edit-backup), including reversible canonical origin/segments and a valid timestamp filename. Only regular matching files strictly older than `now − days × 86,400,000 ms` expire; equality and future timestamps remain. Zero expires earlier archives, not same-instant ones. Filename time, not mtime, determines age. Links are not followed, unknown files/versions are preserved, and only encoded directories made empty by eligible deletions may be removed nonrecursively. Format matching is not cryptographic proof of authorship or protection against arbitrary concurrent filesystem replacement.

Loading, unrelated conversation, archive calls and setting calls do not start retention. Cleanup does not replace required pre-edit archival of Pi originals outside Git. Its automatic scope covers only expired own archives, not arbitrary deletion.
