# Selesai conventions for pstack

This document maps the upstream pstack conventions onto Selesai. The runnable skills and playbooks already carry these conventions; this file explains the mapping and holds the shared delegation examples. It is not a substitute for reading the file a task routes to.

## Conventions

- Invoke installed skills as `$name`. Within Poteto, use its inline skill descriptions and the playbook's cues to choose a helper. Read a linked `SKILL.md` only when the current step needs the full procedure. Don't scan or preload the pack. Resolve links relative to the file that contains them. Direct reads work for private helpers and on follow-ups; `skill_show` is for discovery when you don't have a file reference.
- Generate project skills in `.selesai/skills/` for trusted projects. For portable project skills, follow the existing `.agents/skills/` convention if present. Use `~/.agents/skills/` for personal skills.
- Read optional role preferences from `~/.selesai/agent/pstack-models.md` when selecting a worker model. This is a pstack file, not a Selesai settings file or an automatically loaded rule. Missing roles, `auto`, and `inherit-parent` mean no explicit model override. Use only confirmed `provider/id` values with an optional supported `:thinking` suffix.
- Use the structured `question` tool through codemode for actual operator decisions, or ask in plain text. Keep the checklist in the session when no checklist tool is present.
- `$poteto-mode` authorizes delegation for its task, including every playbook and routed skill it runs. Outside it, work inline unless the operator authorized delegation. Delegate through the native `subagent` tool with a configured local agent, isolate concurrent writers in their own git worktrees, and use native completion notifications for async runs. Label missing independent or cross-model verification honestly.
- For prior work, use workspace-scoped `session_search`, or a transcript path supplied by Selesai or the operator. Never scan sessions outside the active workspace. For worktree cleanup, verify active ownership independently; missing activity evidence is unknown, never idle.
- Use the available forge CLI for requested PR work and the project's existing tools to drive the real app. Treat review-bot comments as ordinary review comments, not required integrations. Don't invent external services or perform unrequested publication.

## Delegation contract

- Spawn children through the native `subagent` tool. Parallel fanout goes through one workflow (`runs.all`), dependent steps through `await runs.run(...)`. Ordinary async completion wakes the parent; never poll, sleep, or loop waiting for a child.
- `$poteto-mode`'s delegation grant is task-scoped. It never covers installs, commits, pushes, PR edits, chat replies, merges, deletion, or deployment; those need specific operator authorization in the brief. Plan-only requests stay plan-only.
- Children get a fresh context by default, file pointers instead of inlined context, and the first line `Read <path>/worker.md before anything else.` with `<path>` the absolute poteto-mode folder path. Children do not spawn further children by default.
- Omit the `model` override unless the child's role has a confirmed `provider/id` in `~/.selesai/agent/pstack-models.md`. Validate ids against the model listing. A requested model that is unavailable is reported as degraded coverage, never silently substituted. A panel without the requested model diversity reports the limitation instead of claiming independence.
- A launch or runtime failure blocks that lane. Report the exact failure and the repo state, retry only through the same native path, and never fall back to a separate CLI, a foreground agent, or another execution mode without the operator's explicit approval.
- Long runs do not activate Selesai Goal mode or its completion APIs without the operator's explicit Goal contract. Selesai has no loop or wake mechanism for unattended re-checks; say so instead of simulating one.

### Delegation examples

Run these only under `$poteto-mode`'s task grant or the operator's explicit delegation authorization; otherwise work inline and launch nothing. Replace `<poteto-mode-dir>` with the absolute poteto-mode skill folder path. Every child task's first line is `Read <poteto-mode-dir>/worker.md before anything else.`, followed by the same folder's `SKILL.md` path, then the bounded brief. The native syntax reference is the pi-subagents `tool-reference` and `workflows` guides.

Parallel writers never share a writable checkout. Give each writer child `worktree: true` (one exclusive managed worktree per child) or its own exclusive `cwd`; read-only children may share the parent cwd. The runtime refuses worktree allocation unless the source checkout is clean ("worktree isolation requires a clean git working tree"); commit or stash first only with the operator's authorization, and never bypass the refusal.

