@narumitw/pi-goal 0.11.0 → 0.12.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 (3) hide show
  1. package/README.md +6 -3
  2. package/package.json +1 -1
  3. package/src/goal.ts +65 -20
package/README.md CHANGED
@@ -2,7 +2,7 @@
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 and a `goal_complete` tool for autonomous, verifiable task completion.
5
+ `@narumitw/pi-goal` is a native [Pi coding agent](https://pi.dev) extension that adds session-scoped `/goal` commands and a `goal_complete({ goal_id, summary })` tool for autonomous, verifiable task completion.
6
6
 
7
7
  Goal mode uses Codex-like persistence instructions and keeps sending guarded continuation messages until the agent calls `goal_complete`, the user pauses or clears the goal, an interrupt/error pauses the goal, or an optional token budget is reached.
8
8
 
@@ -15,12 +15,13 @@ Goal mode uses Codex-like persistence instructions and keeps sending guarded con
15
15
  - Supports optional token budgets such as `/goal --tokens 100k <goal>`.
16
16
  - Tracks `active`, `paused`, `budget_limited`, and `complete` states.
17
17
  - Stores goal state in the current Pi session, following Codex's thread-owned goal model instead of using a global per-directory goal.
18
- - Registers a `goal_complete` tool for explicit completion, and rejects plainly contradictory completion summaries such as “not complete” or “tests still fail”.
18
+ - 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”.
19
19
  - Automatically prompts the agent to continue if an active turn ends early, directly triggering the next turn when Pi is idle and no pending messages are queued.
20
20
  - Pauses and aborts queued goal work when the user pauses a goal or Pi reports a non-retryable aborted/errored assistant turn.
21
21
  - Keeps retryable provider interruptions and Pi compaction retries active without enqueueing duplicate goal continuations while Pi retries.
22
22
  - Preserves active goals across manual, threshold, and overflow compaction.
23
23
  - Guards auto-follow-ups so duplicate, replaced, paused, cleared, completed, or budget-limited goals are not continued.
24
+ - Rotates the completion guard id when a goal is resumed or edited so delayed old turns cannot complete the newer goal instance.
24
25
  - Blocks stale tool calls after pause or non-retryable interruption.
25
26
  - Encourages requirement-by-requirement verification before the goal is marked complete.
26
27
 
@@ -82,7 +83,9 @@ Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed
82
83
 
83
84
  ## ✅ How completion works
84
85
 
85
- While a goal is active, `pi-goal` injects persistence rules and exposes `goal_complete`. If a turn ends before completion, it records usage and sends one guarded continuation only when no other messages are pending. Empty or plainly contradictory completion summaries are rejected as a state-safety guard, not as proof of completion.
86
+ While a goal is active, `pi-goal` injects persistence rules, a `<goal_id>` stale-turn guard, and exposes `goal_complete`. 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, and paused goals cannot be completed until resumed. Empty or plainly contradictory summaries are also rejected; the summary is completion evidence, not the stale-turn safety token.
87
+
88
+ If a turn ends before completion, `pi-goal` records usage and sends one guarded continuation only when no other messages are pending.
86
89
 
87
90
  ## 🛑 Interruption and queued-input behavior
88
91
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Pi extension that keeps working on a /goal until the agent marks it complete.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/goal.ts CHANGED
@@ -28,6 +28,7 @@ interface ActiveGoal {
28
28
 
29
29
  interface GoalCompleteDetails {
30
30
  goal: string;
31
+ goal_id: string;
31
32
  summary: string;
32
33
  }
33
34
 
@@ -130,14 +131,20 @@ const goalCompleteTool = defineTool({
130
131
  name: "goal_complete",
131
132
  label: "Goal Complete",
132
133
  description:
133
- "Mark the active /goal as complete after all required work is done and verified. Do not use for partial progress, blockers, failing, or unverified work.",
134
- promptSnippet: "Mark the active /goal as complete after fully finishing and verifying it",
134
+ "Mark the active /goal as complete after all required work is done and verified, using the current goal_id stale-turn guard. Do not use for partial progress, blockers, failing, or unverified work.",
135
+ promptSnippet:
136
+ "Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id",
135
137
  promptGuidelines: [
136
138
  "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
137
139
  "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
140
+ "Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, paused, replaced, or cleared turn.",
138
141
  "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.",
139
142
  ],
140
143
  parameters: Type.Object({
144
+ goal_id: Type.String({
145
+ description:
146
+ "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
147
+ }),
141
148
  summary: Type.String({
142
149
  description:
143
150
  "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
@@ -146,7 +153,8 @@ const goalCompleteTool = defineTool({
146
153
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
147
154
  const completedGoal = activeGoal;
148
155
  const goal = completedGoal?.text ?? "unknown goal";
149
- const summary = params.summary.trim();
156
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
157
+ const summary = typeof params.summary === "string" ? params.summary.trim() : "";
150
158
 
151
159
  if (!completedGoal) {
152
160
  const rejection = "Goal completion rejected: no active goal.";
@@ -154,7 +162,28 @@ const goalCompleteTool = defineTool({
154
162
 
155
163
  return {
156
164
  content: [{ type: "text", text: rejection }],
157
- details: { goal, summary } satisfies GoalCompleteDetails,
165
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
166
+ };
167
+ }
168
+
169
+ const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
170
+ if (staleGoalRejection) {
171
+ const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
172
+ ctx.ui.notify(rejection, "warning");
173
+
174
+ return {
175
+ content: [{ type: "text", text: rejection }],
176
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
177
+ };
178
+ }
179
+
180
+ if (completedGoal.status !== "active") {
181
+ const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
182
+ ctx.ui.notify(rejection, "warning");
183
+
184
+ return {
185
+ content: [{ type: "text", text: rejection }],
186
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
158
187
  };
159
188
  }
160
189
 
@@ -177,24 +206,22 @@ const goalCompleteTool = defineTool({
177
206
  text: rejection,
178
207
  },
179
208
  ],
180
- details: { goal, summary } satisfies GoalCompleteDetails,
209
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
181
210
  };
182
211
  }
183
212
 
184
- if (completedGoal) {
185
- activeGoal = transitionGoal(completedGoal, "complete");
186
- updateGoalUsage(activeGoal, ctx);
187
- persistGoal(activeGoal);
188
- }
213
+ activeGoal = transitionGoal(completedGoal, "complete");
214
+ updateGoalUsage(activeGoal, ctx);
215
+ persistGoal(activeGoal);
189
216
 
190
- ctx.ui.setStatus(STATUS_KEY, completedGoal ? formatStatus(activeGoal) : undefined);
217
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(activeGoal));
191
218
  clearActiveGoal(ctx);
192
219
  showCompletionStatus(ctx);
193
220
  ctx.ui.notify(`Goal complete: ${goal}`, "info");
194
221
 
195
222
  return {
196
223
  content: [{ type: "text", text: `Goal complete: ${summary}` }],
197
- details: { goal, summary } satisfies GoalCompleteDetails,
224
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
198
225
  terminate: true,
199
226
  };
200
227
  },
@@ -427,7 +454,7 @@ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
427
454
  }
428
455
  clearGoalRecovery();
429
456
  clearStaleGoalToolCallBlock();
430
- activeGoal = transitionGoal(activeGoal, "active");
457
+ activeGoal = transitionGoal(nextGoalInstance(activeGoal), "active");
431
458
  persistGoal(activeGoal);
432
459
  updateStatus(ctx, activeGoal);
433
460
  if (activeGoal.status !== "active") {
@@ -474,7 +501,7 @@ async function editGoal(
474
501
  cancelContinuationPending();
475
502
  clearGoalRecovery();
476
503
  activeGoal = normalizeGoalForBudget({
477
- ...activeGoal,
504
+ ...nextGoalInstance(activeGoal),
478
505
  text: objective,
479
506
  status: editedGoalStatus(activeGoal.status),
480
507
  tokenBudget: tokenBudget ?? activeGoal.tokenBudget,
@@ -521,6 +548,10 @@ function transitionGoal(goal: ActiveGoal, status: GoalStatus): ActiveGoal {
521
548
  return normalizeGoalForBudget({ ...goal, status, updatedAt: Date.now() });
522
549
  }
523
550
 
551
+ function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
552
+ return { ...goal, id: randomUUID(), updatedAt: Date.now() };
553
+ }
554
+
524
555
  function editedGoalStatus(status: GoalStatus): GoalStatus {
525
556
  return status === "paused" ? "paused" : "active";
526
557
  }
@@ -747,34 +778,42 @@ export function formatTokenCount(value: number) {
747
778
 
748
779
  function buildGoalPrompt(goal: ActiveGoal) {
749
780
  const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatTokenCount(goal.tokenBudget)}.`;
750
- return `Goal mode is active. Complete this goal fully:\n\n${goalObjectiveBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("this goal")}`;
781
+ return `Goal mode is active. Complete this goal fully:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("this goal")}`;
751
782
  }
752
783
 
753
784
  function buildObjectiveUpdatedPrompt(goal: ActiveGoal) {
754
785
  const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
755
- return `The active /goal objective was updated. Continue working toward this goal:\n\n${goalObjectiveBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("the updated goal")}`;
786
+ return `The active /goal objective was updated. Continue working toward this goal:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("the updated goal")}`;
756
787
  }
757
788
 
758
789
  function buildResumePrompt(goal: ActiveGoal) {
759
790
  const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
760
- return `The user explicitly resumed the paused /goal. Continue working toward this goal:\n\n${goalObjectiveBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("this goal")}`;
791
+ return `The user explicitly resumed the paused /goal. Continue working toward this goal:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("this goal")}`;
761
792
  }
762
793
 
763
794
  export function buildGoalSystemPrompt(goal: ActiveGoal) {
764
795
  const budgetLine = goal.tokenBudget === undefined ? "" : `\n- Respect the goal token budget (${formatBudget(goal)} used).`;
765
- return `Active /goal:\n${goalObjectiveBlock(goal)}\n\nGoal-mode rules:\n- Keep going until the active goal is completely resolved end-to-end.\n- Treat the current worktree, command output, tests, and external state as authoritative.\n- Do not redefine the goal into a smaller task; audit every requirement before completion.\n- Do not stop at analysis, a plan, TODO list, partial fixes, or suggested next steps.\n- Autonomously perform implementation and verification with the available tools when they are needed to complete the goal.\n- Persevere through recoverable tool failures by trying reasonable alternatives instead of yielding early.\n- If the goal is not complete at the end of a turn, expect an automatic continuation and keep working from where you left off.\n- Only call the goal_complete tool after the goal is fully complete and verified.${budgetLine}`;
796
+ return `Active /goal:\n${goalContextBlock(goal)}\n\nGoal-mode rules:\n- Keep going until the active goal is completely resolved end-to-end.\n- Treat the current worktree, command output, tests, and external state as authoritative.\n- Do not redefine the goal into a smaller task; audit every requirement before completion.\n- Do not stop at analysis, a plan, TODO list, partial fixes, or suggested next steps.\n- Autonomously perform implementation and verification with the available tools when they are needed to complete the goal.\n- Persevere through recoverable tool failures by trying reasonable alternatives instead of yielding early.\n- If the goal is not complete at the end of a turn, expect an automatic continuation and keep working from where you left off.\n- Only call the goal_complete tool after the goal is fully complete and verified, and pass this exact goal_id.${budgetLine}`;
766
797
  }
767
798
 
768
799
  function buildContinuePrompt(goal: ActiveGoal, marker: string) {
769
- return `Continue the active /goal until it is complete:\n\n${goalObjectiveBlock(goal)}\n\nThis is automatic continuation #${goal.iteration}. Current files, command output, tests, and external state are authoritative; re-check them as needed. ${goalPersistenceRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
800
+ return `Continue the active /goal until it is complete:\n\n${goalContextBlock(goal)}\n\nThis is automatic continuation #${goal.iteration}. Current files, command output, tests, and external state are authoritative; re-check them as needed. ${goalPersistenceRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
801
+ }
802
+
803
+ function goalContextBlock(goal: ActiveGoal) {
804
+ return `${goalObjectiveBlock(goal)}\n\n${goalCompletionGuardBlock(goal)}`;
770
805
  }
771
806
 
772
807
  function goalObjectiveBlock(goal: ActiveGoal) {
773
808
  return `<goal_objective>\n${escapeXmlText(goal.text)}\n</goal_objective>`;
774
809
  }
775
810
 
811
+ function goalCompletionGuardBlock(goal: ActiveGoal) {
812
+ return `<goal_id>\n${escapeXmlText(goal.id)}\n</goal_id>\nThis goal_id is only the goal_complete tool stale-turn guard, not part of the objective. If and only if the goal is fully complete, pass this exact goal_id to goal_complete with the completion summary.`;
813
+ }
814
+
776
815
  function goalPersistenceRules(goalLabel: string) {
777
- return `Keep going until ${goalLabel} is completely resolved end-to-end. Do not redefine ${goalLabel} into a smaller task. Do not stop at analysis, a plan, TODO list, partial fixes, or suggested next steps. Autonomously perform implementation and verification with the available tools when they are needed. Treat the current worktree, command output, tests, and external state as authoritative. If a tool call fails, try reasonable alternatives instead of yielding early. Before calling goal_complete, audit ${goalLabel} requirement by requirement against the verified current state. Only call the goal_complete tool after ${goalLabel} is fully complete and verified.`;
816
+ return `Keep going until ${goalLabel} is completely resolved end-to-end. Do not redefine ${goalLabel} into a smaller task. Do not stop at analysis, a plan, TODO list, partial fixes, or suggested next steps. Autonomously perform implementation and verification with the available tools when they are needed. Treat the current worktree, command output, tests, and external state as authoritative. If a tool call fails, try reasonable alternatives instead of yielding early. Before calling goal_complete, audit ${goalLabel} requirement by requirement against the verified current state. Only call the goal_complete tool after ${goalLabel} is fully complete and verified, and pass this exact goal_id. Never reuse a goal_id from an older, paused, replaced, or cleared turn.`;
778
817
  }
779
818
 
780
819
  function hasPendingMessages(ctx: StatusContext) {
@@ -819,6 +858,12 @@ export function isContradictoryCompletionSummary(summary: string) {
819
858
  return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
820
859
  }
821
860
 
861
+ function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
862
+ if (!requestedGoalId) return "missing goal_id";
863
+ if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
864
+ return undefined;
865
+ }
866
+
822
867
  export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
823
868
  if (assistant.stopReason !== "error") return false;
824
869
  if (!assistant.errorMessage) return false;