@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/dist/index.ts CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  stoppedStatusLabel,
41
41
  transitionGoal,
42
42
  validateObjective
43
- } from "./chunks/chunk-ODVXYZXS.js";
43
+ } from "./chunks/chunk-W7AFYZ6J.js";
44
44
  import {
45
45
  DEFAULT_GOAL_SETTINGS,
46
46
  currentTokenTotal,
@@ -60,10 +60,10 @@ import {
60
60
  // src/command-registration.ts
61
61
  function registerGoalCommand(pi, runtime, commands, options = {}) {
62
62
  const loadGoalManager = cachedModuleLoader(
63
- options.loadGoalManager ?? (() => import("./chunks/menu-YILEIJE6.js"))
63
+ options.loadGoalManager ?? (() => import("./chunks/menu-73TCS5P6.js"))
64
64
  );
65
65
  const loadGoalSettings = cachedModuleLoader(
66
- options.loadGoalSettings ?? (() => import("./chunks/settings-ui-HMSJEEZN.js"))
66
+ options.loadGoalSettings ?? (() => import("./chunks/settings-ui-Y5LMEFEH.js"))
67
67
  );
68
68
  pi.registerCommand("goal", {
69
69
  description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
@@ -195,12 +195,16 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
195
195
  }
196
196
  }
197
197
  if (isRequestCurrent && !isRequestCurrent()) return;
198
+ const retainedOwner = this.runtime.ownsWorkflow(existingGoal);
199
+ if (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);
200
+ const acquiredForRequest = !retainedOwner;
198
201
  const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
199
202
  try {
200
203
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
201
204
  } catch (error) {
202
205
  notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, "error");
203
206
  if (existingGoal?.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
207
+ else if (acquiredForRequest) this.runtime.releaseWorkflow();
204
208
  return;
205
209
  }
206
210
  this.runtime.clearGoalWaitTimer();
@@ -213,7 +217,7 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
213
217
  const startedGoal = this.runtime.activeGoal;
214
218
  onActivated?.(startedGoal);
215
219
  if (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);
216
- if (this.runtime.activeGoal?.id !== startedGoal.id || this.runtime.activeGoal.status !== "active") {
220
+ if (this.runtime.activeGoal?.id !== startedGoal.id || !this.runtime.ownsWorkflow(this.runtime.activeGoal)) {
217
221
  return;
218
222
  }
219
223
  this.runtime.updateStatus(ctx, startedGoal);
@@ -242,12 +246,12 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
242
246
  this.runtime.updateStatus(ctx, existingGoal);
243
247
  this.runtime.restoreGoalWaitTimer(ctx);
244
248
  } else if (existingGoal.status === "active") {
245
- this.runtime.stopActiveGoal(ctx, {
246
- kind: "activation_rollback",
247
- expectedGoalId: startedGoal.id,
248
- restoreGoal: existingGoal,
249
- abortTurn: true
250
- });
249
+ this.runtime.activeGoal = existingGoal;
250
+ this.runtime.clearStaleGoalToolCallBlock();
251
+ this.runtime.persistGoal(existingGoal);
252
+ if (this.runtime.activeGoal?.id === existingGoal.id) {
253
+ this.runtime.updateStatus(ctx, existingGoal);
254
+ }
251
255
  } else {
252
256
  this.runtime.activeGoal = existingGoal;
253
257
  if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
@@ -267,15 +271,18 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
267
271
  this.runtime.clearStaleGoalToolCallBlock();
268
272
  ctx.ui.setStatus(STATUS_KEY, void 0);
269
273
  } else {
270
- this.runtime.clearActiveGoal(ctx);
274
+ this.runtime.clearActiveGoal(ctx, "goal activation rolled back", false);
271
275
  }
272
276
  }
273
277
  if (rolledBackStartedGoal) {
274
278
  this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
279
+ if (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {
280
+ this.runtime.releaseWorkflow();
281
+ }
275
282
  }
276
283
  return;
277
284
  }
278
- if (this.runtime.activeGoal?.id !== startedGoal.id || this.runtime.activeGoal.status !== "active") {
285
+ if (this.runtime.activeGoal?.id !== startedGoal.id || !this.runtime.ownsWorkflow(this.runtime.activeGoal)) {
279
286
  return;
280
287
  }
281
288
  const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
@@ -329,11 +336,16 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
329
336
  );
330
337
  return;
331
338
  }
339
+ if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {
340
+ this.reportWorkflowBusy(ctx);
341
+ return;
342
+ }
332
343
  const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
333
344
  try {
334
345
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
335
346
  } catch (error) {
336
347
  notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
348
+ this.runtime.releaseWorkflow();
337
349
  return;
338
350
  }
339
351
  const stoppedGoal = this.runtime.activeGoal;
@@ -346,8 +358,9 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
346
358
  transitionGoal(nextGoalInstance(this.runtime.activeGoal), "active")
347
359
  );