One async child (the default; completion wakes the parent, so never poll for it):

```js
return await tools.subagent({
  agent: "poteto-agent",
  task: "Read <poteto-mode-dir>/worker.md before anything else.\nThen read <poteto-mode-dir>/SKILL.md in full.\n<goal, scope, verification, report contract>"
});
```

One foreground child, only when the parent must block for the result:

```js
return await tools.subagent({
  agent: "poteto-agent",
  task: "Read <poteto-mode-dir>/worker.md before anything else.\nThen read <poteto-mode-dir>/SKILL.md in full.\n<bounded assignment>",
  async: false
});
```

Parallel fanout: one workflow, one isolated child per slice or race arm. The script takes the prebuilt child list as data and launches it in one `runs.all`; it defines no functions. Save this block as `fanout.js` in the working directory (or write it in the reply and call `subagent({ workflow: true, args, cwd })` in the same reply):

```js workflow
const results = await runs.all(args.children);
return results;
```

The complete caller applies the consent and plan-only gates first, then builds one child per arm and makes exactly one workflow call. Include `model` only for a confirmed `provider/id`; a missing role line, `auto`, and `inherit-parent` all omit it. A panel with fewer distinct confirmed models than requested reports the reduced diversity and never claims independence it did not obtain.

```js
if (planOnly) return { launched: false, mode: "plan-only" };
if (!delegationAuthorized) return { launched: false, coverage: "single-session" };
const children = [];
for (const arm of arms) {
  const child = { key: arm.key, agent: "poteto-agent", task: arm.task, worktree: true };
  if (arm.model && arm.model !== "auto" && arm.model !== "inherit-parent") child.model = arm.model;
  children.push(child);
}
return await tools.subagent({ workflow: "./fanout.js", args: { children }, cwd: repoDir });
```

Dependent steps: each step waits for the previous result before launching the next.

```js workflow
const scan = await runs.run("scan", { agent: "scout", task: args.scanTask });
const built = await runs.run("implement", {
  agent: "poteto-agent",
  task: args.implTask + "\n\nScan report:\n" + scan.output
});
return built.output;
```

Read each returned receipt's `ok` and `output`. A launch or runtime failure in any of these blocks that lane: report the exact failure and the repo state, and retry only through the same native path.

## Capability matrix

How each upstream capability maps to Selesai. "Unsupported" means the skill that names it says so and degrades visibly; it is never simulated.

