@narumitw/pi-goal 0.52.3 → 0.53.1

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
@@ -13,7 +13,8 @@ Goal mode adds explicit completion, blocker, and external-wait tools so managed
13
13
  - Uses explicit `goal_complete`, `goal_blocked`, and `goal_wait` tools with stale-goal guards and evidence requirements.
14
14
  - Tracks active, paused, blocked, usage-limited, budget-limited, waiting, and complete outcomes separately.
15
15
  - Pauses after a configurable response limit or repeated no-progress runs and offers a guided review before continuing.
16
- - Supports optional token budgets and a single guarded wrap-up when the budget is exhausted.
16
+ - Supports optional token budgets that stop Goal-owned work immediately when exhausted.
17
+ - Keeps Goal continuation accounting out of the leading system instructions so post-activation provider request prefixes remain stable.
17
18
  - Persists the goal in the current session across reload, resume, compatible forks, and compaction.
18
19
  - Rejects stale continuations and tool calls after replacement, pause, completion, limits, or other terminal state changes.
19
20
  - Optionally exposes a default-off run protocol for trusted sibling extensions to start, observe, and cancel one Goal lifecycle.
@@ -80,7 +81,7 @@ Custom number inputs reject zero, negative numbers, decimals, text, and unsafe i
80
81
  Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime.
81
82
  A successful change updates the visible state immediately.
82
83
  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; retry after Pi settles.
84
+ 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
85
  Escape returns to the previous screen without reverting changes that were already saved.
85
86
 
86
87
  `toolVisibility` accepts:
@@ -126,11 +127,42 @@ In the TUI, Goal Settings becomes a read-only summary that identifies the invali
126
127
  Reload Pi after changing the file.
127
128
  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
 
130
+ Inactive tool widening first takes temporary Workflow Mutex ownership and leaves settings, hidden-tool ownership, and active tools unchanged when another workflow is active.
129
131
  Tool visibility is a baseline, not ownership of Pi's global active-tool list.
130
132
  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.
131
133
  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`.
132
134
  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.
133
135
 
136
+ ## 🤝 Workflow coexistence
137
+
138
+ Goal is independently installable and keeps its standalone behavior when no other protocol participant is present.
139
+ On the characterized Pi `0.84.2` runtime, it participates in the anonymous `workflow:mutex:v1` `agent-workflow` group.
140
+ An active Goal holds the group through ordinary work, external waiting, continuation delivery, compaction recovery, and provider retry.
141
+ Paused, blocked, usage-limited, budget-limited, complete, cleared, and legacy-queue-only states do not hold it.
142
+
143
+ 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.
144
+ Replacing or editing an already active or waiting Goal retains its current owner.
145
+ 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.
146
+
147
+ Restored active Goal state acquires before tool restoration, persistence publication, status, wait timers, retry state, or continuation work.
148
+ 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.
149
+ Restored stopped Goals and inert legacy queues do not acquire or schedule automatic work.
150
+
151
+ Inactive session-start restoration and live settings changes that could alter Goal tool visibility use temporary synchronous ownership.
152
+ A busy result preserves the settings file, in-memory settings, active tools, and hidden-tool retry ownership.
153
+ An active Goal still pauses if a non-participating restrictive policy later removes its required terminal tools.
154
+
155
+ 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.
156
+ A pre-v1, mixed-version, non-participating, forked, or otherwise uncharacterized counterpart remains unsupported for mutual exclusion.
157
+ Goal does not identify, inspect, configure, start, stop, or depend on another extension.
158
+ 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.
159
+
160
+ | Installation | Support |
161
+ | --- | --- |
162
+ | Goal without another workflow participant | Supported standalone behavior |
163
+ | Goal `>=0.53.0` with Plan mode `>=0.52.0` on Pi `0.84.2` | Workflow Mutex v1 coexistence guarantee |
164
+ | Either package below its floor, or another Pi runtime | Standalone behavior only; mutual exclusion unsupported |
165
+
134
166
  ## 💬 Commands
135
167
 
136
168
  ```text
@@ -159,14 +191,14 @@ Arrow keys navigate, Enter selects or submits, Escape goes Back, and Ctrl+C clos
159
191
  Existing direct routes remain immediate for compatibility and automation.
160
192
  - `/goal <goal_to_complete>` starts goal mode.
161
193
  If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters.
162
- Failed kickoff delivery clears a new goal or restores the prior goal; a previously active goal is restored as paused.
194
+ 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.
163
195
  - `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget.
164
196
  `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
