pi-pstack-workflow-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/agents/ci-watcher.md +1 -0
  4. package/agents/comment-sicko.md +1 -0
  5. package/agents/poteto-agent.md +1 -0
  6. package/agents/quality-agent.md +1 -0
  7. package/agents/worker.md +3 -0
  8. package/extensions/catalog-ui.ts +86 -0
  9. package/extensions/delegate.ts +357 -0
  10. package/extensions/forge.ts +245 -0
  11. package/extensions/git.ts +23 -0
  12. package/extensions/index.ts +25 -0
  13. package/extensions/models.ts +115 -0
  14. package/extensions/parent-diff.ts +63 -0
  15. package/extensions/plan.ts +181 -0
  16. package/extensions/records.ts +81 -0
  17. package/extensions/session.ts +124 -0
  18. package/extensions/support.ts +46 -0
  19. package/extensions/worktrees.ts +188 -0
  20. package/lib/catalog-data.json +560 -0
  21. package/lib/catalog.ts +111 -0
  22. package/lib/jobs.ts +5 -0
  23. package/lib/models.ts +124 -0
  24. package/lib/pool.ts +29 -0
  25. package/lib/state.ts +127 -0
  26. package/lib/transcript.ts +44 -0
  27. package/lib/validation.ts +16 -0
  28. package/package.json +68 -4
  29. package/reference/GAPS.md +21 -0
  30. package/reference/PARITY.md +169 -0
  31. package/reference/benny/config.example.json +12 -0
  32. package/reference/benny/repro.md +3 -0
  33. package/reference/benny/setup.md +3 -0
  34. package/reference/benny/triage.md +3 -0
  35. package/reference/parity.json +3095 -0
  36. package/reference/rules/no-inline-imports.md +3 -0
  37. package/reference/rules/typescript-exhaustive-switch.md +3 -0
  38. package/reference/source-map.json +8594 -0
  39. package/scripts/job-input.ts +191 -0
  40. package/scripts/run-job.mjs +119 -0
  41. package/skills/architect/SKILL.md +16 -0
  42. package/skills/arena/SKILL.md +16 -0
  43. package/skills/automate-me/SKILL.md +10 -0
  44. package/skills/benchmark-checklist/SKILL.md +10 -0
  45. package/skills/blast-radius/SKILL.md +10 -0
  46. package/skills/bro/SKILL.md +10 -0
  47. package/skills/check-compiler-errors/SKILL.md +10 -0
  48. package/skills/control-cli/SKILL.md +10 -0
  49. package/skills/control-ui/SKILL.md +10 -0
  50. package/skills/correct/SKILL.md +10 -0
  51. package/skills/create-formal-verification-skill/SKILL.md +16 -0
  52. package/skills/create-verification-skill/SKILL.md +16 -0
  53. package/skills/deslop/SKILL.md +10 -0
  54. package/skills/figure-it-out/SKILL.md +17 -0
  55. package/skills/fix-ci/SKILL.md +10 -0
  56. package/skills/fix-merge-conflicts/SKILL.md +10 -0
  57. package/skills/get-pr-comments/SKILL.md +10 -0
  58. package/skills/how/SKILL.md +10 -0
  59. package/skills/in-your-own-words/SKILL.md +11 -0
  60. package/skills/interrogate/SKILL.md +17 -0
  61. package/skills/ketchup/SKILL.md +10 -0
  62. package/skills/ketchup-video/SKILL.md +10 -0
  63. package/skills/loop-on-ci/SKILL.md +10 -0
  64. package/skills/maintain-formal-verification-skill/SKILL.md +16 -0
  65. package/skills/maintain-verification-skill/SKILL.md +16 -0
  66. package/skills/make-bot-ui/SKILL.md +10 -0
  67. package/skills/make-pr-easy-to-review/SKILL.md +10 -0
  68. package/skills/new-branch-and-pr/SKILL.md +10 -0
  69. package/skills/no-comments/SKILL.md +16 -0
  70. package/skills/poteto-help/SKILL.md +11 -0
  71. package/skills/poteto-mode/SKILL.md +60 -0
  72. package/skills/poteto-mode/playbooks/authoring-a-skill.md +20 -0
  73. package/skills/poteto-mode/playbooks/autonomous-run.md +20 -0
  74. package/skills/poteto-mode/playbooks/autopilot-full.md +25 -0
  75. package/skills/poteto-mode/playbooks/autopilot-stack.md +20 -0
  76. package/skills/poteto-mode/playbooks/babysit.md +21 -0
  77. package/skills/poteto-mode/playbooks/bug-fix.md +26 -0
  78. package/skills/poteto-mode/playbooks/eval.md +20 -0
  79. package/skills/poteto-mode/playbooks/feature.md +26 -0
  80. package/skills/poteto-mode/playbooks/hillclimb.md +24 -0
  81. package/skills/poteto-mode/playbooks/investigation.md +19 -0
  82. package/skills/poteto-mode/playbooks/multi-phase-plan.md +19 -0
  83. package/skills/poteto-mode/playbooks/opening-a-pr.md +20 -0
  84. package/skills/poteto-mode/playbooks/pause-safely.md +18 -0
  85. package/skills/poteto-mode/playbooks/perf-issue.md +24 -0
  86. package/skills/poteto-mode/playbooks/prototype.md +21 -0
  87. package/skills/poteto-mode/playbooks/refactoring.md +23 -0
  88. package/skills/poteto-mode/playbooks/runtime-forensics.md +20 -0
  89. package/skills/poteto-mode/playbooks/session-pickup.md +20 -0
  90. package/skills/poteto-mode/playbooks/shipping.md +24 -0
  91. package/skills/poteto-mode/playbooks/trace-forensics.md +20 -0
  92. package/skills/poteto-mode/playbooks/visual-parity.md +22 -0
  93. package/skills/poteto-mode/playbooks/worktree-cleanup.md +19 -0
  94. package/skills/pr-review-canvas/SKILL.md +10 -0
  95. package/skills/principle-attack-the-premise/SKILL.md +12 -0
  96. package/skills/principle-boundary-discipline/SKILL.md +12 -0
  97. package/skills/principle-build-the-lever/SKILL.md +12 -0
  98. package/skills/principle-encode-lessons-in-structure/SKILL.md +12 -0
  99. package/skills/principle-exhaust-the-design-space/SKILL.md +12 -0
  100. package/skills/principle-experience-first/SKILL.md +12 -0
  101. package/skills/principle-explain-the-number/SKILL.md +12 -0
  102. package/skills/principle-fix-root-causes/SKILL.md +12 -0
  103. package/skills/principle-foundational-thinking/SKILL.md +12 -0
  104. package/skills/principle-guard-the-context-window/SKILL.md +12 -0
  105. package/skills/principle-laziness-protocol/SKILL.md +12 -0
  106. package/skills/principle-make-operations-idempotent/SKILL.md +12 -0
  107. package/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +12 -0
  108. package/skills/principle-minimize-reader-load/SKILL.md +12 -0
  109. package/skills/principle-model-the-domain/SKILL.md +12 -0
  110. package/skills/principle-never-block-on-the-human/SKILL.md +12 -0
  111. package/skills/principle-outcome-oriented-execution/SKILL.md +12 -0
  112. package/skills/principle-prove-it-works/SKILL.md +12 -0
  113. package/skills/principle-redesign-from-first-principles/SKILL.md +12 -0
  114. package/skills/principle-separate-before-serializing-shared-state/SKILL.md +12 -0
  115. package/skills/principle-sequence-verifiable-units/SKILL.md +12 -0
  116. package/skills/principle-subtract-before-you-add/SKILL.md +12 -0
  117. package/skills/principle-test-behavior-not-implementation/SKILL.md +12 -0
  118. package/skills/principle-type-system-discipline/SKILL.md +12 -0
  119. package/skills/recall/SKILL.md +10 -0
  120. package/skills/reflect/SKILL.md +10 -0
  121. package/skills/review-and-ship/SKILL.md +10 -0
  122. package/skills/run-smoke-tests/SKILL.md +10 -0
  123. package/skills/setup-pstack/SKILL.md +17 -0
  124. package/skills/sharpen/SKILL.md +11 -0
  125. package/skills/show-me-your-work/SKILL.md +16 -0
  126. package/skills/statechart/SKILL.md +10 -0
  127. package/skills/swarm/SKILL.md +16 -0
  128. package/skills/tdd/SKILL.md +10 -0
  129. package/skills/teach/SKILL.md +17 -0
  130. package/skills/technical-writing/SKILL.md +10 -0
  131. package/skills/thermo-nuclear-code-quality-review/SKILL.md +10 -0
  132. package/skills/typescript-best-practices/SKILL.md +10 -0
  133. package/skills/unslop/SKILL.md +10 -0
  134. package/skills/verify-this/SKILL.md +17 -0
  135. package/skills/weekly-review/SKILL.md +10 -0
  136. package/skills/what-did-i-get-done/SKILL.md +10 -0
  137. package/skills/why/SKILL.md +10 -0
  138. package/skills/workflow-from-chats/SKILL.md +10 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Josh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # Pi pstack workflow kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An installable Pi package that reimplements the workflows described by the supplied pstack 0.15.46, Team Kit 1.2.0 and Cursor CLI skill map. It uses the current `@earendil-works/pi-coding-agent` extension API, Pi Agent Skills, native Pi child processes, native session entries and native terminal UI. It does not require a Cursor installation, a Cursor account, another coding agent, or an npm runtime dependency beyond the Pi host. It does not ship Cursor's proprietary cloud services.