| Upstream capability | Treatment in Selesai |
|---|---|
| `Task` tool spawns (`subagent_type`, `run_in_background`, `readonly`, `model`, `resume`, `file_attachments`) | Native `subagent` tool with `agent`, `task`, `async`, `model`, `cwd`, `worktree`, `output`. Read-only reviewers use a read-only agent role. |
| Cursor cloud agents (`environment: "cloud"`, `cloud_base_branch`) | Native children with `worktree` isolation; tell each worker which ref to check out. Cloud is not available and never claimed. |
| Parallel fanout / dependent steps | Workflow scripts: `runs.all([...])` parallel, `await runs.run(...)` sequential. |
| Hardcoded model slugs, `~/.cursor/rules/pstack-models.mdc` always-applied rule | Optional `~/.selesai/agent/pstack-models.md` with confirmed `provider/id` (+`:thinking`) or `inherit-parent`/`auto`. No bundled model ids. `AskQuestion` budget wizard → structured `question` tool. |
| Panel model diversity (arena runners, cross-judge pool, interrogate reviewers) | Per-child `model` from the roles file. Unavailable or single-vendor panels are reported as degraded, never as independent. |
| Cursor `/loop` wake mechanism | Explicitly unsupported. No polling, no sleep loops, no simulated loop. Watch-pr runs directly as a one-shot helper. |
| Custom Modes (persistent mode) | Explicitly unsupported. `$poteto-mode` is per-invocation and task-scoped. |
| Bugbot | Not integrated. Bot comments are ordinary review comments; triage them on their merits per the Babysit playbook. |
| `cursor-team-kit` externals (`/deslop`, `control-ui`, `control-cli`) | Not available. Deslop equivalent: review the diff for accidental complexity. UI/CLI verification: the project's own tools and verification skills. |
| Cursor paths (`~/.cursor/plugins/`, `~/.cursor/projects/<slug>/agent-transcripts/`, `.cursor/skills/`, `~/.cursor/rules/`, `plugins/cache/`) | Skill paths are supplied as absolute paths by the parent. Session evidence comes from workspace-scoped `session_search` or a supplied transcript path; a missing path blocks that step, it never triggers a search through Cursor installations. Generated skills go in `.selesai/skills/` (project) or `~/.agents/skills/` (personal). |
| Install / marketplace (`/add-plugin`, `/plugin marketplace`) | Not applicable. pstack ships with Selesai; skills invoke as `$name`. |
| Cursor Automations, Benny webhooks, `SendToUser`, Grok Bot routine cards | Not ported; unsupported. `make-bot-ui` only scopes a UI for a backend the operator already has. |
| `AskQuestion` tool | Structured `question` tool through codemode, or plain text. |
| PR forge (`gh` default, `origin` optional, never Graphite) | Kept, as explicit CLI usage behind operator authorization. |
| git worktrees | Kept as harness-neutral git usage with ownership checks; `worktree-audit.sh` is the adapted lever (below). |
| `readonly: true` subagents | Read-only native agent (`comment-sicko` for comment review, a read-only role for judges and explorers). |
| Video rendering (`/ketchup-video`) | No fixed renderer. Pick an available local tool; if the render fails, say so in one line and give only the calls. |
| `/visualize` chart command | Not available. Use an available chart tool; never invent a number to chart. |
| Cursor's `create-skill` built-in | Not available. Author and validate `SKILL.md` directly. |
| `/reframe` link verification | Confirm links with this session's web research tools. Cut any citation you could not open and say so; never claim an unrun check. |

## Optional tools and scripts

- `bash "<skill dir>/skills/poteto-mode/scripts/worktree-audit.sh"` — the worktree prune audit. Invoke it through `bash` (not `sh`): seeded copies lose the executable bit, and the script needs bash arrays. It never fetches by default; `-f` performs the ref-writing `origin` fetch and needs operator authorization. Set `PSTACK_TRANSCRIPTS_DIR` to a supplied session-evidence directory for the LAST_CHAT column; without it, or when the supplied source is unreadable, has zero matches for a worktree, or a search/stat fails, the column reads `unknown` and no bucket is `safe`. `safe` requires a transcript that literally names the worktree path with a readable modification time outside the recency window; missing chat evidence never proves idleness. `gh`/`origin`, `jq`, `rg` (falls back to `grep`), and `du` are optional; each missing tool degrades a column with a visible warning instead of failing the audit.
- `bun <poteto-mode directory>/scripts/watch-pr/watch-pr` — the GitHub PR watcher, an optional helper with one-time manual dependency installation. It never installs anything itself: `bootstrap.ts` fails closed with the manual install command and a `gh pr view` fallback. Run it directly for a one-shot or bounded watch; it polls inside the operator-invoked process, not the agent loop.
- `sh "<skill dir>/skills/statechart/scripts/statechart"` — TLA+ model checking. The wrapper is POSIX; `sh` invocation works around the lost executable bit. Its first run may install TLC and Java through mise; ask the operator for authorization before any tool installation or download. The `TLA2TOOLS` and `JAVA` environment variables provide an escape hatch.
- `bash "<skill dir>/skills/show-me-your-work/scripts/log.sh"` — decision-log appender (bash, `date`, `tr`; hardens spreadsheet formula injection).
- No script or skill installs dependencies automatically. Every optional dependency names its manual install and degrades with a visible note when absent.
