@narumitw/pi-goal 0.52.2 → 0.53.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.
package/README.md CHANGED
@@ -1,39 +1,22 @@
1
- # 🎯 pi-goal — Goal Mode for the Pi Coding Agent
1
+ # 🎯 pi-goal — Keep Pi Working Toward a Goal
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@narumitw/pi-goal)](https://www.npmjs.com/package/@narumitw/pi-goal) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
4
 
5
- `@narumitw/pi-goal` is a native [Pi coding agent](https://pi.dev) extension that adds session-scoped `/goal` commands, a `goal_complete({ goal_id, summary })` completion tool, a strict `goal_blocked({ goal_id, reason, evidence, repeated_turns })` impasse tool, and a `goal_wait({ goal_id, reason, resume_after_ms? })` tool for external-event waits.
5
+ Give Pi a session-scoped objective and let it continue from each fully settled idle boundary until the work completes, pauses, waits, or reaches a safety limit.
6
6
 
7
- Goal mode uses Codex-like persistence instructions and sends guarded continuation messages from Pi's fully settled idle boundary until the agent completes the goal, explicitly waits for an external event, the user pauses or clears it, a safety circuit breaker trips, a true blocker or provider usage limit stops it, or an optional token budget is reached.
7
+ Goal mode adds explicit completion, blocker, and external-wait tools so managed execution stops for a clear reason instead of looping blindly.
8
8
 
9
9
  ## ✨ Features
10
10
 
11
- - Adds `/goal <goal_to_complete>` to start goal mode, with confirmation before replacing an existing goal.
12
- - Bare `/goal` opens a standard current-state manager in the TUI, with guided start, pause,
13
- resume, edit, settings, status, help, and destructive-action confirmation; RPC mode retains
14
- observable status notifications.
15
- - Keeps direct goal management available through `/goal` subcommands: `status`, `pause`, `resume`, `clear`, and `edit`.
16
- - Exposes only one top-level command: `/goal`.
17
- - Pauses automatic work after 25 Goal-owned model responses by default, preserves progress, and provides a guided review-and-continue flow; custom finite limits and confirmed Unlimited mode remain available.
18
- - Pauses after three consecutive empty or normalized-identical tool-free automatic runs, while distinct short output and tool activity reset the repeat detector.
19
- - Supports optional token budgets such as `/goal --tokens 100k <goal>`, using provider-reported total-token accounting with a cache-inclusive compatibility fallback.
20
- - Tracks distinct `active`, `paused`, `blocked`, `usage_limited`, `budget_limited`, and `complete` states.
21
- - Stores goal state in the current Pi session, following Codex's thread-owned goal model instead of using a global per-directory goal.
22
- - Registers a `goal_complete({ goal_id, summary })` tool for explicit completion, requiring the current goal id and rejecting missing/stale ids plus plainly contradictory summaries such as “not complete” or “tests still fail”.
23
- - Registers `goal_blocked({ goal_id, reason, evidence, repeated_turns })` for true impasses only; it requires the current goal id, concrete evidence, and the same blocker recurring for at least three consecutive goal turns.
24
- - Registers `goal_wait({ goal_id, reason, resume_after_ms? })` for an active Goal that has arranged an external wake message; waiting suppresses automatic continuation while preserving the objective, accounting, and managed-run ownership.
25
- - Starts all three Goal tools inactive by default, reveals them for the first accepted `/goal` activation or an unfinished-goal restore, and keeps them desired for the rest of that extension runtime without overriding a restrictive restore policy. Optional `"always"` visibility keeps them active from session startup.
26
- - Records continuation intent, then triggers exactly one next turn only after Pi reports the agent fully settled, idle, and free of pending messages; an explicit wait remains quiet until non-Goal work or its optional deadline wakes it, and missing terminal tools still pause before another model turn.
27
- - Lets retry, compaction, steering, follow-up, and other queued work settle before automatic goal continuation.
28
- - Separates user interruption (`paused`), true impasse or terminal non-usage error (`blocked`), provider/account quota exhaustion (`usage_limited`), and user token budget exhaustion (`budget_limited`).
29
- - Detects budget exhaustion after completed tool activity when assistant usage is persisted, then injects at most one non-user-authored wrap-up instruction and blocks further substantive tools.
30
- - Keeps retryable provider interruptions and Pi compaction retries active without enqueueing duplicate goal continuations while Pi retries, then marks a matching unresolved error `blocked` only when `agent_settled` proves no retry, compaction, or follow-up remains.
31
- - Preserves active goals across manual, threshold, and overflow compaction.
32
- - Guards auto-follow-ups and Goal-owned kickoff deliveries so duplicate, replaced, stopped, cleared, completed, budget-limited, or stale prompts cannot continue or overwrite a newer goal.
33
- - Rotates the completion guard id when a goal is resumed or edited so delayed old turns cannot complete the newer goal instance.
34
- - Blocks stale tool calls after in-flight work pauses, blocks, or reaches a usage limit, until fresh non-goal user work, successful reactivation/replacement, or clear.
35
- - Applies one evidence-based completion audit across kickoff, resume, edit, system, continuation, and budget-wrap-up prompts.
36
- - Optionally exposes a default-off, run-scoped `pi.events` protocol for trusted sibling extensions to start, observe, and cancel one Goal lifecycle without emulating `/goal` input.
11
+ - Starts or manages a session goal through one `/goal` command and direct status, pause, resume, edit, or clear routes.
12
+ - Continues exactly once from Pi's settled idle boundary after queued work, retries, and compaction have finished.
13
+ - Uses explicit `goal_complete`, `goal_blocked`, and `goal_wait` tools with stale-goal guards and evidence requirements.
14
+ - Tracks active, paused, blocked, usage-limited, budget-limited, waiting, and complete outcomes separately.
15
+ - Pauses after a configurable response limit or repeated no-progress runs and offers a guided review before continuing.
16
+ - Supports optional token budgets that stop Goal-owned work immediately when exhausted.
17
+ - Persists the goal in the current session across reload, resume, compatible forks, and compaction.
18
+ - Rejects stale continuations and tool calls after replacement, pause, completion, limits, or other terminal state changes.
19
+ - Optionally exposes a default-off run protocol for trusted sibling extensions to start, observe, and cancel one Goal lifecycle.
37
20
 
38
21
  ## 📦 Install
39
22
 
@@ -49,20 +32,24 @@ Try without installing permanently:
49
32
  pi -e npm:@narumitw/pi-goal
50
33
  ```
51
34
 
52
- Try this package locally from the repository root:
35
+ Build and try this package locally from the repository root:
53
36
 
54
37
  ```bash
38
+ npm --workspace @narumitw/pi-goal run build
55
39
  pi -e ./packages/pi-goal
56
40
  ```
57
41
 
58
- The package declares `dist/index.ts`, so an unbuilt local checkout must run `npm --workspace @narumitw/pi-goal run build` before Pi loads the package directory.
42
+ The package declares `dist/index.ts`, so an unbuilt local checkout must run the build before Pi loads the package directory.
59
43
 
60
- `just try goal` runs that build automatically.
44
+ ## 🚀 Quick start
61
45
 
62
- ## ⚙️ Configuration
46
+ Run `/goal <objective>` to start working toward an objective, or run `/goal` to open the state-aware manager.
47
+ Use the manager to review status, pause, resume, edit, or clear the current goal.
63
48
 
64
- Settings are optional. When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these
65
- built-in defaults without creating the file:
49
+ ## ⚙️ Settings
50
+
51
+ Settings are optional.
52
+ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults without creating the file:
66
53
 
67
54
  ```json
68
55
  {
@@ -77,40 +64,105 @@ built-in defaults without creating the file:
77
64
  }
78
65
  ```
79
66
 
80
- Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create
81
- and edit it directly. The standard Settings screen keeps all four controls on one level in task
82
- order; the two safety limits open standard choice screens:
67
+ Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create and edit it directly.
68
+ The standard Settings screen keeps all four controls on one level in task order; the two safety limits open standard choice screens:
83
69
 
84
- - **Automatic-work limit** shows the exact response limit or **Unlimited**. Choose **Set response limit…** to edit the current finite value (or the built-in default of 25 when switching from Unlimited), or choose **Unlimited…**. Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
85
- - **No-progress guard** shows **_N_ runs** or **Off**. Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
70
+ - **Automatic-work limit** shows the exact response limit or **Unlimited**.
71
+ Choose **Set response limit…** to edit the current finite value (or the built-in default of 25 when switching from Unlimited), or choose **Unlimited…**.
72
+ Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
73
+ - **No-progress guard** shows **_N_ runs** or **Off**.
74
+ Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
86
75
  - **Goal tools** controls whether all Goal tools are always visible or appear after the first goal.
87
- - **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs. It defaults to **Off** and is a cooperation setting, not an extension security sandbox.
76
+ - **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
77
+ It defaults to **Off** and is a cooperation setting, not an extension security sandbox.
88
78
 
89
- Custom number inputs reject zero, negative numbers, decimals, text, and unsafe integers without saving; use the explicit **Unlimited** or **Off** choice instead. Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime. A successful change updates the visible state immediately. A failed save restores the prior value and reports the settings path so it can be retried. Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy; retry after Pi settles. Escape returns to the previous screen without reverting changes that were already saved.
79
+ Custom number inputs reject zero, negative numbers, decimals, text, and unsafe integers without saving; use the explicit **Unlimited** or **Off** choice instead.
80
+ Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime.
81
+ A successful change updates the visible state immediately.
82
+ A failed save restores the prior value and reports the settings path so it can be retried.
83
+ Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy or another cooperative workflow owns the session; retry after both conditions clear.
84
+ Escape returns to the previous screen without reverting changes that were already saved.
90
85
 
91
86
  `toolVisibility` accepts:
92
87
 
93
88
  - `"always"` — pi-goal does not proactively hide `goal_complete`, `goal_blocked`, or `goal_wait`, keeping the Goal tool schema stable from session startup.
94
- - `"after-first-goal"` (default) — hides all three Goal tools at fresh runtime startup, reveals them for the first accepted Goal activation, and treats an unfinished-goal restore as unlocked for the remainder of that extension runtime. On restore, pi-goal uses the active tools already established by earlier lifecycle handlers; it does not re-add missing terminal tools over a restrictive policy. Failed kickoff, replacement, resume, or reactivating-edit delivery restores the exact pre-activation tool set, including Goal tools exposed by another extension. If revealing the tools would widen an already-running turn, wait for Pi to become idle and retry `/goal`.
89
+ - `"after-first-goal"` (default) — hides all three Goal tools at fresh runtime startup, reveals them for the first accepted Goal activation, and treats an unfinished-goal restore as unlocked for the remainder of that extension runtime.
90
+ On restore, pi-goal uses the active tools already established by earlier lifecycle handlers; it does not re-add missing terminal tools over a restrictive policy.
91
+ Failed kickoff, replacement, resume, or reactivating-edit delivery restores the exact pre-activation tool set, including Goal tools exposed by another extension.
92
+ If revealing the tools would widen an already-running turn, wait for Pi to become idle and retry `/goal`.
95
93
 
96
- `experimental.goals` is a removed legacy setting. If it remains `true`, pi-goal accepts the settings file, ignores the old queue feature, and shows an affected-user warning that recommends `/goal edit` when an active objective exists or `/goal <objectives>` when no active goal exists. Later settings saves preserve unknown legacy fields instead of deleting them.
94
+ `experimental.goals` is a removed legacy setting.
95
+ If it remains `true`, pi-goal accepts the settings file, ignores the old queue feature, and shows an affected-user warning that recommends `/goal edit` when an active objective exists or `/goal <objectives>` when no active goal exists.
96
+ Later settings saves preserve unknown legacy fields instead of deleting them.
97
97
 
98
- `rpc.enabled` accepts a boolean and defaults to `false`. When disabled, a valid managed-run start receives `RPC_DISABLED`; manual and restored Goals remain unchanged. A Settings-menu change applies immediately after its atomic save. Disabling rejects new starts but lets an already accepted run continue publishing its exact state and accept its exact cancellation until terminal, avoiding stranded work. Reload, replacement, and shutdown clear that in-memory ownership.
98
+ `rpc.enabled` accepts a boolean and defaults to `false`.
99
+ When disabled, a valid managed-run start receives `RPC_DISABLED`; manual and restored Goals remain unchanged.
100
+ A Settings-menu change applies immediately after its atomic save.
101
+ Disabling rejects new starts but lets an already accepted run continue publishing its exact state and accept its exact cancellation until terminal, avoiding stranded work.
102
+ Reload, replacement, and shutdown clear that in-memory ownership.
99
103
 
100
104
  `continuationLimits` controls the runaway guards:
101
105
 
102
- - `automaticTurns` accepts a positive safe integer or `null` and defaults to `25`. It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries. The user-triggered kickoff, resume, edit, and ordinary user runs are not charged. At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted before a 26th normal response starts. Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work. Set this field explicitly to `null` to opt into Unlimited mode; existing explicit `null` values remain compatible.
103
- - `noProgressTurns` is a positive safe integer and defaults to `3`. At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercasing, control-character removal, and whitespace collapse. Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent. Consecutive empty or identical tool-free outputs increment the repeat count. Different non-empty output starts a new run at one, and any attempted tool call resets it. Set this field to `null` to disable only this heuristic.
104
-
105
- Settings are reread at Pi startup, session replacement, and `/reload`; direct external file edits are not watched live, while changes made through the Goal menu apply immediately. A missing file remains absent and uses the built-in defaults. The first successful settings change creates the file atomically; later saves preserve unknown fields.
106
-
107
- Omitted fields use the defaults above. Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults. In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and directs the user to fix it and run `/reload`. Reload Pi after changing the file. If a live runtime reloads settings, switching `toolVisibility` to `"always"`
108
- restores only the exact tools that pi-goal previously hid, while switching to
109
- `"after-first-goal"` locks a runtime that has no unfinished goal.
110
-
111
- Tool visibility is a baseline, not ownership of Pi's global active-tool list. Plan mode or another restrictive policy may temporarily hide the tools. pi-goal does not fight that policy on restore or on every turn: activation is rejected if the required terminal tools cannot be made available, and an already-active goal is paused without automatic continuation if they disappear. A restrictive allowlist created before `goal_wait` existed can still run ordinary Goals with `goal_complete` and `goal_blocked`, but the model cannot enter external waiting until that allowlist also includes `goal_wait`. The pause aborts a Goal-owned kickoff, resume, active-edit, or automatic-continuation prompt, but it does not cancel or stale-block an unrelated user or extension turn, including startup follow-ups after a restrictive restore.
112
-
113
- ## 🚀 Commands
106
+ - `automaticTurns` accepts a positive safe integer or `null` and defaults to `25`.
107
+ It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries.
108
+ The user-triggered kickoff, resume, edit, and ordinary user runs are not charged.
109
+ At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted before a 26th normal response starts.
110
+ Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work.
111
+ Set this field explicitly to `null` to opt into Unlimited mode; existing explicit `null` values remain compatible.
112
+ - `noProgressTurns` is a positive safe integer and defaults to `3`.
113
+ At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercasing, control-character removal, and whitespace collapse.
114
+ Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent.
115
+ Consecutive empty or identical tool-free outputs increment the repeat count.
116
+ Different non-empty output starts a new run at one, and any attempted tool call resets it.
117
+ Set this field to `null` to disable only this heuristic.
118
+
119
+ Settings are reread at Pi startup, session replacement, and `/reload`; direct external file edits are not watched live, while changes made through the Goal menu apply immediately.
120
+ A missing file remains absent and uses the built-in defaults.
121
+ The first successful settings change creates the file atomically; later saves preserve unknown fields.
122
+
123
+ Omitted fields use the defaults above.
124
+ Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults.
125
+ In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and directs the user to fix it and run `/reload`.
126
+ Reload Pi after changing the file.
127
+ If a live runtime reloads settings, switching `toolVisibility` to `"always"` restores only the exact tools that pi-goal previously hid, while switching to `"after-first-goal"` locks a runtime that has no unfinished goal.
128
+
129
+ Inactive tool widening first takes temporary Workflow Mutex ownership and leaves settings, hidden-tool ownership, and active tools unchanged when another workflow is active.
130
+ Tool visibility is a baseline, not ownership of Pi's global active-tool list.
131
+ Plan mode or another restrictive policy may temporarily hide the tools. pi-goal does not fight that policy on restore or on every turn: activation is rejected if the required terminal tools cannot be made available, and an already-active goal is paused without automatic continuation if they disappear.
132
+ A restrictive allowlist created before `goal_wait` existed can still run ordinary Goals with `goal_complete` and `goal_blocked`, but the model cannot enter external waiting until that allowlist also includes `goal_wait`.
133
+ The pause aborts a Goal-owned kickoff, resume, active-edit, or automatic-continuation prompt, but it does not cancel or stale-block an unrelated user or extension turn, including startup follow-ups after a restrictive restore.
134
+
135
+ ## 🤝 Workflow coexistence
136
+
137
+ Goal is independently installable and keeps its standalone behavior when no other protocol participant is present.
138
+ On the characterized Pi `0.84.2` runtime, it participates in the anonymous `workflow:mutex:v1` `agent-workflow` group.
139
+ An active Goal holds the group through ordinary work, external waiting, continuation delivery, compaction recovery, and provider retry.
140
+ Paused, blocked, usage-limited, budget-limited, complete, cleared, and legacy-queue-only states do not hold it.
141
+
142
+ Direct starts, menu starts, managed-run starts, stopped resumes, and stopped-goal edits use one final synchronous admission after validation and confirmation but before tool, Goal-state, persistence, prompt, queue, or status mutation.
143
+ Replacing or editing an already active or waiting Goal retains its current owner.
144
+ If admission is busy, TUI and RPC show an anonymous warning, print and JSON direct routes throw before mutation, and managed-run RPC emits one terminal `ACTIVATION_FAILED` event without creating a Goal.
145
+
146
+ Restored active Goal state acquires before tool restoration, persistence publication, status, wait timers, retry state, or continuation work.
147
+ If restoration is busy, the Goal moves only to its existing paused safe state, does not change active tools or schedule work, and can be resumed explicitly after the other workflow ends.
148
+ Restored stopped Goals and inert legacy queues do not acquire or schedule automatic work.
149
+
150
+ Inactive session-start restoration and live settings changes that could alter Goal tool visibility use temporary synchronous ownership.
151
+ A busy result preserves the settings file, in-memory settings, active tools, and hidden-tool retry ownership.
152
+ An active Goal still pauses if a non-participating restrictive policy later removes its required terminal tools.
153
+
154
+ The coexistence guarantee is cooperative and applies only when every contender implements v1 on the characterized Pi runtime and shares its event bus and session-manager identity.
155
+ A pre-v1, mixed-version, non-participating, forked, or otherwise uncharacterized counterpart remains unsupported for mutual exclusion.
156
+ Goal does not identify, inspect, configure, start, stop, or depend on another extension.
157
+ Guaranteed coexistence with Plan mode requires `@narumitw/pi-plan-mode` `0.52.0` or newer and this package at `0.53.0` or newer on the characterized Pi `0.84.2` runtime.
158
+
159
+ | Installation | Support |
160
+ | --- | --- |
161
+ | Goal without another workflow participant | Supported standalone behavior |
162
+ | Goal `>=0.53.0` with Plan mode `>=0.52.0` on Pi `0.84.2` | Workflow Mutex v1 coexistence guarantee |
163
+ | Either package below its floor, or another Pi runtime | Standalone behavior only; mutual exclusion unsupported |
164
+
165
+ ## 💬 Commands
114
166
 
115
167
  ```text
116
168
  /goal
@@ -123,26 +175,34 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
123
175
  /goal clear
124
176
  ```
125
177
 
126
- - In the TUI, `/goal` opens a standard state-aware manager. Its first action follows the current
127
- state: start when empty, pause when active, review a reached automatic-work limit, resume for other
128
- stopped states, or increase an exhausted token budget. Active and paused views show **Automatic
129
- work: _used_ of _limit_ responses** with the remaining count, or explicitly show **Unlimited**.
130
- A hard-cap pause opens **Review and continue…**, which states that objective, cumulative usage,
131
- and active time are preserved and previews that Continue resets the counter to zero and
132
- allows up to one more configured epoch. **Change automatic-work limit…** opens that setting while
133
- leaving the goal paused; Back and Escape make no change. **Start with token budget…** first offers
134
- `25k`, a suggested `100k`, `300k`, and **Set a custom budget…**, then collects the objective with
135
- the selected budget still visible. Custom input accepts examples such as `300000`, `300k`, `2.5k`,
136
- and `1.5m`; invalid input retains its draft for correction. Status, Settings, Help,
137
- invalid-settings guidance, Clear, and Close remain shallow, labeled routes. Arrow keys
138
- navigate, Enter selects or submits, Escape goes Back, and Ctrl+C closes the full flow.
139
- - In RPC mode, bare `/goal` and `/goal status` report the current summary through an observable notification without opening terminal UI. Pi exposes no extension-command output channel in print or JSON mode, so those routes reject with an explicit unsupported-mode error instead of misreporting stderr as status output.
140
- - Menu-driven Replace and Clear actions preview the exact affected goal and require confirmation. Existing direct routes remain immediate for compatibility and automation.
141
- - `/goal <goal_to_complete>` starts goal mode. If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters. Failed kickoff delivery clears a new goal or restores the prior goal; a previously active goal is restored as paused.
142
- - `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget. `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
143
- - `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters. A successful active edit rotates the stale-turn guard and starts a fresh safety epoch. Paused, blocked, and usage-limited goals stay stopped and retain their safety state until resume. A budget-limited goal reactivates only when `edit --tokens` raises its budget above current usage. Failed prompt delivery restores the exact previous safety counters/cause; it restores a budget-limited goal or restores and pauses a previously active goal.
144
- - `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume. Only active goals can be paused.
145
- - `/goal resume` resumes a paused, blocked, usage-limited, or budget-limited goal when its token budget allows it, rotates the stale-turn guard id, resets the automatic-response/repeat safety epoch when the queued resume prompt starts, clears a safety-pause cause, and reports the new finite epoch or explicit Unlimited state. Objective, cumulative usage, and elapsed time are preserved. If prompt delivery fails, the original stopped state, guard id, counters, fingerprint, and cause are restored.
178
+ - In the TUI, `/goal` opens a standard state-aware manager.
179
+ Its first action follows the current state: start when empty, pause when active, review a reached automatic-work limit, resume for other stopped states, or increase an exhausted token budget.
180
+ Active and paused views show **Automatic work: _used_ of _limit_ responses** with the remaining count, or explicitly show **Unlimited**.
181
+ A hard-cap pause opens **Review and continue…**, which states that objective, cumulative usage, and active time are preserved and previews that Continue resets the counter to zero and allows up to one more configured epoch.
182
+ **Change automatic-work limit…** opens that setting while leaving the goal paused; Back and Escape make no change.
183
+ **Start with token budget…** first offers `25k`, a suggested `100k`, `300k`, and **Set a custom budget…**, then collects the objective with the selected budget still visible.
184
+ Custom input accepts examples such as `300000`, `300k`, `2.5k`, and `1.5m`; invalid input retains its draft for correction.
185
+ Status, Settings, Help, invalid-settings guidance, Clear, and Close remain shallow, labeled routes.
186
+ Arrow keys navigate, Enter selects or submits, Escape goes Back, and Ctrl+C closes the full flow.
187
+ - In RPC mode, bare `/goal` and `/goal status` report the current summary through an observable notification without opening terminal UI.
188
+ Pi exposes no extension-command output channel in print or JSON mode, so those routes reject with an explicit unsupported-mode error instead of misreporting stderr as status output.
189
+ - Menu-driven Replace and Clear actions preview the exact affected goal and require confirmation.
190
+ Existing direct routes remain immediate for compatibility and automation.
191
+ - `/goal <goal_to_complete>` starts goal mode.
192
+ If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters.
193
+ Failed kickoff delivery clears a new goal or restores the exact prior Goal and tool-policy snapshot; a previously active or waiting Goal keeps its existing workflow ownership.
194
+ - `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget.
195
+ `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
196
+ - `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters.
197
+ A successful active edit rotates the stale-turn guard and starts a fresh safety epoch.
198
+ Paused, blocked, and usage-limited goals stay stopped and retain their safety state until resume.
199
+ A budget-limited goal reactivates only when `edit --tokens` raises its budget above current usage.
200
+ Failed prompt delivery restores the exact previous Goal, guard id, safety counters, cause, tool-policy snapshot, and active ownership when applicable.
201
+ - `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume.
202
+ Only active goals can be paused.
203
+ - `/goal resume` resumes a paused, blocked, usage-limited, or budget-limited goal when its token budget allows it, rotates the stale-turn guard id, resets the automatic-response/repeat safety epoch when the queued resume prompt starts, clears a safety-pause cause, and reports the new finite epoch or explicit Unlimited state.
204
+ Objective, cumulative usage, and elapsed time are preserved.
205
+ If prompt delivery fails, the original stopped state, guard id, counters, fingerprint, and cause are restored.
146
206
  - `/goal clear` clears the current goal, status, pending continuation, inert legacy queue state, and legacy persisted state for the current working directory without aborting unrelated in-flight work.
147
207
 
148
208
  The experimental ordered-goal queue has been removed.
@@ -152,21 +212,42 @@ For example, if `task b` is complete and `task c` is in progress, edit the objec
152
212
  Former queue command words such as `add`, `prioritize`, `drop-last`, `skip`, `push`, `unshift`, `pop`, and `shift` are ordinary objective text for unaffected users.
153
213
  If a session still has legacy queue settings or persisted queue state, those words show a migration warning instead of replacing the active Goal.
154
214
 
155
- Goal objectives are limited to 4,000 characters. Put longer instructions in a file and reference the file path from `/goal`.
215
+ Goal objectives are limited to 4,000 characters.
216
+ Put longer instructions in a file and reference the file path from `/goal`.
217
+
218
+ ## 🛠️ Tools
219
+
220
+ - `goal_complete` records completion only for the exact active goal id and requires an evidence-based summary.
221
+ - `goal_blocked` records a true repeated impasse with the exact goal id, reason, evidence, and repeated-turn count.
222
+ - `goal_wait` pauses automatic continuation after the agent arranges an external wake source, with an optional bounded resume deadline.
156
223
 
157
224
  ## 🔁 Session and reload behavior
158
225
 
159
- Goal state is stored as Pi session state, similar to Codex's thread-owned goals. `/reload` and reopening the same Pi session can restore that session's unfinished goal. An active restored goal already at or above its finite automatic-work limit pauses before another provider request and reports that progress is saved; use `/goal` to review and continue. A restored waiting Goal remains quiet, excludes offline and waiting wall time from active elapsed time, and restores only its absolute optional deadline timer. With `"after-first-goal"`, an unfinished restore marks the tools unlocked in the new extension runtime, but it does not widen an active-tool set already restricted by an earlier lifecycle handler; an active goal instead restores as paused when either terminal tool is missing. If no unfinished goal remains, a fresh runtime starts locked again. Active elapsed time is checkpointed before shutdown and restarted after reload only when the Goal is not waiting, so offline and stopped wall-clock time is excluded. Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction. A direct non-`/goal` user/RPC input resets the safety epoch only while the goal is active and reclassifies the in-flight run as manual; extension input and messages sent while stopped do not reset it. Starting a new Pi session in the same working directory does not inherit the old goal.
226
+ Goal state is stored as Pi session state, similar to Codex's thread-owned goals.
227
+ `/reload` and reopening the same Pi session can restore that session's unfinished goal.
228
+ An active restored goal already at or above its finite automatic-work limit pauses before another provider request and reports that progress is saved; use `/goal` to review and continue.
229
+ A restored waiting Goal remains quiet, excludes offline and waiting wall time from active elapsed time, and restores only its absolute optional deadline timer.
230
+ With `"after-first-goal"`, an admitted unfinished restore marks the tools unlocked in the new extension runtime, but it does not widen an active-tool set already restricted by an earlier lifecycle handler; an active goal instead restores as paused when admission is busy or either terminal tool is missing.
231
+ If no unfinished goal remains, a fresh runtime starts locked again.
232
+ Active elapsed time is checkpointed before shutdown and restarted after reload only when the Goal is not waiting, so offline and stopped wall-clock time is excluded.
233
+ Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction.
234
+ A direct non-`/goal` user/RPC input resets the safety epoch only while the goal is active and reclassifies the in-flight run as manual; extension input and messages sent while stopped do not reset it.
235
+ Starting a new Pi session in the same working directory does not inherit the old goal.
160
236
 
161
- The legacy `{ goal }` shape remains valid, and missing safety fields normalize to zero/defaults. Sessions created by the former standalone `pi-goals` experiment can still restore exactly one ordinary unfinished goal when no canonical `goal-state` entry exists.
237
+ The legacy `{ goal }` shape remains valid, and missing safety fields normalize to zero/defaults.
238
+ Sessions created by the former standalone `pi-goals` experiment can still restore exactly one ordinary unfinished goal when no canonical `goal-state` entry exists.
162
239
 
163
- If a session still contains old queue metadata, multiple legacy goals, a queued head, or a pending queue transition, pi-goal treats that state as inert legacy data. It does not inject Goal prompts, advance the queue, or run any retained item automatically. Affected users receive a warning that recommends starting one merged objective with `/goal <objectives>`, or using `/goal clear` to discard the old queue state.
240
+ If a session still contains old queue metadata, multiple legacy goals, a queued head, or a pending queue transition, pi-goal treats that state as inert legacy data.
241
+ It does not inject Goal prompts, advance the queue, or run any retained item automatically.
242
+ Affected users receive a warning that recommends starting one merged objective with `/goal <objectives>`, or using `/goal clear` to discard the old queue state.
164
243
 
165
- Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed by working directory. This version no longer reads that global file, and `/goal clear` removes any legacy entry for the current working directory.
244
+ Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed by working directory.
245
+ This version no longer reads that global file, and `/goal clear` removes any legacy entry for the current working directory.
166
246
 
167
247
  ## 📊 Statusline states
168
248
 
169
- `pi-goal` writes compact plain status strings for statusline extensions. `@narumitw/pi-statusline` adds the default `🎯` icon unless configured otherwise:
249
+ `pi-goal` writes compact plain status strings for statusline extensions.
250
+ `@narumitw/pi-statusline` adds the default `🎯` icon unless configured otherwise:
170
251
 
171
252
  - `active 3m · automatic 12/25` — an active goal without a token budget; elapsed time counts only periods when its status is active and not waiting.
172
253
  - `waiting review monitor · automatic 12/25` — an active Goal is quiet until non-Goal work or its optional deadline wakes it; the displayed reason is sanitized and bounded.
@@ -181,33 +262,54 @@ Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed
181
262
 
182
263
  ## 💰 Token budgets and elapsed time
183
264
 
184
- The TUI budget chooser describes token budgets as cumulative Goal usage, warns that the final model
185
- call may exceed the chosen value, and keeps the independent automatic-work response limit visible.
186
- It is not a dollar-cost cap. Choosing a preset or entering a custom value remains provisional until
187
- the objective is submitted; cancelling the chooser, custom input, or objective editor creates no
188
- Goal. **Increase budget and resume…** shows the exact current budget and usage, requires a new total
189
- above current usage, previews the new total plus automatic-work epoch, and resumes only after
190
- confirmation. If the goal or its usage changes while that dialog is open, no change is applied.
265
+ The TUI budget chooser describes token budgets as cumulative Goal usage, warns that the final model call may exceed the chosen value, and keeps the independent automatic-work response limit visible.
266
+ It is not a dollar-cost cap.
267
+ Choosing a preset or entering a custom value remains provisional until the objective is submitted; cancelling the chooser, custom input, or objective editor creates no Goal.
268
+ **Increase budget and resume…** shows the exact current budget and usage, requires a new total above current usage, previews the new total plus automatic-work epoch, and resumes only after confirmation.
269
+ If the goal or its usage changes while that dialog is open, no change is applied.
191
270
 
192
- For each persisted assistant message, `pi-goal` uses finite, non-negative `usage.totalTokens` when available. For compatibility with older or partial records, it otherwise sums finite, non-negative `input + output + cacheRead + cacheWrite`. It does not add `reasoning` because reasoning is already part of output, or `cacheWrite1h` because that is a subset of cache writes. Goal usage is the current branch's cumulative assistant total minus the baseline captured when the goal started, clamped at zero after branch rewinds.
271
+ For each persisted assistant message, `pi-goal` uses finite, non-negative `usage.totalTokens` when available.
272
+ For compatibility with older or partial records, it otherwise sums finite, non-negative `input + output + cacheRead + cacheWrite`.
273
+ It does not add `reasoning` because reasoning is already part of output, or `cacheWrite1h` because that is a subset of cache writes.
274
+ Goal usage is the current branch's cumulative assistant total minus the baseline captured when the goal started, clamped at zero after branch rewinds.
193
275
 
194
- Provider usage becomes authoritative only when an assistant message finishes, so a budget can overshoot by one model call. When completed tool activity first exposes exhaustion, the goal transitions once to `budget_limited`, cancels continuation, and queues one bounded custom wrap-up instruction before the next model call. The instruction permits only a concise progress/results/blockers summary; a substantive tool attempt is blocked and aborts the remaining wrap-up. A rejected `goal_complete` also terminates the wrap-up, while accepted completion still requires existing evidence that proves every requirement—budget exhaustion itself never means completion. If exhaustion is first visible at `agent_end` and no turn remains, the extension stops without creating another model turn.
276
+ Provider usage becomes authoritative only when an assistant message finishes, so a budget can overshoot by one model call.
277
+ When completed tool activity first exposes exhaustion, the goal transitions once to `budget_limited`, cancels continuation, recovery, waits, and stale Goal-owned work, aborts the current turn, and releases workflow ownership.
278
+ It does not queue a summary or another model turn after budget exhaustion.
279
+ Stale Goal tool calls remain blocked until an unrelated user or extension turn begins or the Goal is explicitly reactivated.
280
+ A budget-limited Goal cannot call `goal_complete`; raise its budget above current usage and resume or edit it first.
195
281
 
196
- The default 25-response automatic-work limit is a response-count boundary, not a fixed cost ceiling: context size, cache pricing, output length, and provider rates vary, and the final capped response is still retained. Pi derives displayed cost estimates from provider-reported token usage and local model pricing; pi-goal does not query a billing balance or enforce a dollar cap. For tighter token control, choose a smaller `automaticTurns` value and/or use `/goal --tokens`; choosing Unlimited removes only the response-count boundary.
282
+ The default 25-response automatic-work limit is a response-count boundary, not a fixed cost ceiling: context size, cache pricing, output length, and provider rates vary, and the final capped response is still retained.
283
+ Pi derives displayed cost estimates from provider-reported token usage and local model pricing; pi-goal does not query a billing balance or enforce a dollar cap.
284
+ For tighter token control, choose a smaller `automaticTurns` value and/or use `/goal --tokens`; choosing Unlimited removes only the response-count boundary.
197
285
 
198
- Elapsed time is accumulated only while status is `active`. Pause, blocked, usage-limited, budget-limited, shutdown, and offline periods do not increase it. Legacy session entries are migrated by preserving their accumulated seconds and starting a fresh active clock when loaded.
286
+ Elapsed time is accumulated only while status is `active`.
287
+ Pause, blocked, usage-limited, budget-limited, shutdown, and offline periods do not increase it.
288
+ Legacy session entries are migrated by preserving their accumulated seconds and starting a fresh active clock when loaded.
199
289
 
200
290
  ## ✅ How completion works
201
291
 
202
- While a goal is active, `pi-goal` injects persistence rules, a `<goal_id>` stale-turn guard, and exposes `goal_complete`. Kickoff, resume, edited-objective, system, and automatic-continuation prompts all place a trust boundary before the escaped objective, identifying it as user-provided task data; they preserve its full scope across turns and require the agent to derive concrete requirements from the objective and referenced artifacts. They treat the current worktree, command output, tests, runtime behavior, PR state, rendered artifacts, and external state as authoritative; previous conversation and plans are context rather than proof.
292
+ While a goal is active, `pi-goal` injects persistence rules, a `<goal_id>` stale-turn guard, and exposes `goal_complete`.
293
+ Kickoff, resume, edited-objective, system, and automatic-continuation prompts all place a trust boundary before the escaped objective, identifying it as user-provided task data; they preserve its full scope across turns and require the agent to derive concrete requirements from the objective and referenced artifacts.
294
+ They treat the current worktree, command output, tests, runtime behavior, PR state, rendered artifacts, and external state as authoritative; previous conversation and plans are context rather than proof.
203
295
 
204
- Before completion, the shared audit tells the agent to treat completion as unproven, inspect requirement-by-requirement evidence for every named artifact, command, test, gate, invariant, and deliverable, and match each check's scope to the requirement it supports. Weak, indirect, missing, or merely consistent evidence means work must continue. This prompt wording is a behavioral guardrail, not proof by itself: `pi-goal` can enforce the current goal id and reject empty or plainly contradictory summaries, but it cannot independently prove that external work is complete.
296
+ Before completion, the shared audit tells the agent to treat completion as unproven, inspect requirement-by-requirement evidence for every named artifact, command, test, gate, invariant, and deliverable, and match each check's scope to the requirement it supports.
297
+ Weak, indirect, missing, or merely consistent evidence means work must continue.
298
+ This prompt wording is a behavioral guardrail, not proof by itself: `pi-goal` can enforce the current goal id and reject empty or plainly contradictory summaries, but it cannot independently prove that external work is complete.
205
299
 
206
- To finish, the agent must call `goal_complete` with the exact current `goal_id` and a `summary` of completion evidence. Missing or stale `goal_id` values are rejected before summary validation. Paused, blocked, and usage-limited goals cannot be completed until resumed; a budget-limited goal permits completion only during its bounded in-flight wrap-up. The summary is completion evidence, not the stale-turn safety token.
300
+ To finish, the agent must call `goal_complete` with the exact current `goal_id` and a `summary` of completion evidence.
301
+ Missing or stale `goal_id` values are rejected before summary validation.
302
+ Paused, blocked, usage-limited, and budget-limited goals cannot be completed until resumed.
303
+ The summary is completion evidence, not the stale-turn safety token.
207
304
 
208
- If a turn ends before completion, `pi-goal` records usage and creates one continuation intent unless a circuit breaker pauses it first. It dispatches that continuation only from Pi's `agent_settled` lifecycle after retries, automatic compaction, steering, and follow-up work have drained, `ctx.isIdle()` is true, and no messages are pending. Repeated settled events cannot dispatch the same intent twice. Goal-owned kickoff, resume, active-edit, and automatic-continuation deliveries are bound to the goal instance that created them; a delayed prompt from a replaced goal is aborted without rolling back, injecting, or stopping the newer goal. Plain assistant text never marks a goal complete—even an exact-reply objective pauses safely when the model repeatedly omits `goal_complete`.
305
+ If a turn ends before completion, `pi-goal` records usage and creates one continuation intent unless a circuit breaker pauses it first.
306
+ It dispatches that continuation only from Pi's `agent_settled` lifecycle after retries, automatic compaction, steering, and follow-up work have drained, `ctx.isIdle()` is true, and no messages are pending.
307
+ Repeated settled events cannot dispatch the same intent twice.
308
+ Goal-owned kickoff, resume, active-edit, and automatic-continuation deliveries are bound to the goal instance that created them; a delayed prompt from a replaced goal is aborted without rolling back, injecting, or stopping the newer goal.
309
+ Plain assistant text never marks a goal complete—even an exact-reply objective pauses safely when the model repeatedly omits `goal_complete`.
209
310
 
210
- Manual compaction does not emit `agent_settled`, so its completion hook uses the same single-flight dispatcher as a narrow idle-only fallback. Pi extensions cannot reserve an idle turn atomically like Codex core; another extension can still win the race after the idle check, and its newer turn supersedes the old continuation intent.
311
+ Manual compaction does not emit `agent_settled`, so its completion hook uses the same single-flight dispatcher as a narrow idle-only fallback.
312
+ Pi extensions cannot reserve an idle turn atomically like Codex core; another extension can still win the race after the idle check, and its newer turn supersedes the old continuation intent.
211
313
 
212
314
  ## ⏳ External waiting
213
315
 
@@ -221,31 +323,59 @@ goal_wait({
221
323
  })
222
324
  ```
223
325
 
224
- `goal_id` must match the current active Goal, `reason` must contain 1–1,000 characters, and the optional `resume_after_ms` must be a whole number from 1 through 2,147,483,647. The deadline is a safety wake-up rather than a polling interval. Requests below 10,000 milliseconds are accepted for compatibility but clamped to an effective 10,000-millisecond deadline; the tool result reports both the requested and effective values. Prefer deadlines measured in minutes instead of repeated short wakes. Omitting `resume_after_ms` intentionally permits an indefinite quiet wait.
326
+ `goal_id` must match the current active Goal, `reason` must contain 1–1,000 characters, and the optional `resume_after_ms` must be a whole number from 1 through 2,147,483,647.
327
+ The deadline is a safety wake-up rather than a polling interval.
328
+ Requests below 10,000 milliseconds are accepted for compatibility but clamped to an effective 10,000-millisecond deadline; the tool result reports both the requested and effective values.
329
+ Prefer deadlines measured in minutes instead of repeated short wakes.
330
+ Omitting `resume_after_ms` intentionally permits an indefinite quiet wait.
225
331
 
226
- An accepted call keeps the canonical Goal status active, checkpoints active elapsed time, cancels pending continuation work, persists the reason and absolute optional deadline, and terminates the normal single-tool run. Call `goal_wait` alone because Pi only guarantees early termination when every finalized result in a parallel tool batch terminates.
332
+ An accepted call keeps the canonical Goal status active, checkpoints active elapsed time, cancels pending continuation work, persists the reason and absolute optional deadline, and terminates the normal single-tool run.
333
+ Call `goal_wait` alone because Pi only guarantees early termination when every finalized result in a parallel tool batch terminates.
227
334
 
228
- Interactive input, RPC input, another extension's `sendUserMessage()` input, and supported non-Goal custom follow-ups clear the wait before their turn runs. pi-goal-owned kickoff, resume, edit, continuation, stale, or cancelled prompts do not count as external wake-ups. Pi does not expose the sending extension's identity, so any non-Goal extension message is treated as a wake signal.
335
+ Interactive input, RPC input, another extension's `sendUserMessage()` input, and supported non-Goal custom follow-ups clear the wait before their turn runs. pi-goal-owned kickoff, resume, edit, continuation, stale, or cancelled prompts do not count as external wake-ups.
336
+ Pi does not expose the sending extension's identity, so any non-Goal extension message is treated as a wake signal.
229
337
 
230
- After a waking turn ends, ordinary continuation rules apply again. The agent can complete or block the Goal, continue working, or call `goal_wait` again after arranging the next wake source. `/goal resume` also clears waiting and sends one manual resume prompt without resetting cumulative usage or the safety epoch. `/goal pause`, clear, edit, replace, completion, blocking, terminal limits, tool loss, session replacement, and shutdown cancel the in-memory deadline owner.
338
+ After a waking turn ends, ordinary continuation rules apply again.
339
+ The agent can complete or block the Goal, continue working, or call `goal_wait` again after arranging the next wake source.
340
+ `/goal resume` also clears waiting and sends one manual resume prompt without resetting cumulative usage or the safety epoch.
341
+ `/goal pause`, clear, edit, replace, completion, blocking, terminal limits, tool loss, session replacement, and shutdown cancel the in-memory deadline owner.
231
342
 
232
- A future deadline is restored from its absolute timestamp after reload. Reload never restarts, extends, or newly clamps an already-persisted absolute deadline, including a short deadline written by an older version. An already-due deadline waits for Pi's settled, idle, no-pending-message boundary and then requests exactly one continuation through the normal dispatcher. If that delivery throws, pi-goal restores the wait, retries once after one second, and leaves the Goal visibly waiting after a second failure instead of retry-looping. A deadline never sends a prompt directly from a stale timer.
343
+ A future deadline is restored from its absolute timestamp after reload.
344
+ Reload never restarts, extends, or newly clamps an already-persisted absolute deadline, including a short deadline written by an older version.
345
+ An already-due deadline waits for Pi's settled, idle, no-pending-message boundary and then requests exactly one continuation through the normal dispatcher.
346
+ If that delivery throws, pi-goal restores the wait, retries once after one second, and leaves the Goal visibly waiting after a second failure instead of retry-looping.
347
+ A deadline never sends a prompt directly from a stale timer.
233
348
 
234
- Waiting time is excluded from **Active elapsed**, while tokens, iteration, automatic-response count, no-progress state, managed-run ownership remain preserved. The managed-run protocol continues reporting `active` because waiting is non-terminal. Editing or replacing a waiting Goal clears the previous wait so the updated objective performs a fresh external-state check.
349
+ Waiting time is excluded from **Active elapsed**, while tokens, iteration, automatic-response count, no-progress state, managed-run ownership remain preserved.
350
+ The managed-run protocol continues reporting `active` because waiting is non-terminal.
351
+ Editing or replacing a waiting Goal clears the previous wait so the updated objective performs a fresh external-state check.
235
352
 
236
353
  ## 🚧 Blocked goals
237
354
 
238
- `goal_blocked` is intentionally narrower than completion or ordinary clarification. Every goal-mode prompt repeats the blocked audit: the model must provide the exact current `goal_id`, a specific reason describing the user or external action required (up to 1,000 characters), concrete evidence from the failed resolution attempts (up to 4,000 characters), and `repeated_turns` showing the same blocker recurred for at least three consecutive goal turns. A resumed goal starts a fresh blocker audit. Empty or oversized reasons/evidence, stale ids, non-whole turn counts, stopped goals, and fewer than three turns are rejected. Accepted blocker reports set `blocked`, stop automatic continuation, and terminate the tool batch when Pi can do so safely.
355
+ `goal_blocked` is intentionally narrower than completion or ordinary clarification.
356
+ Every goal-mode prompt repeats the blocked audit: the model must provide the exact current `goal_id`, a specific reason describing the user or external action required (up to 1,000 characters), concrete evidence from the failed resolution attempts (up to 4,000 characters), and `repeated_turns` showing the same blocker recurred for at least three consecutive goal turns.
357
+ A resumed goal starts a fresh blocker audit.
358
+ Empty or oversized reasons/evidence, stale ids, non-whole turn counts, stopped goals, and fewer than three turns are rejected.
359
+ Accepted blocker reports set `blocked`, stop automatic continuation, and terminate the tool batch when Pi can do so safely.
239
360
 
240
- Do not use `goal_blocked` merely because work is difficult, incomplete, uncertain, awaiting normal clarification, or affected by a recoverable tool/provider failure. The user can resolve the external condition and run `/goal resume` to rotate the goal id and continue.
361
+ Do not use `goal_blocked` merely because work is difficult, incomplete, uncertain, awaiting normal clarification, or affected by a recoverable tool/provider failure.
362
+ The user can resolve the external condition and run `/goal resume` to rotate the goal id and continue.
241
363
 
242
364
  ## 🛑 Interruption and queued-input behavior
243
365
 
244
- A user pause or aborted turn produces `paused`; a terminal provider/account quota error produces `usage_limited`; another non-retryable agent error produces `blocked`. Each stopped transition cancels pending continuation intent or delivery, aborts stale work when applicable, and blocks stale tool calls until the next non-goal user prompt, successful reactivation/replacement, or `/goal clear`. On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn. Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries; no extra continuation is queued, and automatic ownership remains charged through retry `agent_start` events. If matching recovery still exists at `agent_settled`, retries are exhausted and the goal becomes `blocked` before any continuation dispatches. Stale recovery cannot block a replacement goal. User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
366
+ A user pause or aborted turn produces `paused`; a terminal provider/account quota error produces `usage_limited`; another non-retryable agent error produces `blocked`.
367
+ Each stopped transition cancels pending continuation intent or delivery, aborts stale work when applicable, and blocks stale tool calls until the next non-goal user prompt, successful reactivation/replacement, or `/goal clear`.
368
+ On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn.
369
+ Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries; no extra continuation is queued, and automatic ownership remains charged through retry `agent_start` events.
370
+ If matching recovery still exists at `agent_settled`, retries are exhausted and the goal becomes `blocked` before any continuation dispatches.
371
+ Stale recovery cannot block a replacement goal.
372
+ User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
245
373
 
246
374
  ## 🤝 Managed run RPC
247
375
 
248
- With `rpc.enabled: true`, pi-goal exposes a session-local, dependency-free protocol over Pi's shared `pi.events` bus. It is intended for trusted sibling extensions that need to start, observe, and cancel one Goal lifecycle without driving the `/goal` command. Installed Pi extensions remain fully privileged: this setting controls only whether pi-goal cooperates with these channels and is not authentication or sandboxing.
376
+ With `rpc.enabled: true`, pi-goal exposes a session-local, dependency-free protocol over Pi's shared `pi.events` bus.
377
+ It is intended for trusted sibling extensions that need to start, observe, and cancel one Goal lifecycle without driving the `/goal` command.
378
+ Installed Pi extensions remain fully privileged: this setting controls only whether pi-goal cooperates with these channels and is not authentication or sandboxing.
249
379
 
250
380
  The public channels are:
251
381
 
@@ -255,7 +385,8 @@ pi-goal:cancel
255
385
  pi-goal:event:${runId}
256
386
  ```
257
387
 
258
- The protocol intentionally has no separate version field or versioned channel namespace. Before starting, the caller must generate a session-unique `runId`, subscribe to its event channel, and then emit:
388
+ The protocol intentionally has no separate version field or versioned channel namespace.
389
+ Before starting, the caller must generate a session-unique `runId`, subscribe to its event channel, and then emit:
259
390
 
260
391
  ```ts
261
392
  pi.events.emit("pi-goal:start", {
@@ -265,7 +396,9 @@ pi.events.emit("pi-goal:start", {
265
396
  });
266
397
  ```
267
398
 
268
- `runId` must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`; UUIDs are recommended. It is a correlation identifier, not a secret or authenticated caller identity. The objective uses the same 4,000-character validation as `/goal`, and `tokenBudget` is an absolute positive integer rather than a `k`/`m` string.
399
+ `runId` must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`; UUIDs are recommended.
400
+ It is a correlation identifier, not a secret or authenticated caller identity.
401
+ The objective uses the same 4,000-character validation as `/goal`, and `tokenBudget` is an absolute positive integer rather than a `k`/`m` string.
269
402
 
270
403
  A successful start produces canonical state on `pi-goal:event:${runId}`:
271
404
 
@@ -278,9 +411,15 @@ A successful start produces canonical state on `pi-goal:event:${runId}`:
278
411
  }
279
412
  ```
280
413
 
281
- Subsequent state events use `active`, `complete`, `blocked`, `paused`, `usage_limited`, `budget_limited`, or `cleared`. `complete` is the only successful terminal outcome. A matching completion may include `summary`; other terminal outcomes may include `reason`. Events come only from canonical Goal persistence and only for the matching managed run. Manual and restored Goals are not adopted or broadcast, unchanged persistence does not duplicate a status, and each run emits at most one terminal event.
414
+ Subsequent state events use `active`, `complete`, `blocked`, `paused`, `usage_limited`, `budget_limited`, or `cleared`.
415
+ `complete` is the only successful terminal outcome.
416
+ A matching completion may include `summary`; other terminal outcomes may include `reason`.
417
+ Events come only from canonical Goal persistence and only for the matching managed run.
418
+ Manual and restored Goals are not adopted or broadcast, unchanged persistence does not duplicate a status, and each run emits at most one terminal event.
282
419
 
283
- Terminal events are dispatched after the underlying Goal transition settles, so a listener can start the next managed run directly after `complete` without re-entering completion cleanup. Other terminal statuses leave a stopped Goal that must be resolved or cleared first. If a manual edit, replacement, or edit transition rotates the Goal id, the prior managed run ends as `cleared` with a superseded reason; the replacement remains outside that run.
420
+ Terminal events are dispatched after the underlying Goal transition settles, so a listener can start the next managed run directly after `complete` without re-entering completion cleanup.
421
+ Other terminal statuses leave a stopped Goal that must be resolved or cleared first.
422
+ If a manual edit, replacement, or edit transition rotates the Goal id, the prior managed run ends as `cleared` with a superseded reason; the replacement remains outside that run.
284
423
 
285
424
  To cancel before or after activation, emit the same `runId`:
286
425
 
@@ -291,7 +430,10 @@ pi.events.emit("pi-goal:cancel", {
291
430
  });
292
431
  ```
293
432
 
294
- Cancellation uses the normal Goal pause transition. It cannot affect a manual, restored, stale, or different run. The resulting `paused` state is the cancellation result; there is no separate reply envelope. A caller must not reopen a terminal `runId`, and a later manual `/goal resume` is outside that completed managed run.
433
+ Cancellation uses the normal Goal pause transition.
434
+ It cannot affect a manual, restored, stale, or different run.
435
+ The resulting `paused` state is the cancellation result; there is no separate reply envelope.
436
+ A caller must not reopen a terminal `runId`, and a later manual `/goal resume` is outside that completed managed run.
295
437
 
296
438
  Rejected operations emit a structured error on the same run event channel:
297
439
 
@@ -307,11 +449,16 @@ Rejected operations emit a structured error on the same run event channel:
307
449
  }
308
450
  ```
309
451
 
310
- Stable codes are `RPC_DISABLED`, `INVALID_REQUEST`, `NO_ACTIVE_SESSION`, `RUN_ID_IN_USE`, `RUN_NOT_FOUND`, `GOAL_ALREADY_EXISTS`, `ACTIVATION_FAILED`, and `SUPERSEDED`. Consumers branch on `code`; `message` is diagnostic. An unsafe or missing `runId` is ignored because there is no safe response channel.
452
+ Stable codes are `RPC_DISABLED`, `INVALID_REQUEST`, `NO_ACTIVE_SESSION`, `RUN_ID_IN_USE`, `RUN_NOT_FOUND`, `GOAL_ALREADY_EXISTS`, `ACTIVATION_FAILED`, and `SUPERSEDED`.
453
+ Consumers branch on `code`; `message` is diagnostic.
454
+ An unsafe or missing `runId` is ignored because there is no safe response channel.
311
455
 
312
- Start never prompts for replacement: any pre-existing Goal is rejected. The protocol binds only after current settings and restored Goal state load, and unbinds before session shutdown. A caller must not assume that `emit()` waits for Goal completion; it should wait for a terminal run event and participate in its own session-shutdown cleanup.
456
+ Start never prompts for replacement: any pre-existing Goal is rejected.
457
+ The protocol binds only after current settings and restored Goal state load, and unbinds before session shutdown.
458
+ A caller must not assume that `emit()` waits for Goal completion; it should wait for a terminal run event and participate in its own session-shutdown cleanup.
313
459
 
314
- This breaking contract replaces and removes `pi-goal:rpc:start`, `pi-goal:rpc:pause`, request-scoped start replies, and the global `pi-goal:state` broadcast. No compatibility aliases are registered.
460
+ This breaking contract replaces and removes `pi-goal:rpc:start`, `pi-goal:rpc:pause`, request-scoped start replies, and the global `pi-goal:state` broadcast.
461
+ No compatibility aliases are registered.
315
462
 
316
463
  ## 🧠 Use cases
317
464
 
@@ -349,7 +496,8 @@ packages/pi-goal/
349
496
  └── package.json
350
497
  ```
351
498
 
352
- `index.ts` is the Pi entrypoint and forwards to `goal.ts`; the other source modules are internal. The package exposes its Pi extension through `package.json`:
499
+ `index.ts` is the Pi entrypoint and forwards to `goal.ts`; the other source modules are internal.
500
+ The package exposes its Pi extension through `package.json`:
353
501
 
354
502
  ```json
355
503
  {
@@ -367,4 +515,5 @@ Pi extension, Pi coding agent, goal mode, autonomous coding agent, AI agent work
367
515
 
368
516
  ## 📄 License
369
517
 
370
- MIT. See [`LICENSE`](./LICENSE).
518
+ MIT.
519
+ See [`LICENSE`](./LICENSE).