165
197
  - `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters.
166
198
  A successful active edit rotates the stale-turn guard and starts a fresh safety epoch.
167
199
  Paused, blocked, and usage-limited goals stay stopped and retain their safety state until resume.
168
200
  A budget-limited goal reactivates only when `edit --tokens` raises its budget above current usage.
169
- Failed prompt delivery restores the exact previous safety counters/cause; it restores a budget-limited goal or restores and pauses a previously active goal.
201
+ Failed prompt delivery restores the exact previous Goal, guard id, safety counters, cause, tool-policy snapshot, and active ownership when applicable.
170
202
  - `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume.
171
203
  Only active goals can be paused.
172
204
  - `/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.
@@ -196,7 +228,7 @@ Goal state is stored as Pi session state, similar to Codex's thread-owned goals.
196
228
  `/reload` and reopening the same Pi session can restore that session's unfinished goal.
197
229
  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.
198
230
  A restored waiting Goal remains quiet, excludes offline and waiting wall time from active elapsed time, and restores only its absolute optional deadline timer.
199
- 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.
231
+ 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.
200
232
  If no unfinished goal remains, a fresh runtime starts locked again.
201
233
  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.
202
234
  Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction.
@@ -243,10 +275,10 @@ It does not add `reasoning` because reasoning is already part of output, or `cac
243
275
  Goal usage is the current branch's cumulative assistant total minus the baseline captured when the goal started, clamped at zero after branch rewinds.
244
276
 
245
277
  Provider usage becomes authoritative only when an assistant message finishes, so a budget can overshoot by one model call.
246
- 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.
247
- The instruction permits only a concise progress/results/blockers summary; a substantive tool attempt is blocked and aborts the remaining wrap-up.
248
- 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.
249
- If exhaustion is first visible at `agent_end` and no turn remains, the extension stops without creating another model turn.
278
+ 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.
279
+ It does not queue a summary or another model turn after budget exhaustion.
280
+ Stale Goal tool calls remain blocked until an unrelated user or extension turn begins or the Goal is explicitly reactivated.
281
+ A budget-limited Goal cannot call `goal_complete`; raise its budget above current usage and resume or edit it first.
250
282
 
251
283
  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.
252
284
  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.
@@ -258,17 +290,24 @@ Legacy session entries are migrated by preserving their accumulated seconds and
258
290
 
259
291
  ## ✅ How completion works
260
292
 
261
- While a goal is active, `pi-goal` injects persistence rules, a `<goal_id>` stale-turn guard, and exposes `goal_complete`.
262
- 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.
293
+ While a goal is active, Goal-owned messages carry persistence rules and a `<goal_id>` stale-turn guard, and pi-goal exposes `goal_complete`.
294
+ Kickoff, resume, edited-objective, wait-resume, 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.
263
295
  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.
264
296
 
297
+ With the default `toolVisibility: "after-first-goal"`, the first accepted Goal activation intentionally reveals the three Goal tools and changes the tool-definition prefix once.
298
+ After that activation boundary, pi-goal does not change the base system instructions or ordered active tools merely for continuation, token accounting, or wait resume.
299
+ Current token-budget usage is carried by the newly appended Goal prompt instead of rewriting leading system instructions.
300
+ For every active Goal, one deterministic hidden Goal contract occupies a fixed leading boundary and excludes mutable token, iteration, and elapsed-time counters.
301
+ This contract follows leading summaries after compaction and also restores Goal instructions when persisted active state has no retained handoff.
302
+ These structural guarantees make provider prefix reuse possible, but the provider still decides cache eligibility, cache hits, pricing, and billing.
303
+
265
304
  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.
266
305
  Weak, indirect, missing, or merely consistent evidence means work must continue.
267
306
  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.
268
307
 
269
308
  To finish, the agent must call `goal_complete` with the exact current `goal_id` and a `summary` of completion evidence.
270
309
  Missing or stale `goal_id` values are rejected before summary validation.
271
- 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.
310
+ Paused, blocked, usage-limited, and budget-limited goals cannot be completed until resumed.
272
311
  The summary is completion evidence, not the stale-turn safety token.
273
312
 
274
313
  If a turn ends before completion, `pi-goal` records usage and creates one continuation intent unless a circuit breaker pauses it first.
@@ -451,6 +490,7 @@ packages/pi-goal/
451
490
  │ ├── commands.ts # Per-factory user-command controller