348
360
  this.runtime.persistGoal(this.runtime.activeGoal);
349
- this.runtime.updateStatus(ctx, this.runtime.activeGoal);
350
361
  if (this.runtime.activeGoal.status !== "active") {
362
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
363
+ this.runtime.releaseWorkflow();
351
364
  notifyTerminal(
352
365
  ctx.ui,
353
366
  `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,
@@ -355,6 +368,8 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
355
368
  );
356
369
  return;
357
370
  }
371
+ if (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;
372
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
358
373
  const resumedGoal = this.runtime.activeGoal;
359
374
  const sent = await this.runtime.sendOwnedGoalPrompt(
360
375
  ctx,
@@ -370,9 +385,11 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
370
385
  this.runtime.blockStaleGoalToolCalls();
371
386
  }
372
387
  this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
388
+ this.runtime.releaseWorkflow();
373
389
  }
374
390
  return;
375
391
  }
392
+ if (!this.runtime.ownsWorkflow(resumedGoal)) return;
376
393
  const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
377
394
  notifyTerminal(
378
395
  ctx.ui,
@@ -384,6 +401,10 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
384
401
  const waitingGoal = this.runtime.activeGoal;
385
402
  const waiting = waitingGoal?.waiting;
386
403
  if (waitingGoal?.status !== "active" || !waiting) return;
404
+ if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {
405
+ this.reportWorkflowBusy(ctx);
406
+ return;
407
+ }
387
408
  try {
388
409
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
389
410
  } catch (error) {
@@ -406,6 +427,7 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
406
427
  }
407
428
  return;
408
429
  }
430
+ if (!this.runtime.ownsWorkflow(resumedGoal)) return;
409
431
  notifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, "info");
410
432
  }
411
433
  clearGoal(ctx) {
@@ -439,42 +461,59 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
439
461
  notifyTerminal(ctx.ui, "No active goal. Use /goal <objective> to start one.", "warning");
440
462
  return;
441
463
  }
442
- this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
443
- const previousGoal = { ...this.runtime.activeGoal };
464
+ const currentGoal = this.runtime.activeGoal;
465
+ const effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;
466
+ if (currentGoal.status === "budget_limited" && effectiveTokenBudget !== void 0 && effectiveTokenBudget <= currentGoal.tokensUsed) {
467
+ notifyTerminal(
468
+ ctx.ui,
469
+ `Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,
470
+ "warning"
471
+ );
472
+ return;
473
+ }
474
+ const previousStatus = currentGoal.status;
475
+ const intendsActive = editedGoalStatus(previousStatus) === "active";
476
+ const retainedOwner = this.runtime.ownsWorkflow(currentGoal);
477
+ if (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {
478
+ this.reportWorkflowBusy(ctx);
479
+ return;
480
+ }
481
+ const acquiredForEdit = intendsActive && !retainedOwner;
482
+ const goalToolVisibilityBeforeActivation = intendsActive ? this.runtime.toolPolicy.snapshot() : void 0;
483
+ if (intendsActive) {
484
+ try {
485
+ this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
486
+ } catch (error) {
487
+ notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
488
+ if (currentGoal.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
489
+ else if (acquiredForEdit) this.runtime.releaseWorkflow();
490
+ return;
491
+ }
492
+ }
493
+ this.runtime.recordGoalUsage(currentGoal, ctx);
494
+ const previousGoal = { ...currentGoal };
444
495
  this.runtime.clearGoalWaitTimer();
445
496
  this.runtime.cancelContinuationWork();
446
497
  this.runtime.clearGoalRecovery();
447
498
  this.runtime.clearBudgetWrapUp();
448
- const previousStatus = this.runtime.activeGoal.status;
449
- const rotatedGoal = nextGoalInstance(this.runtime.activeGoal);
499
+ const rotatedGoal = nextGoalInstance(currentGoal);
450
500
  const transitionedGoal = transitionGoal(
451
501
  {
452
502
  ...rotatedGoal,
453
503
  text: objective,
454
- tokenBudget: tokenBudget ?? this.runtime.activeGoal.tokenBudget,
504
+ tokenBudget: effectiveTokenBudget,
455
505
  waiting: void 0
456
506
  },
457
507
  editedGoalStatus(previousStatus)
458
508
  );
459
509
  const nextGoal = transitionedGoal.status === "active" ? queueGoalSafetyReset(transitionedGoal) : transitionedGoal;
460
- const goalToolVisibilityBeforeActivation = nextGoal.status === "active" ? this.runtime.toolPolicy.snapshot() : void 0;
461
- if (nextGoal.status === "active") {
462
- try {
463
- this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
464
- } catch (error) {
465
- notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
466
- if (this.runtime.activeGoal?.status === "active") {
467
- this.runtime.pauseGoalForUnavailableTools(ctx);
468
- }
469
- return;
470
- }
471
- }
472
510
  this.runtime.activeGoal = nextGoal;
473
511
  this.runtime.persistGoal(this.runtime.activeGoal);
474
512
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
475
513
  const editedGoal = this.runtime.activeGoal;
476
514
  if (!editedGoal) return;
477
515
  if (editedGoal.status === "active") {
516
+ if (!this.runtime.ownsWorkflow(editedGoal)) return;
478
517
  this.runtime.clearStaleGoalToolCallBlock();
479
518
  const sent = await this.runtime.sendOwnedGoalPrompt(
480
519
  ctx,
@@ -490,12 +529,12 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
490
529
  this.runtime.updateStatus(ctx, previousGoal);
491
530
  this.runtime.restoreGoalWaitTimer(ctx);
492
531
  } else if (previousStatus === "active") {
493
- this.runtime.stopActiveGoal(ctx, {
494
- kind: "activation_rollback",
495
- expectedGoalId: editedGoal.id,
496
- restoreGoal: previousGoal,
497
- abortTurn: true
498
- });
532
+ this.runtime.activeGoal = previousGoal;
533
+ this.runtime.clearStaleGoalToolCallBlock();
534
+ this.runtime.persistGoal(previousGoal);
535
+ if (this.runtime.activeGoal?.id === previousGoal.id) {
536
+ this.runtime.updateStatus(ctx, previousGoal);
537
+ }
499
538
  } else {
500
539
  this.runtime.activeGoal = previousGoal;
501
540
  if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
@@ -509,16 +548,29 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
509
548
  if (goalToolVisibilityBeforeActivation) {
510
549
  this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
511
550
  }
551
+ if (acquiredForEdit && previousStatus !== "active") {
552
+ this.runtime.releaseWorkflow();
553
+ }
512
554
  }
513
555
  return;
514
556
  }
557
+ if (!this.runtime.ownsWorkflow(editedGoal)) return;
515
558
  } else if (blocksStaleGoalToolCalls(editedGoal.status)) {
516
559
  this.runtime.blockStaleGoalToolCalls();
517
560
  } else {
518
561
  this.runtime.clearStaleGoalToolCallBlock();
519
562
  }
563
+ if (editedGoal.status !== "active" && (retainedOwner || acquiredForEdit)) {
564
+ this.runtime.releaseWorkflow();
565
+ }
520
566
  notifyTerminal(ctx.ui, `Goal updated: ${objective}`, "info");
521
567
  }
