pi-better-goal 0.11.0 → 0.12.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ import { Type } from "typebox";
6
6
  import { commandAvailable, commandInvocation, resolveGoalCommand } from "./command-binding.js";
7
7
  import { goalPreferencesPath, readGoalPreferences, writeGoalPreference, type GoalPreferences } from "./preferences.js";
8
8
  import { createGoalSettingsPage } from "./settings-page.js";
9
+ import { OPERATION_RESUME_ADMISSION, operationOwnerMatches, type OperationResumeRequest } from "./operation-admission.js";
9
10
 
10
11
  import {
11
12
  collectActivitySnapshot,
@@ -29,6 +30,7 @@ import {
29
30
  } from "./goal-state.js";
30
31
  import { continuationEvidence, type ContinuationEvidence } from "./continuation.js";
31
32
  import { currentPermissionHold, logicalPermissionBlockerKey, MAX_PERMISSION_BLOCKERS, MAX_PERMISSION_RECORDS, permissionHoldRecord, permissionInstruction, permissionRecord, reportedPermissionBlockers, reportedPermissionGap, type PermissionHold } from "./permission-hold.js";
33
+ import { publishGoalGuidance } from "./prompt.js";
32
34
  import { observeGoalStall } from "./stall.js";
33
35
  import {
34
36
  flattenObjectiveForRail,
@@ -41,7 +43,7 @@ import { createRenderScheduler } from "./shared-render-scheduler.js";
41
43
  import { initializeNavigatorPanels, setNavigatorPanel } from "./shared-navigator-panels.js";
42
44
  import { collectSubagentActivity } from "./subagents.js";
43
45
  import { currentWorkflowOwner, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
44
- import { completionGate, pauseGate, schedulerWaitUntil } from "./workflow-gates.js";
46
+ import { completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
45
47
  import { workflowRehydrateMessage, WORKFLOW_REHYDRATE_MESSAGE_TYPE } from "./rehydrate.js";
46
48
  import { requestTaskContext } from "./task-context.js";
47
49
  import {
@@ -313,6 +315,7 @@ export default function (pi: ExtensionAPI): void {
313
315
 
314
316
  let currentCtx: ExtensionContext | undefined;
315
317
  let executionGeneration = 0;
318
+ let operationAdmissionRevision = 0;
316
319
  let agentGeneration = -1;
317
320
  let turnGeneration = 0;
318
321
  let escapeAbortSuppression: { session: number; turn: number; execution: number } | undefined;
@@ -862,6 +865,51 @@ export default function (pi: ExtensionAPI): void {
862
865
  );
863
866
  };
864
867
 
868
+ const unsubscribeOperationAdmission = pi.events.on(OPERATION_RESUME_ADMISSION, (value) => {
869
+ const request = value as Partial<OperationResumeRequest> | undefined;
870
+ if (request?.version !== 1 || !request.owner || typeof request.reply !== "function") return;
871
+ const ctx = currentCtx;
872
+ const revision = executionGeneration;
873
+ const preferencesRevision = operationAdmissionRevision;
874
+ const reply = request.reply;
875
+ const held = (reason: string) => reply({ allowed: false, reason, revision: executionGeneration });
876
+ if (!operationOwnerMatches(ctx, request.owner) || !ctx) { held("Owning parent session or branch is inactive"); return; }
877
+ const goal = getGoal(ctx);
878
+ if ((request.owner.goalId ?? null) !== (goal?.goalId ?? null)) { held("Owning Goal is no longer current"); return; }
879
+ if (goal && !preferences.autoContinue) { held("Goal automatic continuation is disabled"); return; }
880
+ if (goal && !isPokeable(goal)) { held("Goal is not active"); return; }
881
+ if (goal && currentPermissionHold(ctx, goal.goalId).blockers.length) { held("Goal has an active permission hold"); return; }
882
+ if (goal && currentContinuationState(ctx, goal.goalId)?.blocked) { held("Goal continuation requires human resume"); return; }
883
+ if (goal && !boundCommandReady(goal, ctx)) { held("Bound workflow is not ready"); return; }
884
+ const workflow = getWorkflow(ctx);
885
+ void (workflow ? operationResumeSchedulerGate(ctx.sessionManager.getBranch(), workflow) : Promise.resolve({ ok: true as const, waitUntil: undefined })).then((gate) => {
886
+ if (ctx !== currentCtx || revision !== executionGeneration || preferencesRevision !== operationAdmissionRevision || !operationOwnerMatches(currentCtx, request.owner!)) {
887
+ held("Parent execution changed during resume admission"); return;
888
+ }
889
+ const latest = getGoal(ctx);
890
+ if ((request.owner!.goalId ?? null) !== (latest?.goalId ?? null)) { held("Owning Goal changed during resume admission"); return; }
891
+ if (latest && !preferences.autoContinue) { held("Goal automatic continuation is disabled"); return; }
892
+ if (latest && (!isPokeable(latest) || currentPermissionHold(ctx, latest.goalId).blockers.length || currentContinuationState(ctx, latest.goalId)?.blocked)) {
893
+ held("Goal became held during resume admission"); return;
894
+ }
895
+ if (!gate.ok) { held(gate.reason); return; }
896
+ if (gate.waitUntil && gate.waitUntil > Date.now()) { held("Workflow scheduler is waiting"); return; }
897
+ // An in-process capability lets the dispatcher validate this admission
898
+ // after its last await and immediately before releasing execution.
899
+ const isCurrent = (): boolean => {
900
+ if (ctx !== currentCtx || revision !== executionGeneration || preferencesRevision !== operationAdmissionRevision
901
+ || !operationOwnerMatches(currentCtx, request.owner!)) return false;
902
+ const active = getGoal(ctx);
903
+ if ((request.owner!.goalId ?? null) !== (active?.goalId ?? null)) return false;
904
+ if (JSON.stringify(getWorkflow(ctx)) !== JSON.stringify(workflow)) return false;
905
+ return !active || (preferences.autoContinue && isPokeable(active)
906
+ && !currentPermissionHold(ctx, active.goalId).blockers.length
907
+ && !currentContinuationState(ctx, active.goalId)?.blocked && boundCommandReady(active, ctx));
908
+ };
909
+ reply({ allowed: true, revision, isCurrent });
910
+ }, () => held("Workflow admission evidence is unavailable"));
911
+ });
912
+
865
913
  pi.events.on(EVENT_REGISTER_PROVIDER, (provider) => {
866
914
  const candidate = provider as Partial<BackgroundActivityProvider> | undefined;
867
915
  if (!candidate || typeof candidate.id !== "string" || typeof candidate.getActivity !== "function") {
@@ -880,6 +928,7 @@ export default function (pi: ExtensionAPI): void {
880
928
  const changePreference = async (ctx: ExtensionCommandContext, key: keyof GoalPreferences, enabled: boolean): Promise<void> => {
881
929
  const previous = preferences;
882
930
  preferences = writeGoalPreference(key, enabled);
931
+ operationAdmissionRevision += 1;
883
932
  if (previous.autoContinue !== preferences.autoContinue) clearIdleContinuation();
884
933
  syncResumeTool(getGoal(ctx));
885
934
  if (!previous.autoContinue && preferences.autoContinue) {
@@ -1312,12 +1361,12 @@ export default function (pi: ExtensionAPI): void {
1312
1361
  (permissions.blockers.length === 0 ? "\nBlocker evidence is unavailable. Stay held; do not invent a retry scope." : "") : "";
1313
1362
  // A held goal overrides workflow ownership without invoking or invalidating that workflow.
1314
1363
  if (permissionPrompt && goal?.status === "paused") {
1315
- return { systemPrompt: `${event.systemPrompt}\n\n${permissionPrompt}` };
1364
+ return publishGoalGuidance(event, permissionPrompt);
1316
1365
  }
1317
1366
  const pausedInstruction = permissionPrompt || (goal?.status === "paused" && (goal.pauseReason === "interrupt" || goal.pauseReason === "handback")
1318
1367
  ? pausedGoalPrompt(goal, preferences.conversationalResume, !harnessPresent) : "");
1319
1368
  if (!isPokeable(goal) && !owner) {
1320
- return pausedInstruction ? { systemPrompt: `${event.systemPrompt}\n\n${pausedInstruction}` } : undefined;
1369
+ return publishGoalGuidance(event, pausedInstruction);
1321
1370
  }
1322
1371
 
1323
1372
  const questionInstruction = snapshot.backgroundRunning
@@ -1331,31 +1380,28 @@ export default function (pi: ExtensionAPI): void {
1331
1380
  if (!workflowAvailable(owner)) {
1332
1381
  if (isPokeable(goal)) setGoal(goalWithStatus(goal, "paused"), ctx, "runtime");
1333
1382
  recordWorkflow(null);
1334
- return { systemPrompt: `${event.systemPrompt}\n\nWorkflow ${owner.name} is no longer a registered, valid skill. Stop work and ask the user to reinvoke the skill.` };
1383
+ return publishGoalGuidance(event, `Workflow ${owner.name} is no longer a registered, valid skill. Stop work and ask the user to reinvoke the skill.`);
1335
1384
  }
1336
1385
  let instructions: string;
1337
1386
  try {
1338
1387
  instructions = readFileSync(owner.path, "utf8");
1339
1388
  } catch {
1340
1389
  if (isPokeable(goal)) setGoal(goalWithStatus(goal, "paused"), ctx, "runtime");
1341
- return { systemPrompt: `${event.systemPrompt}\n\nWorkflow ${owner.name} is unavailable. Stop work and ask the user to restore or reinvoke the skill.` };
1390
+ return publishGoalGuidance(event, `Workflow ${owner.name} is unavailable. Stop work and ask the user to restore or reinvoke the skill.`);
1342
1391
  }
1343
- return {
1344
- systemPrompt: `${event.systemPrompt}\n\n` +
1345
- (pausedInstruction
1346
- ? `${pausedInstruction}\n` + (permissionPrompt
1347
- ? "These permission constraints override the workflow instructions below.\n\n"
1348
- : "While the goal is paused, this overrides the workflow instructions below: do not advance the workflow until the goal is resumed.\n\n")
1349
- : "") +
1350
- `Active workflow: ${owner.name} (${owner.path}). Its task plan owns planning and the parent is a coordinator, not a product-code implementer. Follow the workflow instructions below, including on resumed turns:\n\n${instructions}` +
1351
- (isPokeable(goal)
1352
- ? harnessPresent
1353
- ? "\n\nComplete the goal only after the workflow completion audit."
1354
- : `\n\nActive objective: ${goal.objective}. Complete it only after the workflow completion audit.`
1355
- : "") +
1356
- (questionInstruction ? `\n\n${questionInstruction.trim()}` : "") +
1357
- (heldInstruction ? `\n\n${heldInstruction}` : ""),
1358
- };
1392
+ return publishGoalGuidance(
1393
+ event,
1394
+ pausedInstruction &&
1395
+ `${pausedInstruction}\n` + (permissionPrompt
1396
+ ? "These permission constraints override the workflow instructions below.\n\n"
1397
+ : "While the goal is paused, this overrides the workflow instructions below: do not advance the workflow until the goal is resumed.\n\n"),
1398
+ `Active workflow: ${owner.name} (${owner.path}). Its task plan owns planning and the parent is a coordinator, not a product-code implementer. Follow the workflow instructions below, including on resumed turns:\n\n${instructions}`,
1399
+ isPokeable(goal) && (harnessPresent
1400
+ ? "Complete the goal only after the workflow completion audit."
1401
+ : `Active objective: ${goal.objective}. Complete it only after the workflow completion audit.`),
1402
+ questionInstruction && questionInstruction.trim(),
1403
+ heldInstruction,
1404
+ );
1359
1405
  }
1360
1406
 
1361
1407
  if (!isPokeable(goal)) return;
@@ -1365,18 +1411,19 @@ export default function (pi: ExtensionAPI): void {
1365
1411
  if (harnessPresent) {
1366
1412
  // Harness owns the outcome text. Retain only the Goal-specific guidance
1367
1413
  // that the Outcome & Todo prompt cannot replace.
1368
- const retained = [heldInstruction, backgroundInstruction.trim(), questionInstruction.trim(), permissionPrompt]
1369
- .filter((part) => part.length > 0);
1370
- return retained.length > 0
1371
- ? { systemPrompt: `${event.systemPrompt}\n\n${retained.join("\n\n")}` }
1372
- : undefined;
1373
- }
1374
- return {
1375
- systemPrompt:
1376
- `${event.systemPrompt}\n\n` +
1377
- `Pi Better Goal active objective: ${goal.objective}. ${heldInstruction || "Keep working through clear low-risk next steps, and mark complete only after an evidence-backed completion audit."}${backgroundInstruction}${questionInstruction}` +
1378
- (permissionPrompt ? `\n\n${permissionPrompt}` : ""),
1379
- };
1414
+ return publishGoalGuidance(
1415
+ event,
1416
+ heldInstruction,
1417
+ backgroundInstruction.trim(),
1418
+ questionInstruction.trim(),
1419
+ permissionPrompt,
1420
+ );
1421
+ }
1422
+ return publishGoalGuidance(
1423
+ event,
1424
+ `Pi Better Goal active objective: ${goal.objective}. ${heldInstruction || "Keep working through clear low-risk next steps, and mark complete only after an evidence-backed completion audit."}${backgroundInstruction}${questionInstruction}`,
1425
+ permissionPrompt,
1426
+ );
1380
1427
  });
1381
1428
 
1382
1429
  pi.on("agent_start", async (_event, ctx) => {
@@ -1576,6 +1623,7 @@ export default function (pi: ExtensionAPI): void {
1576
1623
 
1577
1624
  pi.on("session_shutdown", async (_event, ctx) => {
1578
1625
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
1626
+ if (typeof unsubscribeOperationAdmission === "function") unsubscribeOperationAdmission();
1579
1627
 
1580
1628
  executionGeneration += 1;
1581
1629
  sessionGeneration += 1;
@@ -0,0 +1,16 @@
1
+ import type {ExtensionContext} from '@earendil-works/pi-coding-agent';
2
+
3
+ export const OPERATION_RESUME_ADMISSION='pi-better-goal:operation-resume-admission';
4
+ export interface OperationResumeOwner {sessionId:string;workspace:string;branchId?:string|null;goalId?:string|null}
5
+ export interface OperationResumeGate {allowed:boolean;reason?:string;revision:number;isCurrent?:()=>boolean}
6
+ export interface OperationResumeRequest {version:1;owner:OperationResumeOwner;reply:(gate:OperationResumeGate)=>void}
7
+
8
+ /** A recorded branch anchor remains valid on descendants, not on an abandoned fork. */
9
+ export function operationOwnerMatches(ctx:ExtensionContext|undefined,owner:OperationResumeOwner):boolean {
10
+ if(!ctx||ctx.cwd!==owner.workspace)return false;
11
+ try{
12
+ if(ctx.sessionManager.getSessionId()!==owner.sessionId)return false;
13
+ if(owner.branchId&&!ctx.sessionManager.getBranch().some(entry=>entry.id===owner.branchId))return false;
14
+ return true;
15
+ }catch{return false;}
16
+ }
package/src/prompt.ts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Goal-owned system-prompt guidance.
3
+ *
4
+ * Published as a named section on hosts that render sections, never as a returned
5
+ * `systemPrompt` there: returning text sets `forceSystemPrompt`, and the request
6
+ * then carries an opaque rendered snapshot, so a section published afterwards
7
+ * never reaches the model.
8
+ *
9
+ * On older hosts (this package declares support back to pi 0.84.4) custom sections
10
+ * do not render at all, so the same text is appended instead. Publishing alone
11
+ * would silently deliver nothing on those versions.
12
+ */
13
+ export const GOAL_SECTION = "goal";
14
+
15
+ /** The minimum shape this module needs; both the event options and a test double satisfy it. */
16
+ export interface PromptSectionTarget {
17
+ sections?: Record<string, string>;
18
+ }
19
+
20
+ /** What a handler receives; only these two fields are used. */
21
+ export interface BeforeAgentStartEvent {
22
+ systemPrompt: string;
23
+ systemPromptOptions?: unknown;
24
+ }
25
+
26
+ /** Mirrors `supportsPromptSections` in the vendored execution policy. */
27
+ function rendersSections(options: unknown): boolean {
28
+ const sections = (options as { sections?: unknown } | undefined)?.sections;
29
+ return typeof sections === "object" && sections !== null;
30
+ }
31
+
32
+ /**
33
+ * Deliver guidance, choosing the channel this host understands.
34
+ *
35
+ * Appending within one turn is safe: pi normalizes a fresh options object for
36
+ * every `before_agent_start`, so this never accumulates between requests, and
37
+ * within a turn the parts belong together and keep their order.
38
+ */
39
+ export function publishGoalGuidance(
40
+ event: BeforeAgentStartEvent,
41
+ ...parts: Array<string | undefined | false>
42
+ ): { systemPrompt: string } | undefined {
43
+ const text = parts.filter((part): part is string => typeof part === "string" && part.trim().length > 0).join("\n\n");
44
+ if (!text) return undefined;
45
+ if (!rendersSections(event.systemPromptOptions)) {
46
+ return { systemPrompt: `${event.systemPrompt}\n\n${text}` };
47
+ }
48
+ const target = event.systemPromptOptions as PromptSectionTarget;
49
+ const sections = (target.sections ??= {});
50
+ const existing = sections[GOAL_SECTION];
51
+ sections[GOAL_SECTION] = existing ? `${existing}\n\n${text}` : text;
52
+ return undefined;
53
+ }
@@ -262,6 +262,21 @@ export function waitUntil(due: readonly SchedulerAction[]): number | undefined {
262
262
  return times.length > 0 ? Math.min(...times) : undefined;
263
263
  }
264
264
 
265
+ export type OperationResumeSchedulerGate = { ok: true; waitUntil: number | undefined } | { ok: false; reason: string };
266
+
267
+ /** Automatic worker admission cannot treat unavailable workflow evidence as permission. */
268
+ export async function operationResumeSchedulerGate(
269
+ entries: Iterable<EntryLike>,
270
+ owner: WorkflowOwner,
271
+ options: { timeoutMs?: number } = {},
272
+ ): Promise<OperationResumeSchedulerGate> {
273
+ const located = locateRun(entries, owner);
274
+ if ("warning" in located) return { ok: false, reason: located.warning };
275
+ const run = await runScheduler(located.script, located.runDir, options.timeoutMs);
276
+ if (!run.ok) return { ok: false, reason: `Workflow admission evidence unavailable: ${run.reason}` };
277
+ return { ok: true, waitUntil: waitUntil(run.due) };
278
+ }
279
+
265
280
  /** When the bound run next wants a continuation, or undefined when it is not only waiting. */
266
281
  export async function schedulerWaitUntil(
267
282
  entries: Iterable<EntryLike>,