452
491
  │ ├── tools.ts # Goal completion and blocker tool adapters
453
492
  │ ├── lifecycle.ts # Pi session, agent, tool, and compaction event adapter
493
+ │ ├── goal-contract.ts # Deterministic post-compaction model contract
454
494
  │ ├── runtime.ts # Per-factory Goal state, transitions, prompts, and budgets
455
495
  │ ├── tool-policy.ts # Goal tool visibility ownership and rollback
456
496
  │ ├── safety.ts # Output normalization and no-progress fingerprint state
@@ -429,18 +429,18 @@ ${goalContextBlock(goal)}${budgetLine}
429
429
 
430
430
  ${goalModeRules("this goal")}`;
431
431
  }
432
- function buildGoalSystemPrompt(goal) {
433
- const budgetLine = goal.tokenBudget === void 0 ? "" : `
434
- - Respect the goal token budget (${formatBudget(goal)} used).`;
435
- return `Active /goal:
432
+ function buildGoalContextPrompt(goal) {
433
+ return `Active /goal context:
436
434
  ${goalContextBlock(goal)}
437
435
 
438
- ${goalModeRules("the active goal")}${budgetLine}`;
436
+ ${goalModeRules("the active goal")}`;
439
437
  }
440
438
  function buildContinuePrompt(goal, marker) {
439
+ const budgetLine = goal.tokenBudget === void 0 ? "" : `
440
+ Token budget: ${formatBudget(goal)} used.`;
441
441
  return `Continue the active /goal until it is complete:
442
442
 
443
- ${goalContextBlock(goal)}
443
+ ${goalContextBlock(goal)}${budgetLine}
444
444
 
445
445
  This is automatic continuation #${goal.iteration}. The full objective persists across turns; continue from the authoritative current state.
446
446
 
@@ -629,6 +629,8 @@ var GoalToolPolicy = class {
629
629
  this.reveal();
630
630
  return;
631
631
  }
632
+ if (this.hasHiddenTools()) this.restoreHidden();
633
+ this.unlock();
632
634
  this.assertAvailable();
633
635
  }
634
636
  prepareSessionStart(visibility, previous) {
@@ -700,6 +702,69 @@ var GoalToolPolicy = class {
700
702
  }
701
703
  };
702
704
 
705
+ // src/workflow-mutex.ts
706
+ var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
707
+ var AGENT_WORKFLOW_GROUP = "agent-workflow";
708
+ var WorkflowMutex = class {
709
+ session;
710
+ heldGroups = /* @__PURE__ */ new Map();
711
+ generation = 0;
712
+ pi;
713
+ constructor(pi) {
714
+ this.pi = pi;
715
+ pi.events.on(WORKFLOW_MUTEX_CHANNEL, (payload) => {
716
+ this.answer(payload);
717
+ });
718
+ }
719
+ bindSession(session) {
720
+ this.generation += 1;
721
+ this.heldGroups.clear();
722
+ this.session = session;
723
+ }
724
+ unbindSession(session) {
725
+ if (this.session !== session) return;
726
+ this.generation += 1;
727
+ this.heldGroups.clear();
728
+ this.session = void 0;
729
+ }
730
+ acquire(group = AGENT_WORKFLOW_GROUP) {
731
+ const session = this.session;
732
+ const generation = this.generation;
733
+ if (!session || this.heldGroups.has(group)) return void 0;
734
+ const attempt = { session, group, busy: false };
735
+ try {
736
+ this.pi.events.emit(WORKFLOW_MUTEX_CHANNEL, attempt);
737
+ } catch {
738
+ return void 0;
739
+ }
740
+ if (this.session !== session || this.generation !== generation || attempt.session !== session || attempt.group !== group || attempt.busy !== false || this.heldGroups.has(group)) {
741
+ return void 0;
742
+ }
743
+ const owner = Symbol(group);
744
+ this.heldGroups.set(group, owner);
745
+ return owner;
746
+ }
747
+ isOwner(owner, group = AGENT_WORKFLOW_GROUP) {
748
+ return owner !== void 0 && this.heldGroups.get(group) === owner;
749
+ }
750
+ release(owner, group = AGENT_WORKFLOW_GROUP) {
751
+ if (!this.isOwner(owner, group)) return;
752
+ this.heldGroups.delete(group);
753
+ }
754
+ answer(payload) {
755
+ try {
756
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
757
+ const attempt = payload;
758
+ if (attempt.session !== this.session) return;
759
+ if (attempt.group !== AGENT_WORKFLOW_GROUP) return;
760
+ if (typeof attempt.busy !== "boolean") return;
761
+ if (!this.heldGroups.has(attempt.group)) return;
762
+ attempt.busy = true;
763
+ } catch {
764
+ }
765
+ }
766
+ };
767
+
703
768
  // src/runtime.ts
