pi-better-goal 0.17.1 → 0.18.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.17.1",
3
+ "version": "0.18.2",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/goal-state.ts CHANGED
@@ -16,6 +16,7 @@ interface GoalLike {
16
16
  goalId: string;
17
17
  objective: string;
18
18
  command?: unknown;
19
+ workflowBinding?: { name?: unknown; path?: unknown } | null;
19
20
  status: GoalStatus;
20
21
  pauseReason?: unknown;
21
22
  tokenBudget?: number | null;
@@ -133,6 +134,9 @@ function normalizeGoal(goal: GoalLike): GoalSnapshot {
133
134
  goalId: goal.goalId,
134
135
  objective: goal.objective,
135
136
  ...(isCommandBinding(goal.command) ? { command: goal.command } : {}),
137
+ ...(goal.workflowBinding === null ? { workflowBinding: null } :
138
+ typeof goal.workflowBinding?.name === "string" && typeof goal.workflowBinding.path === "string"
139
+ ? { workflowBinding: { name: goal.workflowBinding.name, path: goal.workflowBinding.path } } : {}),
136
140
  status: goal.status,
137
141
  ...(pauseReason ? { pauseReason } : {}),
138
142
  tokenBudget: typeof goal.tokenBudget === "number" ? goal.tokenBudget : null,
package/src/index.ts CHANGED
@@ -43,12 +43,15 @@ import {
43
43
  import { createRenderScheduler } from "./shared-render-scheduler.js";
44
44
  import { initializeNavigatorPanels, setNavigatorPanel } from "./shared-navigator-panels.js";
45
45
  import { collectSubagentActivity } from "./subagents.js";
46
- import { currentWorkflowOwner, ISSUE_WORKFLOW_SKILLS, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
47
- import { completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
46
+ import { currentWorkflowOwner, restoredWorkflowMatches, ISSUE_WORKFLOW_SKILLS, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
47
+ import { boundPlanEntry, WORKFLOW_PLAN_ENTRY, completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
48
48
  import { workflowRehydrateMessage, WORKFLOW_REHYDRATE_MESSAGE_TYPE } from "./rehydrate.js";
49
49
  import { canStartGoalFromOutcome, GOAL_PANEL_START_EVENT, type GoalPanelStartRequest, OUTCOME_ACCEPTED_EVENT, requestTaskContext, type OutcomeAcceptedEvent } from "./task-context.js";
50
50
  import {
51
51
  EVENT_ACTIVITY,
52
+ sessionIdleEvent,
53
+ type SessionIdleInspection,
54
+ type SessionIdleState,
52
55
  EVENT_READY,
53
56
  EVENT_REGISTER_PROVIDER,
54
57
  EVENT_TERMINAL_ATTENTION,
@@ -348,6 +351,27 @@ export default function (pi: ExtensionAPI): void {
348
351
  let collecting = false;
349
352
  let collectionPending = false;
350
353
  let latestSnapshot: ActivitySnapshot | null = null;
354
+ let idleChannel: string | undefined;
355
+ let stopIdleInspection: (() => void) | undefined;
356
+ let sessionIdle: SessionIdleState = false;
357
+ let verifyIdleOnSettle = false;
358
+
359
+ function setSessionIdle(idle: SessionIdleState) {
360
+ if (!idleChannel || idle === sessionIdle) return;
361
+ sessionIdle = idle;
362
+ pi.events.emit(idleChannel, idle);
363
+ }
364
+
365
+ function updateSessionIdle(goal: GoalSnapshot | null) {
366
+ if (foregroundRunning || (goal && goal.status !== "paused" && goal.status !== "complete")) {
367
+ setSessionIdle(false);
368
+ } else if (dirtyProviders.size || lastAppliedSnapshotSequence !== snapshotSequence) {
369
+ setSessionIdle("checking");
370
+ } else {
371
+ setSessionIdle(latestSnapshot?.coverage === "verified" && !latestSnapshot.foregroundRunning && !latestSnapshot.backgroundRunning);
372
+ }
373
+ }
374
+
351
375
  let backgroundDrainTracker: BackgroundDrainTracker | null = null;
352
376
  let lastAttentionSignature = "";
353
377
  let continuationQueuedFor: string | null = null;
@@ -374,8 +398,9 @@ export default function (pi: ExtensionAPI): void {
374
398
  return false;
375
399
  }
376
400
  };
377
- const recordWorkflow = (owner: ReturnType<typeof currentWorkflowOwner>, resumePlan = false): void => {
378
- pi.appendEntry(WORKFLOW_ENTRY_TYPE, { ...workflowEntry(owner), ...(resumePlan && { resumePlan }) });
401
+ const recordWorkflow = (owner: ReturnType<typeof currentWorkflowOwner>, plan?: ReturnType<typeof boundPlanEntry>): void => {
402
+ pi.appendEntry(WORKFLOW_ENTRY_TYPE, workflowEntry(owner));
403
+ if (plan) pi.appendEntry(WORKFLOW_PLAN_ENTRY, plan);
379
404
  pi.events.emit("pi-better-workflow:changed", owner);
380
405
  };
381
406
 
@@ -435,6 +460,7 @@ export default function (pi: ExtensionAPI): void {
435
460
  clearIdleContinuation();
436
461
  syncPollingState();
437
462
  syncResumeTool(goal);
463
+ updateSessionIdle(goal);
438
464
  // Force a full redraw when the dock height changes (absent ↔ visible clock).
439
465
  refreshGoalWidget?.(!wasVisible || !isGoalClockVisible(goal));
440
466
  };
@@ -453,6 +479,7 @@ export default function (pi: ExtensionAPI): void {
453
479
  clearIdleContinuation();
454
480
  syncPollingState();
455
481
  syncResumeTool(null);
482
+ updateSessionIdle(null);
456
483
  refreshGoalWidget?.(wasVisible);
457
484
  };
458
485
 
@@ -503,15 +530,13 @@ export default function (pi: ExtensionAPI): void {
503
530
  ? workflowOwnerFromSkill(goal.command.name.slice("skill:".length), goal.command.path, registeredSkillPath)
504
531
  : null;
505
532
 
506
- /**
507
- * The session's workflow owner when an active goal is bound to it through its skill command, else
508
- * null. Only these goals are gated by the workflow's scheduler.
509
- */
510
533
  const boundWorkflow = (goal: GoalSnapshot, ctx: ExtensionContext): NonNullable<ReturnType<typeof currentWorkflowOwner>> | null => {
511
534
  const owner = getWorkflow(ctx);
512
- if (!owner || goal.status !== "active" || goal.command?.source !== "skill") return null;
535
+ if (!owner || goal.command?.source !== "skill") return null;
513
536
  try {
514
537
  const bound = goalWorkflowOwner(goal);
538
+ if (goal.workflowBinding !== undefined &&
539
+ (goal.workflowBinding?.name !== bound?.name || goal.workflowBinding?.path !== bound?.path)) return null;
515
540
  return bound?.name === owner.name && bound.path === owner.path ? owner : null;
516
541
  } catch {
517
542
  return null;
@@ -672,6 +697,7 @@ export default function (pi: ExtensionAPI): void {
672
697
  const owner = command?.source === "skill"
673
698
  ? workflowOwnerFromSkill(command.name.slice("skill:".length), command.path, registeredSkillPath)
674
699
  : null;
700
+ if (command?.source === "skill") goal.workflowBinding = owner ? { name: owner.name, path: owner.path } : null;
675
701
  if (getWorkflow(ctx)) recordWorkflow(null);
676
702
  setGoal(goal, ctx, source);
677
703
  if (command) {
@@ -699,6 +725,7 @@ export default function (pi: ExtensionAPI): void {
699
725
  if (cached && !provider.onActivityChanged && !explicit && Date.now() < (compatibilityReadAt.get(provider.id) ?? 0)) return cached;
700
726
  if (cached && provider.onActivityChanged && !dirtyProviders.has(provider.id) &&
701
727
  !(typeof cached.nextDeadline === "number" && cached.nextDeadline <= Date.now())) return cached;
728
+ if (sessionIdle === true) setSessionIdle("checking");
702
729
  dirtyProviders.delete(provider.id);
703
730
  let value: BackgroundProviderSnapshot;
704
731
  try {
@@ -748,6 +775,7 @@ export default function (pi: ExtensionAPI): void {
748
775
  clearIdleContinuation();
749
776
  }
750
777
 
778
+ updateSessionIdle(goal);
751
779
  pi.events.emit(EVENT_ACTIVITY, snapshot);
752
780
  if (execution !== executionGeneration) return null;
753
781
  const attention = terminalAttentionSignature(snapshot);
@@ -855,6 +883,7 @@ export default function (pi: ExtensionAPI): void {
855
883
  providerUnsubscribers.set(provider.id, provider.onActivityChanged(() => {
856
884
  if (!currentCtx || execution !== executionGeneration || providers.get(provider.id) !== provider) return;
857
885
  dirtyProviders.add(provider.id);
886
+ if (sessionIdle === true) setSessionIdle("checking");
858
887
  collectIfPossible();
859
888
  }, currentCtx));
860
889
  }
@@ -997,6 +1026,7 @@ export default function (pi: ExtensionAPI): void {
997
1026
  providerCache.delete(accepted.id);
998
1027
  providerCacheSequences.set(accepted.id, ++snapshotSequence);
999
1028
  dirtyProviders.add(accepted.id);
1029
+ if (sessionIdle === true) setSessionIdle("checking");
1000
1030
  providerBindings.delete(accepted.id);
1001
1031
  bindProviderSubscriptions();
1002
1032
  if (latestSnapshot) collectIfPossible();
@@ -1007,7 +1037,7 @@ export default function (pi: ExtensionAPI): void {
1007
1037
  const invalid = validateObjective(objective);
1008
1038
  if (invalid) return invalid;
1009
1039
  const owner = getWorkflow(ctx);
1010
- if (owner && !workflowAvailable(owner)) return `Restore /skill:${owner.name} before continuing its Todo.`;
1040
+ if (!previous && owner && !workflowAvailable(owner)) return `Restore /skill:${owner.name} before continuing its Todo.`;
1011
1041
  if (previous) {
1012
1042
  const blocker = resumeBlocker(previous, ctx);
1013
1043
  if (blocker) return blocker;
@@ -1015,17 +1045,19 @@ export default function (pi: ExtensionAPI): void {
1015
1045
  if (objective.startsWith("/") && (!previous?.command || previous.objective.trim() !== objective)) {
1016
1046
  return "Reinvoke the original command to continue this Goal.";
1017
1047
  }
1018
- const command = previous?.command ?? (owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null);
1048
+ const command = previous ? previous.command : owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null;
1019
1049
  const goal = createGoalSnapshot(objective, null, undefined, command ?? undefined);
1020
1050
  const restoredOwner = previous?.command ? goalWorkflowOwner(goal) : null;
1021
- const completedOwner = previous?.command?.source === "skill"
1022
- ? currentWorkflowOwner(ctx.sessionManager.getBranch(), previous.goalId) : null;
1023
- if ((completedOwner && (restoredOwner?.name !== completedOwner.name || restoredOwner.path !== completedOwner.path)) ||
1024
- (handoffOwner && restoredOwner?.name !== handoffOwner) ||
1025
- (restoredOwner && owner && (restoredOwner.name !== owner.name || restoredOwner.path !== owner.path))) {
1051
+ if (previous?.command?.source === "skill" && !restoredWorkflowMatches(previous, ctx.sessionManager.getBranch(), restoredOwner)) {
1026
1052
  return "Reinvoke the original workflow to continue its Todo.";
1027
1053
  }
1028
- return { goal, restore: owner ? null : restoredOwner };
1054
+ if (handoffOwner && restoredOwner?.name !== handoffOwner) return "Reinvoke the original workflow to continue its Todo.";
1055
+ if (command?.source === "skill") {
1056
+ const binding = previous ? restoredOwner : owner;
1057
+ goal.workflowBinding = binding ? { name: binding.name, path: binding.path } : null;
1058
+ }
1059
+ const plan = restoredOwner && previous ? boundPlanEntry(ctx.sessionManager.getBranch(), restoredOwner, previous.goalId) : undefined;
1060
+ return { goal, restore: restoredOwner, plan };
1029
1061
  };
1030
1062
 
1031
1063
  const unsubscribeOutcomeAccepted = pi.events.on(OUTCOME_ACCEPTED_EVENT, (value: unknown) => {
@@ -1040,8 +1072,8 @@ export default function (pi: ExtensionAPI): void {
1040
1072
  if (!canStartGoalFromOutcome(event.outcome, reopenedGoal)) return;
1041
1073
  const prepared = prepareSavedGoal(ctx, event.outcome.objective.trim(), reopenedGoal);
1042
1074
  if (typeof prepared === "string") return;
1075
+ if (prepared.restore) recordWorkflow(prepared.restore, prepared.plan);
1043
1076
  setGoal(prepared.goal, ctx, "runtime", "bind");
1044
- if (prepared.restore) recordWorkflow(prepared.restore, true);
1045
1077
  resetContinuationState(prepared.goal);
1046
1078
  });
1047
1079
 
@@ -1088,8 +1120,8 @@ export default function (pi: ExtensionAPI): void {
1088
1120
  const prepared = prepareSavedGoal(ctx, savedGoal.objective, previous, handoffOwner);
1089
1121
  if (typeof prepared === "string") { warn(prepared); return; }
1090
1122
  const { goal } = prepared;
1123
+ if (prepared.restore) recordWorkflow(prepared.restore, prepared.plan);
1091
1124
  setGoal(action === "pause" ? goalWithStatus(goal, "paused") : goal, ctx, "command", "adopt");
1092
- if (prepared.restore) recordWorkflow(prepared.restore, true);
1093
1125
  if (action === "resume") queueGoalContinuation(goal, ctx);
1094
1126
  } else if (action === "resume") {
1095
1127
  if (!current) { warn("No saved Goal or unfinished Todo to resume."); return; }
@@ -1210,8 +1242,9 @@ export default function (pi: ExtensionAPI): void {
1210
1242
  notifyGoal(ctx, "No goal is set.", "warning");
1211
1243
  return;
1212
1244
  }
1245
+ const releaseOwner = current.status !== "complete" ? boundWorkflow(current, ctx) : null;
1213
1246
  setGoal(goalWithStatus(current, "complete"), ctx, "command");
1214
- if (getWorkflow(ctx)) recordWorkflow(null);
1247
+ if (releaseOwner) recordWorkflow(null);
1215
1248
  notifyGoal(ctx, "Goal marked complete.");
1216
1249
  return;
1217
1250
  }
@@ -1284,7 +1317,8 @@ export default function (pi: ExtensionAPI): void {
1284
1317
  details: { ok: true, goal: current },
1285
1318
  };
1286
1319
  }
1287
- const gated = boundWorkflow(current, ctx);
1320
+ const releaseOwner = boundWorkflow(current, ctx);
1321
+ const gated = current.status === "active" ? releaseOwner : null;
1288
1322
  const verdict = gated ? await completionGate(ctx.sessionManager.getBranch(), gated) : null;
1289
1323
  if (verdict && !verdict.allow) {
1290
1324
  return {
@@ -1296,13 +1330,15 @@ export default function (pi: ExtensionAPI): void {
1296
1330
  if (latest?.goalId !== current.goalId || latest.status !== current.status) {
1297
1331
  return { content: [{ type: "text", text: "Goal changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1298
1332
  }
1299
- if (gated) {
1300
- const owner = getWorkflow(ctx);
1301
- if (owner?.name !== gated.name || owner.path !== gated.path) {
1302
- return { content: [{ type: "text", text: "Workflow changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1303
- }
1333
+ const activeOwner = boundWorkflow(latest, ctx);
1334
+ if (releaseOwner?.name !== activeOwner?.name || releaseOwner?.path !== activeOwner?.path) {
1335
+ return { content: [{ type: "text", text: "Workflow changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1336
+ }
1337
+ const audit = requestTaskContext(pi, "audit", current);
1338
+ if (audit.enabled && !audit.auditHandled) {
1339
+ return { content: [{ type: "text", text: "Harness did not confirm the Todo audit. Update Harness before completing this Goal." }],
1340
+ details: { ok: false, goal: current } };
1304
1341
  }
1305
- const audit = requestTaskContext(pi, { action: "audit", workflowOwnsPlan: !!gated }, current);
1306
1342
  const criteria = audit.doneWhen?.length ? audit.doneWhen : audit.objective ? [audit.objective] : [];
1307
1343
  const evidence = [...input.evidence ?? [], ...audit.evidence ?? []];
1308
1344
  const missing = criteria.filter(criterion => !evidence.some(item => item.criterion === criterion && item.result.trim()));
@@ -1317,7 +1353,7 @@ export default function (pi: ExtensionAPI): void {
1317
1353
  }
1318
1354
  const goal = goalWithStatus(latest, "complete");
1319
1355
  setGoal(goal, ctx, "tool");
1320
- if (gated) recordWorkflow(null);
1356
+ if (releaseOwner) recordWorkflow(null);
1321
1357
  const warning = verdict?.allow ? verdict.warning : undefined;
1322
1358
  return {
1323
1359
  content: [{ type: "text", text: warning ? `Goal marked complete. ${warning}` : "Goal marked complete." }],
@@ -1401,7 +1437,7 @@ export default function (pi: ExtensionAPI): void {
1401
1437
  const owner = getWorkflow(ctx);
1402
1438
  if (!owner) return { content: [{ type: "text", text: "No workflow owns this session." }], details: { released: false } };
1403
1439
  const goal = getGoal(ctx);
1404
- const gated = goal ? boundWorkflow(goal, ctx) : null;
1440
+ const gated = goal?.status === "active" ? boundWorkflow(goal, ctx) : null;
1405
1441
  const verdict = gated ? await pauseGate(ctx.sessionManager.getBranch(), gated) : null;
1406
1442
  if (verdict && !verdict.allow) {
1407
1443
  return { content: [{ type: "text", text: verdict.message }], details: { released: false, goalPaused: false } };
@@ -1467,6 +1503,29 @@ export default function (pi: ExtensionAPI): void {
1467
1503
  preferences = { ...preferences, autoStartFromOutcome: false };
1468
1504
  notifyGoal(ctx, error instanceof Error ? error.message : String(error), "error");
1469
1505
  }
1506
+ if (typeof stopIdleInspection === "function") stopIdleInspection();
1507
+ idleChannel = undefined;
1508
+ sessionIdle = false;
1509
+ verifyIdleOnSettle = false;
1510
+ latestSnapshot = null;
1511
+ const sessionId = ctx.sessionManager.getSessionId?.();
1512
+ if (ctx.hasUI && ctx.mode === "tui" && sessionId) {
1513
+ idleChannel = sessionIdleEvent(sessionId);
1514
+ stopIdleInspection = pi.events.on(idleChannel + ":inspect", (value) => {
1515
+ const request = value as SessionIdleInspection;
1516
+ request.idle = sessionIdle;
1517
+ // A plain conversation may only have a passive, unverified provider cache.
1518
+ if (!request.verify) return;
1519
+ if (foregroundRunning) {
1520
+ // The Recap settlement handler can run before Goal's handler.
1521
+ verifyIdleOnSettle = true;
1522
+ return;
1523
+ }
1524
+ if (!latestSnapshot || !hasUnverifiedActivity(latestSnapshot)) return;
1525
+ const goal = getGoal(ctx);
1526
+ if (!goal || goal.status === "paused" || goal.status === "complete") void publishSnapshot(ctx, true, "connect");
1527
+ });
1528
+ }
1470
1529
  const restoredGoal = getGoal(ctx);
1471
1530
  if (restoredGoal?.status === "active" && !restoredGoal.command && skillCommandName(restoredGoal.objective)) {
1472
1531
  setGoal(goalWithStatus(restoredGoal, "paused"), ctx, "runtime");
@@ -1516,6 +1575,8 @@ export default function (pi: ExtensionAPI): void {
1516
1575
  backgroundDrainTracker = null;
1517
1576
  continuationQueuedFor = null;
1518
1577
  providerCache.clear();
1578
+ latestSnapshot = null;
1579
+ setSessionIdle(false);
1519
1580
  currentCtx = ctx;
1520
1581
  await publishSnapshot(ctx);
1521
1582
  syncPollingState();
@@ -1640,6 +1701,8 @@ export default function (pi: ExtensionAPI): void {
1640
1701
  agentGeneration = executionGeneration;
1641
1702
  currentCtx = ctx;
1642
1703
  foregroundRunning = true;
1704
+ verifyIdleOnSettle = false;
1705
+ setSessionIdle(false);
1643
1706
  agentLoopActive = true;
1644
1707
  clearIdleContinuation();
1645
1708
  continuationQueuedFor = null;
@@ -1730,7 +1793,9 @@ export default function (pi: ExtensionAPI): void {
1730
1793
  escapeAbortSuppression = undefined;
1731
1794
  currentCtx = ctx;
1732
1795
  foregroundRunning = false;
1733
- const snapshot = await publishSnapshot(ctx);
1796
+ const verify = verifyIdleOnSettle;
1797
+ verifyIdleOnSettle = false;
1798
+ const snapshot = await publishSnapshot(ctx, true, verify ? "connect" : undefined);
1734
1799
  if (!snapshot) return;
1735
1800
  const goal = getGoal(ctx);
1736
1801
  if (!isPokeable(goal) || snapshot.backgroundRunning || hasUnverifiedActivity(snapshot)) {
@@ -1834,6 +1899,9 @@ export default function (pi: ExtensionAPI): void {
1834
1899
  clearIdleContinuation();
1835
1900
  currentCtx = undefined;
1836
1901
  latestSnapshot = null;
1902
+ if (typeof stopIdleInspection === "function") stopIdleInspection();
1903
+ stopIdleInspection = undefined;
1904
+ idleChannel = undefined;
1837
1905
  collectionPending = false;
1838
1906
  try {
1839
1907
  setNavigatorPanel(ctx, EXTENSION_NAME, undefined);
@@ -44,6 +44,7 @@ export function canStartGoalFromOutcome(value: unknown, reopenedGoal?: Pick<Goal
44
44
  */
45
45
  export interface TaskContextRequest {
46
46
  action: TaskContextAction;
47
+ auditHandled?: boolean;
47
48
  savedGoal?: { objective: string; status: string; goalId?: string; reopenedGoalId?: string };
48
49
  handoffOwner?: string;
49
50
  manual?: boolean;
package/src/types.ts CHANGED
@@ -9,6 +9,11 @@ export const EVENT_REGISTER_PROVIDER = "pi-better-goal:register-provider";
9
9
  export const EVENT_ACTIVITY = "pi-better-goal:activity";
10
10
  export const EVENT_TERMINAL_ATTENTION = "pi-better-goal:terminal-attention";
11
11
 
12
+ /** Session-local transition and synchronous inspection of verified foreground/worker idleness. */
13
+ export const sessionIdleEvent = (sessionId: string) => `pi-better-goal:idle:${sessionId}`;
14
+ export type SessionIdleState = boolean | "checking";
15
+ export interface SessionIdleInspection { idle?: SessionIdleState; verify?: boolean }
16
+
12
17
  export type ActivityCategory =
13
18
  | "foreground-running"
14
19
  | "background-running"
@@ -97,6 +102,8 @@ export interface GoalSnapshot {
97
102
  goalId: string;
98
103
  objective: string;
99
104
  command?: GoalCommandBinding;
105
+ /** Canonical coordinator of a skill at creation; older Goals predate this field. */
106
+ workflowBinding?: { name: string; path: string } | null;
100
107
  status: GoalStatus;
101
108
  /** Present only while `status` is "paused". */
102
109
  pauseReason?: GoalPauseReason;
@@ -4,10 +4,11 @@ import { mkdir, mkdtemp, readdir, readFile, rm, stat, utimes, writeFile } from "
4
4
  import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
+ import { EXTENSION_NAME } from "./types.js";
7
8
  import { ISSUE_WORKFLOW_SKILLS, type WorkflowOwner } from "./workflow.js";
8
9
 
9
10
  /** Branch entry the plan extension writes when it binds a workflow-owned task plan. */
10
- const WORKFLOW_PLAN_ENTRY = "pi-better-workflow-plan";
11
+ export const WORKFLOW_PLAN_ENTRY = "pi-better-workflow-plan";
11
12
  const WORKFLOW_ENTRY = "pi-better-workflow";
12
13
  export const SCHEDULER_TIMEOUT_MS = 20_000;
13
14
  // Live tree queries allow three 60-second attempts plus follow-ups; cached probes stay cheap.
@@ -68,19 +69,63 @@ export function findScheduler(owner: WorkflowOwner): string | undefined {
68
69
  * The task-plan.json the session bound for `owner`, or undefined before a plan is bound.
69
70
  * Invoking a workflow skill again starts a new run, so a later owner entry drops the old binding.
70
71
  */
71
- export function boundPlanPath(entries: Iterable<EntryLike>, owner: WorkflowOwner): string | undefined {
72
- let path: string | undefined;
72
+ export function boundPlanEntry(entries: Iterable<EntryLike>, owner: WorkflowOwner, goalId?: string) {
73
+ let plan: { version: 1; kind: "set"; owner: string; path: string; runId?: string } | undefined;
74
+ let ownsRun = false;
75
+ let foundGoal = false;
76
+ let handback: "paused" | "released" | "rebound" | undefined;
73
77
  for (const entry of entries) {
74
- if (entry.type !== "custom") continue;
78
+ // resumeGoal records the owner and then activates the same Goal. A separate
79
+ // invocation can bind the same skill, but cannot supply that Goal transition.
80
+ if (handback === "rebound" && entry.type === "message") handback = "released";
81
+ if (entry.type !== "custom" || !isRecord(entry.data)) continue;
75
82
  const data = entry.data;
76
- if (entry.customType === WORKFLOW_ENTRY && isRecord(data) && data.version === 1 && data.kind === "set") {
77
- if (data.resumePlan !== true || !isRecord(data.owner) || data.owner.name !== owner.name) path = undefined;
83
+ if (goalId && entry.customType === EXTENSION_NAME && data.kind === "set" && isRecord(data.goal)) {
84
+ if (foundGoal && (data.goal.goalId !== goalId || data.goal.status === "complete")) break;
85
+ if (data.goal.goalId === goalId) foundGoal = true;
86
+ if (handback === "released") {
87
+ if (data.goal.status === "paused" && data.goal.pauseReason === "handback") continue;
88
+ break;
89
+ }
90
+ if (handback === "rebound") {
91
+ if (data.goal.status !== "active") break;
92
+ plan = undefined;
93
+ }
94
+ handback = foundGoal && data.goal.status === "paused" && data.goal.pauseReason === "handback" ? "paused" : undefined;
95
+ }
96
+ if (data.version !== 1) continue;
97
+ if (entry.customType === WORKFLOW_ENTRY) {
98
+ if (handback === "paused" && ownsRun && data.kind === "clear") {
99
+ handback = "released";
100
+ continue;
101
+ }
102
+ if (handback === "released" || handback === "rebound") {
103
+ handback = data.kind === "set" && isRecord(data.owner) && data.owner.name === owner.name && data.owner.path === owner.path
104
+ ? "rebound" : "released";
105
+ continue;
106
+ }
107
+ // A later invocation, even of the same skill, starts a different run.
108
+ if (foundGoal && ownsRun && (data.kind === "set" || data.kind === "clear")) break;
109
+ if (data.kind === "clear") ownsRun = false;
110
+ if (data.kind === "set") {
111
+ ownsRun = isRecord(data.owner) && data.owner.name === owner.name && data.owner.path === owner.path;
112
+ if (data.resumePlan !== true || !ownsRun) plan = undefined;
113
+ }
114
+ }
115
+ if (entry.customType !== WORKFLOW_PLAN_ENTRY) continue;
116
+ if (handback === "released") continue;
117
+ if (handback === "rebound") { handback = "released"; continue; }
118
+ if (data.kind === "clear") plan = undefined;
119
+ else if (data.kind === "set" && data.owner === owner.name && typeof data.path === "string") {
120
+ plan = { version: 1, kind: "set", owner: owner.name, path: data.path,
121
+ ...(typeof data.runId === "string" && { runId: data.runId }) };
78
122
  }
79
- if (entry.customType !== WORKFLOW_PLAN_ENTRY || !isRecord(data) || data.version !== 1) continue;
80
- if (data.kind === "clear") path = undefined;
81
- else if (data.kind === "set" && data.owner === owner.name && typeof data.path === "string") path = data.path;
82
123
  }
83
- return path;
124
+ return !goalId || (foundGoal && ownsRun) ? plan : undefined;
125
+ }
126
+
127
+ export function boundPlanPath(entries: Iterable<EntryLike>, owner: WorkflowOwner): string | undefined {
128
+ return boundPlanEntry(entries, owner)?.path;
84
129
  }
85
130
 
86
131
  function parseSchedulerOutput(stdout: string): SchedulerRun {
package/src/workflow.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { parse } from "yaml";
3
- import { EXTENSION_NAME } from "./types.js";
3
+ import { EXTENSION_NAME, type GoalSnapshot } from "./types.js";
4
4
 
5
5
  export const WORKFLOW_ENTRY_TYPE = "pi-better-workflow";
6
6
 
@@ -84,13 +84,19 @@ export function workflowEntry(owner: WorkflowOwner | null) {
84
84
  : { version: 1, kind: "set" as const, owner };
85
85
  }
86
86
 
87
- export function currentWorkflowOwner(entries: Iterable<SessionEntryLike>, atGoalCompletion?: string): WorkflowOwner | null {
87
+ export function currentWorkflowOwner(entries: Iterable<SessionEntryLike>, atGoalStart?: string): WorkflowOwner | null {
88
88
  let owner: WorkflowOwner | null = null;
89
+ let awaitingInitialBinding = false;
89
90
  for (const entry of entries) {
91
+ if (awaitingInitialBinding && (entry.type === "message" || entry.customType === EXTENSION_NAME)) return null;
90
92
  if (entry.type !== "custom") continue;
91
- if (atGoalCompletion && entry.customType === EXTENSION_NAME) {
93
+ if (atGoalStart && entry.customType === EXTENSION_NAME) {
92
94
  const data = entry.data as { kind?: string; goal?: { goalId?: string; status?: string } } | null;
93
- if (data?.kind === "set" && data.goal?.goalId === atGoalCompletion && data.goal.status === "complete") return owner;
95
+ if (data?.kind === "set" && data.goal?.goalId === atGoalStart) {
96
+ // Automatic Goals inherit the active owner. Explicit skill Goals record it just after creation.
97
+ if (owner) return owner;
98
+ awaitingInitialBinding = true;
99
+ }
94
100
  }
95
101
  if (entry.customType !== WORKFLOW_ENTRY_TYPE) continue;
96
102
  const data = entry.data as { version?: unknown; kind?: unknown; owner?: Partial<WorkflowOwner> } | null;
@@ -100,8 +106,15 @@ export function currentWorkflowOwner(entries: Iterable<SessionEntryLike>, atGoal
100
106
  typeof data.owner.path === "string" && data.owner.role === "coordinator" && data.owner.planOwner === "workflow") {
101
107
  owner = data.owner as WorkflowOwner;
102
108
  }
109
+ if (awaitingInitialBinding) return owner;
103
110
  }
104
- return atGoalCompletion ? null : owner;
111
+ return atGoalStart ? null : owner;
112
+ }
113
+
114
+ export function restoredWorkflowMatches(goal: GoalSnapshot, entries: Iterable<SessionEntryLike>, restored: WorkflowOwner | null): boolean {
115
+ const original = goal.workflowBinding === undefined ? currentWorkflowOwner(entries, goal.goalId) : goal.workflowBinding;
116
+ if (goal.workflowBinding === undefined && !original) return true;
117
+ return original?.name === restored?.name && original?.path === restored?.path;
105
118
  }
106
119
 
107
120
  export function skillCommandName(text: string): string | null {