568
+ reportWorkflowBusy(ctx) {
569
+ const message = "Another workflow is active in this session. End it before starting Goal.";
570
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(message);
571
+ notifyTerminal(ctx.ui, message, "warning");
572
+ return { kind: "busy" };
573
+ }
522
574
  showGoal(ctx) {
523
575
  if (!this.runtime.activeGoal) {
524
576
  ctx.ui.setStatus(STATUS_KEY, void 0);
@@ -558,6 +610,7 @@ var REMOVED_QUEUE_SETTING_WARNING = "Ordered goal queue has been removed. Use /g
558
610
  var REMOVED_PERSISTED_QUEUE_WARNING = "Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.";
559
611
  function registerGoalLifecycle(pi, runtime, runController, options = {}) {
560
612
  pi.on("session_start", async (_event, ctx) => {
613
+ runtime.bindWorkflowSession(ctx.sessionManager);
561
614
  runtime.replaceMenuSession();
562
615
  runtime.clearCompletionStatusTimer();
563
616
  runtime.clearContinuationTracking();
@@ -573,8 +626,13 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
573
626
  runtime.clearTerminalDetails();
574
627
  const previousToolVisibility = runtime.settings.toolVisibility;
575
628
  const settingsResult = readGoalSettings(options.settingsPath);
629
+ const loaded = loadGoalStateFromSession(ctx);
576
630
  runtime.settings = settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
577
631
  runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : void 0;
632
+ runtime.activeGoal = void 0;
633
+ runtime.legacyQueueState = loaded.legacyQueueState;
634
+ runtime.legacyExperimentalGoalsSetting = settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
635
+ runController.bindSession(ctx);
578
636
  if (settingsResult.kind === "invalid") {
579
637
  notifyTerminal(
580
638
  ctx.ui,
@@ -582,56 +640,96 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
582
640
  "warning"
583
641
  );
584
642
  }
585
- runtime.legacyExperimentalGoalsSetting = settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
643
+ if (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {
644
+ notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, "warning");
645
+ }
646
+ if (loaded.goal?.status === "active") {
647
+ if (!runtime.acquireWorkflow()) {
648
+ runtime.activeGoal = transitionGoal(loaded.goal, "paused");
649
+ runtime.persistGoal(runtime.activeGoal);
650
+ runtime.updateStatus(ctx, runtime.activeGoal);
651
+ notifyTerminal(
652
+ ctx.ui,
653
+ "Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.",
654
+ "warning"
655
+ );
656
+ return;
657
+ }
658
+ runtime.activeGoal = loaded.goal;
659
+ try {
660
+ runtime.toolPolicy.prepareSessionStart(
661
+ runtime.settings.toolVisibility,
662
+ previousToolVisibility
663
+ );
664
+ } catch (error) {
665
+ notifyTerminal(
666
+ ctx.ui,
667
+ `Could not restore always-visible goal tools: ${formatError(error)}`,
668
+ "error"
669
+ );
670
+ }
671
+ if (runtime.activeGoal.safetyResetPending) {
672
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
673
+ }
674
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
675
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
676
+ if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {
677
+ return;
678
+ }
679
+ runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);
680
+ if (!runtime.toolPolicy.toolsAvailable()) {
681
+ runtime.pauseGoalForUnavailableTools(ctx, false);
682
+ return;
683
+ }
684
+ runtime.persistGoal(runtime.activeGoal);
685
+ if (!runtime.ownsWorkflow(runtime.activeGoal)) return;
686
+ runtime.updateStatus(ctx, runtime.activeGoal);
687
+ runtime.restoreGoalWaitTimer(ctx);
688
+ return;
689
+ }
690
+ runtime.activeGoal = loaded.goal;
691
+ let appliedInactivePolicy = false;
692
+ let inactivePolicyFailed = false;
586
693
  try {
587
- runtime.toolPolicy.prepareSessionStart(
588
- runtime.settings.toolVisibility,
589
- previousToolVisibility
590
- );
694
+ appliedInactivePolicy = runtime.withTemporaryWorkflowAccess(() => {
695
+ runtime.toolPolicy.prepareSessionStart(
696
+ runtime.settings.toolVisibility,
697
+ previousToolVisibility
698
+ );
699
+ runtime.toolPolicy.reconcileRestoredState(
700
+ runtime.settings.toolVisibility,
701
+ runtime.activeGoal !== void 0 && runtime.legacyQueueState === void 0
702
+ );
703
+ });
591
704
  } catch (error) {
705
+ inactivePolicyFailed = true;
592
706
  notifyTerminal(
593
707
  ctx.ui,
594
708
  `Could not restore always-visible goal tools: ${formatError(error)}`,
595
709
  "error"
596
710
  );
597
711
  }
598
- const loaded = loadGoalStateFromSession(ctx);
599
- runtime.activeGoal = loaded.goal;
600
- runtime.legacyQueueState = loaded.legacyQueueState;
601
- runController.bindSession(ctx);
712
+ if (!appliedInactivePolicy && !inactivePolicyFailed) {
713
+ notifyTerminal(
714
+ ctx.ui,
715
+ "Goal tool visibility was deferred because another workflow is active in this session.",
716
+ "warning"
717
+ );
718
+ }
602
719
  if (runtime.legacyQueueState) {
603
- runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
604
720
  ctx.ui.setStatus(STATUS_KEY, void 0);
605
721
  notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
606
722
  return;
607
723
  }
608
- if (runtime.legacyExperimentalGoalsSetting) {
609
- notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, "warning");
610
- }
611
724
  if (runtime.activeGoal) {
612
- if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
613
- runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
614
- }
615
- if (runtime.activeGoal.status === "active") {
616
- runtime.recordGoalUsage(runtime.activeGoal, ctx);
617
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
618
- if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx))
619
- return;
620
- }
621
- runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);
622
- if (runtime.activeGoal.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
623
- runtime.pauseGoalForUnavailableTools(ctx, false);
624
- return;
625
- }
626
725
  runtime.persistGoal(runtime.activeGoal);