4
+
5
+ **Status: source-map-complete implementation candidate, not certified behavioral parity.** All 161 node IDs, 163 dependency edges, and 65 views are retained and mapped. The skills and playbooks are independently written from the JSON descriptions, with selected official upstream source cross-checks. They are not a complete copy of the upstream pinned repository's leaf files, scripts, templates, or full playbook contracts. Some nodes are model-mediated skills or require a project's own tools. The managed service gaps and test limits are explicit in `reference/PARITY.md` and `reference/GAPS.md`.
6
+
7
+ ## Install
8
+
9
+ Requires Pi and Node.js 22.19 or newer. Verification below uses Pi 1.6.0, Bun, and Python 3.9 or newer for the generator checks. Pi's own minimum runtime version takes precedence. Git is required for worktree features and the integration tests. GitHub CLI (`gh`) and authentication are required for GitHub operations. Browser, terminal, formal proof, video, Slack and tracker workflows depend on the relevant configured project tools.
10
+
11
+ Install current Pi if needed, following the official [Quickstart](https://docs.pi.dev/latest/quickstart) or [pi.dev](https://pi.dev/):
12
+
13
+ ```sh
14
+ npm install -g --ignore-scripts @earendil-works/pi-coding-agent
15
+ ```
16
+
17
+ Install the npm package in Pi:
18
+
19
+ ```sh
20
+ pi install npm:pi-pstack-workflow-kit
21
+ pi list
22
+ ```
23
+
24
+ Use `pi -e npm:pi-pstack-workflow-kit` to try it for one session. Add `--local` to `pi install` to register it in the current project instead. For a source checkout, run `pi install "$PWD"` from the package directory. Project resources require Pi project trust. Review the extension before granting trust, then use `/reload` or restart Pi.
25
+
26
+ ## Use
27
+
28
+ ```text
29
+ /setup-pstack
30
+ /setup-pstack show
31
+ /poteto-mode on
32
+ /pstack-run bug-fix Reproduce the failing login, fix it, and prove the original flow passes
33
+ /pstack-status
34
+ /pstack-map
35
+ /pstack-map all-dependencies
36
+ /pstack-map cli-cloud
37
+ /pstack-goal All required checks pass on the verified patch
38
+ /pstack-loop 60 10 Check current-head CI and stop when green or blocked
39
+ /pstack-loop stop
40
+ /pstack-pause
41
+ /pstack-clear
42
+ /poteto-mode off
43
+ ```
44
+
45
+ `/poteto-mode <goal>` attaches the workflow to one request. `/poteto-mode on` persists the router for the selected session branch. The receiving session selects and owns the playbook. `/pstack-run <route> <goal>` selects an explicit playbook. The native task tool initializes ordered steps, records evidence and requires each step to be completed or explicitly skipped before finishing. The router chooses `figure-it-out` for broad/unmatched work. Use `/skill:principle-...` to read a specific principle; the principles are conditional rather than a fixed sequence.
46
+
47
+ The package registers 52 original slash-skill names (34 ordinary pstack and 18 Team Kit) and nine model-callable tools. All 76 skills, including 24 principle leaves, use the standard `/skill:<name>` interface. Playbooks remain supporting files, not 22 extra ordinary skills. Use Pi's standard `/model`, `/resume`, `/tree`, `/compact`, `/mcp`, `/reload`, `pi install`, and headless JSON/RPC interfaces for host capabilities.
48
+
49
+ | Tool | Behavior |
50
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------- |
51
+ | `pstack_catalog` | Search, inspect nodes, read instructions, list route triggers and browse dependency views. |
52
+ | `pstack_plan` | Start, update, inspect or finish a branch-local task list with evidence. |
53
+ | `pstack_delegate` | Single, swarm, arena or interrogate workers using independent native Pi CLI processes. |
54
+ | `pstack_log` | Append a timestamped decision record to a TSV. |
55
+ | `pstack_history` | Read bounded entries on the active native session branch. |
56
+ | `pstack_wake` | Inspect or stop a bounded operator-started loop. |
57
+ | `pstack_worktree` | Create isolated Git worktrees, inspect dirty/merged state, approve safe removal. |
58
+ | `pstack_pr` | Read fresh GitHub PR state, head and checks. |
59
+ | `pstack_ship` | Require a shipping or autopilot-full plan and operator confirmation; recheck and merge the verified contiguous prefix. |
60
+
61
+ ## Configuration and workers
62
+
63
+ `/setup-pstack` uses Pi's model registry and native selection dialogs. Nine role selections and the reasoning budget are saved atomically at `$PI_CODING_AGENT_DIR/pstack-models.json`, default `~/.pi/agent/pstack-models.json`. The file uses a `defaults: 3` marker. The parent model remains unchanged. Cursor-specific model slugs do not map reliably to Pi provider IDs, so unconfigured roles inherit the parent; explicitly choose available `provider/id` models. The picker lists models in the current scope and excludes providers registered by extensions. Both `auto` and `inherit-parent` resolve to the current parent model; setup warns if workers cannot use it. Delegation checks availability only for the workers and judge selected for that run. For arena and interrogate configure at least two panel seats. Arena uses the first available judge in the configured pool whose vendor differs from the parent and every candidate. Pi itself may clamp reasoning to model support. The `large`, `medium`, `small` budgets lower the role's reasoning target; the Gemini panel seat uses its higher target where selected.
64
+
65
+ Each delegate starts a fresh Pi CLI process via `pi.exec`. `PSTACK_PI_BIN` can select the Pi binary. Concurrency is bounded to eight workers, with default three concurrent workers. Each job retains its report and native JSONL session. Only bounded output excerpts return to the parent. Read-only reviewers receive only Pi's read/grep/find/ls tools; no shell, write, edit, MCP or discovered extensions. Write delegates require explicit confirmation in the terminal UI or via Pi RPC and get separate detached Git worktrees at the selected committed ref (default HEAD). Uncommitted parent files are not copied automatically; the parent saves a repository-root-relative patch of up to 2 MiB. If tracked changes alone exceed the limit, no patch is attached. Otherwise, untracked, non-ignored files are added as whole patches while space remains, and workers are told which files were omitted. The parent inspects, reconciles and verifies worker output. Workers never automatically merge, cherry-pick, or delete worktrees. Worktrees are isolation of checkout state, not an OS security sandbox. Child processes inherit the OS environment and cannot use provider registrations supplied exclusively by disabled extensions; delegation refuses such models before starting any worker. Use a real external sandbox for untrusted code or secrets.
66
+
67
+ Arena stores candidate sessions, removes model metadata and known model names from message projections, asks the independent judge to read the actual projected transcripts, and audits read tool calls. This is partial blinding: transcript text, tool paths or outputs can still identify an author; a read call alone cannot prove the judge read every line. It does not claim a fully controlled evaluation environment. If judging fails, the tool returns an inconclusive judgment alongside the completed candidate reports and their artifact directory.
68
+
69
+ ## Session state and delivery
70
+
71
+ Task and mode state use Pi's branch-local custom entries. Timers stop on session shutdown, branch change, abort, completion, or iteration limit. Restored sessions recover state with wake loops paused. If the latest saved pstack state is invalid or unsupported, the extension starts with empty state rather than reviving an older plan. Wakes only run while a terminal Pi session is open. `/pstack-pause` saves a resume note without implicitly committing, deleting or changing a branch. Artifacts live under `$PI_CODING_AGENT_DIR/pstack/sessions/<session-id>/`.
72
+
73
+ The shipping gate uses GitHub CLI and requires an active shipping or autopilot-full plan. Finishing the plan closes the gate. It requires independent evidence tied to each exact head, shows the exact PR URLs and heads for explicit approval in the terminal UI or via Pi RPC, and checks readiness immediately before each `gh pr merge --match-head-commit`. If an initial PR lookup fails, the gate can still offer the verified prefix before it and reports the failed lookup as `lookupFailure`. A merge counts as confirmed only when GitHub reports `MERGED` at the approved head. If a merge was attempted but its result could not be confirmed, the tool reports its PR number separately as `unconfirmed`, not `unmerged`. Inspect the forge state before retrying. The operator must verify that order and the provenance of the evidence; the extension cannot prove the stack topology or that a model's evidence string is truthful. The gate applies to its own tool, not arbitrary user-installed tools or the parent's general shell. It does not merge in autopilot-stack or in print or JSON mode. The model cannot select the `shipping` or `autopilot-full` route through `pstack_plan` without a confirmation; `/pstack-run` selects it directly. Worktree removal and write delegation also require a confirmation-capable UI. Removal deletes ignored files in the worktree. The confirmation counts individual ignored paths, including files inside ignored directories, and shows the first ten. Removal stops if the path list changes after approval. Origin-specific operations are instructions only; no Origin service is bundled.
74
+
75
+ ## Benny and automation
76
+
77
+ `/pstack-automation benny-triage`, `/pstack-automation benny-repro`, or `/pstack-automation custom` creates an initially disabled draft in the session artifact directory. It refuses to overwrite a previous draft. Copy the Benny configuration template to a trusted target project outside the package. Configure project-specific Slack/tracker/control MCP tools, and use an explicit allowlist in the draft. Review the tool semantics. Benny requires narrowly scoped tools and prohibits the generic shell, codemode, dynamic tool search and MCP tool names whose words (snake_case, kebab-case or camelCase) indicate merge, squash, rebase, push, commit, deploy, publish, delete, exec, shell, script or command operations, or create/update/write of files, branches or refs. Native `edit` and `write` are accepted only for `benny-repro`; `benny-triage` is read-only. Pull request creation tools are accepted only for `benny-repro` with `allowDraftPr: true`. This is not a security sandbox; configured MCP permissions must enforce those restrictions too.
78
+
79
+ `node scripts/run-job.mjs --run /absolute/path/job.json [signed-event.json]` is a local headless Pi entrypoint. It is not a daemon, managed cloud worker, Slack subscription, or scheduler. The job and Benny config must be separately enabled by the operator. The external trusted event adapter must provide an envelope `{ "payload": "<JSON string>", "signature": "<HMAC-SHA256 hex>" }`, signed with `PSTACK_EVENT_SECRET`. A report payload includes `type: "report"`, `topLevel: true`, `channel`, `thread`, and `eventId`. A reproduction payload includes `type: "triage-marker"`, `trusted: true`, `classification: "bug"` or `"performance"`, `ticket`, and the same immutable thread identity fields. The adapter, not arbitrary Slack text, establishes trust. A claimed run directory is unique per workflow/thread; repeated dispatches fail closed. If Pi cannot start, the runner prints the claim location and writes a sanitized `not-started` receipt to `result.json`. An absent receipt is not proof that Pi never started. Investigate ambiguous failures before rearming any event. The runner removes the event signing secret from the child environment and sends the prompt through stdin rather than as process arguments. Pi can load skills and prompt templates from the trusted project; the job's explicit tool allowlist still applies. It preserves private run logs and uses Pi's native MCP integration for explicitly named external tools. Benny's application-specific adapter, event receiver, tracker actions and real end-to-end proof are not implemented by this generic package. See `reference/benny/`.
80
+
81
+ ## Verify
82
+
83
+ Run the development checks from a source checkout:
84
+
85
+ ```sh
86
+ bun install --frozen-lockfile
87
+ bun run check:ci
88
+ bun run smoke
89
+ ```
90
+
91
+ `check:ci` checks that generated files match their sources, then runs lint, format checks, the TypeScript compiler against the installed Pi SDK, and the Node test suite with an 80% gate for line, branch, and function coverage. Use `bun run check` to run the same checks with the local TSRS compiler, or `bun run test` to run only the tests. The suite uses a mock Pi host and forge, a fake child CLI for job dispatch, and temporary real Git repositories.
92
+
93
+ `smoke` launches real Pi in an isolated RPC session without model requests. It checks discovery of all 76 native skills and 52 original slash names, then writes and reads mode state. Set `PSTACK_PI_BIN` to point to a different Pi executable. This smoke does not exercise live models, GitHub, Slack, or MCP services. Test those integrations with disposable resources before relying on them.
94
+
95
+ ## Files
96
+
97
+ - `extensions/`: one file per feature: `session.ts` (branch state and wake timer), `plan.ts`, `catalog-ui.ts`, `records.ts`, `models.ts`, `delegate.ts`, `parent-diff.ts`, `worktrees.ts`, `forge.ts`, with `git.ts` and `support.ts` shared.
98
+ - `lib/`: type-checked TypeScript with no Pi dependency: `catalog.ts`, `models.ts`, `state.ts`, `pool.ts`, `transcript.ts`, `jobs.ts`, `validation.ts`.
99
+ - `scripts/catalog-source.json`: the instructions written for Pi: playbook steps, principle rules, skill bodies and implementation classifications. Edit this, not the generated files.
100
+ - `scripts/generate.py`: `bun run generate` rebuilds `skills/`, `lib/catalog-data.json`, `reference/parity.json` and `reference/PARITY.md` from the source map and `catalog-source.json`. Regeneration removes obsolete generator-marked skill and playbook files, not hand-authored files. `bun run check:generated` reports drift without writing.
101
+ - `skills/`: 76 native skill directories and 22 nested ordered playbooks (generated).
102
+ - `agents/`: worker and reviewer contracts.
103
+ - `reference/source-map.json`: original attachment, unchanged byte-for-byte.
104
+ - `reference/parity.json` (generated): machine-readable original IDs, edges and views with implementation classifications.
105
+ - `reference/PARITY.md`, `reference/GAPS.md`: audit matrix and residual gaps.
106
+ - `reference/benny/`: dormant configuration and workflow instructions.
107
+ - `scripts/run-job.mjs`, `scripts/job-input.ts`, `scripts/smoke.mjs`, `tests/`: runner, job validation and verification.
108
+
109
+ ## Official references
110
+
111
+ The extension targets the `@earendil-works` Pi SDK, not the older `@mariozechner` namespace.
112
+
113
+ - [Extensions](https://docs.pi.dev/latest/extensions)
114
+ - [Packages](https://docs.pi.dev/latest/packages)
115
+ - [Skills](https://docs.pi.dev/latest/skills)
116
+ - [Command line](https://docs.pi.dev/latest/cli)
117
+ - [RPC commands](https://docs.pi.dev/latest/rpc-commands)
118
+ - [Configuration](https://docs.pi.dev/latest/configuration)
119
+ - [Environment variables](https://docs.pi.dev/latest/environment-variables)
120
+ - [Pinned original router](https://github.com/cursor/plugins/blob/7a583913eb1b8d1a0ee76753d1a2cf072e7b54f9/pstack/skills/poteto-mode/SKILL.md)
121
+ - [Pinned original setup](https://github.com/cursor/plugins/blob/7a583913eb1b8d1a0ee76753d1a2cf072e7b54f9/pstack/skills/setup-pstack/SKILL.md)
122
+
123
+ Every upstream source URL from the map remains in `reference/source-map.json` and `reference/parity.json`. No claim is made that the independently authored instructions reproduce every detail in those upstream files.
@@ -0,0 +1 @@
1
+ Read-only CI review. Report the PR head, check names, statuses, and log pointers supplied by the parent. Identify stale results and blockers. Do not modify or merge.
@@ -0,0 +1 @@
1
+ Read-only comment review. Inspect the actual diff. Identify redundant, misleading or implementation-narrating comments with exact paths/lines and a proposed deletion or structural replacement. Keep necessary constraints and public API documentation. Do not modify files.
@@ -0,0 +1 @@
1
+ Read worker.md and the full poteto-mode skill. Implement only the parent’s scoped task; the parent owns routing. Name the data shape first, select applicable principles and run the actual acceptance check. Return a diff or artifact location and evidence.
@@ -0,0 +1 @@
1
+ Read-only independent maintainability review. Locate concrete coupling, complexity, type holes, unnecessary indirection and excessive mutable state. Supply a reproducible finding with a file pointer and minimal remedy. Do not modify files.
@@ -0,0 +1,3 @@
1
+ # Pi worker contract
2
+
3
+ Read this file first. Read the poteto-mode skill before any direct implementation work. The parent owns the playbook, verification, and delivery. Start with the goal and scope, respect all supplied approval boundaries, and work only on your assigned output. Do not merge, deploy, force-push, post external messages, or delete unrelated work. Do not open PRs unless the parent explicitly requests it and grants the necessary scope. Return actual commands, exit results, artifact paths, unresolved risks, and a concise summary. Preserve your worktree and session for inspection. Do not claim a test you did not run.
@@ -0,0 +1,86 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+
4
+ import {
5
+ lookup,
6
+ nativeNode,
7
+ nodes,
8
+ routeTriggers,
9
+ slashSkills,
10
+ view,
11
+ views,
12
+ workflowPrompt,
13
+ } from "../lib/catalog.ts";
14
+ import { result, text, type Notify, stringEnum } from "./support.ts";
15
+
16
+ const ownCommands = new Set(["setup-pstack", "poteto-mode"]);
17
+
18
+ async function browse(pi: ExtensionAPI, ctx: ExtensionContext, start: string) {
19
+ let current = start;
20
+ for (;;) {
21
+ const v = view(current);
22
+ const choices = [
23
+ ...(v.parent ? [`view:${v.parent} (back)`] : []),
24
+ ...v.children.map((c) => `view:${c}`),
25
+ ...v.nodes.map((n) => `node:${n.id}`),
26
+ "Exit",
27
+ ];
28
+ // oxlint-disable-next-line eslint/no-await-in-loop -- The next screen depends on the user's choice.
29
+ const chosen = await ctx.ui.select(`${v.title}\n${v.caption}`, choices);
30
+ if (!chosen || chosen === "Exit") return;
31
+ if (chosen.startsWith("view:")) {
32
+ current = chosen.slice(5).split(" ")[0];
33
+ continue;
34
+ }
35
+ const n = nativeNode(chosen.slice(5));
36
+ const links = n.outgoing.map((e) => `${e.to}: ${e.label} (${e.when})`).join("\n");
37
+ // oxlint-disable-next-line eslint/no-await-in-loop -- Wait for the node action before navigating.
38
+ const action = await ctx.ui.select(
39
+ `${n.id}: ${n.what}\n${n.when}\n${n.implementation}\n${links}`,
40
+ ["Back", "Send full details to transcript"],
41
+ );
42
+ if (action === "Send full details to transcript")
43
+ pi.sendMessage({ customType: "pstack-map", content: text(n), display: true });
44
+ }
45
+ }
46
+
47
+ export const sendWorkflow = (pi: ExtensionAPI, id: string, request: string) =>
48
+ pi.sendUserMessage(workflowPrompt(id, request), { deliverAs: "followUp" });
49
+
50
+ export function registerCatalog(pi: ExtensionAPI, notify: Notify) {
51
+ for (const n of slashSkills.filter((skill) => !ownCommands.has(skill.id))) {
52
+ pi.registerCommand(n.label.slice(1), {
53
+ description: n.what,
54
+ handler: async (args) => sendWorkflow(pi, n.id, args.trim()),
55
+ });
56
+ }
57
+ pi.registerCommand("pstack-create-skill", {
58
+ description: "Author a project-local Agent Skill",
59
+ handler: async (args) => sendWorkflow(pi, "pb-authoring-a-skill", args),
60
+ });
61
+ pi.registerCommand("pstack-map", {
62
+ description: "Browse all source map nodes, relationships and views",
63
+ handler: async (args, ctx) => {
64
+ const id = args.trim() || "root";
65
+ if (!views.has(id)) return notify(ctx, text(nodes.has(id) ? nativeNode(id) : lookup(id)));
66
+ if (!ctx.hasUI) return notify(ctx, text(view(id)));
67
+ await browse(pi, ctx, id);
68
+ },
69
+ });
70
+ pi.registerTool({
71
+ name: "pstack_catalog",
72
+ label: "Pstack catalog",
73
+ description:
74
+ "Read a skill/playbook or native implementation mapping, search the map, list routes, or inspect a view. Conditional edges are not a call sequence.",
75
+ parameters: Type.Object({
76
+ action: stringEnum(["node", "routes", "view", "search"]),
77
+ id: Type.Optional(Type.String()),
78
+ }),
79
+ async execute(_id, p) {
80
+ if (p.action === "routes") return result(routeTriggers());
81
+ if (p.action === "search") return result(lookup(p.id ?? ""));
82
+ if (p.action === "view") return result(view(p.id ?? "root"));
83
+ return result(nativeNode(p.id ?? ""));
84
+ },
85
+ });
86
+ }
@@ -0,0 +1,357 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+
5
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { Type, type Static } from "typebox";
7
+
8
+ import { root } from "../lib/catalog.ts";
9
+ import {
10
+ crossJudge,
11
+ effort,
12
+ isRole,
13
+ judgeRole,
14
+ modelFor,
15
+ selectPanel,
16
+ type Budget,
17
+ type Effort,
18
+ type Role,
19
+ type RoleConfig,
20
+ } from "../lib/models.ts";
21
+ import { pool, type PoolResult } from "../lib/pool.ts";
22
+ import { blindTranscript, readPaths } from "../lib/transcript.ts";
23
+ import { errorMessage } from "../lib/validation.ts";
24
+ import { gitIn } from "./git.ts";
25
+ import { availableWorkerModels, readConfig } from "./models.ts";
26
+ import { saveParentDiff, type ParentDiff } from "./parent-diff.ts";
27
+ import { artifacts, fail, result, stringEnum } from "./support.ts";
28
+ import { createWorktree } from "./worktrees.ts";
29
+
30
+ const modes = ["single", "swarm", "arena", "interrogate"] as const;
31
+ type Mode = (typeof modes)[number];
32
+
33
+ interface WorkerRole {
34
+ alwaysReadOnly: boolean;
35
+ modelRole: Role;
36
+ contract?: string;
37
+ }
38
+ const reviewer = (contract: string): WorkerRole => ({
39
+ alwaysReadOnly: true,
40
+ modelRole: "judgment and prose",
41
+ contract,
42
+ });
43
+ export const workerRoles = new Map<string, WorkerRole>([
44
+ [
45
+ "poteto-agent",
46
+ { alwaysReadOnly: false, modelRole: "feature, refactoring", contract: "poteto-agent.md" },
47
+ ],
48
+ ["comment-sicko", reviewer("comment-sicko.md")],
49
+ ["ci-watcher", reviewer("ci-watcher.md")],
50
+ ["quality-agent", reviewer("quality-agent.md")],
51
+ ["general-purpose", { alwaysReadOnly: false, modelRole: "judgment and prose" }],
52
+ ]);
53
+ const panelModelRoles: Partial<Record<Mode, Role>> = {
54
+ arena: "arena runners",
55
+ interrogate: "interrogate reviewers",
56
+ swarm: "swarm workers",
57
+ };
58
+
59
+ const piBin = process.env.PSTACK_PI_BIN ?? "pi";
60
+ const parameters = Type.Object({
61
+ mode: stringEnum(modes),
62
+ tasks: Type.Array(Type.String({ minLength: 1 }), { minItems: 1, maxItems: 8 }),
63
+ role: Type.Optional(Type.String()),
64
+ modelRole: Type.Optional(Type.String()),
65
+ readOnly: Type.Optional(Type.Boolean()),
66
+ rubric: Type.Optional(Type.String()),
67
+ base: Type.Optional(Type.String()),
68
+ concurrency: Type.Optional(Type.Integer({ minimum: 1, maximum: 8 })),
69
+ });
70
+ type DelegateParams = Static<typeof parameters>;
71
+
72
+ function resolveWorkers(
73
+ p: DelegateParams,
74
+ config: RoleConfig,
75
+ parent: string,
76
+ available: ReadonlySet<string>,
77
+ ) {
78
+ const role = p.role ?? (p.mode === "single" ? "poteto-agent" : "general-purpose");
79
+ const worker = workerRoles.get(role);
80
+ if (!worker) fail("Unknown worker role");
81
+ const modelRole = p.modelRole ?? panelModelRoles[p.mode] ?? worker.modelRole;
82
+ if (!isRole(modelRole)) fail("Unknown model role");
83
+ const readOnly = worker.alwaysReadOnly || p.mode === "interrogate" || p.readOnly !== false;
84
+ if (p.mode !== "swarm" && p.tasks.length !== 1)
85
+ fail("Single, arena and interrogate require one shared task");
86
+ if (p.mode === "arena" && !p.rubric?.trim()) fail("Arena requires a common evaluation rubric");
87
+ const choices = config.roles[modelRole];
88
+ const panel = p.mode === "arena" || p.mode === "interrogate";
89
+ if (panel && choices.length < 2) fail("Configure at least two panel seats in /setup-pstack");
90
+ const tasks = panel ? choices.map(() => p.tasks[0]) : p.tasks;
91
+ const models = selectPanel(config, modelRole, tasks.length).map((m) => modelFor(m, parent));
92
+ assertReachable(available, models);
93
+ const judge = p.mode === "arena" ? crossJudge(config, parent, models, available) : undefined;
94
+ if (p.mode === "arena" && !judge)
95
+ fail(
96
+ `Configure an available judge from another provider than the parent and all candidates in /setup-pstack. Configured pool: ${config.roles[judgeRole].join(", ") || "(empty)"}.`,
97
+ );
98
+ return { role, modelRole, readOnly, tasks, models, judge };
99
+ }
100
+
101
+ export function workerArgs(options: {
102
+ model: string;
103
+ thinking: Effort;
104
+ readOnly: boolean;
105
+ sessionDir: string;
106
+ sessionId: string;
107
+ prompt: string;
108
+ }) {
109
+ return [
110
+ "--print",
111
+ "--no-approve",
112
+ "--no-extensions",
113
+ "--no-skills",
114
+ "--no-prompt-templates",
115
+ "--no-themes",
116
+ "--no-mcp",
117
+ "--tools",
118
+ options.readOnly ? "read,grep,find,ls" : "read,grep,find,ls,bash,edit,write",
119
+ "--session-dir",
120
+ options.sessionDir,
121
+ "--session-id",
122
+ options.sessionId,
123
+ "--model",
124
+ options.model,
125
+ "--thinking",
126
+ options.thinking,
127
+ "--",
128
+ options.prompt,
129
+ ];
130
+ }
131
+
132
+ interface WorkerRequest {
133
+ task: string;
134
+ model: string;
135
+ index: number;
136
+ readOnly: boolean;
137
+ role: string;
138
+ modelRole: Role;
139
+ }
140
+ interface RunnerOptions {
141
+ dir: string;
142
+ budget: Budget;
143
+ rubric?: string;
144
+ base?: string;
145
+ diff?: ParentDiff;
146
+ signal?: AbortSignal;
147
+ progress: (message: string) => void;
148
+ }
149
+
150
+ function diffNotes(diff: ParentDiff | undefined) {
151
+ if (!diff)
152
+ return [
153
+ "Parent diff artifact unavailable; uncommitted parent changes are not described anywhere.",
154
+ ];
155
+ const more = diff.omitted.length > 50 ? ` and ${diff.omitted.length - 50} more` : "";
156
+ return [
157
+ `Parent diff artifact (tracked changes and untracked files): ${diff.path}. Write worktrees start at the selected committed base and do not include uncommitted changes.`,
158
+ diff.omitted.length &&
159
+ `Untracked files omitted from the artifact (too large, too many or unreadable): ${diff.omitted.slice(0, 50).join(", ")}${more}.`,
160
+ ];
161
+ }
162
+
163
+ async function workerPrompt(request: WorkerRequest, options: RunnerOptions) {
164
+ const kickoffPath = join(root, "agents", "worker.md");
165
+ const contract = workerRoles.get(request.role)?.contract;
166
+ return [
167
+ `Read ${kickoffPath} before anything else.`,
168
+ await readFile(kickoffPath, "utf8"),
169
+ contract
170
+ ? await readFile(join(root, "agents", contract), "utf8")
171
+ : "Independent scoped worker.",
172
+ request.role === "poteto-agent" &&
173
+ (await readFile(join(root, "skills", "poteto-mode", "SKILL.md"), "utf8")),
174
+ `Assigned task: ${request.task}`,
175
+ options.rubric && `Finish predicate / rubric: ${options.rubric}`,
176
+ ...diffNotes(options.diff),
177
+ "Return evidence and artifact paths; do not perform external side effects.",
178
+ ]
179
+ .filter(Boolean)
180
+ .join("\n");
181
+ }
182
+
183
+ function createRunner(
184
+ pi: ExtensionAPI,
185
+ ctx: ExtensionContext,
186
+ active: Set<string>,
187
+ options: RunnerOptions,
188
+ ) {
189
+ return async (request: WorkerRequest) => {
190
+ const { dir, signal } = options;
191
+ if (signal?.aborted) fail("Cancelled");
192
+ const { index, readOnly, model, modelRole } = request;
193
+ const id = `worker-${index + 1}-${randomUUID().slice(0, 8)}`;
194
+ const tree = readOnly
195
+ ? { path: ctx.cwd, base: null }
196
+ : await createWorktree(gitIn(pi, ctx.cwd, signal), ctx, id, options.base);
197
+ if (!readOnly) active.add(tree.path);
198
+ try {
199
+ const sessionDir = join(dir, id);
200
+ await mkdir(sessionDir, { mode: 0o700 });
201
+ const args = workerArgs({
202
+ model,
203
+ thinking: effort(modelRole, options.budget, model),
204
+ readOnly,
205
+ sessionDir,
206
+ sessionId: id,
207
+ prompt: await workerPrompt(request, options),
208
+ });
209
+ options.progress(`Running ${id}`);
210
+ const run = await pi.exec(piBin, args, {
211
+ cwd: tree.path,
212
+ signal,
213
+ timeout: 30 * 60 * 1000,
214
+ maxBuffer: 4 * 1024 * 1024,
215
+ });
216
+ const report = join(dir, `${id}.txt`);
217
+ await Promise.all([
218
+ writeFile(report, run.stdout, { mode: 0o600 }),
219
+ writeFile(join(dir, `${id}.stderr.txt`), run.stderr, { mode: 0o600 }),
220
+ ]);
221
+ if (run.code !== 0 || run.truncated || run.killed)
222
+ fail(`Worker ${id} failed (${run.code}); inspect ${report}`);
223
+ const sessions = (await readdir(sessionDir, { recursive: true })).filter((path) =>
224
+ path.endsWith(".jsonl"),
225
+ );
226
+ const transcript = sessions.length === 1 ? join(sessionDir, sessions[0]) : null;
227
+ return {
228
+ id,
229
+ model,
230
+ ...tree,
231
+ report,
232
+ transcript,
233
+ sessionDir,
234
+ summary: run.stdout.slice(-6000),
235
+ };
236
+ } finally {
237
+ if (!readOnly) active.delete(tree.path);
238
+ }
239
+ };
240
+ }
241
+
242
+ type RunWorker = ReturnType<typeof createRunner>;
243
+ type WorkerReport = Awaited<ReturnType<RunWorker>>;
244
+ async function judgeArena(
245
+ dir: string,
246
+ outputs: PoolResult<WorkerReport>[],
247
+ rubric: string | undefined,
248
+ judge: string,
249
+ run: RunWorker,
250
+ ) {
251
+ if (!outputs.every((entry) => entry.status === "fulfilled"))
252
+ return { status: "INCONCLUSIVE: a candidate failed" };
253
+ const candidates = outputs.map((entry) => entry.value);
254
+ const blindDir = join(dir, "blinded");
255
+ await mkdir(blindDir, { mode: 0o700 });
256
+ const files = await Promise.all(
257
+ candidates.map(async ({ model, transcript }, i) => {
258
+ if (!transcript) return null;
259
+ const projection = blindTranscript(await readFile(transcript, "utf8"), model);
260
+ if (!projection.trim()) return null;
261
+ const path = join(blindDir, `candidate-${i + 1}.jsonl`);
262
+ await writeFile(path, projection, { mode: 0o600 });
263
+ return path;
264
+ }),
265
+ );
266
+ if (!files.every((path) => path !== null))
267
+ return { status: "INCONCLUSIVE: missing or empty candidate transcript" };
268
+ const worktrees = candidates
269
+ .map((candidate, i) => `Candidate ${i + 1}: ${candidate.path}`)
270
+ .join("; ");
271
+ const assessment = await run({
272
+ task: `Judge these ${files.length} anonymous candidate message transcripts: ${files.join(", ")}. Read every file in full, including tool results; rubric: ${rubric}. Rank by actual evidence; note missing artifacts or unverifiable claims. For write candidates, inspect candidate worktrees if necessary: ${worktrees}. Do not infer provider identity.`,
273
+ model: judge,
274
+ index: candidates.length,
275
+ readOnly: true,
276
+ role: "general-purpose",
277
+ modelRole: judgeRole,
278
+ });
279
+ const reads = new Set(
280
+ assessment.transcript ? readPaths(await readFile(assessment.transcript, "utf8")) : [],
281
+ );
282
+ const readAudit = files.map((path) => ({ path, read: reads.has(path) }));
283
+ return {
284
+ ...assessment,
285
+ readAudit,
286
+ status: readAudit.every((entry) => entry.read)
287
+ ? "reviewed"
288
+ : "INCONCLUSIVE: judge did not read every projected transcript",
289
+ };
290
+ }
291
+
292
+ function assertReachable(available: ReadonlySet<string>, models: string[]) {
293
+ const unreachable = [...new Set(models)].filter((model) => !available.has(model));
294
+ if (unreachable.length)
295
+ fail(
296
+ `Workers run without extensions. Unavailable in the current worker scope: ${unreachable.join(", ")}. Choose an available model in /setup-pstack.`,
297
+ );
298
+ }
299
+
300
+ export function registerDelegation(pi: ExtensionAPI, active: Set<string>) {
301
+ pi.registerTool({
302
+ name: "pstack_delegate",
303
+ label: "Pstack Pi workers",
304
+ description:
305
+ "Run independent native Pi CLI sessions: single, swarm, arena or interrogate. Read-only by default; write workers use detached worktrees. Child sessions and reports are retained.",
306
+ parameters,
307
+ async execute(_id, p, signal, onUpdate, ctx) {
308
+ const config = await readConfig();
309
+ if (!ctx.model) fail("Select a parent model first");
310
+ const parent = `${ctx.model.provider}/${ctx.model.id}`;
311
+ const available = new Set(availableWorkerModels(ctx));
312
+ const { role, modelRole, readOnly, tasks, models, judge } = resolveWorkers(
313
+ p,
314
+ config,
315
+ parent,
316
+ available,
317
+ );
318
+ if (
319
+ !readOnly &&
320
+ (!ctx.hasUI ||
321
+ !(await ctx.ui.confirm(
322
+ "Authorize isolated write workers?",
323
+ `${tasks.length} worker(s), detached worktrees from ${p.base ?? "HEAD"}. Workers can execute shell commands; worktrees are not a security sandbox.`,
324
+ )))
325
+ )
326
+ fail("Write delegation not authorized");
327
+ const dir = join(artifacts(ctx), "workers", randomUUID());
328
+ await mkdir(dir, { recursive: true, mode: 0o700 });
329
+ const run = createRunner(pi, ctx, active, {
330
+ dir,
331
+ signal,
332
+ diff: await saveParentDiff(pi, ctx.cwd, dir, signal),
333
+ budget: config.budget,
334
+ base: p.base,
335
+ rubric: p.rubric,
336
+ progress: (message) => onUpdate?.(result(message)),
337
+ });
338
+ const outputs = await pool(tasks, p.concurrency ?? 3, (task, index) =>
339
+ run({ task, index, model: models[index], readOnly, role, modelRole }),
340
+ );
341
+ const judgment =
342
+ judge &&
343
+ (await judgeArena(dir, outputs, p.rubric, judge, run).catch((error: unknown) => ({
344
+ status: "INCONCLUSIVE: could not complete arena judgment",
345
+ model: judge,
346
+ error: errorMessage(error),
347
+ })));
348
+ return result({
349
+ outputs,
350
+ judgment,
351
+ dir,
352
+ warning:
353
+ "Local workers only. Review actual artifacts and rerun acceptance checks; report text is not proof.",
354
+ });
355
+ },
356
+ });
357
+ }