@wichayutdew/pi-workflows 2.0.1 → 2.2.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 (43) hide show
  1. package/README.md +19 -955
  2. package/dist/index.js +841 -535
  3. package/examples/mr-comments.workflow.yaml +1 -1
  4. package/examples/prompts/mr-comments/plan.md +8 -1
  5. package/examples/starter-kit/mr-comment.workflow.yaml +1 -1
  6. package/examples/starter-kit/mr-review.workflow.yaml +4 -2
  7. package/examples/starter-kit/steps/mr-comment/plan.md +9 -2
  8. package/examples/starter-kit/steps/mr-review/publish.md +9 -2
  9. package/examples/starter-kit/steps/mr-review/review.md +9 -2
  10. package/examples/starter-kit/steps/mr-review/verify.md +16 -5
  11. package/examples/starter-kit/steps/shared/prepare-workspace.md +42 -4
  12. package/examples/starter-kit/steps/ticket/plan.md +31 -2
  13. package/examples/starter-kit/steps/work/plan.md +31 -2
  14. package/examples/starter-kit/ticket.workflow.yaml +14 -2
  15. package/examples/starter-kit/work.workflow.yaml +14 -2
  16. package/package.json +1 -1
  17. package/schemas/workflow.schema.json +1 -0
  18. package/src/command-names.ts +1 -0
  19. package/src/commands.ts +14 -0
  20. package/src/config/types.ts +1 -1
  21. package/src/config/validation/prompt.ts +3 -0
  22. package/src/engine/create-run.ts +4 -0
  23. package/src/engine/gate-transitions.ts +80 -33
  24. package/src/engine/run-advance.ts +36 -3
  25. package/src/engine/run-lifecycle.ts +69 -0
  26. package/src/engine/run-reconciliation.ts +2 -0
  27. package/src/engine/run-validation.ts +24 -1
  28. package/src/engine/state-types.ts +10 -0
  29. package/src/engine/state.ts +1 -0
  30. package/src/engine/transitions.ts +1 -0
  31. package/src/harness/action-context.ts +6 -0
  32. package/src/harness/core-actions.ts +2 -0
  33. package/src/harness/dependencies.ts +4 -0
  34. package/src/harness/lifecycle-actions.ts +14 -1
  35. package/src/harness/session-persistence.ts +66 -0
  36. package/src/harness/start-actions.ts +188 -1
  37. package/src/harness.ts +20 -0
  38. package/src/prompt/step-sections.ts +14 -0
  39. package/src/prompt/step-task.ts +3 -0
  40. package/src/prompt/template.ts +6 -3
  41. package/src/workflow-doctor.ts +1 -1
  42. package/src/workflow-status/render-summary.ts +3 -0
  43. package/src/workflow-status/view.ts +29 -3