627
726
  runtime.updateStatus(ctx, runtime.activeGoal);
628
- runtime.restoreGoalWaitTimer(ctx);
629
727
  } else {
630
- runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
631
728
  ctx.ui.setStatus(STATUS_KEY, void 0);
632
729
  }
633
730
  });
634
731
  pi.on("session_shutdown", (_event, ctx) => {
732
+ const shutdownSession = ctx.sessionManager;
635
733
  runController.unbindSession();
636
734
  runtime.closeMenuSession();
637
735
  runtime.clearGoalWaitTimer();
@@ -654,13 +752,17 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
654
752
  ctx.ui.setStatus(STATUS_KEY, void 0);
655
753
  runtime.clearCompletionStatusTimer();
656
754
  runtime.clearTerminalDetails();
755
+ runtime.releaseWorkflow();
756
+ runtime.unbindWorkflowSession(shutdownSession);
657
757
  });
658
758
  pi.on("session_before_compact", (event, ctx) => {
659
759
  if (runtime.activeGoal?.status === "budget_limited") {
660
760
  if (event.willRetry === true) return { cancel: true };
661
761
  return;
662
762
  }
663
- if (runtime.activeGoal?.status !== "active") return;
763
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
764
+ return;
765
+ }
664
766
  if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
665
767
  runtime.cancelContinuationWork();
666
768
  runtime.persistGoal(runtime.activeGoal);
@@ -668,7 +770,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
668
770
  if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true };