704
769
  var STATUS_KEY = "goal";
705
770
  var GOAL_STATE_ENTRY_TYPE2 = "goal-state";
@@ -749,6 +814,9 @@ var GoalRuntime = class {
749
814
  guardAbortGoalId;
750
815
  staleGoalToolCallsBlocked = false;
751
816
  toolPolicy;
817
+ workflowMutex;
818
+ workflowOwner;
819
+ workflowSession;
752
820
  pendingGoalPromptMarkers = /* @__PURE__ */ new Map();
753
821
  claimedGoalPromptMarkers = /* @__PURE__ */ new Map();
754
822
  cancelledGoalPromptMarkers = /* @__PURE__ */ new Map();
@@ -760,8 +828,61 @@ var GoalRuntime = class {
760
828
  pi;
761
829
  constructor(pi) {
762
830
  this.pi = pi;
831
+ this.workflowMutex = new WorkflowMutex(pi);
763
832
  this.toolPolicy = new GoalToolPolicy(pi);
764
833
  }
834
+ bindWorkflowSession(session) {
835
+ this.workflowSession = session;
836
+ this.workflowOwner = void 0;
837
+ this.workflowMutex.bindSession(session);
838
+ }
839
+ unbindWorkflowSession(session) {
840
+ if (this.workflowSession !== session) return;
841
+ this.workflowMutex.unbindSession(session);
842
+ this.workflowOwner = void 0;
843
+ this.workflowSession = void 0;
844
+ }
845
+ acquireWorkflow(session) {
846
+ if (session && typeof session === "object" && this.workflowSession !== session) {
847
+ this.bindWorkflowSession(session);
848
+ }
849
+ if (this.workflowMutex.isOwner(this.workflowOwner)) return true;
850
+ const owner = this.workflowMutex.acquire();
851
+ if (!owner) return false;
852
+ this.workflowOwner = owner;
853
+ return true;
854
+ }
855
+ ownsWorkflow(goal = this.activeGoal) {
856
+ return goal?.status === "active" && this.workflowMutex.isOwner(this.workflowOwner);
857
+ }
858
+ releaseWorkflow() {
859
+ const owner = this.workflowOwner;
860
+ this.workflowMutex.release(owner);
861
+ if (!this.workflowMutex.isOwner(owner)) this.workflowOwner = void 0;
862
+ }
863
+ beginTemporaryWorkflowAccess(session) {
864
+ if (session && typeof session === "object" && this.workflowSession !== session) {
865
+ this.bindWorkflowSession(session);
866
+ }
867
+ const alreadyOwned = this.workflowMutex.isOwner(this.workflowOwner);
868
+ if (!alreadyOwned && !this.acquireWorkflow()) return void 0;
869
+ let released = false;
870
+ return () => {
871
+ if (released) return;
872
+ released = true;
873
+ if (!alreadyOwned) this.releaseWorkflow();
874
+ };
875
+ }
876
+ withTemporaryWorkflowAccess(action, session) {
877
+ const release = this.beginTemporaryWorkflowAccess(session);
878
+ if (!release) return false;
879
+ try {
880
+ action();
881
+ return true;
882
+ } finally {
883
+ release();
884
+ }
885
+ }
765
886
  hasLegacyQueueInterface() {
766
887
  return this.legacyExperimentalGoalsSetting || this.legacyQueueState !== void 0;
767
888
  }
@@ -832,6 +953,7 @@ var GoalRuntime = class {
832
953
  return true;
833
954
  }
834
955
  requestContinuation(goal) {
956
+ if (!this.ownsWorkflow(goal)) return false;
835
957
  if (goal.waiting || this.hasContinuationWorkForGoal(goal.id)) return false;
836
958
  const marker = continuationMarker(goal);
837
959
  this.continuationIntent = {
@@ -844,6 +966,10 @@ var GoalRuntime = class {
844
966
  }
845
967
  dispatchContinuationIfSettled(ctx) {
846
968
  const intent = this.continuationIntent;
969
+ if (!this.ownsWorkflow()) {
970
+ this.cancelContinuationWork();
971
+ return false;
972
+ }
847
973
  if (!intent) return false;
848
974
  if (this.activeGoal?.status === "active" && !this.toolPolicy.toolsAvailable()) {
849
975
  this.pauseGoalForUnavailableTools(ctx);
@@ -879,7 +1005,7 @@ var GoalRuntime = class {
879
1005
  }
880
1006
  enterGoalWait(ctx, goalId, waiting) {
881
1007
  const goal = this.activeGoal;
882
- if (!goal || goal.id !== goalId || goal.status !== "active") return void 0;
1008
+ if (!goal || goal.id !== goalId || !this.ownsWorkflow(goal)) return void 0;
883
1009
  this.recordGoalUsage(goal, ctx, false);
884
1010
  this.cancelContinuationWork();
885
1011
  this.clearGoalRecoveryForGoal(goal.id);
@@ -897,7 +1023,7 @@ var GoalRuntime = class {
897
1023
  }
898
1024
  clearGoalWait(ctx, goalId) {
899
1025
  const goal = this.activeGoal;
900
- if (!goal || goal.id !== goalId || goal.status !== "active" || !goal.waiting) return false;
1026
+ if (!goal || goal.id !== goalId || !this.ownsWorkflow(goal) || !goal.waiting) return false;
901
1027
  this.clearGoalWaitTimer();
902
1028
  const { waiting: _waiting, ...nextGoal } = goal;
903
1029
  const now = Date.now();
@@ -911,6 +1037,7 @@ var GoalRuntime = class {
911
1037
  restoreGoalWaitTimer(ctx) {
912
1038
  this.clearGoalWaitTimer();
913
1039
  const goal = this.activeGoal;
1040
+ if (!this.ownsWorkflow(goal)) return false;
914
1041
  const resumeAt = goal?.status === "active" ? goal.waiting?.resumeAt : void 0;
915
1042
  if (!goal || resumeAt === void 0) return false;
916
1043
  this.scheduleGoalWaitTimer(ctx, goal.id, resumeAt);
@@ -918,6 +1045,7 @@ var GoalRuntime = class {
918
1045
  }
919
1046
  dispatchDueGoalWait(ctx) {
920
1047
  const goal = this.activeGoal;
1048
+ if (!this.ownsWorkflow(goal)) return false;
921
1049
  const waiting = goal?.status === "active" ? goal.waiting : void 0;
922
1050
  const resumeAt = waiting?.resumeAt;
923
1051
  if (!goal || !waiting || resumeAt === void 0) return false;
@@ -947,7 +1075,9 @@ var GoalRuntime = class {
947
1075
  scheduleGoalWaitTimer(ctx, goalId, wakeAt) {
948
1076
  const generation = this.menuGeneration;
949
1077
  this.goalWaitTimer.schedule(wakeAt, () => {
950
- if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId) return;
1078
+ if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
1079
+ return;
1080
+ }
951
1081
  try {
952
1082
  this.dispatchDueGoalWait(ctx);
953
1083
  } catch (error) {
@@ -1008,6 +1138,8 @@ var GoalRuntime = class {
1008
1138
  this.cancelContinuationWork();
1009
1139
  this.clearGoalRecoveryForGoal(goal.id);
1010
1140
  this.clearBudgetWrapUp();
1141
+ this.blockStaleGoalToolCalls();
1142
+ abortCurrentTurn(ctx);
1011
1143
  status = "budget_limited";
1012
1144
  terminalReason = request.reason;
1013
1145
  break;
@@ -1075,6 +1207,7 @@ var GoalRuntime = class {
1075
1207
  this.persistGoal(stoppedGoal);
1076
1208
  if (this.activeGoal?.id === stoppedGoal.id && this.activeGoal.status === stoppedGoal.status) {
1077
1209
  this.updateStatus(ctx, stoppedGoal);
1210
+ this.releaseWorkflow();
1078
1211
  }
1079
1212
  return stoppedGoal;
1080
1213
  }
@@ -1113,6 +1246,7 @@ var GoalRuntime = class {
1113
1246
  return this.isActiveBudgetWrapUpMessage(message);
1114
1247
  }
1115
1248
  queueBudgetWrapUp(ctx, goal) {
1249
+ if (!this.ownsWorkflow(goal)) return false;
1116
1250
  if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
1117
1251
  this.budgetWrapUp = { goalId: goal.id, delivered: false };
1118
1252
  }
@@ -1268,9 +1402,10 @@ var GoalRuntime = class {
1268
1402
  this.pendingNonGoalInputs = [];
1269
1403
  }
1270
1404
  async sendOwnedGoalPrompt(ctx, goalId, prompt, resetSafetyEpoch = true, isCurrent) {
1405
+ if (this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) return false;
1271
1406
  const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
1272
1407
  const sent = await sendPrompt(this.pi, ctx, pending.prompt, isCurrent);
1273
- if (!sent || isCurrent && !isCurrent()) {
1408
+ if (!sent || isCurrent && !isCurrent() || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
1274
1409
  this.pendingGoalPromptMarkers.delete(pending.marker);
1275
1410
  return false;
1276
1411
  }
@@ -1289,7 +1424,7 @@ var GoalRuntime = class {
1289
1424
  const generation = this.menuGeneration;
1290
1425
  this.continuationDispatchTimer = setTimeout(() => {
1291
1426
  this.continuationDispatchTimer = void 0;
1292
- if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId || this.activeGoal.status !== "active") {
1427
+ if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
1293
1428
  return;
1294
1429
  }
1295
1430
  this.dispatchContinuationIfSettled(ctx);
@@ -1455,7 +1590,7 @@ var GoalRuntime = class {
1455
1590
  this.clearTerminalDetails();
1456
1591
  clearLegacyPersistedGoal(cwd);
1457
1592
  }
1458
- clearActiveGoal(ctx, reason = "goal cleared") {
1593
+ clearActiveGoal(ctx, reason = "goal cleared", releaseWorkflow = true) {
1459
1594
  const clearedGoal = this.activeGoal;
1460
1595
  this.clearGoalWaitTimer();
1461
1596
  this.cancelContinuationWork();
@@ -1466,6 +1601,7 @@ var GoalRuntime = class {
1466
1601
  this.legacyQueueState = void 0;
1467
1602
  this.clearPersistedGoal(ctx.cwd, clearedGoal, reason);
1468
1603
  ctx.ui.setStatus(STATUS_KEY, void 0);
1604
+ if (releaseWorkflow) this.releaseWorkflow();
1469
1605
  }
1470
1606
  snapshotSettingsApplicationState() {
1471
1607
  return {
@@ -1485,6 +1621,9 @@ var GoalRuntime = class {
1485
1621
  };
1486
1622
  }
1487
1623
  restoreSettingsApplicationState(snapshot) {
1624
+ if (snapshot.activeGoal?.status === "active" && !this.acquireWorkflow()) {
1625
+ throw new Error("another workflow became active before Goal settings could roll back");
1626
+ }
1488
1627
  this.settings = structuredClone(snapshot.settings);
1489
1628
  this.activeGoal = snapshot.activeGoal ? structuredClone(snapshot.activeGoal) : void 0;
1490
1629
  this.legacyQueueState = snapshot.legacyQueueState ? structuredClone(snapshot.legacyQueueState) : void 0;
@@ -1684,10 +1823,10 @@ function abortCurrentTurn(ctx) {
1684
1823
  }
1685
1824
  }
1686
1825
  function blocksStaleGoalToolCalls(status) {
1687
- return status === "paused" || status === "blocked" || status === "usage_limited";
1826
+ return status === "paused" || status === "blocked" || status === "usage_limited" || status === "budget_limited";
1688
1827
  }
1689
1828
  function isResumableGoalStatus(status) {
1690
- return blocksStaleGoalToolCalls(status) || status === "budget_limited";
1829
+ return blocksStaleGoalToolCalls(status);
1691
1830
  }
1692
1831
  function stoppedStatusLabel2(status) {
1693
1832
  if (status === "usage_limited") return "usage-limited";
@@ -1753,7 +1892,7 @@ export {
1753
1892
  buildObjectiveUpdatedPrompt,
1754
1893
  buildResumePrompt,
1755
1894
  buildWaitingResumePrompt,
1756
- buildGoalSystemPrompt,
1895
+ buildGoalContextPrompt,
1757
1896
  queueGoalSafetyReset,
1758
1897
  resetGoalSafetyEpoch,
1759
1898
  hasAssistantToolCall,
@@ -1779,4 +1918,4 @@ export {
1779
1918
  isContradictoryCompletionSummary,
1780
1919
  goalIdRejectionReason
1781
1920
  };
1782
- //# sourceMappingURL=chunk-ODVXYZXS.ts.map
1921
+ //# sourceMappingURL=chunk-4GOI2LMD.ts.map