package/README.md CHANGED
@@ -1,966 +1,30 @@
1
- # Pi Workflows
2
-
3
- **Turn repeatable agent work into declarative, pauseable workflows that cannot
4
- silently loop forever.** Put the steps, tools, prompts, approvals, and outcomes
5
- in YAML; Pi Workflows supplies durable checkpoints, finite automatic execution,
6
- and a live status view without learning your language, framework, or process.
7
-
8
1
  [![codecov](https://codecov.io/gh/wichayutdew/pi-workflows/graph/badge.svg?token=33xrCBRM82)](https://codecov.io/gh/wichayutdew/pi-workflows)
9
2
 
10
- ```bash
11
- pi install npm:@wichayutdew/pi-workflows
12
- ```
13
-
14
- - Compose main-agent and isolated subagent steps from one strict YAML contract.
15
- - Pause for built-in or Plannotator review, then resume the same checkpoint.
16
- - Reject dead-end graphs up front and pause bounded cycles at `maxStepVisits`.
17
- - Keep every domain decision in your workflow files—not in the harness.
18
-
19
- ## Overview
20
-
21
- Pi Workflows keeps orchestration code generic and moves workflow behavior into
22
- small YAML configuration and prompt files. Each workflow defines its
23
- own steps, transitions, execution mode, tool access, MCP access, Bash policy,
24
- extensions, skills, dependency checks, and optional human-review gate.
25
-
26
- The harness owns state transitions. A step runs in the main Pi agent by default,
27
- or in a separate [pi-subagents](https://github.com/nicobailon/pi-subagents)
28
- child when it declares `subagent`. Main-agent steps advance through
29
- `workflow_complete_step`; delegated steps return the same validated contract
30
- through pi-subagents' correlated `structured_output`.
31
-
32
- ## Install
33
-
34
- Install Pi Workflows from npm:
35
-
36
- ```bash
37
- pi install npm:@wichayutdew/pi-workflows
38
- ```
39
-
40
- For local development, install it from the repository instead:
41
-
42
- ```bash
43
- pi install /absolute/path/to/pi-workflows
44
- ```
45
-
46
- For the strongest context isolation and browser-based review experience, use it
47
- with both [pi-subagents](https://github.com/nicobailon/pi-subagents) and
48
- [Plannotator](https://github.com/backnotprop/plannotator):
49
-
50
- ```bash
51
- pi install npm:pi-subagents
52
- pi install npm:@plannotator/pi-extension
53
- ```
54
-
55
- Neither integration is required, but both are highly recommended together for
56
- the best isolation and review experience. Delegated steps require
57
- pi-subagents `0.36.0` or newer. Run `/subagents-doctor` if an explicitly
58
- delegated step cannot start.
59
-
60
- Pi loads `src/index.ts` through the package manifest. Restart Pi or run `/reload` after changing extension source.
61
-
62
- ## Quick start: bootstrap four practical workflows
63
-
64
- The checked-in [`examples/starter-kit`](./examples/starter-kit) is a portable,
65
- user-owned starting point for:
66
-
67
- | Command | Included flow |
68
- | ------------- | ---------------------------------------------------------------------------------------------------------- |
69
- | `/work` | Prepare or reuse one dedicated Git worktree, plan, approve, implement, and verify local work. |
70
- | `/ticket` | Prepare or reuse one dedicated Git worktree, read a ticket, plan, approve, implement, and verify. |
71
- | `/mr-review` | Fetch a hosted review, produce a child review, approve it, publish it, and verify the remote effect. |
72
- | `/mr-comment` | Fetch review comments, plan and approve fixes, edit only the current branch/worktree, verify, push, reply. |
73
-
74
- The starter YAML explicitly selects Pi Subagents' standard role profiles:
75
- `scout` for evidence gathering, `planner` for implementation plans, `worker`
76
- for mutations and publication, and `reviewer` for independent review and
77
- verification. Change those `subagent.agent` values when your own Pi Subagents
78
- configuration uses different profiles. The generic `pi-workflows.step` profile
79
- remains available for user-authored `subagent: {}` steps, but the starter kit
80
- does not rely on it.
81
-
82
- Install the integrations required by these four examples:
83
-
84
- ```bash
85
- pi install npm:pi-subagents
86
- pi install npm:@plannotator/pi-extension
87
- ```
88
-
89
- Configure a Pi MCP proxy for the `atlassian`, `gitlab`, and/or `github` server
90
- IDs when you want that access route. The MR examples try a matching MCP server
91
- first but can fall back to the repository/host CLIs or cURL named in their
92
- YAML; ensure at least one route is authenticated and available. The ticket
93
- example requires Atlassian MCP by default. MCP server names, authentication,
94
- tool availability, Git hosting, and repository commands are environment
95
- choices, so adapt the selectors, `requires`, and Bash rules instead of
96
- expecting the extension to infer them.
97
-
98
- Copy the starter files into the user workflow directory:
99
-
100
- ```bash
101
- mkdir -p ~/.pi/agent/workflows
102
- cp examples/starter-kit/*.workflow.yaml ~/.pi/agent/workflows/
103
- cp -R examples/starter-kit/steps ~/.pi/agent/workflows/
104
- ```
105
-
106
- If files with those names already exist, review and merge them instead of
107
- overwriting your working configuration. Then customize:
108
-
109
- 1. In `work.workflow.yaml` and `ticket.workflow.yaml`, set each
110
- `workspace.allowedRoots` to relative directories where the preparation
111
- prompt may create or reuse a worktree.
112
- 2. Replace or narrow the `atlassian`, `gitlab`, and `github` MCP selectors to
113
- match your configured adapter. Remove an unused host consistently from the
114
- relevant `permissions.mcp` blocks and prompts.
115
- 3. Review every Bash mode and executable. The starter implementation and
116
- verification steps are deliberately language-neutral and therefore
117
- unrestricted; replace them with repository-specific allow lists when
118
- possible. Command syntax—including package-manager argument order—belongs
119
- in your prompt and repository context.
120
- 4. Edit the prompt files under `steps/` to define your artifact format,
121
- acceptance criteria, publication policy, and organization-specific rules.
122
- Pi Workflows treats all of that content as opaque domain configuration.
123
-
124
- Reload and diagnose every graph before the first run:
125
-
126
- ```text
127
- /reload
128
- /workflow-reload
129
- /workflow-doctor work
130
- /workflow-doctor ticket
131
- /workflow-doctor mr-review
132
- /workflow-doctor mr-comment
133
- ```
134
-
135
- Start them from the repository checkout that should supply the initial
136
- workspace:
137
-
138
- ```text
139
- /work update the navigation
140
- /ticket PROJ-123 retry failed requests
141
- /mr-review https://gitlab.example.com/group/project/-/merge_requests/42
142
- /mr-comment https://github.com/example/project/pull/42
143
- ```
144
-
145
- `/work` and `/ticket` bind the exact worktree returned by their user-authored
146
- preparation prompt. `/mr-comment` intentionally has no workspace-binding step:
147
- every child stays on the branch and worktree from which the run started.
148
- Approval rejection pauses either review workflow; it never launches an
149
- automatic replacement plan. Remote publication prompts first check whether an
150
- approved effect already exists because the harness cannot guarantee
151
- exactly-once external side effects.
152
-
153
- ## Add a workflow
154
-
155
- User workflows live in one of these formats:
156
-
157
- ```text
158
- ~/.pi/agent/workflows/*.workflow.yaml
159
- ~/.pi/agent/workflows/*.workflow.yml
160
- ```
161
-
162
- YAML keeps nested steps and permission lists compact. The loader uses the
163
- strict YAML 1.2 core schema: duplicate keys, merge keys, invalid tags,
164
- multiple documents, non-1.2 directives, and excessive alias expansion fail
165
- closed.
166
-
167
- Set `PI_WORKFLOWS_DIR` to use another directory. For a complete portable
168
- starting point, copy the four-workflow starter kit above. Every configured
169
- command is also available as `/workflow-start <workflow-id> [input]`.
170
-
171
- ## Minimal workflow
172
-
173
- ```yaml
174
- # yaml-language-server: $schema=./schemas/workflow.schema.json
175
- version: 1
176
- id: fix
177
- command: fix
178
- description: Inspect, implement, and verify a change
179
- start: inspect
180
- steps:
181
- inspect:
182
- prompt: Inspect {{workflow.input}} without modifying files.
183
- permissions:
184
- tools: [read, grep, bash]
185
- bash:
186
- mode: allow-list
187
- allow:
188
- - executable: git
189
- argsPrefixes: [[status], [diff]]
190
- - executable: rg
191
- requires:
192
- tools: [read, bash]
193
- transitions:
194
- ready: implement
195
- blocked: $pause
196
-
197
- implement:
198
- prompt:
199
- file: prompts/implement.md
200
- permissions:
201
- tools: [read, edit, write, bash]
202
- bash:
203
- mode: allow-list
204
- allow:
205
- - executable: project-check
206
- argsPrefix: [test]
207
- transitions:
208
- done: $done
209
- blocked: $pause
210
- ```
211
-
212
- The loader rejects unknown properties, duplicate identifiers, missing targets,
213
- unsafe prompt paths, invalid gate contracts, Pi command-name conflicts, and
214
- project permissions above the user ceiling. Conflicts with commands from other
215
- loaded extensions or prompt resources are diagnosed before aliases register.
216
-
217
- ## Configuration
218
-
219
- Top-level fields:
220
-
221
- | Field | Required | Default | Description |
222
- | ----------------- | -------- | ------- | -------------------------------------------------------------------------------------------------- |
223
- | `version` | Yes | — | Configuration contract version. Currently `1`. |
224
- | `id` | Yes | — | Stable workflow identifier. |
225
- | `command` | Yes | — | Slash command without `/`. |
226
- | `description` | Yes | — | Command description. |
227
- | `start` | Yes | — | First step identifier. |
228
- | `steps` | Yes | — | Step map. Order is controlled by transitions, not file order. |
229
- | `maxStepVisits` | No | `5` | Loop guard for each step. |
230
- | `summaryMaxChars` | No | `4000` | Maximum step `summary` length. Reviewed gate artifacts use their separate 200,000-character limit. |
231
-
232
- Each step supports:
233
-
234
- | Field | Required | Description |
235
- | ------------- | -------- | ----------------------------------------------------------------------------------------------------- |
236
- | `title` | No | Human-readable name. Defaults to the step identifier. |
237
- | `prompt` | Yes | Inline text or `{ "file": "relative/path.md" }`. |
238
- | `subagent` | No | Opt into isolated delegation and select the Pi Subagents profile and execution budgets. |
239
- | `permissions` | No | Resources callable during this step. Everything defaults to denied. |
240
- | `requires` | No | Dependencies that must be detectable before the step starts. |
241
- | `transitions` | Yes | Exact outcome to next step, `$pause`, or `$done`. |
242
- | `gate` | No | Built-in prompt or Plannotator human-review gate. |
243
- | `workspace` | No | Bind one delegated step result as the working directory for all reachable downstream delegated steps. |
244
-
245
- Supported prompt variables:
246
-
247
- ```text
248
- {{workflow.input}}
249
- {{workflow.id}}
250
- {{run.id}}
251
- {{step.id}}
252
- {{step.title}}
253
- {{last.summary}}
254
- {{reviewed.artifact}}
255
- {{reviewed.feedback}}
256
- {{gate.feedback}}
257
- {{resume.input}}
258
- ```
259
-
260
- Unknown variables fail configuration loading.
261
-
262
- `{{last.summary}}` normally contains the previous completed step's handoff.
263
- After a step-requested `$pause`, it contains both the preserved incoming
264
- previous-step handoff and the latest paused-attempt summary. Gate artifacts and
265
- summaries stay separate: prompts opt into the opaque approved artifact through
266
- `{{reviewed.artifact}}`.
267
- `{{resume.input}}` contains guidance supplied to the current attempt through
268
- `/workflow-resume [guidance]`. If a prompt omits that variable, the harness
269
- adds the guidance in a clearly delimited standard section, so every workflow
270
- can still use it. Standard-section guidance is an authoritative task-level
271
- amendment for that retry, but it cannot change the workflow graph or bypass
272
- YAML-enforced resource and workspace boundaries. The value is replaced on each
273
- explicit resume and cleared after the step returns an outcome.
274
-
275
- ### Per-step subagents
276
-
277
- Omit `subagent` to execute the step entirely in the main Pi agent. This is the
278
- portable default and requires no other extension:
279
-
280
- ```yaml
281
- steps:
282
- inspect:
283
- prompt: Inspect the request.
284
- permissions:
285
- tools: [read]
286
- transitions:
287
- done: $done
288
- ```
289
-
290
- Add `subagent: {}` to delegate through the public
291
- `pi-subagents/delegation` v1 API with safe defaults:
292
-
293
- ```yaml
294
- steps:
295
- inspect:
296
- subagent: {}
297
- prompt: Inspect the request.
298
- transitions:
299
- done: $done
300
- ```
301
-
302
- The expanded defaults are `agent: pi-workflows.step`, `context: fresh`,
303
- `timeoutMs: 900000`, `artifacts: false`, and `retryToolFailures: false`. The
304
- `agent` value is the actual Pi Subagents profile launched for that step.
305
- `fresh` is the only supported workflow-step context: each child receives the
306
- original workflow input and the previous step's compact handoff, never the
307
- parent or a sibling transcript.
308
-
309
- The run captures Pi's current working directory when it starts. Without a
310
- `workspace` binding, every delegated visit—including cycles, retries, and
311
- resumed steps—uses that directory.
312
-
313
- One delegated, non-gated step may bind a different directory through structured
314
- result data:
315
-
316
- ```yaml
317
- workspace:
318
- bindOn: [ready]
319
- allowedRoots: ['..']
320
- ```
321
-
322
- On a binding outcome, the result must include
323
- `workspace: { cwd: "/absolute/directory" }`. The harness resolves its real path,
324
- requires an existing directory under one configured root relative to the
325
- run-start directory, persists it once, and passes that exact directory to every
326
- reachable downstream child, revisit, recovery attempt, and resume. Other
327
- outcomes must omit `workspace`; later results cannot replace the binding. All
328
- reachable nonterminal steps after a binding must be delegated because the main
329
- Pi process cannot change its working directory.
330
-
331
- The workflow prompt owns how the directory is prepared and what it represents.
332
- The harness does not know Git, worktrees, languages, frameworks, or command
333
- syntax, and it never derives a directory from summaries or gate artifacts. A
334
- legacy checkpoint without a captured directory fails closed before delegation;
335
- abort it and start a new run.
336
-
337
- Use a profile name directly when only the child profile changes:
338
-
339
- ```yaml
340
- steps:
341
- inspect:
342
- subagent: scout
343
- prompt: Inspect the request.
344
- transitions:
345
- done: $done
346
- ```
347
-
348
- This name-only form inherits the same execution defaults and launches the
349
- configured Pi Subagents `scout` profile. Its system prompt and profile defaults
350
- provide the specialty, while the workflow prompt supplies the exact step
351
- contract. Use the object form when the step also needs a model, timeout, budget,
352
- or artifact override:
353
-
354
- ```yaml
355
- subagent:
356
- agent: reviewer
357
- context: fresh
358
- timeoutMs: 600000
359
- ```
360
-
361
- Pi Workflows passes `subagent.agent` directly to Pi Subagents. Built-in profiles
362
- such as `scout`, `planner`, `worker`, and `reviewer` therefore retain their own
363
- system prompts, models, and specialty defaults. The bundled
364
- `pi-workflows.step` profile remains the default general-purpose profile when
365
- `agent` is omitted.
366
-
367
- Every delegated request sets `context: fresh`, `output: false`, an
368
- `outputSchema` for the workflow result, and `agentContract: { version: 1 }`.
369
- Pi Subagents supplies `structured_output`, validates the schema, and emits the
370
- single correlated terminal response. Pi Workflows' child policy independently
371
- validates the declared outcome and compact handoff before the parent advances.
372
- Request-level model, timeout, turn-budget, tool-budget, skills, and artifact
373
- options are still forwarded. Use `/subagents-models <agent>` to inspect the
374
- selected profile and `/subagents-doctor` to diagnose discovery or loading
375
- problems. Workflow project trust and permission ceilings remain separately
376
- configured in `~/.pi/agent/workflows/settings.yaml`.
377
-
378
- Supported fields:
379
-
380
- | Field | Default | Description |
381
- | ------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
382
- | `agent` | `pi-workflows.step` | Actual Pi Subagents profile, such as `scout`, `planner`, `worker`, or `reviewer`. |
383
- | `context` | `fresh` | Always isolated; parent and sibling transcripts are never inherited. |
384
- | `model` | Profile/default model | Optional pi-subagents model override for the selected profile. |
385
- | `timeoutMs` | `900000` | Child deadline, from 1 second through 24 hours. |
386
- | `turnBudget` | pi-subagents default | `{ "maxTurns": n, "graceTurns": n }`. |
387
- | `toolBudget` | pi-subagents default | `{ "soft": n, "hard": n, "block": "*" }`; `block` may instead be a tool-name array. |
388
- | `artifacts` | `false` | Ask pi-subagents to retain its normal run artifacts. |
389
- | `retryToolFailures` | `false` | Authorize the bounded automatic recovery sequence in allow-list or unrestricted Bash mode; every failed attempt still needs a complete audit proving that its actual calls were mutation-safe. |
390
-
391
- Pi Workflows installs an inert listener in every Pi Subagents child and
392
- activates policy only after a valid, single-use workflow capability arrives, so
393
- ordinary subagent runs remain unchanged. Delegated completion uses the
394
- `structured_output` tool provided by Pi Subagents; `workflow_complete_step`
395
- remains the completion tool only for main-agent steps.
396
-
397
- After capability verification, Pi Workflows resolves the step permissions
398
- against every tool registered in the child and activates only that exact set,
399
- plus the upstream structured completion tool. The selected profile's ordinary
400
- active-tool allow-list is not a second workflow policy. Profile extension
401
- loading still controls which extension providers exist in the child; a workflow
402
- cannot activate a tool whose provider was not loaded.
403
-
404
- Workflow `permissions.skills` is sent as Pi Subagents' request-level skill
405
- selection, so it replaces the selected profile's normal skill list for that
406
- step; an empty list disables injected skills. `output: false` prevents a
407
- profile-default output file, while omitting acceptance under agent contract v1
408
- avoids a second acceptance gate. The schema, harness, declared outcomes, and
409
- optional human review gate own correlated completion.
410
-
411
- At runtime:
412
-
413
- 1. The harness creates a correlated child policy and result channel.
414
- 2. pi-subagents starts one foreground child using the step's configured agent profile.
415
- 3. The child runtime activates the workflow-permitted registered tools and validates `structured_output`.
416
- 4. The parent waits for the correlated terminal response, applies the transition, and launches the next fresh-context step.
417
-
418
- Main-agent mode uses the same per-step tool, MCP, Bash, extension-tool, and
419
- completion enforcement, but it cannot unload globally visible skills or
420
- extension event handlers from the parent process. Use pi-subagents when fresh
421
- context, skill isolation, process separation, model selection, or turn/tool
422
- budgets matter.
423
-
424
- ### Per-step permissions
425
-
426
- `tools` contains exact Pi tool names available to the active step.
427
-
428
- `mcp` contains `server` or `server/tool` selectors for the generic `mcp` proxy:
429
-
430
- ```yaml
431
- mcp:
432
- - gitlab/get_merge_request
433
- - gitlab/list_merge_request_discussions
434
- ```
435
-
436
- The harness requires an explicit `server` and `tool` on every proxy call. Proxy search, discovery, connection, and authentication modes are blocked while a workflow step is running.
437
-
438
- The generic `mcp` proxy is the portable choice for workflow steps. The bundled
439
- runtime may also expose direct MCP tools through Pi Subagents settings; Pi
440
- Workflows still requires each direct runtime name in `tools`.
441
-
442
- `extensions` contains case-insensitive fragments matched against tool source metadata. Tools registered by matching extensions become visible and callable:
443
-
444
- ```yaml
445
- extensions: [some-extension]
446
- ```
447
-
448
- The MCP adapter is excluded from this broad extension rule. Grant proxy access through `mcp`, and grant a direct MCP tool only by its exact name in `tools`.
449
-
450
- For delegated steps, `skills` states which skills pi-subagents injects into the
451
- child. In main-agent mode it documents and preflights the intended skills, but
452
- Pi cannot hide other globally loaded skill text. Put mandatory resources under
453
- `requires`:
454
-
455
- ```yaml
456
- permissions:
457
- skills: [superpowers:test-driven-development]
458
- extensions: [plannotator]
459
- requires:
460
- skills: [superpowers:test-driven-development]
461
- extensions: [plannotator]
462
- ```
463
-
464
- The harness preflights required resources, passes selected skills to
465
- pi-subagents when delegation is enabled, restricts active tools, and authorizes
466
- every model tool call. Loaded extension event handlers still execute in their
467
- process; the tool policy does not unload extension code.
468
-
469
- ### Bash modes
470
-
471
- | Mode | Behavior |
472
- | -------------- | ------------------------------------------------------------------- |
473
- | `deny` | Blocks Bash. This is the default. |
474
- | `allow-list` | Allows one executable plus user-configured argument prefixes. |
475
- | `unrestricted` | Allows any Bash command. Use only in trusted, user-owned workflows. |
476
-
477
- Allow-list mode rejects shell operators, substitutions, expansions, wrapper
478
- shells, and environment assignments before matching the declarative rule.
479
-
480
- Allow-list entries are OR alternatives. `argsPrefix` is one ordered token
481
- sequence:
482
-
483
- ```yaml
484
- mode: allow-list
485
- allow:
486
- - executable: git
487
- argsPrefix: [status]
488
- - executable: project-check
489
- argsPrefix: [test]
490
- ```
491
-
492
- This permits `project-check test --focused` but not `project-check build`.
493
-
494
- Use `argsPrefixes` to merge several alternatives for one executable without
495
- widening permission:
496
-
497
- ```yaml
498
- mode: allow-list
499
- allow:
500
- - executable: git
501
- argsPrefixes: [[status], [diff], [show, --stat]]
502
- - executable: gh
503
- argsPrefixes: [[pr, view], [pr, diff], [api]]
504
- ```
505
-
506
- The inner arrays are OR alternatives. Tokens inside one inner array are an
507
- ordered prefix. Therefore `argsPrefix: [status, diff]` means the literal
508
- sequence `git status diff`; it does not mean “status or diff.” `argsPrefix` and
509
- `argsPrefixes` are mutually exclusive in one rule. Omitting both allows that
510
- executable with any safely tokenized arguments.
511
-
512
- The engine deliberately has no package-manager, language, framework, Git, or
513
- hosted-API command knowledge. It does not rewrite command argument order and
514
- does not derive Bash authority from prompts, summaries, or gate artifacts.
515
- Command meaning and syntax belong to the step prompt and the agent's own
516
- context; executable scope belongs entirely to the YAML `allow` rules.
517
-
518
- Hard turn and tool-call budgets are best for non-mutating inspection and
519
- verification steps. For a step that edits files, use a generous timeout and no
520
- hard count budget unless partial edits are acceptable; inspect the working tree
521
- after any interruption before resuming.
522
-
523
- ## Built-in review gate
524
-
525
- Human review works without Plannotator. Omit `provider` (or set it to `prompt`)
526
- to use Pi's built-in prompt panel:
527
-
528
- ```yaml
529
- gate:
530
- submitOutcome: submit
531
- approvedOutcome: approved
532
- rejectedOutcome: changes-requested
533
- transitions:
534
- approved: implement
535
- changes-requested: $pause
536
- blocked: $pause
537
- ```
538
-
539
- When the step completes with outcome `submit`, it must include the full content
540
- in `artifact`. Pi shows Approve, Request changes, and Pause workflow. Requested
541
- changes are returned through `{{gate.feedback}}`; approval persists the
542
- artifact as `{{reviewed.artifact}}` while the step's `summary` remains the
543
- compact handoff. A requested change pauses at the same step with feedback, so
544
- revision starts only after explicit `/workflow-resume`. Dismissing the panel
545
- keeps the pending artifact, so `/workflow-resume` reopens the same review.
546
-
547
- Dialog-capable UI is available in Pi TUI and RPC modes. In print or JSON mode,
548
- the gate pauses safely until resumed in TUI or RPC.
549
-
550
- ## Works great with Plannotator
551
-
552
- [Plannotator](https://github.com/backnotprop/plannotator) gives Pi a local,
553
- browser-based surface for visually reviewing and annotating plans. It is
554
- optional, but highly recommended for rich plan feedback. Install its Pi
555
- extension alongside Pi Workflows:
556
-
557
- ```bash
558
- pi install npm:@plannotator/pi-extension
559
- ```
560
-
561
- Pi Workflows uses Plannotator's shared extension API as a human approval gate:
562
-
563
- - A workflow submits its plan or other Markdown artifact.
564
- - Plannotator opens the visual review in your browser.
565
- - Approval advances through the configured transition.
566
- - Requested changes follow the workflow's configured transition with structured
567
- feedback.
568
- - Pausing never discards a decision; resume queries the same review identifier.
569
-
570
- This keeps workflow order and permissions declarative while Plannotator handles
571
- the human review experience.
572
-
573
- ### Configure a Plannotator gate
574
-
575
- A step can submit an artifact to the installed Plannotator extension:
576
-
577
- ```yaml
578
- gate:
579
- provider: plannotator
580
- submitOutcome: submit
581
- approvedOutcome: approved
582
- rejectedOutcome: changes-requested
583
- timeoutMs: 30000
584
- transitions:
585
- approved: implement
586
- changes-requested: $pause
587
- blocked: $pause
588
- ```
589
-
590
- Setting `provider: plannotator` is the entire opt-in; do not also grant the
591
- planning child Plannotator extension tools. The harness preflights the installed
592
- extension automatically. A main-agent planning step calls
593
- `workflow_complete_step`; a delegated planning child calls
594
- `structured_output`. In either case it uses the configured submit outcome and
595
- places the review content in `artifact`. The harness correlates the Plannotator
596
- review identifier and accepts only the matching decision. On approval, the
597
- artifact is preserved as an opaque template value; the separate `summary`
598
- remains the next step's compact handoff.
599
-
600
- The artifact is never substituted for a missing summary. If an older pending
601
- gate has no separately stored summary, its transition uses an empty compact
602
- handoff.
603
-
604
- If review finishes while the workflow is paused, the result is checkpointed and applied only after `/workflow-resume`. Resume also queries Plannotator’s durable review status, so a decision made while Pi was closed is not lost.
605
-
606
- ### Artifact format belongs to the workflow
607
-
608
- Pi Workflows imposes no plan headings, acceptance-criteria layout,
609
- machine-readable appendix, command schema, or other Plannotator prompt format.
610
- The step's YAML prompt defines what the artifact means and how downstream steps
611
- use `{{reviewed.artifact}}`. Outcome names are equally opaque: names such as
612
- `approved`, `retry`, or `replan` have only the transitions and meanings the
613
- workflow author gives them.
614
-
615
- In print or JSON mode, a pending built-in plan review remains safely paused.
616
- Reopen the same session in TUI or RPC mode and run `/workflow-resume` to show
617
- the preserved review instead of restarting the planning child.
618
-
619
- ## Pause, repair, resume
620
-
621
- Use:
622
-
623
- ```text
624
- /workflow-pause <optional reason>
625
- ```
626
-
627
- The harness stops the active main-agent turn, dismisses a built-in review, or
628
- sends the versioned pi-subagents cancellation event for a delegated step. It
629
- keeps the exact current step and pending gate, then persists the checkpoint in
630
- the Pi session. A late completion cannot advance a paused, aborted,
631
- reconfigured, or replaced run.
632
-
633
- When a step itself transitions to `$pause`, the checkpoint keeps both the
634
- incoming previous-step handoff and the latest failed-attempt summary. The
635
- resumed execution sees both. The run-start directory, any accepted workspace
636
- binding, and any separately persisted reviewed artifact are preserved without
637
- being interpreted.
638
-
639
- Every settled step also posts one visible chat summary without starting another
640
- agent turn. Successful and `$pause` outcomes show only the step's validated
641
- `summary`; the final one also states that the workflow completed. Manual,
642
- restored-session, and review pauses show their concise pause reason. Runtime
643
- failures show only a short, redacted failure summary—not the task, artifact,
644
- tool transcript, or full diagnostic. Complete evidence remains available in
645
- the status explorer.
646
-
647
- For a delegated step, if child termination is not confirmed within five
648
- seconds, the pause is recorded but main tools remain isolated and resume is
649
- blocked. Wait for the terminal event; if the delegation channel has already
650
- failed, restart Pi before resuming. This prevents an old writer and a resumed
651
- writer from overlapping.
652
-
653
- When a delegated child returns `failed`, `structured_output_failed`,
654
- `timed_out`, `turn_budget_exhausted`, or `tool_budget_exhausted`, the harness
655
- audits the retained Pi child session before deciding whether to launch a fresh
656
- automatic recovery child. The audit accepts only regular, non-symlink session
657
- files contained by the current parent session's child-run root, requires the
658
- persisted policy-stripped task and its per-request binding to match the active
659
- delegation, reads a bounded complete tail, and proves that every recorded call
660
- used a known-safe non-Bash tool or was rejected by policy before execution.
661
- A zero-tool attempt is also replay-safe when the complete bound transcript
662
- proves it. Executed Bash is treated as an unknown effect; automatic recovery
663
- requires explicit authorization and still cannot claim that a domain-specific
664
- command was non-mutating.
665
-
666
- When the terminal error identifies a failed tool, the harness also records the
667
- exact correlated call, tool error, subagent exit code, terminal error, and
668
- validated diagnostic session path. If exact correlation is unavailable, the
669
- generic terminal evidence is retained without claiming an unrelated command.
670
- A failed process status is treated as resolved when the transcript proves a
671
- successful `structured_output` occurred after every failed tool result and the
672
- correlated result validates. This accepts the same finalized child result; it
673
- never replays mutation-capable work.
674
-
675
- Without a valid finalized result, the next fresh child receives the bounded
676
- history of distinct terminal evidence in an escaped JSON data boundary and is
677
- told to inspect current state, change its approach, resolve the cause, and
678
- finish the original step. The harness launches at most two automatic recovery
679
- children and stops early when the semantic failure fingerprint repeats.
680
- Availability of `edit` or `write` is not itself a veto: the complete audit must
681
- prove that the failed attempt did not actually make or attempt a mutation.
682
- Mutation-capable or unknown-effect calls, reported file mutation, a truncated or
683
- malformed transcript, a missing active-request binding, cancellation,
684
- interruption, detached or stopped execution, and protocol/configuration errors
685
- remain hard stops. Local channel failures also wait for confirmed child
686
- termination instead of risking two live children.
687
-
688
- Temporary delegation-workspace removal is best-effort housekeeping. A cleanup
689
- error produces a warning but cannot pause an otherwise healthy next step or
690
- recovery child. Synchronous startup exceptions are contained by the serialized
691
- failure path. Each recovery uses a new request identity, private result
692
- capability, and fresh context. The fixed two-attempt bound means a failing step
693
- can consume at most three times its per-child timeout, turn budget, and tool
694
- budget.
695
-
696
- Inside a live child, recovery is not tied to a list of known error strings. The
697
- agent receives the exact error and current state, then follows the user-authored
698
- step prompt and configured outcomes. The engine does not assign a recovery,
699
- pause, or replanning meaning to any outcome name.
700
-
701
- While paused, fix repository code, workflow YAML, prompts, MCP configuration,
702
- an extension, or any other environmental problem. Then run:
703
-
704
- ```text
705
- /workflow-resume inspect the existing partial output before retrying
706
- ```
707
-
708
- Resume reloads configuration before continuing:
709
-
710
- - Optional text after `/workflow-resume` is passed as a user-authored
711
- task-level amendment for this attempt. It may supersede conflicting prompt or
712
- handoff instructions, but never YAML-enforced resource or workspace policy.
713
- - The paused step restarts in its configured main-agent or delegated mode.
714
- - A changed current step restarts that step.
715
- - A changed ordinary completed step restarts the earliest changed completed step.
716
- - A completed human-approved gate keeps its opaque reviewed artifact; later prompt or configuration digest changes do not reopen that gate while its configuration and approved outcome still match.
717
- - Future-only changes preserve the current checkpoint.
718
- - Removing the current or a completed step fails closed and requires restoring configuration or aborting.
719
- - Restoring a Pi session automatically pauses an in-progress workflow for inspection.
720
- - A pending built-in prompt review reopens with the same artifact.
721
- - An interrupted Plannotator submission without a review identifier restarts the current step for resubmission.
722
-
723
- ## Commands
724
-
725
- The full status overlay is an on-demand verification and history page. Toggle
726
- it with `Ctrl+Alt+W` by default (`q` or `Esc` hides the board). Set
727
- `statusShortcut` in `settings.yaml` to another Pi key identifier, then run Pi's
728
- `/reload` to re-register it; `/workflow-reload` cannot change extension
729
- shortcuts. The overlay shows run timing, execution or review, pause reasons,
730
- configuration drift, and the completed attempt path without a task-viewer pane
731
- below the editor. The main surface shows only one small animated
732
- `◐`/`◓`/`◑`/`◒` working
733
- indicator followed by the workflow id and current step title/id while a
734
- workflow runs, then clears it when execution stops. This makes live progress
735
- visible without opening the status page. All attempt logs, history, failure,
736
- and review detail stays in the overlay. There, `✓` marks a completed step, `✕`
737
- a failed or aborted run, and `◆` a paused step or pending review.
738
-
739
- Use `↑`/`↓` or `j`/`k` to select a step, then `Enter`, `→`, or `l` to inspect
740
- the bounded task supplied to each attempt, its result and gate decision, and a
741
- chronological execution log when available. In the detail view,
742
- `↑`/`↓` or `j`/`k` scrolls; `←`, `h`, or `Esc` returns to the board; `q` or the
743
- configured shortcut closes it. PgUp/PgDn and Home/End retain page navigation.
744
- Trace references and bounded task/result evidence live in the checkpoint, so
745
- completed, paused, resumed, and restored runs remain inspectable. Child logs
746
- are path-confined, size-bounded, control-sanitized, and redact common
747
- credential forms.
748
- For new main-agent attempts, the extension arms only on the exact workflow
749
- task and checkpoints a redacted, size-bounded prefix of finalized assistant
750
- and tool events in source order. This log remains part of the parent session,
751
- but the explorer never reads unrelated parent-session traffic. Legacy
752
- checkpoints without a main-agent log still show their bounded task and result.
753
- Long reasons are clamped to the display width while the durable checkpoint
754
- retains the full reason.
755
-
756
- | Command | Purpose |
757
- | ------------------------------- | --------------------------------------------------------- |
758
- | `/workflow-list` | List loaded workflows and their configured commands. |
759
- | `/workflow-doctor [id]` | Diagnose completion paths, unreachable steps, and cycles. |
760
- | `/workflow-start <id> [input]` | Start by workflow identifier. |
761
- | `/<configured-command> [input]` | Start through a workflow alias. |
762
- | `/workflow-pause [reason]` | Halt without losing the checkpoint. |
763
- | `/workflow-resume [guidance]` | Reload, reconcile, and continue with an optional hint. |
764
- | `/workflow-abort [reason]` | End the active run and restore baseline tools. |
765
- | `/workflow-reload` | Reload definitions while no workflow is running. |
766
-
767
- Before a workflow starts or resumes, the doctor rejects graphs whose start
768
- cannot reach `$done` or whose reachable branches contain a step that cannot
769
- reach `$done`.
770
- Unreachable steps and cycles are reported as warnings; a cycle with an exit may
771
- run, but `maxStepVisits` pauses the uninterrupted run before a step can execute
772
- more than its configured limit. An explicit resume can continue from that
773
- checkpoint, so the guard bounds automatic graph advancement rather than
774
- guaranteeing completion or wall-clock duration.
775
-
776
- Configured aliases also accept multiline input. For example, if `work` is a
777
- loaded workflow command, Pi Workflows normalizes:
778
-
779
- ```text
780
- /work
781
- """inspect and update this repository"""
782
- ```
783
-
784
- to the same command with an argument instead of letting the raw multiline text
785
- start an unrelated parent-agent turn.
786
-
787
- ## User and project configuration
788
-
789
- User workflows are loaded first. A project may add workflows from:
790
-
791
- ```text
792
- <project>/.pi/workflows/*.workflow.yaml
793
- <project>/.pi/workflows/*.workflow.yml
794
- ```
795
-
796
- Project workflows are disabled by default. Enable them in the user-owned
797
- `~/.pi/agent/workflows/settings.yaml`:
798
-
799
- ```yaml
800
- # yaml-language-server: $schema=/absolute/path/to/pi-workflows/schemas/settings.schema.json
801
- version: 1
802
- allowProjectWorkflows: true
803
- statusShortcut: ctrl+alt+w
804
- permissionCeiling:
805
- tools: [read, grep, bash]
806
- mcp: []
807
- extensions: []
808
- skills: []
809
- bash:
810
- mode: allow-list
811
- allow:
812
- - executable: git
813
- argsPrefixes: [[status], [diff]]
814
- - executable: rg
815
- subagent:
816
- agents: [scout, planner, worker, reviewer]
817
- contexts: [fresh]
818
- models: []
819
- maxTimeoutMs: 900000
820
- maxTurns: 40
821
- maxGraceTurns: 3
822
- maxToolCalls: 100
823
- artifacts: false
824
- retryToolFailures: false
825
- ```
826
-
827
- Settings use the same strict YAML 1.2 parser as workflow definitions. The
828
- `settings.schema.json` file remains JSON Schema so YAML-aware editors can
829
- validate `settings.yaml`; adjust or remove the schema comment for your install
830
- path.
831
-
832
- Project workflows load only when Pi trusts the project and every step stays
833
- within this ceiling. The `subagent` ceiling is optional for main-only project
834
- workflows; if omitted, any project step that declares `subagent` is rejected.
835
- Project workflows cannot declare `workspace` binding at all, even when their
836
- other permissions fit the ceiling. Keep workflows that create, choose, or bind
837
- a different execution directory in the user-owned workflow directory.
838
- Each delegated project step must declare `turnBudget` and `toolBudget` with
839
- `"block": "*"`, so it cannot silently inherit unbounded child defaults or keep
840
- mutation tools after reaching the hard limit. The ceiling also controls
841
- agent profile names, fresh-context use, model overrides, timeouts, artifact
842
- retention, and the Bash rules that a project workflow may request. Project
843
- workflows cannot override user workflow identifiers or commands.
844
-
845
- ## Architecture
846
-
847
- The package keeps the Pi entry point intentionally small:
848
-
849
- | Module | Responsibility |
850
- | --------------------------------- | --------------------------------------------------------------- |
851
- | `src/index.ts` | Pi entry point only. |
852
- | `src/harness.ts` | Runtime orchestration and session lifecycle. |
853
- | `src/commands.ts` | User command surface. |
854
- | `src/config/` | Types, strict validation, prompt loading, precedence, ceilings. |
855
- | `src/engine/` | Serializable run state and deterministic transitions. |
856
- | `src/policy/` | Tool, MCP, and Bash enforcement. |
857
- | `src/workflow-doctor.ts` | Deterministic transition-graph liveness diagnostics. |
858
- | `src/integrations/subagents/` | Delegation client, child protocol, and child policy runtime. |
859
- | `src/integrations/plannotator.ts` | Versioned Plannotator gate adapter. |
860
- | `src/integrations/prompt-gate.ts` | Built-in Pi prompt review adapter. |
861
- | `src/runtime/` | Shared completion parsing and main-agent step runtime. |
862
- | `src/preflight.ts` | Required tool, extension, and skill checks. |
863
- | `src/prompt.ts` | Template rendering and step contract. |
864
- | `agents/step.md` | Default general-purpose profile plus workflow child guidance. |
865
-
866
- The engine and policy modules do not depend on Pi runtime types, so they are fast to test.
867
-
868
- ## Security model
869
-
870
- Pi extensions are not an operating-system sandbox. Installed extensions execute with the user’s process permissions.
871
-
872
- The harness provides model-level least privilege in both execution modes, plus
873
- process separation when a step opts into pi-subagents:
874
-
875
- - active-tool narrowing for every step;
876
- - authoritative `tool_call` blocking and immutable authorized arguments;
877
- - completion as the sole call in its tool batch;
878
- - optional separate pi-subagents child process per delegated step;
879
- - an idle, tool-isolated main agent while a delegated step runs;
880
- - a single-use, parent-created child capability tied to the delegated step;
881
- - explicit MCP server and tool checks;
882
- - restricted Bash parsing;
883
- - exact user-declared Bash executable and argument-prefix rules;
884
- - project trust and a user-owned permission ceiling;
885
- - fail-closed durable state, correlated child results, and correlated gate results.
886
-
887
- It does not restrict commands the human explicitly runs with Pi’s `!` Bash
888
- input. In main-agent mode it cannot hide globally loaded skills or isolate the
889
- transcript. In either mode it cannot disable side effects performed
890
- autonomously by a loaded extension. Review workflow, agent, and extension
891
- source before installing or enabling it.
892
-
893
- Step completion is structurally validated—policy digest, declared outcome,
894
- non-empty bounded summary, required gate artifact, and sole completion call—but
895
- the harness cannot prove that a model's semantic claims or test evidence are
896
- true. Put exact checks and acceptance criteria in the workflow prompt, use an
897
- independent verification step, and keep consequential actions behind a human
898
- gate.
899
-
900
- The harness does not provide exactly-once external effects. If a publish step
901
- is interrupted after a remote action succeeds but before it checkpoints, a
902
- resumed execution receives the same declarative step permissions. Publish
903
- prompts should query the remote effect first, skip only proven-complete actions,
904
- and pause on ambiguous state.
905
-
906
- ## Development
907
-
908
- ```bash
909
- bun install
910
- bun run check
911
- ```
912
-
913
- Tests cover graph validation, prompt confinement, command conflicts, project
914
- ceilings, deterministic transitions, configuration reconciliation, pause/resume
915
- state, gate handling, MCP isolation, Bash policy, extension tool selection,
916
- main-agent completion, built-in feedback/approval, subagent request correlation
917
- and cancellation, child policy enforcement, and dependency preflight,
918
- including bounded automatic recovery after replay-safe terminal errors,
919
- timeouts, budget exhaustion, and nonzero exits; duplicate-failure stopping;
920
- opaque gate artifacts; workspace binding and cwd reuse; workflow liveness
921
- diagnostics; and fail-closed legacy checkpoints.
922
- `bun run check` also launches real Pi RPC subprocesses, invokes
923
- `/work`, and verifies fresh `scout`, `worker`, and `reviewer` children receive
924
- only the explicit compact handoff from the immediately preceding step. The
925
- real-Pi scenario binds a sibling workspace, revisits its worker once, and
926
- verifies that every downstream visit keeps the bound cwd and receives no
927
- undeclared `replan` outcome.
928
-
929
- ## Publishing checklist
930
-
931
- Before publishing:
932
-
933
- 1. Confirm the package name and repository metadata.
934
- 2. Run `bun run check`.
935
- 3. Merge a Conventional Commit PR and verify its GitHub Release artifact.
3
+ # Pi Workflows
936
4
 
937
- The `pi-package` keyword makes the package discoverable by the Pi package gallery.
5
+ **Make repeatable Pi agent work explicit, durable, and safe to continue.**
938
6
 
939
- ## Good next parameters
7
+ Pi Workflows is a declarative, pauseable workflow harness for Pi. Define steps,
8
+ tools, prompts, approvals, and outcomes in YAML; it provides bounded execution,
9
+ durable checkpoints, isolated subagent work, and a live status view without
10
+ dictating your language, framework, or delivery process.
940
11
 
941
- The current schema covers the execution harness requested here. Useful future
942
- extensions, without hard-coding them into the orchestrator, are:
12
+ ## Why Pi Workflows
943
13
 
944
- | Parameter | Why it belongs in configuration |
945
- | --------------------------------- | -------------------------------------------------------------------------------------------------- |
946
- | Configurable recovery and backoff | Replace the fixed two-attempt recovery cap with a ceiling-aware per-step transient-failure policy. |
947
- | Acceptance criteria | Give each step machine-checkable completion evidence and verification commands. |
948
- | Parallel groups and join policy | Run independent steps together and declare fail-fast, quorum, or all-success behavior. |
949
- | Generic gates | Add ticket, CI, chat, or custom approval providers behind the same versioned gate contract. |
950
- | Output schema and named artifacts | Pass structured data between steps instead of relying only on a summary. |
951
- | Cost and token ceilings | Bound model spend independently from turn and tool-call budgets. |
952
- | Environment and secret references | Select named credentials without embedding secret values in workflow files. |
953
- | Logging and retention | Configure progress events, redaction, child artifact retention, and checkpoint history. |
14
+ - Turn multi-step agent work into clear, reviewable workflow definitions.
15
+ - Pause for human approval and resume from the same durable checkpoint.
16
+ - Keep worktree-bound iterations safe, including follow-up enhancements.
17
+ - Enforce declared resources and stop unsafe loops before they run away.
954
18
 
955
- ## Current limits
19
+ ## Explore
956
20
 
957
- - A delegated workflow step uses one foreground subagent. Parallel or chained children inside one step are not yet a workflow-level primitive.
958
- - Gate providers are built-in prompt and Plannotator; custom providers are not yet configurable.
959
- - Delegated steps require pi-subagents 0.36.0 or newer and launch the actual profile selected by `subagent.agent`.
960
- - Extension tools are enforced; autonomous extension event-handler side effects cannot be disabled per step.
961
- - Completion evidence is model-reported; use declarative executable checks and a fresh verification step when correctness matters.
962
- - Workflow configuration uses YAML. Prompt bodies may live in separate Markdown files.
21
+ - [Getting started guide](./GETTING_STARTED.md) install Pi Workflows and
22
+ run your first workflow.
23
+ - [Contribution guide](./CONTRIBUTING.md) set up the project, validate a
24
+ change, and open a focused pull request.
25
+ - [Documentation OpenWiki](./openwiki/quickstart.md) architecture,
26
+ workflow authoring, security, integrations, and development references.
963
27
 
964
28
  ## License
965
29
 
966
- Licensed under the [MIT License](./LICENSE).
30
+ [MIT](./LICENSE)