669
771
  });
670
772
  pi.on("session_compact", async (event, ctx) => {
671
- if (runtime.activeGoal?.status !== "active") {
773
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
672
774
  runtime.clearGoalRecovery();
673
775
  return;
674
776
  }
@@ -745,7 +847,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
745
847
  }
746
848
  return;
747
849
  }
748
- if (runtime.activeGoal?.id !== ownedPrompt.goalId || runtime.activeGoal.status !== "active") {
850
+ if (runtime.activeGoal?.id !== ownedPrompt.goalId || !runtime.ownsWorkflow(runtime.activeGoal)) {
749
851
  return;
750
852
  }
751
853
  if (runtime.agentRunGoalId !== void 0 && runtime.agentRunGoalId !== ownedPrompt.goalId) {
@@ -793,7 +895,9 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
793
895
  runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
794
896
  return;
795
897
  }
796
- if (runtime.activeGoal?.status !== "active") return;
898
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
899
+ return;
900
+ }
797
901
  if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
798
902
  runtime.persistGoal(runtime.activeGoal);
799
903
  runtime.updateStatus(ctx, runtime.activeGoal);
@@ -821,6 +925,12 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
821
925
  runtime.supersedeOwnedInputCollision(event.prompt);
822
926
  if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
823
927
  }
928
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
929
+ runtime.cancelContinuationWork();
930
+ runtime.clearGoalRecovery();
931
+ abortCurrentTurn(ctx);
932
+ return;
933
+ }
824
934
  const runOrigin = continuationGoalId ? "automatic" : activeGoalRecovery && runtime.goalRecovery?.automaticOwner ? "automatic" : "manual";
825
935
  if (activeBudgetWrapUp && runtime.activeGoal) {
826
936
  runtime.beginAgentRun(runtime.activeGoal.id, "manual");
@@ -834,7 +944,9 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
834
944
  abortCurrentTurn(ctx);
835
945
  return;
836
946
  }
837
- if (runtime.activeGoal?.status !== "active") return;
947
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
948
+ return;
949
+ }
838
950
  runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
839
951
  if (!runtime.toolPolicy.toolsAvailable()) {
840
952
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== void 0);
@@ -879,7 +991,9 @@ ${buildGoalSystemPrompt(runtime.activeGoal)}`
879
991
  runtime.clearBudgetWrapUp();
880
992
  return;
881
993
  }
882
- if (runtime.activeGoal.status !== "active") return;
994
+ if (runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
995
+ return;
996
+ }
883
997
  const goalId = runtime.activeGoal.id;
884
998
  const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
885
999
  const finalAssistant = findFinalAssistantMessage(event.messages);
@@ -939,6 +1053,12 @@ ${buildGoalSystemPrompt(runtime.activeGoal)}`
939
1053
  runtime.requestContinuation(currentGoal);
940
1054
  });
941
1055
  pi.on("agent_settled", (_event, ctx) => {
1056
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
1057
+ runtime.cancelContinuationWork();
1058
+ runtime.clearGoalRecovery();
1059
+ runtime.clearSettledSafetyTracking();
1060
+ return;
1061
+ }
942
1062
  runtime.finalizeSettledRecovery(ctx);
943
1063
  const resumedWait = runtime.dispatchDueGoalWait(ctx);
944
1064
  if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
@@ -1121,7 +1241,7 @@ var GoalRunController = class {
1121
1241
  this.run = run;
1122
1242
  this.usedRunIds.add(runId);
1123
1243
  try {
1124
- await this.commands.startGoal(
1244
+ const activation = await this.commands.startGoal(
1125
1245
  parsed.objective,
1126
1246
  parsed.tokenBudget,
1127
1247
  session.ctx,
@@ -1130,6 +1250,16 @@ var GoalRunController = class {
1130
1250
  },
1131
1251
  () => this.ownsRun(run, session.generation)
1132
1252
  );
1253
+ if (activation?.kind === "busy" && this.ownsRun(run, session.generation)) {
1254
+ this.closeCurrentRun();
1255
+ this.emitError(
1256
+ runId,
1257
+ "start",
1258
+ "ACTIVATION_FAILED",
1259
+ "Another workflow is active in this session. End it before starting Goal."
1260
+ );
1261
+ return;
1262
+ }
1133
1263
  } catch (error) {
1134
1264
  if (this.ownsRun(run, session.generation)) {
1135
1265
  this.closeCurrentRun();
@@ -1302,6 +1432,14 @@ function registerGoalTools(pi, runtime) {
1302
1432
  };
1303
1433
  }
1304
1434
  const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
1435
+ if (completedGoal.status === "active" && !runtime.ownsWorkflow(completedGoal)) {
1436
+ const rejection = "Goal completion rejected: active Goal no longer owns its workflow.";
1437
+ notifyTerminal(ctx.ui, rejection, "warning");
1438
+ return {
1439
+ content: toolContent(rejection),
1440
+ details: completionDetails(goal2, requestedGoalId, summary)
1441
+ };
1442
+ }
1305
1443
  if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
1306
1444
  const rejection = "Goal completion rejected: current run does not own the active goal.";
1307
1445
  notifyTerminal(ctx.ui, rejection, "warning");
@@ -1421,6 +1559,8 @@ function registerGoalTools(pi, runtime) {
1421
1559
  if (blockedGoal.status !== "active") {
1422
1560
  return reject(`goal is ${blockedGoal.status}, not active`);
1423
1561
  }
1562
+ if (!runtime.ownsWorkflow(blockedGoal))
1563
+ return reject("active Goal no longer owns its workflow");
1424
1564
  if (!reason) return reject("reason is empty");
1425
1565
  if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
1426
1566
  if (!evidence) return reject("evidence is empty");
@@ -1495,6 +1635,8 @@ function registerGoalTools(pi, runtime) {
1495
1635
  if (activeGoal.status !== "active") {
1496
1636
  return reject(`goal is ${activeGoal.status}, not active`);
1497
1637
  }
1638
+ if (!runtime.ownsWorkflow(activeGoal))
1639
+ return reject("active Goal no longer owns its workflow");
1498
1640
  if (activeGoal.waiting) return reject("goal is already waiting");
1499
1641
  if (!reason) return reject("reason is empty");
1500
1642
  if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject("reason is too long");