@fractaal/pi-goal-x 0.20.1 → 0.28.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.
Files changed (95) hide show
  1. package/README.md +42 -290
  2. package/dist/goal-auditor.d.ts +7 -61
  3. package/dist/goal-auditor.js +98 -300
  4. package/dist/goal-auditor.js.map +1 -1
  5. package/dist/goal-contract.d.ts +205 -0
  6. package/dist/goal-contract.js +135 -0
  7. package/dist/goal-contract.js.map +1 -0
  8. package/dist/goal-transcript-events.d.ts +54 -0
  9. package/dist/goal-transcript-events.js +177 -0
  10. package/dist/goal-transcript-events.js.map +1 -0
  11. package/dist/goal-widget.d.ts +13 -0
  12. package/dist/goal-widget.js +45 -0
  13. package/dist/goal-widget.js.map +1 -0
  14. package/dist/goal.d.ts +8 -49
  15. package/dist/goal.js +519 -3643
  16. package/dist/goal.js.map +1 -1
  17. package/dist/legacy-migration.d.ts +61 -0
  18. package/dist/legacy-migration.js +306 -0
  19. package/dist/legacy-migration.js.map +1 -0
  20. package/docs/architecture.md +14 -232
  21. package/extensions/goal-auditor.ts +108 -363
  22. package/extensions/goal-contract.ts +149 -0
  23. package/extensions/goal-transcript-events.ts +194 -0
  24. package/extensions/goal-widget.ts +50 -0
  25. package/extensions/goal.ts +557 -3927
  26. package/extensions/legacy-migration.ts +340 -0
  27. package/package.json +46 -19
  28. package/dist/goal-compaction.d.ts +0 -10
  29. package/dist/goal-compaction.js +0 -104
  30. package/dist/goal-compaction.js.map +0 -1
  31. package/dist/goal-core.d.ts +0 -19
  32. package/dist/goal-core.js +0 -66
  33. package/dist/goal-core.js.map +0 -1
  34. package/dist/goal-draft.d.ts +0 -71
  35. package/dist/goal-draft.js +0 -201
  36. package/dist/goal-draft.js.map +0 -1
  37. package/dist/goal-ledger.d.ts +0 -139
  38. package/dist/goal-ledger.js +0 -306
  39. package/dist/goal-ledger.js.map +0 -1
  40. package/dist/goal-policy.d.ts +0 -127
  41. package/dist/goal-policy.js +0 -359
  42. package/dist/goal-policy.js.map +0 -1
  43. package/dist/goal-pool.d.ts +0 -17
  44. package/dist/goal-pool.js +0 -85
  45. package/dist/goal-pool.js.map +0 -1
  46. package/dist/goal-questionnaire.d.ts +0 -56
  47. package/dist/goal-questionnaire.js +0 -733
  48. package/dist/goal-questionnaire.js.map +0 -1
  49. package/dist/goal-record.d.ts +0 -94
  50. package/dist/goal-record.js +0 -155
  51. package/dist/goal-record.js.map +0 -1
  52. package/dist/goal-settings.d.ts +0 -56
  53. package/dist/goal-settings.js +0 -184
  54. package/dist/goal-settings.js.map +0 -1
  55. package/dist/goal-tool-names.d.ts +0 -20
  56. package/dist/goal-tool-names.js +0 -69
  57. package/dist/goal-tool-names.js.map +0 -1
  58. package/dist/prompts/goal-prompts.d.ts +0 -17
  59. package/dist/prompts/goal-prompts.js +0 -304
  60. package/dist/prompts/goal-prompts.js.map +0 -1
  61. package/dist/storage/goal-files.d.ts +0 -40
  62. package/dist/storage/goal-files.js +0 -320
  63. package/dist/storage/goal-files.js.map +0 -1
  64. package/dist/widgets/goal-escape-dialog.d.ts +0 -15
  65. package/dist/widgets/goal-escape-dialog.js +0 -118
  66. package/dist/widgets/goal-escape-dialog.js.map +0 -1
  67. package/dist/widgets/goal-notifications.d.ts +0 -5
  68. package/dist/widgets/goal-notifications.js +0 -9
  69. package/dist/widgets/goal-notifications.js.map +0 -1
  70. package/dist/widgets/goal-widget.d.ts +0 -58
  71. package/dist/widgets/goal-widget.js +0 -282
  72. package/dist/widgets/goal-widget.js.map +0 -1
  73. package/dist/widgets/task-list-overlay.d.ts +0 -8
  74. package/dist/widgets/task-list-overlay.js +0 -321
  75. package/dist/widgets/task-list-overlay.js.map +0 -1
  76. package/docs/agent-flow-design.md +0 -432
  77. package/docs/agentic-runtime-prd.md +0 -764
  78. package/docs/goal-ts-refactor-test-strategy.md +0 -82
  79. package/docs/pi-autoresearch-survey.md +0 -45
  80. package/extensions/goal-compaction.ts +0 -133
  81. package/extensions/goal-core.ts +0 -77
  82. package/extensions/goal-draft.ts +0 -263
  83. package/extensions/goal-ledger.ts +0 -354
  84. package/extensions/goal-policy.ts +0 -389
  85. package/extensions/goal-pool.ts +0 -98
  86. package/extensions/goal-questionnaire.ts +0 -779
  87. package/extensions/goal-record.ts +0 -256
  88. package/extensions/goal-settings.ts +0 -181
  89. package/extensions/goal-tool-names.ts +0 -76
  90. package/extensions/prompts/goal-prompts.ts +0 -308
  91. package/extensions/storage/goal-files.ts +0 -352
  92. package/extensions/widgets/goal-escape-dialog.ts +0 -146
  93. package/extensions/widgets/goal-notifications.ts +0 -9
  94. package/extensions/widgets/goal-widget.ts +0 -378
  95. package/extensions/widgets/task-list-overlay.ts +0 -389
@@ -1,4009 +1,639 @@
1
- import { StringEnum, Type, isContextOverflow, type AssistantMessage } from "@earendil-works/pi-ai";
2
- import { defineTool, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
3
- import { matchesKey, Text, visibleWidth } from "@earendil-works/pi-tui";
1
+ import { randomUUID } from "node:crypto";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
4
+ import { Text } from "@earendil-works/pi-tui";
5
+ import { runGoalCompletionAuditor } from "./goal-auditor.ts";
4
6
  import {
5
- footerStatus,
6
- formatDuration,
7
- formatTokenValue,
8
- statusLabel,
9
- truncateText,
10
- } from "./goal-core.ts";
7
+ GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH,
8
+ GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH,
9
+ GOAL_COMPLETION_SUMMARY_MAX_LENGTH,
10
+ GOAL_CONTINUATION_MESSAGE,
11
+ GOAL_OBJECTIVE_MAX_LENGTH,
12
+ GOAL_PAUSE_REASON_MAX_LENGTH,
13
+ GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH,
14
+ GOAL_PROPOSAL_EVENT,
15
+ GOAL_PROPOSAL_REVISION_ENTRY,
16
+ GOAL_RECEIPT_ENTRY,
17
+ GOAL_SCHEMA_VERSION,
18
+ GOAL_STATE_ENTRY,
19
+ GOAL_STATE_EVENT,
20
+ GOAL_STATE_REQUEST_EVENT,
21
+ isGoalState,
22
+ parseGoalState,
23
+ type Goal,
24
+ type GoalProposal,
25
+ type GoalState,
26
+ } from "./goal-contract.ts";
11
27
  import {
12
- buildDraftConfirmationText,
13
- buildTweakConfirmationText,
14
- extractVerificationContract,
15
- goalDraftingPrompt,
16
- renderConfirmationTasks,
17
- validateGoalDraftProposal,
18
- type GoalDraftingFocus,
19
- } from "./goal-draft.ts";
28
+ LEGACY_MIGRATION_ENTRY,
29
+ findLegacyGoalCandidates,
30
+ planLegacyMigration,
31
+ writeLegacyMigration,
32
+ type LegacyGoalCandidate,
33
+ } from "./legacy-migration.ts";
20
34
  import {
21
- runGoalCompletionAuditor,
22
- } from "./goal-auditor.ts";
23
- import {
24
- goalSettingsPath,
25
- isAuditorEnabledByDefault,
26
- loadGoalSettings,
27
- loadGoalSettingsFileConfig,
28
- saveGoalSettingsFileConfig,
29
- type GoalSettings,
30
- } from "./goal-settings.ts";
31
- import {
32
- hasGoalQuestionnaireUi,
33
- proposalDialogFailureMessage,
34
- registerQuestionnaireTools,
35
- shouldAutoConfirmProposal,
36
- showProposalDialog,
37
- } from "./goal-questionnaire.ts";
38
- import {
39
- ABORT_GOAL_TOOL_NAME,
40
- ACTIVE_GOAL_TOOL_NAMES,
41
- COMPLETE_TASK_TOOL_NAME,
42
- CREATE_GOAL_TOOL_NAME,
43
- POST_STOP_ALLOWED_TOOLS,
44
- PROPOSE_DRAFT_TOOL_NAME,
45
- PROPOSE_TASK_LIST_TOOL_NAME,
46
- PROPOSE_TWEAK_TOOL_NAME,
47
- QUESTIONNAIRE_TOOL_NAME,
48
- QUESTION_TOOL_NAME,
49
- SISYPHUS_STEP_TOOL_NAME,
50
- GOAL_PROGRESS_TOOL_NAMES,
51
- lifecycleToolNamesForGoalStatus,
52
- SKIP_TASK_TOOL_NAME,
53
- } from "./goal-tool-names.ts";
54
- import {
55
- asRecord,
56
- cloneGoal,
57
- createGoal,
58
- goalFocusDetails,
59
- normalizeGoalRecord,
60
- normalizeGoalFocusEntry,
61
- normalizeTaskItem,
62
- nowIso,
63
- type AssistantMessageLike,
64
- type DraftingFocus,
65
- type GoalFocusEntry,
66
- type GoalFocusReason,
67
- type GoalCreationConfig,
68
- type GoalEventDetails,
69
- type GoalEventKind,
70
- type GoalRecord,
71
- type GoalStateEntry,
72
- type GoalStatus,
73
- type StopReason,
74
- type GoalTask,
75
- type GoalTaskList,
76
- } from "./goal-record.ts";
77
- import {
78
- appendGoalEvent,
79
- latestAuditorResultForGoal,
80
- readGoalLedger,
81
- readLegacyGoalLedger,
82
- type GoalLedgerEvent,
83
- } from "./goal-ledger.ts";
84
- import { buildCompactionSummary } from "./goal-compaction.ts";
85
- import {
86
- archiveGoalFile,
87
- atomicWriteGoalFile,
88
- ensureDirectory,
89
- GOALS_DIR,
90
- mergeGoalPromptFromDisk,
91
- readActiveGoalPool,
92
- readLegacyActiveGoalFiles,
93
- safeUnlinkGoalFile,
94
- sanitizeGoalPaths,
95
- serializeGoalFile,
96
- writeActiveGoalFile,
97
- } from "./storage/goal-files.ts";
98
- import {
99
- buildGoalListText,
100
- buildUnfocusedOpenGoalsSummary,
101
- focusedGoalFromPool,
102
- goalSelectorLabel,
103
- mergeFocusedGoalWithDisk,
104
- openGoalsFromPool,
105
- otherOpenGoalCount,
106
- resolveSessionFocus,
107
- } from "./goal-pool.ts";
108
- import {
109
- continuationPrompt,
110
- goalPrompt,
111
- goalTweakDraftingPrompt,
112
- staleContinuationPrompt,
113
- unfocusedOpenGoalsPrompt,
114
- untrustedObjectiveBlock,
115
- } from "./prompts/goal-prompts.ts";
116
- import { buildGoalRunningNotification } from "./widgets/goal-notifications.ts";
117
- import { GoalWidgetComponent, type AuditorWidgetProgress } from "./widgets/goal-widget.ts";
118
- import { showEscapeDialog, type EscapeDialogResult } from "./widgets/goal-escape-dialog.ts";
119
- import { showTaskListOverlay } from "./widgets/task-list-overlay.ts";
35
+ GOAL_TRANSCRIPT_EVENT,
36
+ createGoalTranscriptEvent,
37
+ type GoalTranscriptEvent,
38
+ type GoalTranscriptEventInput,
39
+ } from "./goal-transcript-events.ts";
40
+ import { GoalWidget } from "./goal-widget.ts";
120
41
 
121
- import {
122
- abortGoalCommandMessage,
123
- buildAbortedByAgentGoal,
124
- buildCompletionReport,
125
- buildGoalCreatedReport,
126
- buildPausedByAgentGoal,
127
- buildTaskSummary,
128
- clearGoalCommandMessage,
129
- shouldArmPostCompactReminder,
130
- shouldInjectPostCompactReminder,
131
- taskCompletionBlockWarning,
132
- validateGoalAbort,
133
- validateGoalCompletion,
134
- validatePauseGoal,
135
- checkSubtasksComplete,
136
- findSubtaskDepthViolation,
137
- findTaskInTree,
138
- skipAllSubtasks,
139
- updateTaskInTree,
140
- validateResumeGoal,
141
- validateTaskCompletion,
142
- validateTaskListProposal,
143
- validateTaskSkip,
144
- validateVerificationSummary,
145
- } from "./goal-policy.ts";
42
+ export * from "./goal-contract.ts";
43
+ export * from "./goal-transcript-events.ts";
44
+ export * from "./legacy-migration.ts";
146
45
 
147
- const STATE_ENTRY = "pi-goal-state";
148
- const FOCUS_ENTRY = "pi-goal-focus";
149
- const LEGACY_MIGRATION_ENTRY = "pi-goal-legacy-migration";
150
- const GOAL_EVENT_ENTRY = "pi-goal-event";
151
- const GOAL_AUDIT_ENTRY = "pi-goal-audit-event";
152
- const GOAL_STATE_EVENT = "pi-goal:state";
153
- const GOAL_PROPOSAL_EVENT = "pi-goal:proposal";
154
- const COMPLETE_STATUS = "complete";
155
- const CONTINUATION_IDLE_RETRY_MS = 50;
156
- const CONTINUATION_COMPACTION_SETTLE_MS = 500;
157
- const STATUS_REFRESH_MS = 1000;
158
- /**
159
- * Tools that count as "real work" toward the active goal. If a non-tool-use
160
- * turn ends without any of these having been called, we DO NOT queue the next
161
- * autoContinue — the agent was just chatting. This stops infinite chat loops.
162
- */
163
- const GOAL_PROGRESS_TOOL_SET = new Set<string>(GOAL_PROGRESS_TOOL_NAMES);
46
+ const GOAL_CONTINUATION_TEXT = "Continue the Goal.";
164
47
 
165
- export type StructuredGoalProposal =
166
- | {
167
- id: string;
168
- kind: "goal-draft";
169
- focus: GoalDraftingFocus;
170
- title: string;
171
- originalTopic: string;
172
- objective: string;
173
- autoContinue: boolean;
174
- verificationContract?: string;
175
- tasks?: GoalTask[];
176
- auditorEnabledDefault: boolean;
177
- }
178
- | {
179
- id: string;
180
- kind: "goal-tweak";
181
- focus: GoalDraftingFocus;
182
- title: string;
183
- currentObjective: string;
184
- newObjective: string;
185
- changeSummary: string;
186
- verificationContract?: string;
187
- auditorEnabledDefault: boolean;
188
- }
189
- | {
190
- id: string;
191
- kind: "task-list";
192
- focus: "goal";
193
- title: string;
194
- currentObjective: string;
195
- tasks: GoalTask[];
196
- blockCompletion: boolean;
197
- auditorEnabledDefault: boolean;
198
- };
48
+ type IdleExtensionContext = ExtensionContext & {
49
+ onIdle(callback: () => void): () => void;
50
+ };
199
51
 
200
- export interface GoalStateEventPayload {
201
- version: 1;
202
- emittedAt: string;
203
- reason: string;
204
- goal: GoalRecord | null;
205
- focusedGoalId: string | null;
206
- openGoalCount: number;
52
+ function nowIso(): string {
53
+ return new Date().toISOString();
207
54
  }
208
55
 
209
- export interface GoalProposalEventPayload {
210
- version: 1;
211
- emittedAt: string;
212
- proposal: StructuredGoalProposal | null;
213
- reason?: string;
56
+ function boundedRequiredText(value: string, label: string, maxLength: number): string {
57
+ const trimmed = value.trim();
58
+ if (!trimmed) throw new Error(`${label} requires non-empty text.`);
59
+ if (trimmed.length > maxLength) throw new Error(`${label} exceeds the ${maxLength}-character producer state bound.`);
60
+ return trimmed;
214
61
  }
215
62
 
216
-
217
- /**
218
- * Tools that are NEVER blocked by the post-stop in-turn block. After pause_goal,
219
- * abort_goal, or complete_goal fires, the agent should
220
- * yield the turn; we block all subsequent tool calls except these read-only inspections.
221
- */
222
- const POST_STOP_ALLOWED_TOOL_SET = new Set<string>(POST_STOP_ALLOWED_TOOLS);
223
-
224
- /**
225
- * When non-null, /goal-tweak drafting is in progress for this goal id and the
226
- * agent is allowed to call propose_goal_tweak. Cleared after the tweak is applied
227
- * or when a user-driven turn arrives without a tweak follow-through. This is
228
- * the schema-level affordance gate that prevents the agent from "tweaking" via
229
- * arbitrary write/edit calls.
230
- */
231
- let tweakDraftingFor: string | null = null;
232
-
233
- /**
234
- * Thin session-local confirmation intent for /goals and /sisyphus.
235
- * It protects mode consistency and user confirmation without turning drafting
236
- * into a separate long-running runtime state machine.
237
- */
238
- interface GoalConfirmationIntent {
239
- focus: GoalDraftingFocus;
240
- originalTopic: string;
241
- startedAt: number;
63
+ function boundedOptionalText(value: string | undefined, label: string, maxLength: number): string | undefined {
64
+ const trimmed = value?.trim();
65
+ if (!trimmed) return undefined;
66
+ if (trimmed.length > maxLength) throw new Error(`${label} exceeds the ${maxLength}-character producer state bound.`);
67
+ return trimmed;
242
68
  }
243
- let confirmationIntent: GoalConfirmationIntent | null = null;
244
-
245
69
 
246
- // ---------- summaries ----------
247
-
248
- function usageLines(goal: GoalRecord): string[] {
249
- return [
250
- `Time spent: ${formatDuration(goal.usage.activeSeconds)}`,
251
- `Tokens used: ${formatTokenValue(goal.usage.tokensUsed)}`,
252
- ];
70
+ function emptyState(): GoalState {
71
+ return { schemaVersion: GOAL_SCHEMA_VERSION, revision: 0, goal: null };
253
72
  }
254
73
 
255
- function detailedSummary(goal: GoalRecord | null): string {
256
- if (!goal) return "No goal is set. Use /goals <topic> or /sisyphus <topic> to discuss, or /goals-set <objective> / /sisyphus-set <objective> to start immediately.";
257
- const lines = [
258
- `Goal: ${goal.objective}`,
259
- `Status: ${statusLabel(goal)}`,
260
- `Auto-continue: ${goal.autoContinue ? "on" : "off"}`,
261
- ...usageLines(goal),
262
- ];
263
- if (goal.sisyphus) {
264
- lines.push("Mode: Sisyphus (prompt/criteria variant; shared goal lifecycle)");
265
- }
266
- if (goal.taskList) {
267
- const taskSummary = buildTaskSummary(goal.taskList);
268
- lines.push(`Tasks: ${taskSummary}`);
269
- // Find first pending task at any depth (BFS)
270
- const queue = [...(goal.taskList.tasks ?? [])];
271
- let firstPending: { id: string; title: string } | undefined;
272
- while (queue.length > 0 && !firstPending) {
273
- const t = queue.shift()!;
274
- if (t.status === "pending") firstPending = t;
275
- else if (t.subtasks) queue.push(...t.subtasks);
276
- }
277
- if (firstPending) {
278
- lines.push(`Next pending task: ${firstPending.id} — ${firstPending.title}`);
74
+ function loadProposalRevision(ctx: ExtensionContext): number {
75
+ const branch = ctx.sessionManager.getBranch();
76
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
77
+ const entry = branch[index] as { type?: string; customType?: string; data?: unknown };
78
+ if (entry.type !== "custom" || entry.customType !== GOAL_PROPOSAL_REVISION_ENTRY) continue;
79
+ const revision = entry.data !== null && typeof entry.data === "object" ? (entry.data as { revision?: unknown }).revision : undefined;
80
+ if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 0) {
81
+ throw new Error(`Invalid ${GOAL_PROPOSAL_REVISION_ENTRY} at the active branch leaf; refusing to reset the event revision.`);
279
82
  }
83
+ return revision;
280
84
  }
281
- if (goal.activePath) lines.push(`File: ${goal.activePath}`);
282
- if (goal.archivedPath) lines.push(`Archive: ${goal.archivedPath}`);
283
- if (goal.stopReason) lines.push(`Stop reason: ${goal.stopReason}`);
284
- if (goal.pauseReason) lines.push(`Agent pause reason: ${goal.pauseReason}`);
285
- if (goal.pauseSuggestedAction) lines.push(`Agent suggests: ${goal.pauseSuggestedAction}`);
286
- return lines.join("\n");
287
- }
288
-
289
- function oneLineSummary(goal: GoalRecord | null): string {
290
- if (!goal) return "No goal is set.";
291
- const tail = goal.usage.tokensUsed > 0 ? ` [${formatTokenValue(goal.usage.tokensUsed).split(" ")[0]}]` : "";
292
- return `${statusLabel(goal)}${tail} - ${truncateText(goal.objective)}`;
293
- }
294
-
295
- // ---------- entry / render helpers ----------
296
-
297
- function goalDetails(goal: GoalRecord | null): GoalStateEntry {
298
- return { version: 3, goal: goal ? cloneGoal(goal) : null };
299
- }
300
-
301
- function renderGoalResult(result: { details?: unknown; content: Array<{ type: string; text?: string }> }, theme: Theme): Text {
302
- const first = result.content.find((item) => item.type === "text" && typeof item.text === "string");
303
- const firstText = first?.text ?? "";
304
- const details = result.details as GoalStateEntry | undefined;
305
- if (!details || typeof details !== "object" || !("goal" in details)) {
306
- return new Text(firstText, 0, 0);
307
- }
308
- if (
309
- firstText.startsWith("Goal audit ")
310
- || firstText.startsWith("Goal completion rejected")
311
- || firstText.startsWith("Goal complete.")
312
- || firstText.startsWith("Goal paused.")
313
- || firstText.startsWith("Goal aborted.")
314
- || firstText.startsWith("Goal confirmed and created.")
315
- ) {
316
- return new Text(firstText, 0, 0);
317
- }
318
- return new Text(theme.fg("accent", "Goal ") + theme.fg("muted", oneLineSummary(details.goal)), 0, 0);
85
+ return 0;
319
86
  }
320
87
 
321
- function normalizeGoalEventDetails(value: unknown): GoalEventDetails {
322
- const raw = asRecord(value);
323
- const kind: GoalEventKind = raw?.kind === "stale" ? "stale" : raw?.kind === "drafting" ? "drafting" : "checkpoint";
324
- const goalId = typeof raw?.goalId === "string" ? raw.goalId : "unknown";
325
- const focus: DraftingFocus | undefined = raw?.focus === "sisyphus" ? "sisyphus" : raw?.focus === "goal" ? "goal" : undefined;
326
- const status = raw?.status === "active" || raw?.status === "paused" || raw?.status === "complete" ? (raw.status as GoalStatus) : undefined;
327
- const currentStatus =
328
- raw?.currentStatus === "active" || raw?.currentStatus === "paused" || raw?.currentStatus === "complete"
329
- ? (raw.currentStatus as GoalStatus)
330
- : raw?.currentStatus === null
331
- ? null
332
- : undefined;
333
- return {
334
- kind,
335
- goalId,
336
- status,
337
- objective: typeof raw?.objective === "string" ? raw.objective : undefined,
338
- timestamp: typeof raw?.timestamp === "number" ? raw.timestamp : undefined,
339
- currentGoalId: typeof raw?.currentGoalId === "string" || raw?.currentGoalId === null ? raw.currentGoalId : undefined,
340
- currentStatus,
341
- focus,
342
- };
343
- }
344
-
345
- interface GoalAuditEventDetails {
346
- phase: "started" | "approved" | "rejected" | "skipped";
347
- goalId: string;
348
- auditor?: string;
349
- }
350
-
351
- function renderGoalEvent(message: { details?: GoalEventDetails }, options: { expanded: boolean }, theme: Theme): Text {
352
- const details = normalizeGoalEventDetails(message.details);
353
- const label =
354
- details.kind === "stale" ? "stale checkpoint"
355
- : details.kind === "drafting" ? (details.focus === "sisyphus" ? "sisyphus drafting" : "goal drafting")
356
- : "checkpoint";
357
- if (!options.expanded) {
358
- return new Text(theme.fg("customMessageLabel", "Goal ") + theme.fg("customMessageText", label), 0, 0);
359
- }
360
- const lines = [`Status: ${details.status === "active" ? "running" : details.status ?? "unknown"}`];
361
- if (details.objective) lines.push(`Objective: ${details.objective}`);
362
- lines.push(`Goal id: ${details.goalId}`);
363
- if (details.currentGoalId || details.currentStatus) {
364
- lines.push(`Current: ${details.currentGoalId ?? "none"}${details.currentStatus ? ` (${details.currentStatus})` : ""}`);
88
+ function loadGoalState(ctx: ExtensionContext): GoalState | null {
89
+ const branch = ctx.sessionManager.getBranch();
90
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
91
+ const entry = branch[index] as { type?: string; customType?: string; data?: unknown };
92
+ if (entry.type !== "custom" || entry.customType !== GOAL_STATE_ENTRY) continue;
93
+ const parsed = parseGoalState(entry.data);
94
+ if (!parsed) throw new Error(`Invalid ${GOAL_STATE_ENTRY} snapshot at the active branch leaf; refusing to fall back to older Goal state.`);
95
+ return parsed;
365
96
  }
366
- return new Text(
367
- theme.fg("customMessageLabel", `Goal ${label}`) + "\n" + theme.fg("customMessageText", lines.join("\n")),
368
- 0,
369
- 0,
370
- );
371
- }
372
-
373
- function renderGoalAuditEvent(message: { content?: unknown; details?: GoalAuditEventDetails }, _options: { expanded: boolean }, theme: Theme): Text {
374
- const phase = message.details?.phase ?? "started";
375
- const label = phase === "approved" ? "approved" : phase === "rejected" ? "rejected" : phase === "skipped" ? "skipped" : "started";
376
- const content = typeof message.content === "string" ? message.content : `Goal audit ${label}.`;
377
- return new Text(
378
- theme.fg("customMessageLabel", `Goal audit ${label}`) + "\n" + theme.fg("customMessageText", content),
379
- 0,
380
- 0,
381
- );
382
- }
383
-
384
- function extractGoalIdFromInjectedMessage(text: string): string | null {
385
- // Drafting messages (new goal, sisyphus, or tweak) have no continuation goalId and
386
- // must never be treated as stale-continuation triggers.
387
- if (/^\[GOAL (?:DRAFTING|TWEAK DRAFTING)\b/.test(text)) return null;
388
- // Phase 5 C1: structured outer marker `<pi_goal_continuation goal_id="..." kind="...">`.
389
- // Borrowed from pi-codex-goal. More robust than bare bracket text because
390
- // the angle brackets + attributes are nearly impossible for users to type
391
- // by accident, and the structure is grep-able / parse-able by external tooling.
392
- const xmlMatch = text.match(/^<pi_goal_continuation\s+goal_id=\"([^\"]+)\"/);
393
- if (xmlMatch) return xmlMatch[1] ?? null;
394
- const match = text.match(/^\[(?:GOAL CHECKPOINT|GOAL CONTINUATION|GOAL STALE) goalId=([^\]\s]+)\]/);
395
- return match?.[1] ?? null;
396
- }
397
-
398
- function extractContinuationEpochFromInjectedMessage(text: string): number | null {
399
- const match = text.match(/^<pi_goal_continuation\b[^>]*\bepoch=\"(\d+)\"/);
400
- if (!match?.[1]) return null;
401
- const value = Number(match[1]);
402
- return Number.isSafeInteger(value) ? value : null;
403
- }
404
-
405
- function goalEventMessageId(message: { customType?: string; details?: unknown; content?: unknown }): string | null {
406
- if (message.customType !== GOAL_EVENT_ENTRY) return null;
407
- const details = asRecord(message.details);
408
- // Drafting messages never correspond to a real goal id; they must not be staleness-checked.
409
- if (details?.kind === "drafting") return null;
410
- const goalId = details && typeof details.goalId === "string" ? details.goalId : null;
411
- if (goalId) return goalId;
412
- return typeof message.content === "string" ? extractGoalIdFromInjectedMessage(message.content) : null;
413
- }
414
-
415
- function goalEventEpoch(message: { customType?: string; details?: unknown; content?: unknown }): number | null {
416
- if (message.customType !== GOAL_EVENT_ENTRY) return null;
417
- const details = asRecord(message.details);
418
- const raw = details?.continuationEpoch;
419
- if (typeof raw === "number" && Number.isSafeInteger(raw)) return raw;
420
- return typeof message.content === "string" ? extractContinuationEpochFromInjectedMessage(message.content) : null;
97
+ return null;
421
98
  }
422
99
 
423
- function isAbortedAssistantMessage(message: unknown): boolean {
424
- const raw = asRecord(message);
425
- return raw?.role === "assistant" && raw.stopReason === "aborted";
426
- }
427
-
428
- function isLengthAssistantMessage(message: unknown): boolean {
429
- const raw = asRecord(message);
430
- return raw?.role === "assistant" && raw.stopReason === "length";
431
- }
432
-
433
- function isToolUseAssistantMessage(message: unknown): boolean {
434
- const raw = asRecord(message);
435
- return raw?.role === "assistant" && raw.stopReason === "toolUse";
436
- }
437
-
438
- function isContextOverflowAssistantMessage(message: unknown, contextWindow?: number): boolean {
439
- const raw = asRecord(message);
440
- if (!raw || raw.role !== "assistant") return false;
441
- const usage = asRecord(raw.usage);
442
- const assistant: AssistantMessage = {
443
- role: "assistant",
444
- content: Array.isArray(raw.content) ? raw.content as AssistantMessage["content"] : [],
445
- api: typeof raw.api === "string" ? raw.api : "",
446
- provider: typeof raw.provider === "string" ? raw.provider : "",
447
- model: typeof raw.model === "string" ? raw.model : "",
448
- usage: {
449
- input: usageChannelTokens(usage?.input),
450
- output: usageChannelTokens(usage?.output),
451
- cacheRead: usageChannelTokens(usage?.cacheRead),
452
- cacheWrite: usageChannelTokens(usage?.cacheWrite),
453
- totalTokens: usageChannelTokens(usage?.totalTokens),
454
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
455
- },
456
- stopReason: typeof raw.stopReason === "string" ? raw.stopReason as AssistantMessage["stopReason"] : "error",
457
- errorMessage: typeof raw.errorMessage === "string" ? raw.errorMessage : undefined,
458
- timestamp: typeof raw.timestamp === "number" ? raw.timestamp : Date.now(),
459
- };
460
- return isContextOverflow(assistant, contextWindow);
461
- }
462
-
463
- function hasAbortedAssistantMessage(messages: unknown[]): boolean {
464
- return messages.some(isAbortedAssistantMessage);
465
- }
466
-
467
- function hasLengthAssistantMessage(messages: unknown[]): boolean {
468
- return messages.some(isLengthAssistantMessage);
100
+ function hasMigrationMarker(ctx: ExtensionContext, status?: string): boolean {
101
+ return ctx.sessionManager.getBranch().some((item) => {
102
+ const entry = item as { type?: string; customType?: string; data?: unknown };
103
+ if (entry.type !== "custom" || entry.customType !== LEGACY_MIGRATION_ENTRY) return false;
104
+ if (!status) return true;
105
+ return entry.data !== null && typeof entry.data === "object" && (entry.data as { status?: unknown }).status === status;
106
+ });
469
107
  }
470
108
 
471
- function hasContextOverflowAssistantMessage(messages: unknown[], contextWindow?: number): boolean {
472
- return messages.some((message) => isContextOverflowAssistantMessage(message, contextWindow));
109
+ function assistantTokens(message: unknown): number {
110
+ if (message === null || typeof message !== "object") return 0;
111
+ const raw = message as { role?: unknown; usage?: { input?: unknown; output?: unknown } };
112
+ if (raw.role !== "assistant") return 0;
113
+ const input = typeof raw.usage?.input === "number" && Number.isFinite(raw.usage.input) ? raw.usage.input : 0;
114
+ const output = typeof raw.usage?.output === "number" && Number.isFinite(raw.usage.output) ? raw.usage.output : 0;
115
+ return Math.max(0, Math.trunc(input)) + Math.max(0, Math.trunc(output));
473
116
  }
474
117
 
475
- function usageChannelTokens(value: unknown): number {
476
- if (typeof value !== "number" || !Number.isFinite(value)) return 0;
477
- return Math.max(0, Math.trunc(value));
118
+ function renderGoalContext(state: GoalState): string {
119
+ const goal = state.goal;
120
+ if (!goal) return "";
121
+ const lines = [
122
+ `[PI GOAL ${goal.status.toUpperCase()} revision=${state.revision} goalId=${goal.id}]`,
123
+ "<goal_objective>",
124
+ goal.objective.replace(/<\/?goal_objective>/gi, (tag) => tag.replaceAll("<", "&lt;").replaceAll(">", "&gt;")),
125
+ "</goal_objective>",
126
+ ];
127
+ if (goal.status === "active") {
128
+ lines.push("Keep this objective in force. Continue with concrete work; call pause_goal for a real blocker, abandon_goal if it should be abandoned, or complete_goal only after the objective is genuinely complete.");
129
+ } else if (goal.status === "paused") {
130
+ lines.push(`The Goal is paused: ${goal.pause?.reason ?? "no reason recorded"}. Do not resume substantive Goal work until resume_goal is called.`);
131
+ if (goal.pause?.suggestedAction) lines.push(`Suggested unblock action: ${goal.pause.suggestedAction}`);
132
+ } else {
133
+ lines.push("The Goal passed its independent audit. Write one normal final response now and do not call tools.");
134
+ }
135
+ if (goal.lastAuditRejection) lines.push(`Latest auditor objection: ${goal.lastAuditRejection.report}`);
136
+ return lines.join("\n");
478
137
  }
479
138
 
480
- function assistantTurnTokens(message: unknown): number {
481
- const raw = asRecord(message);
482
- if (!raw || raw.role !== "assistant") return 0;
483
- const usage = asRecord(raw.usage);
484
- if (!usage) return 0;
485
- return usageChannelTokens(usage.input) + usageChannelTokens(usage.output);
139
+ function stateText(state: GoalState): string {
140
+ const goal = state.goal;
141
+ if (!goal) return "No Goal is active on this branch.";
142
+ const lines = [`Goal ${goal.status}: ${goal.objective}`, `Revision: ${state.revision}`, `Auto-continue: ${goal.autoContinue ? "on" : "off"}`];
143
+ if (goal.pause) lines.push(`Reason: ${goal.pause.reason}`);
144
+ if (goal.pause?.suggestedAction) lines.push(`Suggested action: ${goal.pause.suggestedAction}`);
145
+ if (goal.lastAuditRejection) lines.push(`Latest audit rejection: ${goal.lastAuditRejection.report}`);
146
+ return lines.join("\n");
486
147
  }
487
148
 
488
- function isMeaningfulProgressToolCall(toolName: string, args: unknown): boolean {
489
- if (!GOAL_PROGRESS_TOOL_SET.has(toolName)) return false;
490
- if (toolName === "read") {
491
- const path = asRecord(args)?.path;
492
- if (typeof path === "string" && (path === ".pi/goals" || path.startsWith(".pi/goals/"))) return false;
149
+ export default function goalExtension(
150
+ pi: ExtensionAPI,
151
+ dependencies: { runCompletionAuditor?: typeof runGoalCompletionAuditor } = {},
152
+ ): void {
153
+ let state = emptyState();
154
+ let proposal: GoalProposal = { schemaVersion: GOAL_SCHEMA_VERSION, revision: 0, proposal: null };
155
+ let proposalSequence = 0;
156
+ let lastAccountedAt: number | null = null;
157
+ let auditing = false;
158
+ let widget: GoalWidget | null = null;
159
+ let widgetContext: ExtensionContext | null = null;
160
+ let migrationCandidates: LegacyGoalCandidate[] = [];
161
+ let idleContinuationCancel: (() => void) | undefined;
162
+
163
+ function emitState(): void {
164
+ pi.events.emit(GOAL_STATE_EVENT, structuredClone(state));
165
+ }
166
+
167
+ function emitProposal(): void {
168
+ pi.events.emit(GOAL_PROPOSAL_EVENT, structuredClone(proposal));
169
+ }
170
+
171
+ function updateWidget(ctx: ExtensionContext): void {
172
+ widgetContext = ctx;
173
+ if (!ctx.hasUI || !state.goal) {
174
+ ctx.ui.setWidget("pi-goal", undefined);
175
+ widget = null;
176
+ return;
493
177
  }
494
- if (toolName === "bash") {
495
- const command = asRecord(args)?.command;
496
- if (typeof command === "string" && /^\s*echo\b/.test(command)) return false;
178
+ if (widget) {
179
+ widget.update();
180
+ return;
497
181
  }
498
- return true;
499
- }
500
-
501
- // ---------- extension entry point ----------
502
-
503
- export default function goalExtension(pi: ExtensionAPI): void {
504
- let goalsById = new Map<string, GoalRecord>();
505
- let focusedGoalId: string | null = null;
506
- const state = {
507
- get goal(): GoalRecord | null {
508
- return focusedGoalFromPool(goalsById, focusedGoalId);
509
- },
510
- set goal(next: GoalRecord | null) {
511
- if (next) {
512
- goalsById.set(next.id, next);
513
- focusedGoalId = next.id;
514
- return;
515
- }
516
- if (focusedGoalId) goalsById.delete(focusedGoalId);
517
- focusedGoalId = null;
518
- },
519
- };
520
- let continuationQueuedFor: string | null = null;
521
- let continuationScheduledFor: string | null = null;
522
- let continuationTimer: ReturnType<typeof setTimeout> | null = null;
523
- let continuationEpoch = 0;
524
- let compactionSettleUntil = 0;
525
- let postCompactionContinuationGoalId: string | null = null;
526
- let runningGoalId: string | null = null;
527
- let terminalInputUnsubscribe: (() => void) | null = null;
528
- let statusRefreshTimer: ReturnType<typeof setInterval> | null = null;
529
- let statusRefreshCtx: ExtensionContext | null = null;
530
- let auditProgress: AuditorWidgetProgress | null = null;
531
- let auditAnimationTimer: ReturnType<typeof setInterval> | null = null;
532
- let auditAbortController: AbortController | null = null;
533
- let showingEscapeDialog = false;
534
- let debugMode = false;
535
- let debugGoalCounter = 0;
536
- let debugMockAuditTimer: ReturnType<typeof setInterval> | null = null;
537
- const DEBUG_GOALS_DIR = ".pi/goals/debug";
538
-
539
-
540
- // Per-turn flags reset in turn_start (#4, C9 fix).
541
- // goalWorkToolCalledThisTurn: tracks whether a real goal-work tool was called.
542
- // If false at turn_end, we don't queue another autoContinue (empty chat turn).
543
- // turnStoppedFor: set by pause_goal / complete_goal / propose_goal_tweak
544
- // after their successful execute. Once set, pi.on("tool_call") blocks all
545
- // subsequent in-turn tool calls except POST_STOP_ALLOWED_TOOLS. This is the
546
- // schema fix for "agent keeps writing files after pause_goal".
547
- // turnSeq: lightweight generation counter, incremented at each turn start.
548
- // Used to scope turnStoppedFor so stale markers from prior turns or sessions
549
- // cannot poison a resumed active goal.
550
- // checkpointGoalId: remembers the incoming goal id from queued continuations.
551
- // When set but the goal is no longer active/autoContinue, work tools are blocked.
552
- let goalWorkToolCalledThisTurn = false;
553
- let turnSeq = 0;
554
- let turnStoppedFor: { goalId: string; turnSeq: number } | null = null;
555
- let checkpointGoalId: string | null = null;
556
- let checkpointBlocked = false;
557
-
558
- function clearCheckpointBlock(): void {
559
- checkpointGoalId = null;
560
- checkpointBlocked = false;
182
+ ctx.ui.setWidget("pi-goal", (tui, theme) => {
183
+ widget = new GoalWidget(tui, theme, () => state, () => auditing);
184
+ return widget;
185
+ }, { placement: "aboveEditor" });
561
186
  }
562
187
 
563
- // #5 post-compaction resync: when a compaction just happened, the next agent
564
- // turn gets an extra reminder block. Set in session_compact, consumed
565
- // (cleared) in before_agent_start.
566
- let postCompactReminderPending = false;
567
-
568
- const accounting = {
569
- activeGoalId: null as string | null,
570
- lastAccountedAt: null as number | null,
571
- };
572
- let goalProposalSequence = 0;
573
-
574
- function nextGoalProposalId(kind: StructuredGoalProposal["kind"]): string {
575
- goalProposalSequence += 1;
576
- return `${kind}-${Date.now().toString(36)}-${goalProposalSequence}`;
188
+ function persist(nextGoal: Goal | null, ctx: ExtensionContext): void {
189
+ const nextState = {
190
+ schemaVersion: GOAL_SCHEMA_VERSION,
191
+ revision: state.revision + 1,
192
+ goal: nextGoal ? structuredClone(nextGoal) : null,
193
+ };
194
+ if (!isGoalState(nextState)) throw new Error("Goal mutation exceeds the exported producer state contract.");
195
+ state = nextState;
196
+ pi.appendEntry(GOAL_STATE_ENTRY, state);
197
+ emitState();
198
+ updateWidget(ctx);
577
199
  }
578
200
 
579
- function emitGoalState(reason: string): void {
580
- const displayGoal = goalForDisplay() ?? state.goal;
581
- pi.events?.emit(GOAL_STATE_EVENT, {
582
- version: 1,
583
- emittedAt: nowIso(),
584
- reason,
585
- goal: displayGoal ? cloneGoal(displayGoal) : null,
586
- focusedGoalId,
587
- openGoalCount: openGoals().length,
588
- } satisfies GoalStateEventPayload);
201
+ function publishReceipt(input: GoalTranscriptEventInput): GoalTranscriptEvent {
202
+ const receipt = createGoalTranscriptEvent(input, nowIso());
203
+ pi.appendEntry(GOAL_RECEIPT_ENTRY, receipt);
204
+ pi.events.emit(GOAL_TRANSCRIPT_EVENT, receipt);
205
+ return receipt;
589
206
  }
590
207
 
591
- function emitGoalProposal(proposal: StructuredGoalProposal | null, reason?: string): void {
592
- pi.events?.emit(GOAL_PROPOSAL_EVENT, {
593
- version: 1,
594
- emittedAt: nowIso(),
595
- proposal,
596
- ...(reason ? { reason } : {}),
597
- } satisfies GoalProposalEventPayload);
208
+ function goalFields(goal: Goal | null): Pick<GoalTranscriptEventInput, "goalId" | "objective" | "autoContinue"> {
209
+ return goal ? { goalId: goal.id, objective: goal.objective, autoContinue: goal.autoContinue } : {};
598
210
  }
599
211
 
600
- async function showStructuredProposalDialog(
601
- ctx: ExtensionContext,
602
- proposal: StructuredGoalProposal,
603
- confirmationText: string,
604
- focus: GoalDraftingFocus,
605
- defaultAuditorEnabled: boolean,
606
- ): Promise<{ decision: "confirm" | "continue"; auditorEnabled: boolean }> {
607
- emitGoalProposal(proposal, "opened");
608
- try {
609
- return await showProposalDialog(ctx, confirmationText, focus, defaultAuditorEnabled);
610
- } finally {
611
- emitGoalProposal(null, "closed");
612
- }
212
+ function nextProposalRevision(): number {
213
+ proposalSequence += 1;
214
+ pi.appendEntry(GOAL_PROPOSAL_REVISION_ENTRY, { schemaVersion: GOAL_SCHEMA_VERSION, revision: proposalSequence });
215
+ return proposalSequence;
613
216
  }
614
217
 
615
- const goalExecutionWorkTools = ["read", "bash", "edit", "write"] as const;
616
-
617
- function syncGoalTools(): void {
618
- try {
619
- const initialTools = pi.getActiveTools();
620
- if (!Array.isArray(initialTools)) {
621
- console.error("[pi-goal] syncGoalTools: pi.getActiveTools() did not return an array, got", typeof initialTools);
622
- return;
623
- }
624
- const active = new Set(initialTools);
625
- for (const name of goalExecutionWorkTools) active.add(name);
626
- active.delete(QUESTION_TOOL_NAME);
627
- active.delete(QUESTIONNAIRE_TOOL_NAME);
628
- for (const name of ACTIVE_GOAL_TOOL_NAMES) active.delete(name);
629
- const phase = confirmationIntent !== null ? "drafting" : tweakDraftingFor !== null ? "tweakDrafting" : "normal";
630
- const lifecycleTools = lifecycleToolNamesForGoalStatus(state.goal?.status, phase);
631
- for (const name of lifecycleTools) active.add(name);
632
- // Sisyphus is now a prompt/criteria style, not a separate step-counter
633
- // mechanism. Keep step_complete registered for legacy transcripts, but do
634
- // not expose it as an active work tool.
635
- active.delete(SISYPHUS_STEP_TOOL_NAME);
636
- // propose_goal_tweak is always available for active/paused goals via lifecycle tools.
637
- // During a /goal-tweak drafting flow, additionally expose question tools.
638
- if (state.goal && tweakDraftingFor === state.goal.id) {
639
- active.add(PROPOSE_TWEAK_TOOL_NAME);
640
- active.add(QUESTION_TOOL_NAME);
641
- active.add(QUESTIONNAIRE_TOOL_NAME);
642
- }
643
- // Outside of active/paused states, remove propose_goal_tweak
644
- if (!state.goal || state.goal.status === "complete") {
645
- active.delete(PROPOSE_TWEAK_TOOL_NAME);
646
- }
647
-
648
- // Keep the commit tool available and let its validator enforce that a
649
- // drafting flow is active. This avoids fragile hidden-tool drift after
650
- // question turns, compaction, or active-tool resync.
651
- active.add(PROPOSE_DRAFT_TOOL_NAME);
652
- // create_goal stays hidden — hard invariant: user must confirm via propose_goal_draft.
653
- active.delete(CREATE_GOAL_TOOL_NAME);
654
- if (confirmationIntent !== null) {
655
- active.add(QUESTION_TOOL_NAME);
656
- active.add(QUESTIONNAIRE_TOOL_NAME);
657
- } else if (state.goal?.status === "active") {
658
- for (const name of goalExecutionWorkTools) active.add(name);
659
- active.add(QUESTION_TOOL_NAME);
660
- active.add(QUESTIONNAIRE_TOOL_NAME);
661
- }
662
- pi.setActiveTools(Array.from(active));
663
- } catch (err) {
664
- console.error("[pi-goal] syncGoalTools error:", err instanceof Error ? err.message : String(err));
665
- }
218
+ function setProposal(kind: "create" | "tweak", objective: string, currentObjective?: string): void {
219
+ const boundedObjective = boundedRequiredText(objective, "Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
220
+ const boundedCurrentObjective = boundedOptionalText(currentObjective, "Current Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
221
+ proposal = {
222
+ schemaVersion: GOAL_SCHEMA_VERSION,
223
+ revision: nextProposalRevision(),
224
+ proposal: { kind, objective: boundedObjective, ...(boundedCurrentObjective ? { currentObjective: boundedCurrentObjective } : {}) },
225
+ };
226
+ emitProposal();
666
227
  }
667
228
 
668
- function stopAuditAnimation(): void {
669
- if (auditAnimationTimer) {
670
- clearInterval(auditAnimationTimer);
671
- auditAnimationTimer = null;
672
- }
229
+ function clearProposal(): void {
230
+ proposal = { schemaVersion: GOAL_SCHEMA_VERSION, revision: nextProposalRevision(), proposal: null };
231
+ emitProposal();
673
232
  }
674
233
 
675
- function abortAudit(ctx: ExtensionContext): void {
676
- if (!auditAbortController || !auditProgress) return;
677
- const settings = loadGoalSettingsFileConfig(ctx.cwd);
678
- auditAbortController.abort();
679
- auditAbortController = null;
680
- stopAuditAnimation();
681
- auditProgress = null;
682
- goalWidgetComponent?.invalidate();
683
- if (state.goal) {
684
- try {
685
- appendGoalEvent(ctx, {
686
- type: "audit_skipped",
687
- goalId: state.goal.id,
688
- reason: "user_aborted",
689
- provider: settings.provider,
690
- model: settings.model,
691
- thinkingLevel: settings.thinkingLevel,
692
- at: nowIso(),
693
- });
694
- } catch {
695
- // Ledger append failure should not block skip
696
- }
697
- }
234
+ function cancelContinuation(): void {
235
+ idleContinuationCancel?.();
236
+ idleContinuationCancel = undefined;
698
237
  }
699
238
 
700
- function stopStatusRefresh(): void {
701
- if (statusRefreshTimer) {
702
- clearInterval(statusRefreshTimer);
703
- statusRefreshTimer = null;
704
- }
705
- statusRefreshCtx = null;
239
+ function continueGoal(): void {
240
+ const goal = state.goal;
241
+ if (!goal || goal.status !== "active" || !goal.autoContinue) return;
242
+ pi.sendMessage({
243
+ customType: GOAL_CONTINUATION_MESSAGE,
244
+ content: GOAL_CONTINUATION_TEXT,
245
+ display: false,
246
+ }, { deliverAs: "followUp", triggerTurn: true });
247
+ }
248
+
249
+ function requestContinuation(ctx: ExtensionContext): void {
250
+ if (!state.goal || state.goal.status !== "active" || !state.goal.autoContinue || idleContinuationCancel) return;
251
+ idleContinuationCancel = (ctx as IdleExtensionContext).onIdle(() => {
252
+ idleContinuationCancel = undefined;
253
+ continueGoal();
254
+ });
706
255
  }
707
256
 
708
- function syncStatusRefresh(ctx: ExtensionContext): void {
709
- if (!ctx.hasUI || state.goal?.status !== "active") {
710
- stopStatusRefresh();
257
+ function currentGoal(requiredStatus?: "active" | "paused-or-active"): Goal {
258
+ const goal = state.goal;
259
+ if (!goal) throw new Error("No Goal is active on this branch.");
260
+ if (requiredStatus === "active" && goal.status !== "active") throw new Error(`The Goal is ${goal.status}, not active.`);
261
+ if (requiredStatus === "paused-or-active" && goal.status === "complete") throw new Error("The Goal is already complete and awaiting final settlement.");
262
+ return goal;
263
+ }
264
+
265
+ async function confirmProposal(ctx: ExtensionContext, title: string, objective: string): Promise<boolean> {
266
+ if (!ctx.hasUI) throw new Error("Goal proposal requires an interactive user confirmation surface.");
267
+ return ctx.ui.confirm(title, objective);
268
+ }
269
+
270
+ function pause(ctx: ExtensionContext, reason: string, suggestedAction?: string): Goal {
271
+ const goal = currentGoal("active");
272
+ const trimmedReason = boundedRequiredText(reason, "Goal pause reason", GOAL_PAUSE_REASON_MAX_LENGTH);
273
+ const trimmedSuggestedAction = boundedOptionalText(suggestedAction, "Goal pause suggested action", GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH);
274
+ const next: Goal = {
275
+ ...goal,
276
+ status: "paused",
277
+ autoContinue: false,
278
+ updatedAt: nowIso(),
279
+ pause: { reason: trimmedReason, ...(trimmedSuggestedAction ? { suggestedAction: trimmedSuggestedAction } : {}) },
280
+ };
281
+ persist(next, ctx);
282
+ publishReceipt({ kind: "goal_paused", level: "warning", ...goalFields(next), reason: trimmedReason, suggestedAction: trimmedSuggestedAction, tuiMessage: `Goal paused: ${trimmedReason}` });
283
+ return next;
284
+ }
285
+
286
+ function resume(ctx: ExtensionContext): Goal {
287
+ const goal = currentGoal("paused-or-active");
288
+ if (goal.status === "active") throw new Error("The Goal is already active.");
289
+ const { pause: _pause, ...resumedGoal } = goal;
290
+ const next: Goal = { ...resumedGoal, status: "active", autoContinue: true, updatedAt: nowIso() };
291
+ persist(next, ctx);
292
+ publishReceipt({ kind: "goal_resumed", level: "info", ...goalFields(next), tuiMessage: "Goal resumed." });
293
+ requestContinuation(ctx);
294
+ return next;
295
+ }
296
+
297
+ function abandon(ctx: ExtensionContext, reason: string): Goal {
298
+ const goal = currentGoal("paused-or-active");
299
+ const trimmedReason = reason.trim();
300
+ if (!trimmedReason) throw new Error("abandon_goal requires a non-empty reason.");
301
+ persist(null, ctx);
302
+ publishReceipt({ kind: "goal_abandoned", level: "warning", ...goalFields(goal), reason: trimmedReason, tuiMessage: `Goal abandoned: ${trimmedReason}` });
303
+ return goal;
304
+ }
305
+
306
+ function loadOrMigrate(ctx: ExtensionContext): void {
307
+ const loaded = loadGoalState(ctx);
308
+ if (loaded) {
309
+ state = loaded;
310
+ migrationCandidates = [];
711
311
  return;
712
312
  }
713
- statusRefreshCtx = ctx;
714
- if (statusRefreshTimer) return;
715
- statusRefreshTimer = setInterval(() => {
716
- if (!statusRefreshCtx || state.goal?.status !== "active") {
717
- stopStatusRefresh();
718
- return;
719
- }
720
- const displayGoal = goalForDisplay();
721
- if (displayGoal) {
722
- const otherCount = otherOpenGoalCount(goalsById, focusedGoalId);
723
- statusRefreshCtx.ui.setStatus("goal", `${footerStatus(displayGoal)}${otherCount > 0 ? ` (+${otherCount} open)` : ""}`);
724
- emitGoalState("status_tick");
725
- }
726
- // Live-tick the above-editor widget so duration/tokens update.
727
- goalWidgetComponent?.update();
728
- }, STATUS_REFRESH_MS);
729
- statusRefreshTimer.unref?.();
730
- }
731
-
732
- function clearContinuationTimer(): void {
733
- if (continuationTimer) {
734
- clearTimeout(continuationTimer);
735
- continuationTimer = null;
313
+ state = emptyState();
314
+ if (hasMigrationMarker(ctx, "complete")) return;
315
+ const plan = planLegacyMigration(ctx);
316
+ if (plan.kind === "migrate") {
317
+ writeLegacyMigration(pi, plan);
318
+ state = plan.goal;
319
+ migrationCandidates = [];
320
+ return;
736
321
  }
737
- continuationScheduledFor = null;
738
- }
739
-
740
- function clearContinuationState(): void {
741
- clearContinuationTimer();
742
- continuationQueuedFor = null;
743
- }
744
-
745
- function invalidateQueuedContinuations(): void {
746
- continuationEpoch += 1;
747
- clearContinuationState();
748
- }
749
-
750
- function deferContinuationUntilAfterCompaction(goalId: string | null | undefined): void {
751
- postCompactionContinuationGoalId = goalId ?? null;
752
- compactionSettleUntil = Date.now() + CONTINUATION_COMPACTION_SETTLE_MS;
753
- invalidateQueuedContinuations();
754
- }
755
-
756
- function clearActiveAccounting(): void {
757
- accounting.activeGoalId = null;
758
- accounting.lastAccountedAt = null;
759
- }
760
-
761
- function advanceTurnSeq(): void {
762
- turnSeq += 1;
763
- if (turnStoppedFor?.turnSeq !== turnSeq) turnStoppedFor = null;
764
- }
765
-
766
- function currentTurnStoppedGoalId(): string | null {
767
- if (!turnStoppedFor) return null;
768
- if (turnStoppedFor.turnSeq !== turnSeq) {
769
- turnStoppedFor = null;
770
- return null;
322
+ if (plan.kind === "ambiguous") {
323
+ migrationCandidates = plan.candidates;
324
+ if (!hasMigrationMarker(ctx, "selection_required")) {
325
+ pi.appendEntry(LEGACY_MIGRATION_ENTRY, {
326
+ schemaVersion: 1,
327
+ status: "selection_required",
328
+ candidateIds: plan.candidates.map((item) => item.id),
329
+ sourcePreserved: true,
330
+ });
331
+ }
771
332
  }
772
- return turnStoppedFor.goalId;
773
- }
774
-
775
- function markTurnStopped(goalId: string | null | undefined): void {
776
- turnStoppedFor = goalId ? { goalId, turnSeq } : null;
777
333
  }
778
334
 
779
- function isActionableContinuationGoal(goalId: string | null | undefined): goalId is string {
780
- return !!goalId && state.goal?.id === goalId && state.goal.status === "active" && state.goal.autoContinue;
781
- }
782
-
783
- function isCurrentContinuationEpoch(epoch: number | null): boolean {
784
- return epoch === continuationEpoch || (epoch === null && continuationEpoch === 0);
785
- }
335
+ pi.events.on(GOAL_STATE_REQUEST_EVENT, () => {
336
+ emitState();
337
+ emitProposal();
338
+ });
786
339
 
787
- function isStaleCheckpointBlockedToolCall(toolName: string): boolean {
788
- return !POST_STOP_ALLOWED_TOOL_SET.has(toolName);
789
- }
340
+ const currentPi = pi as unknown as {
341
+ registerEntryRenderer<T>(customType: string, renderer: (entry: { data: T }, options: { expanded: boolean }, theme: Theme) => Text): void;
342
+ };
343
+ currentPi.registerEntryRenderer<GoalTranscriptEvent>(GOAL_RECEIPT_ENTRY, (entry, _options, theme) => {
344
+ const receipt = entry.data;
345
+ const label = receipt.kind.replace(/^goal_/, "Goal ").replaceAll("_", " ");
346
+ const message = receipt.message ?? receipt.reason ?? receipt.changeSummary ?? receipt.completionSummary ?? receipt.objective ?? "";
347
+ return new Text(`${theme.fg(receipt.level === "error" ? "error" : receipt.level === "warning" ? "warning" : "accent", theme.bold(label))}${message ? `\n${theme.fg("muted", message)}` : ""}`, 0, 0);
348
+ });
790
349
 
791
- function clearStoppedRuntimeState(): void {
792
- clearContinuationState();
793
- clearActiveAccounting();
794
- }
350
+ pi.registerTool({
351
+ name: "propose_goal",
352
+ label: "Propose Goal",
353
+ description: "Propose one Goal after ordinary conversation has made the objective clear. User confirmation creates and starts it.",
354
+ promptSnippet: "Propose one confirmed Goal from an aligned objective.",
355
+ promptGuidelines: ["Use propose_goal only after normal conversation has made a concrete objective clear enough for user confirmation."],
356
+ parameters: Type.Object({ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH, description: "The complete Goal contract. Markdown is allowed." }) }, { additionalProperties: false }),
357
+ executionMode: "sequential",
358
+ async execute(_id, params, _signal, _update, ctx) {
359
+ if (state.goal) throw new Error("A Goal already exists. Use tweak_goal, pause_goal, abandon_goal, or complete_goal.");
360
+ const objective = boundedRequiredText(params.objective, "Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
361
+ setProposal("create", objective);
362
+ let confirmed = false;
363
+ try {
364
+ confirmed = await confirmProposal(ctx, "Confirm Goal", objective);
365
+ } finally {
366
+ clearProposal();
367
+ }
368
+ if (!confirmed) return { content: [{ type: "text", text: "Goal proposal declined. Continue the ordinary conversation and propose again only after the user asks for a change." }], details: state };
369
+ const timestamp = nowIso();
370
+ const goal: Goal = { id: randomUUID(), objective, status: "active", autoContinue: true, usage: { tokensUsed: 0, activeSeconds: 0 }, createdAt: timestamp, updatedAt: timestamp };
371
+ persist(goal, ctx);
372
+ publishReceipt({ kind: "goal_started", level: "info", ...goalFields(goal), tuiMessage: "Goal started." });
373
+ requestContinuation(ctx);
374
+ return { content: [{ type: "text", text: "Goal confirmed and started. Autonomous continuation is active." }], details: state, terminate: true };
375
+ },
376
+ });
795
377
 
378
+ pi.registerTool({
379
+ name: "tweak_goal",
380
+ label: "Tweak Goal",
381
+ description: "Propose a complete revised objective for the current Goal. The revision applies only after user confirmation.",
382
+ promptSnippet: "Propose a confirmed revision to the current Goal objective.",
383
+ promptGuidelines: ["Use tweak_goal when user feedback changes the current Goal contract; pass the complete revised objective, not a patch."],
384
+ parameters: Type.Object({ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH }) }, { additionalProperties: false }),
385
+ executionMode: "sequential",
386
+ async execute(_id, params, _signal, _update, ctx) {
387
+ const goal = currentGoal("paused-or-active");
388
+ const objective = boundedRequiredText(params.objective, "Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
389
+ setProposal("tweak", objective, goal.objective);
390
+ let confirmed = false;
391
+ try {
392
+ confirmed = await confirmProposal(ctx, "Confirm Goal revision", `Current:\n${goal.objective}\n\nRevised:\n${objective}`);
393
+ } finally {
394
+ clearProposal();
395
+ }
396
+ if (!confirmed) return { content: [{ type: "text", text: "Goal revision declined. The current Goal is unchanged." }], details: state };
397
+ const { lastAuditRejection: _lastAuditRejection, ...revisedGoal } = goal;
398
+ const next: Goal = { ...revisedGoal, objective, updatedAt: nowIso() };
399
+ persist(next, ctx);
400
+ publishReceipt({ kind: "goal_updated", level: "info", ...goalFields(next), changeSummary: "Goal objective revised with user confirmation.", tuiMessage: "Goal updated." });
401
+ if (next.status === "active") requestContinuation(ctx);
402
+ return { content: [{ type: "text", text: "Goal revision confirmed." }], details: state, terminate: true };
403
+ },
404
+ });
796
405
 
797
- const activeGetGoalTurnsByGoalId = new Map<string, number>();
406
+ pi.registerTool({
407
+ name: "pause_goal",
408
+ label: "Pause Goal",
409
+ description: "Pause an active Goal at a real blocker and record the reason and optional unblock action.",
410
+ promptSnippet: "Pause the active Goal with a concrete blocker.",
411
+ parameters: Type.Object({
412
+ reason: Type.String({ minLength: 1, maxLength: GOAL_PAUSE_REASON_MAX_LENGTH }),
413
+ suggestedAction: Type.Optional(Type.String({ minLength: 1, maxLength: GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH })),
414
+ }, { additionalProperties: false }),
415
+ executionMode: "sequential",
416
+ async execute(_id, params, _signal, _update, ctx) {
417
+ const next = pause(ctx, params.reason, params.suggestedAction);
418
+ return { content: [{ type: "text", text: `Goal paused: ${next.pause?.reason}` }], details: state, terminate: true };
419
+ },
420
+ });
798
421
 
799
- function resetGetGoalNudgeState(goalId: string | null | undefined): void {
800
- if (goalId) {
801
- activeGetGoalTurnsByGoalId.delete(goalId);
802
- }
803
- }
422
+ pi.registerTool({
423
+ name: "resume_goal",
424
+ label: "Resume Goal",
425
+ description: "Resume the paused Goal from its exact current state and restart autonomous continuation.",
426
+ promptSnippet: "Resume the paused Goal.",
427
+ parameters: Type.Object({}, { additionalProperties: false }),
428
+ executionMode: "sequential",
429
+ async execute(_id, _params, _signal, _update, ctx) {
430
+ resume(ctx);
431
+ return { content: [{ type: "text", text: "Goal resumed. Autonomous continuation is active." }], details: state, terminate: true };
432
+ },
433
+ });
804
434
 
805
- function openGoals(): GoalRecord[] {
806
- return openGoalsFromPool(goalsById);
807
- }
435
+ pi.registerTool({
436
+ name: "abandon_goal",
437
+ label: "Abandon Goal",
438
+ description: "Abandon the active or paused Goal without marking it complete.",
439
+ promptSnippet: "Abandon the Goal with a concrete reason.",
440
+ parameters: Type.Object({ reason: Type.String({ minLength: 1 }) }, { additionalProperties: false }),
441
+ executionMode: "sequential",
442
+ async execute(_id, params, _signal, _update, ctx) {
443
+ abandon(ctx, params.reason);
444
+ return { content: [{ type: "text", text: `Goal abandoned: ${params.reason.trim()}` }], details: state, terminate: true };
445
+ },
446
+ });
808
447
 
809
- function isLegacyCwdActiveGoalPath(relPath: string | undefined): boolean {
810
- return typeof relPath === "string" && relPath.startsWith(`${GOALS_DIR}/active_goal_`);
811
- }
448
+ pi.registerTool({
449
+ name: "complete_goal",
450
+ label: "Complete Goal",
451
+ description: "Request independent audit of the active or paused Goal. Approval permits one final prose response, then archival.",
452
+ promptSnippet: "Submit genuinely complete Goal work for independent audit.",
453
+ promptGuidelines: ["Use complete_goal only when the complete Goal objective is satisfied; the summary is an audit claim, not proof."],
454
+ parameters: Type.Object({ summary: Type.String({ minLength: 1, maxLength: GOAL_COMPLETION_SUMMARY_MAX_LENGTH, description: "Concise completion claim and available verification evidence." }) }, { additionalProperties: false }),
455
+ executionMode: "sequential",
456
+ async execute(_id, params, signal, _update, ctx) {
457
+ const target = structuredClone(currentGoal("paused-or-active"));
458
+ const summary = boundedRequiredText(params.summary, "Goal completion summary", GOAL_COMPLETION_SUMMARY_MAX_LENGTH);
459
+ auditing = true;
460
+ widget?.update();
461
+ const auditor = await (dependencies.runCompletionAuditor ?? runGoalCompletionAuditor)({ ctx, goal: target, completionSummary: summary, signal });
462
+ auditing = false;
463
+ widget?.update();
464
+ if (state.goal?.id !== target.id || state.goal.updatedAt !== target.updatedAt) throw new Error("Goal changed while the completion audit was running; audit result discarded.");
465
+ if (!auditor.approved) {
466
+ const report = boundedRequiredText(
467
+ auditor.output.trim() || auditor.error || "The independent auditor did not approve completion.",
468
+ "Goal audit rejection report",
469
+ GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH,
470
+ );
471
+ const { pause: _pause, ...rejectedGoal } = target;
472
+ const next: Goal = { ...rejectedGoal, status: "active", autoContinue: true, updatedAt: nowIso(), lastAuditRejection: { rejectedAt: nowIso(), report } };
473
+ persist(next, ctx);
474
+ publishReceipt({ kind: "goal_completion_rejected", level: auditor.error ? "error" : "warning", ...goalFields(next), reason: auditor.error ?? "Rejected by independent auditor.", auditorReport: report, message: "Goal completion rejected by independent auditor.", tuiMessage: `Goal completion rejected.\n${report}` });
475
+ return { content: [{ type: "text", text: `Goal completion rejected. Address these objections before retrying:\n\n${report}` }], details: state };
476
+ }
477
+ const auditorReport = boundedRequiredText(auditor.output, "Goal completion auditor report", GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH);
478
+ const { pause: _pause, ...auditedGoal } = target;
479
+ const completed: Goal = {
480
+ ...auditedGoal,
481
+ status: "complete",
482
+ autoContinue: false,
483
+ updatedAt: nowIso(),
484
+ completion: { approvedAt: nowIso(), summary, auditorReport },
485
+ };
486
+ persist(completed, ctx);
487
+ return {
488
+ content: [{ type: "text", text: `Goal audit approved.\n\n${auditor.output}\n\nWrite one normal final response now: explain what was completed, what changed or was produced, what was verified, and the final state or relevant next step. Do not call tools.` }],
489
+ details: state,
490
+ };
491
+ },
492
+ });
812
493
 
813
- function reconcileFocusedGoalFromDisk(ctx: ExtensionContext, opts: { preserveMemoryUsage?: boolean } = {}): boolean {
814
- const current = state.goal;
815
- const fresh = readActiveGoalPool(ctx);
816
- if (!focusedGoalId) {
817
- goalsById = fresh;
818
- return true;
819
- }
820
- const diskGoal = fresh.get(focusedGoalId) ?? null;
821
- if (!diskGoal) {
822
- if (current && isLegacyCwdActiveGoalPath(current.activePath)) {
823
- const migrated = writeActiveGoalFile(ctx, current);
824
- goalsById = fresh;
825
- goalsById.set(migrated.id, migrated);
826
- focusedGoalId = migrated.id;
827
- return true;
494
+ pi.registerCommand("goal", {
495
+ description: "Discuss a Goal in normal conversation; the model proposes it once aligned.",
496
+ handler: async (args, ctx) => {
497
+ const topic = args.trim();
498
+ if (!topic) {
499
+ ctx.ui.setEditorText(state.goal ? "I want to revise the current Goal: " : "I want to set a Goal: ");
500
+ return;
828
501
  }
829
- if (current && !current.activePath) {
830
- goalsById = fresh;
831
- goalsById.set(current.id, current);
832
- focusedGoalId = current.id;
833
- return true;
502
+ pi.sendUserMessage(state.goal
503
+ ? `I want to revise the current Goal: ${topic}. Discuss this with me normally, then use tweak_goal once we are aligned.`
504
+ : `I want to set a Goal: ${topic}. Discuss this with me normally, then use propose_goal once we are aligned.`);
505
+ },
506
+ });
507
+ pi.registerCommand("goal-status", { description: "Show the current Goal state.", handler: async (_args, ctx) => ctx.ui.notify(stateText(state), "info") });
508
+ pi.registerCommand("goal-pause", {
509
+ description: "Pause the active Goal.",
510
+ handler: async (args, ctx) => { pause(ctx, args.trim() || "Paused by user."); },
511
+ });
512
+ pi.registerCommand("goal-resume", { description: "Resume the paused Goal.", handler: async (_args, ctx) => { resume(ctx); } });
513
+ pi.registerCommand("goal-abandon", {
514
+ description: "Abandon the active or paused Goal.",
515
+ handler: async (args, ctx) => { abandon(ctx, args.trim() || "Abandoned by user."); },
516
+ });
517
+ pi.registerCommand("goal-migrate", {
518
+ description: "Choose a legacy Goal when migration found multiple open candidates.",
519
+ handler: async (_args, ctx) => {
520
+ if (loadGoalState(ctx) || hasMigrationMarker(ctx, "complete")) {
521
+ ctx.ui.notify("Legacy migration is already complete or this branch already has new Goal state.", "info");
522
+ return;
834
523
  }
835
- goalsById = fresh;
836
- focusedGoalId = null;
837
- invalidateQueuedContinuations();
838
- clearActiveAccounting();
839
- if (current) resetGetGoalNudgeState(current.id);
840
- if (tweakDraftingFor !== null) tweakDraftingFor = null;
841
- syncGoalTools();
842
- updateUI(ctx);
843
- return false;
844
- }
845
- const reconciled = current && opts.preserveMemoryUsage
846
- ? mergeFocusedGoalWithDisk({ memoryGoal: current, diskGoal })
847
- : diskGoal;
848
- goalsById = fresh;
849
- goalsById.set(reconciled.id, reconciled);
850
- focusedGoalId = reconciled.id;
851
- if (reconciled.status !== "active" || !reconciled.autoContinue) invalidateQueuedContinuations();
852
- if (reconciled.status !== "active") clearActiveAccounting();
853
- return true;
854
- }
855
-
856
- function appendFocusEntry(goalId: string | null, reason: GoalFocusReason): void {
857
- pi.appendEntry(FOCUS_ENTRY, goalFocusDetails(goalId, reason));
858
- }
859
-
860
- function appendLegacyMigrationEntry(ctx: ExtensionContext): void {
861
- pi.appendEntry(LEGACY_MIGRATION_ENTRY, {
862
- version: 1,
863
- sessionId: ctx.sessionManager?.getSessionId?.() ?? null,
864
- at: nowIso(),
865
- });
866
- }
867
-
868
- function setFocusedGoalId(goalId: string | null, ctx: ExtensionContext, reason: GoalFocusReason): void {
869
- const previousGoalId = focusedGoalId;
870
- focusedGoalId = goalId && goalsById.has(goalId) ? goalId : null;
871
- if (previousGoalId !== focusedGoalId) {
872
- invalidateQueuedContinuations();
873
- clearActiveAccounting();
874
- resetGetGoalNudgeState(previousGoalId);
875
- resetGetGoalNudgeState(focusedGoalId);
876
- if (tweakDraftingFor !== null && tweakDraftingFor !== focusedGoalId) tweakDraftingFor = null;
877
- }
878
- appendFocusEntry(focusedGoalId, reason);
879
- // Append ledger event for focus changes
880
- try {
881
- if (focusedGoalId) {
882
- appendGoalEvent(ctx, { type: "goal_focused", goalId: focusedGoalId, reason, at: nowIso() });
883
- } else if (previousGoalId) {
884
- appendGoalEvent(ctx, { type: "goal_unfocused", reason, at: nowIso() });
524
+ if (migrationCandidates.length === 0) migrationCandidates = findLegacyGoalCandidates(ctx).candidates;
525
+ if (migrationCandidates.length === 0) {
526
+ ctx.ui.notify("No legacy Goals require migration.", "info");
527
+ return;
885
528
  }
886
- } catch {
887
- // Ledger append failure should not crash focus change
888
- }
889
- syncGoalTools();
890
- updateUI(ctx);
891
- }
892
-
893
- function updateFocusedGoal(next: GoalRecord, ctx: ExtensionContext, shouldPersist = true): void {
894
- const previousGoalId = focusedGoalId;
895
- goalsById.set(next.id, next);
896
- focusedGoalId = next.id;
897
- if (previousGoalId !== focusedGoalId) {
898
- resetGetGoalNudgeState(previousGoalId);
899
- resetGetGoalNudgeState(focusedGoalId);
900
- }
901
- if (shouldPersist) persist(ctx);
902
- else syncGoalTools();
903
- updateUI(ctx);
904
- }
905
-
906
- function armFocusedContinuation(ctx: ExtensionContext): void {
907
- beginAccounting();
908
- if (state.goal?.status === "active" && state.goal.autoContinue) queueContinuation(ctx, true);
909
- }
910
-
911
- function removeFocusedGoal(ctx: ExtensionContext, reason: GoalFocusReason): void {
912
- const previousGoalId = focusedGoalId;
913
- if (focusedGoalId) goalsById.delete(focusedGoalId);
914
- focusedGoalId = null;
915
- clearStoppedRuntimeState();
916
- resetGetGoalNudgeState(previousGoalId);
917
- appendFocusEntry(null, reason);
918
- syncGoalTools();
919
- updateUI(ctx);
920
- }
921
-
922
- function beginAccounting(): void {
923
- if (confirmationIntent !== null || tweakDraftingFor !== null) {
924
- clearActiveAccounting();
925
- return;
926
- }
927
- if (!state.goal || (state.goal.status !== "active")) {
928
- clearActiveAccounting();
929
- return;
930
- }
931
- accounting.activeGoalId = state.goal.id;
932
- accounting.lastAccountedAt = Date.now();
933
- }
934
-
935
- function goalForDisplay(): GoalRecord | null {
936
- if (!state.goal || state.goal.status !== "active" || accounting.activeGoalId !== state.goal.id || accounting.lastAccountedAt === null) {
937
- return state.goal;
938
- }
939
- const liveSeconds = Math.max(0, Math.floor((Date.now() - accounting.lastAccountedAt) / 1000));
940
- if (liveSeconds === 0) return state.goal;
941
- const live = cloneGoal(state.goal);
942
- live.usage.activeSeconds += liveSeconds;
943
- return live;
944
- }
945
-
946
- function accountProgress(ctx: ExtensionContext, opts: { completedTurnTokens?: number } = {}): void {
947
- if (confirmationIntent !== null || tweakDraftingFor !== null) {
948
- clearActiveAccounting();
949
- return;
950
- }
951
- // Skip disk reconciliation for complete goals — they are pending archival at turn_end.
952
- if (state.goal?.activePath && state.goal?.status !== "complete" && !reconcileFocusedGoalFromDisk(ctx, { preserveMemoryUsage: true })) return;
953
- if (!state.goal || state.goal.status !== "active" || accounting.activeGoalId !== state.goal.id) {
954
- beginAccounting();
955
- return;
956
- }
957
-
958
- const now = Date.now();
959
- const elapsedSeconds = accounting.lastAccountedAt === null ? 0 : Math.floor((now - accounting.lastAccountedAt) / 1000);
960
- accounting.lastAccountedAt = now;
961
-
962
- const tokens = Math.max(0, Math.trunc(opts.completedTurnTokens ?? 0));
963
- if (tokens === 0 && elapsedSeconds === 0) return;
964
-
965
- const next = cloneGoal(state.goal);
966
- next.usage.tokensUsed += tokens;
967
- next.usage.activeSeconds += elapsedSeconds;
968
- next.updatedAt = nowIso();
969
- state.goal = next;
970
- persist(ctx);
971
- }
972
-
973
- function syncGoalPromptFromDisk(ctx: ExtensionContext): boolean {
974
- if (!state.goal || state.goal.status === "complete") return false;
975
- const previousObjective = state.goal.objective;
976
- state.goal = mergeGoalPromptFromDisk(ctx, state.goal);
977
- return state.goal.objective !== previousObjective;
978
- }
979
-
980
- function persist(ctx?: ExtensionContext): void {
981
- const current = state.goal;
982
- if (current) {
983
- state.goal = { ...current, updatedAt: nowIso() };
984
- if (ctx) {
985
- syncGoalPromptFromDisk(ctx);
986
- const next = state.goal;
987
- if (next) state.goal = next.status === "complete" ? archiveGoalFile(ctx, next) : writeActiveGoalFile(ctx, next);
529
+ if (!ctx.hasUI) {
530
+ ctx.ui.notify(`Legacy Goal selection required: ${migrationCandidates.map((item) => item.id).join(", ")}`, "warning");
531
+ return;
988
532
  }
989
- }
990
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
991
- syncGoalTools();
992
- if (ctx) updateUI(ctx);
993
- }
533
+ const labels = migrationCandidates.map((item) => `${item.id}: ${item.objective.replace(/\s+/g, " ").slice(0, 100)}`);
534
+ const selected = await ctx.ui.select("Migrate which legacy Goal?", labels);
535
+ const selectedIndex = selected ? labels.indexOf(selected) : -1;
536
+ if (selectedIndex < 0) return;
537
+ const plan = planLegacyMigration(ctx, migrationCandidates[selectedIndex]?.id);
538
+ if (plan.kind !== "migrate") throw new Error("Legacy Goal selection could not be migrated.");
539
+ writeLegacyMigration(pi, plan);
540
+ state = plan.goal;
541
+ migrationCandidates = [];
542
+ emitState();
543
+ updateWidget(ctx);
544
+ requestContinuation(ctx);
545
+ },
546
+ });
994
547
 
995
- function refreshGoalDisplayFromDisk(ctx: ExtensionContext): void {
996
- if (!state.goal || state.goal.status === "complete") return;
997
- if (syncGoalPromptFromDisk(ctx)) {
998
- state.goal = { ...state.goal, updatedAt: nowIso() };
999
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
1000
- }
1001
- syncGoalTools();
1002
- updateUI(ctx);
1003
- }
548
+ pi.on("context", (event) => {
549
+ const reminder = renderGoalContext(state);
550
+ if (!reminder) return;
551
+ return {
552
+ messages: [...event.messages, {
553
+ role: "custom",
554
+ customType: "pi-goal-context",
555
+ content: reminder,
556
+ display: false,
557
+ timestamp: Date.now(),
558
+ } as typeof event.messages[number]],
559
+ };
560
+ });
1004
561
 
1005
- /**
1006
- * Live above-editor widget for the active goal. Inspired by rpiv-todo's
1007
- * TodoOverlay: register the widget once with a factory, read live state
1008
- * via the closure at render time, and call `tui.requestRender()` on every
1009
- * state change so the overlay refreshes without re-registration.
1010
- *
1011
- * Layout (sisyphus, running):
1012
- * ◆ Sisyphus [▰▰▰▱▱] 3/5
1013
- * ├─ ⟡ extract validator … wire it … update tests.
1014
- * ├─ Status: sisyphus running · auto-continue · 14m 21s · 24.3k tokens
1015
- * └─ .pi/goals/active_goal_xxx.md
1016
- *
1017
- * Layout (paused with blocker):
1018
- * ⊘ Goal paused
1019
- * ├─ ⟡ improve benchmark coverage for the parser
1020
- * ├─ Status: paused (agent) · 2m 14s · 12.4k tokens
1021
- * ├─ Blocker: cannot find the tests directory
1022
- * └─ Suggested: ask the user for the test location
1023
- */
1024
- const GOAL_WIDGET_KEY = "goal";
1025
- let widgetRegistered = false;
1026
- let goalWidgetComponent: GoalWidgetComponent | null = null;
562
+ pi.on("before_agent_start", () => {
563
+ lastAccountedAt = state.goal?.status === "active" ? Date.now() : null;
564
+ });
1027
565
 
1028
- function clearGoalWidget(ctx: ExtensionContext): void {
1029
- ctx.ui.setStatus("goal", undefined);
1030
- ctx.ui.setWidget(GOAL_WIDGET_KEY, undefined);
1031
- widgetRegistered = false;
1032
- goalWidgetComponent = null;
1033
- }
566
+ pi.on("tool_call", () => {
567
+ if (state.goal?.status === "complete") return { block: true, reason: "The Goal is complete. Write the final user-facing response without calling tools." };
568
+ });
1034
569
 
1035
- function updateUI(ctx: ExtensionContext): void {
1036
- emitGoalState("ui_update");
1037
- if (!ctx.hasUI) return;
1038
- const totalOpen = openGoals().length;
1039
- if (!state.goal && totalOpen === 0) {
1040
- clearGoalWidget(ctx);
1041
- stopStatusRefresh();
570
+ pi.on("agent_end", (event, ctx) => {
571
+ const assistant = [...event.messages].reverse().find((message) => message.role === "assistant");
572
+ if (!assistant) return;
573
+ if (assistant.stopReason === "error" || assistant.stopReason === "aborted") {
574
+ cancelContinuation();
1042
575
  return;
1043
576
  }
1044
- if (!state.goal) {
1045
- ctx.ui.setStatus("goal", `goal: unfocused [${totalOpen} open] - /goal-focus`);
1046
- if (!widgetRegistered) {
1047
- ctx.ui.setWidget(
1048
- GOAL_WIDGET_KEY,
1049
- (tui, theme) => {
1050
- goalWidgetComponent = new GoalWidgetComponent({
1051
- tui,
1052
- theme,
1053
- getGoal: () => goalForDisplay() ?? state.goal,
1054
- getOpenGoalCount: () => openGoals().length,
1055
- getAuditorProgress: () => auditProgress,
1056
- getSettings: () => loadGoalSettings(ctx.cwd),
1057
- getDebugMode: () => debugMode,
1058
- });
1059
- return goalWidgetComponent;
1060
- },
1061
- { placement: "aboveEditor" },
1062
- );
1063
- widgetRegistered = true;
1064
- } else {
1065
- goalWidgetComponent?.update();
1066
- }
1067
- stopStatusRefresh();
1068
- return;
1069
- }
1070
-
1071
- const displayGoal = goalForDisplay() ?? state.goal;
1072
- const otherCount = otherOpenGoalCount(goalsById, focusedGoalId);
1073
- ctx.ui.setStatus("goal", `${footerStatus(displayGoal)}${otherCount > 0 ? ` (+${otherCount} open)` : ""}`);
1074
-
1075
- if (!widgetRegistered) {
1076
- ctx.ui.setWidget(
1077
- GOAL_WIDGET_KEY,
1078
- (tui, theme) => {
1079
- goalWidgetComponent = new GoalWidgetComponent({
1080
- tui,
1081
- theme,
1082
- getGoal: () => goalForDisplay() ?? state.goal,
1083
- getOpenGoalCount: () => openGoals().length,
1084
- getAuditorProgress: () => auditProgress,
1085
- getSettings: () => loadGoalSettings(ctx.cwd),
1086
- getDebugMode: () => debugMode,
1087
- });
1088
- return goalWidgetComponent;
1089
- },
1090
- { placement: "aboveEditor" },
1091
- );
1092
- widgetRegistered = true;
1093
- } else {
1094
- goalWidgetComponent?.update();
1095
- }
577
+ const goal = state.goal;
578
+ if (!goal || goal.status !== "active" || !goal.autoContinue) return;
579
+ if (assistant.stopReason !== "stop" && assistant.stopReason !== "length" && assistant.stopReason !== "toolUse") return;
580
+ requestContinuation(ctx);
581
+ });
1096
582
 
1097
- if (state.goal.status === "complete") {
1098
- stopStatusRefresh();
1099
- } else {
1100
- syncStatusRefresh(ctx);
1101
- }
1102
- }
583
+ pi.on("turn_end", (event, ctx) => {
584
+ const goal = state.goal;
585
+ if (!goal || goal.status !== "active") return;
586
+ const now = Date.now();
587
+ const elapsed = lastAccountedAt === null ? 0 : Math.max(0, Math.floor((now - lastAccountedAt) / 1000));
588
+ lastAccountedAt = now;
589
+ const tokens = assistantTokens(event.message);
590
+ if (elapsed === 0 && tokens === 0) return;
591
+ persist({ ...goal, usage: { tokensUsed: goal.usage.tokensUsed + tokens, activeSeconds: goal.usage.activeSeconds + elapsed }, updatedAt: nowIso() }, ctx);
592
+ });
1103
593
 
1104
- function migrateLegacyPoolForSession(ctx: ExtensionContext, legacySessionSeen: boolean, legacyGoal: GoalRecord | null, legacyMigrationSeen: boolean): void {
1105
- if (!ctx.sessionManager?.getSessionId?.()) return;
1106
- if (!legacySessionSeen && !legacyGoal) return;
1107
- if (legacyMigrationSeen) return;
1108
- const legacyFiles = readLegacyActiveGoalFiles(ctx);
1109
- const shouldMigrateLegacyGoal = !!legacyGoal && legacyGoal.status !== "complete" && isLegacyCwdActiveGoalPath(legacyGoal.activePath);
1110
- if (legacyFiles.length === 0 && !shouldMigrateLegacyGoal) return;
1111
- for (const legacy of legacyFiles) {
1112
- if (goalsById.has(legacy.id)) continue;
1113
- const migrated = writeActiveGoalFile(ctx, legacy);
1114
- goalsById.set(migrated.id, migrated);
1115
- }
1116
- if (shouldMigrateLegacyGoal && !goalsById.has(legacyGoal.id)) {
1117
- const migrated = writeActiveGoalFile(ctx, legacyGoal);
1118
- goalsById.set(migrated.id, migrated);
1119
- }
1120
- try {
1121
- if (readGoalLedger(ctx).events.length === 0) {
1122
- for (const event of readLegacyGoalLedger(ctx).events) appendGoalEvent(ctx, event);
1123
- }
1124
- } catch {
1125
- // Legacy ledger migration should not block loading the session.
1126
- }
1127
- try {
1128
- appendLegacyMigrationEntry(ctx);
1129
- } catch {
1130
- // A failed marker append should not block loading the session.
1131
- }
1132
- }
594
+ pi.on("session_start", (_event, ctx) => {
595
+ loadOrMigrate(ctx);
596
+ proposalSequence = loadProposalRevision(ctx);
597
+ proposal = { schemaVersion: GOAL_SCHEMA_VERSION, revision: proposalSequence, proposal: null };
598
+ emitState();
599
+ emitProposal();
600
+ updateWidget(ctx);
601
+ if (migrationCandidates.length > 1) ctx.ui.notify("Multiple legacy Goals need selection. Run /goal-migrate; no Goal was guessed and all legacy sources remain unchanged.", "warning");
602
+ requestContinuation(ctx);
603
+ });
604
+ pi.on("session_tree", (_event, ctx) => {
605
+ loadOrMigrate(ctx);
606
+ proposalSequence = loadProposalRevision(ctx);
607
+ proposal = { schemaVersion: GOAL_SCHEMA_VERSION, revision: proposalSequence, proposal: null };
608
+ emitState();
609
+ emitProposal();
610
+ updateWidget(ctx);
611
+ requestContinuation(ctx);
612
+ });
613
+ pi.on("session_compact", (_event, ctx) => {
614
+ pi.appendEntry(GOAL_STATE_ENTRY, state);
615
+ emitState();
616
+ updateWidget(ctx);
617
+ });
1133
618
 
1134
- function loadState(ctx: ExtensionContext): void {
1135
- goalsById = readActiveGoalPool(ctx);
1136
- focusedGoalId = null;
1137
- let focusEntry: GoalFocusEntry | null = null;
1138
- let legacyGoal: GoalRecord | null = null;
1139
- let legacyStateSeen = false;
1140
- let legacyMigrationSeen = false;
1141
- const entries = ctx.sessionManager.getBranch();
1142
- for (let i = entries.length - 1; i >= 0; i--) {
1143
- const entry = entries[i] as { type?: string; customType?: string; data?: unknown };
1144
- if (entry.type !== "custom") continue;
1145
- if (!focusEntry && entry.customType === FOCUS_ENTRY) {
1146
- focusEntry = normalizeGoalFocusEntry(entry.data);
1147
- }
1148
- if (!legacyMigrationSeen && entry.customType === LEGACY_MIGRATION_ENTRY) {
1149
- legacyMigrationSeen = asRecord(entry.data)?.version === 1;
1150
- }
1151
- if (!legacyStateSeen && entry.customType === STATE_ENTRY) {
1152
- legacyGoal = normalizeGoalRecord(asRecord(entry.data)?.goal);
1153
- legacyStateSeen = true;
1154
- }
1155
- if (focusEntry && legacyStateSeen && legacyMigrationSeen) break;
1156
- }
1157
- if (legacyGoal && legacyGoal.status !== "complete") {
1158
- legacyGoal = sanitizeGoalPaths(ctx, mergeGoalPromptFromDisk(ctx, legacyGoal));
1159
- }
1160
- migrateLegacyPoolForSession(ctx, legacyStateSeen || !!focusEntry, legacyGoal, legacyMigrationSeen);
1161
- const focusLegacyGoal = ctx.sessionManager?.getSessionId?.() ? null : legacyGoal;
1162
- focusedGoalId = resolveSessionFocus({ pool: goalsById, focusEntry, legacyGoal: focusLegacyGoal });
1163
- if (!focusEntry && focusedGoalId) {
1164
- try {
1165
- appendFocusEntry(focusedGoalId, legacyGoal?.id === focusedGoalId ? "migrated" : "selected");
1166
- } catch {}
1167
- }
1168
- for (const [id, current] of goalsById) {
1169
- if (current.status === "complete") {
1170
- goalsById.delete(id);
1171
- }
1172
- }
1173
- clearStoppedRuntimeState();
1174
- runningGoalId = null;
1175
- updateUI(ctx);
1176
- }
1177
-
1178
- function setGoal(next: GoalRecord | null, ctx: ExtensionContext, shouldPersist = true, focusReason?: GoalFocusReason): void {
1179
- const previousGoalId = state.goal?.id ?? null;
1180
- state.goal = next;
1181
- const focusChanged = previousGoalId !== focusedGoalId;
1182
- invalidateQueuedContinuations();
1183
- if (focusChanged) {
1184
- clearActiveAccounting();
1185
- resetGetGoalNudgeState(previousGoalId);
1186
- resetGetGoalNudgeState(focusedGoalId);
1187
- }
1188
- if (focusReason && focusChanged) appendFocusEntry(focusedGoalId, focusReason);
1189
- if (!state.goal || (state.goal.status !== "active") || !state.goal.autoContinue) {
1190
- clearContinuationState();
1191
- }
1192
- if (!state.goal || state.goal.status === "paused" || state.goal.status === "complete") {
1193
- clearActiveAccounting();
1194
- }
1195
- if (!state.goal || state.goal.id !== previousGoalId) {
1196
- // Drop any stale tweak-edit-gate that didn't belong to this goal.
1197
- if (tweakDraftingFor !== null && tweakDraftingFor !== state.goal?.id) tweakDraftingFor = null;
1198
- }
1199
- if (shouldPersist) persist(ctx);
1200
- else syncGoalTools();
1201
- updateUI(ctx);
1202
- }
1203
-
1204
- function archiveCurrentGoal(ctx: ExtensionContext, reason: StopReason | undefined): GoalRecord | null {
1205
- if (!state.goal) return null;
1206
- let archived = mergeGoalPromptFromDisk(ctx, state.goal);
1207
- archived = { ...archived, status: archived.status === "complete" ? "complete" : "paused", stopReason: reason };
1208
- return archiveGoalFile(ctx, archived);
1209
- }
1210
-
1211
- function stopActiveGoal(status: Exclude<GoalStatus, "active">, reason: StopReason | undefined, ctx: ExtensionContext): void {
1212
- if (!state.goal) return;
1213
- let next = mergeGoalPromptFromDisk(ctx, state.goal);
1214
- next = { ...next, status, stopReason: reason, updatedAt: nowIso() };
1215
- setGoal(next, ctx);
1216
- // Append ledger event for pauses (user or agent initiated)
1217
- if (status === "paused") {
1218
- try {
1219
- appendGoalEvent(ctx, {
1220
- type: "goal_paused",
1221
- goalId: next.id,
1222
- reason: reason ?? "unknown",
1223
- suggestedAction: next.pauseSuggestedAction,
1224
- status,
1225
- at: next.updatedAt,
1226
- });
1227
- } catch {
1228
- // Ledger append failure should not crash pause
1229
- }
1230
- }
1231
- }
1232
-
1233
- function pauseActiveGoal(ctx: ExtensionContext): void {
1234
- if (!state.goal || state.goal.status !== "active") return;
1235
- const pausedGoalId = state.goal.id;
1236
- // User-initiated pause (Esc / aborted turn). Clear any stale agent pause reason.
1237
- state.goal = { ...state.goal, autoContinue: false, pauseReason: undefined, pauseSuggestedAction: undefined };
1238
- stopActiveGoal("paused", "user", ctx);
1239
- resetGetGoalNudgeState(pausedGoalId);
1240
- ctx.ui.notify("Goal paused.", "info");
1241
- }
1242
-
1243
- function deferAfterCoreContextOverflow(ctx: ExtensionContext, messages: unknown[]): boolean {
1244
- if (!state.goal || state.goal.status !== "active" || !state.goal.autoContinue) return false;
1245
- if (!hasContextOverflowAssistantMessage(messages, ctx.model?.contextWindow)) return false;
1246
-
1247
- // Core owns context-overflow recovery. Goal mode only stands down: it parks
1248
- // its next continuation until core's session_compact event says the transcript
1249
- // is replay-safe again. Do not start nested compaction here, and never mutate
1250
- // the assistant overflow message; core classifies overflow before extension hooks.
1251
- deferContinuationUntilAfterCompaction(state.goal.id);
1252
- persist(ctx);
1253
- updateUI(ctx);
1254
- return true;
1255
- }
1256
-
1257
- function syncTerminalInputPause(ctx: ExtensionContext): void {
1258
- if (!ctx.hasUI) return;
1259
- terminalInputUnsubscribe?.();
1260
- terminalInputUnsubscribe = ctx.ui.onTerminalInput((data) => {
1261
- // If an audit is running, Escape aborts the audit instead of pausing.
1262
- // Must return { consume: true } so the TUI doesn't also process the key
1263
- // and abort the running tool execution, which would cascade into pausing
1264
- // the entire goal (agent_end sees ctx.signal?.aborted and calls pauseActiveGoal).
1265
- if (showingEscapeDialog) return undefined;
1266
- if (matchesKey(data, "escape") && auditProgress) {
1267
- abortAudit(ctx);
1268
- return { consume: true };
1269
- }
1270
- if (matchesKey(data, "escape") && state.goal?.status === "active" && state.goal.autoContinue) {
1271
- pauseActiveGoal(ctx);
1272
- // We consume Escape here, so mirror Pi's core interrupt path instead of only stopping auto-continue.
1273
- ctx.abort?.();
1274
- return { consume: true };
1275
- }
1276
-
1277
- // Ctrl+Shift+T — show task list overlay for all open goals
1278
- if (matchesKey(data, "ctrl+shift+t")) {
1279
- showTaskListOverlay(ctx, goalsById, focusedGoalId);
1280
- return { consume: true };
1281
- }
1282
-
1283
- // ── Debug mode keybindings (hidden from normal view) ────────────────
1284
-
1285
- // Ctrl+Shift+X — toggle debug mode on/off
1286
- if (matchesKey(data, "ctrl+shift+x")) {
1287
- debugMode = !debugMode;
1288
- ctx.ui.notify(debugMode ? "Debug mode ON" : "Debug mode OFF", "info");
1289
- goalWidgetComponent?.invalidate();
1290
- return { consume: true };
1291
- }
1292
-
1293
- // Only process the following debug keybindings when debug mode is active
1294
- if (!debugMode) return undefined;
1295
-
1296
- // Ctrl+Shift+N — create a test goal
1297
- if (matchesKey(data, "ctrl+shift+n")) {
1298
- createDebugGoal(ctx);
1299
- return { consume: true };
1300
- }
1301
-
1302
- // Ctrl+Shift+T — inject sample tasks into current goal
1303
- if (matchesKey(data, "ctrl+shift+t")) {
1304
- injectDebugTasks(ctx);
1305
- return { consume: true };
1306
- }
1307
-
1308
- // Ctrl+Shift+R — start mock completion audit
1309
- if (matchesKey(data, "ctrl+shift+r")) {
1310
- startMockAudit(ctx);
1311
- return { consume: true };
1312
- }
1313
-
1314
- // Ctrl+Shift+O — open proposal dialog with sample data
1315
- if (matchesKey(data, "ctrl+shift+o")) {
1316
- openDebugProposal(ctx);
1317
- return { consume: true };
1318
- }
1319
-
1320
- return undefined;
1321
- });
1322
-
1323
- /** Toggle a test goal: create (first press) or remove (second press) */
1324
- function createDebugGoal(ctx: ExtensionContext): void {
1325
- const prev = state.goal;
1326
- if (prev && prev.id.startsWith("debug-")) {
1327
- // Toggle off — remove debug goal entirely (no archive, full delete)
1328
- const filePath = `${DEBUG_GOALS_DIR}/debug_goal.md`;
1329
- try {
1330
- safeUnlinkGoalFile({ cwd: ctx.cwd }, DEBUG_GOALS_DIR, filePath);
1331
- } catch {}
1332
- const prevId = prev.id;
1333
- state.goal = null;
1334
- if (focusedGoalId === prevId) {
1335
- goalsById.delete(prevId);
1336
- focusedGoalId = null;
1337
- }
1338
- clearStoppedRuntimeState();
1339
- syncGoalTools();
1340
- updateUI(ctx);
1341
- ctx.ui.notify("Debug goal removed", "info");
1342
- return;
1343
- }
1344
-
1345
- // Toggle on — create a new debug goal, write to temp dir
1346
- debugGoalCounter++;
1347
- const goal = createGoal({
1348
- objective: "=== Goal ===\nObjective: Debug test goal",
1349
- autoContinue: true,
1350
- sisyphus: false,
1351
- });
1352
- goal.id = `debug-${nowIso().replace(/[:.]/g, "-")}-${debugGoalCounter}`;
1353
- goal.createdAt = nowIso();
1354
- goal.updatedAt = nowIso();
1355
- goal.activePath = `${DEBUG_GOALS_DIR}/debug_goal.md`;
1356
- const gfc = { cwd: ctx.cwd };
1357
- ensureDirectory(gfc, DEBUG_GOALS_DIR);
1358
- atomicWriteGoalFile(gfc, DEBUG_GOALS_DIR, goal.activePath, serializeGoalFile(goal));
1359
- setGoal(goal, ctx, false, "created"); // no persist (we already wrote the file)
1360
- ctx.ui.notify(`Debug goal created: ${goal.id}`, "info");
1361
- }
1362
-
1363
- /** Inject 3-4 sample tasks into the current goal */
1364
- function injectDebugTasks(ctx: ExtensionContext): void {
1365
- if (!state.goal) {
1366
- ctx.ui.notify("No goal to inject tasks into; create one first (Ctrl+Shift+N)", "warning");
1367
- return;
1368
- }
1369
- const now = nowIso();
1370
- const tasks: GoalTask[] = [
1371
- {
1372
- id: "t1",
1373
- title: "Set up project structure",
1374
- status: "complete",
1375
- completedAt: now,
1376
- subtasks: [
1377
- { id: "t1a", title: "Initialize repo", status: "complete", completedAt: now },
1378
- { id: "t1b", title: "Add build config", status: "pending" },
1379
- ],
1380
- },
1381
- {
1382
- id: "t2",
1383
- title: "Implement core feature",
1384
- status: "pending",
1385
- },
1386
- {
1387
- id: "t3",
1388
- title: "Write tests",
1389
- status: "pending",
1390
- },
1391
- ];
1392
- const next = cloneGoal(state.goal);
1393
- next.taskList = { tasks, blockCompletion: false, proposedAt: now };
1394
- next.updatedAt = now;
1395
- setGoal(next, ctx);
1396
- ctx.ui.notify("Sample tasks injected (3 tasks, 1 completed)", "info");
1397
- }
1398
-
1399
- /** Stop mock audit timer if running */
1400
- function stopMockAuditTimer(): void {
1401
- if (debugMockAuditTimer) {
1402
- clearInterval(debugMockAuditTimer);
1403
- debugMockAuditTimer = null;
1404
- }
1405
- }
1406
-
1407
- /** Start a mock completion audit that transitions through phases */
1408
- function startMockAudit(ctx: ExtensionContext): void {
1409
- stopMockAuditTimer();
1410
- const startedAt = Date.now();
1411
- const phases: { phase: AuditorWidgetProgress["phase"]; atMs: number; label: string; percentage: number }[] = [
1412
- { phase: "tool_executing", atMs: 0, label: "Checking test results...", percentage: 10 },
1413
- { phase: "tool_executing", atMs: 800, label: "Verifying requirements...", percentage: 30 },
1414
- { phase: "thinking", atMs: 1800, label: "Evaluating completion criteria...", percentage: 60 },
1415
- { phase: "producing_report", atMs: 3200, label: "Writing audit report...", percentage: 85 },
1416
- { phase: "done", atMs: 4800, label: "Audit complete", percentage: 100 },
1417
- ];
1418
- auditProgress = {
1419
- recentOutput: [],
1420
- phase: "running",
1421
- elapsedMs: 0,
1422
- };
1423
- goalWidgetComponent?.invalidate();
1424
-
1425
- debugMockAuditTimer = setInterval(() => {
1426
- const elapsed = Date.now() - startedAt;
1427
- let currentPhase: AuditorWidgetProgress["phase"] = "done";
1428
- let currentLabel = "Audit complete";
1429
- let currentPct = 100;
1430
- for (let i = phases.length - 1; i >= 0; i--) {
1431
- if (elapsed >= phases[i].atMs) {
1432
- currentPhase = phases[i].phase;
1433
- currentLabel = phases[i].label;
1434
- currentPct = phases[i].percentage;
1435
- break;
1436
- }
1437
- }
1438
- auditProgress = {
1439
- phase: currentPhase,
1440
- label: currentLabel,
1441
- percentage: currentPct,
1442
- elapsedMs: elapsed,
1443
- recentOutput: auditProgress?.recentOutput ?? [],
1444
- };
1445
- if (currentPhase === "done") {
1446
- if (auditProgress) auditProgress.recentOutput = [
1447
- "✓ All requirements verified",
1448
- "✓ Tests pass: 310/310",
1449
- "✓ No truncation cap remaining",
1450
- ];
1451
- stopMockAuditTimer();
1452
- // Auto-clear audit after 3 more seconds
1453
- setTimeout(() => {
1454
- auditProgress = null;
1455
- goalWidgetComponent?.invalidate();
1456
- }, 3000);
1457
- }
1458
- goalWidgetComponent?.invalidate();
1459
- }, 100);
1460
- debugMockAuditTimer.unref?.();
1461
- }
1462
-
1463
- /** Render task lines exactly like propose_task_list does */
1464
- function renderDebugTaskLines(tasks: GoalTask[], indent = 0): string[] {
1465
- const prefix = " ".repeat(indent);
1466
- const lines: string[] = [];
1467
- for (const t of tasks) {
1468
- const marker = t.status === "complete" ? "[x]" : t.status === "skipped" ? "[~]" : "[ ]";
1469
- const lw = t.lightweightSubtasks ? " (lightweight)" : "";
1470
- lines.push(`${prefix}${marker} ${t.id}: ${t.title}${lw}`);
1471
- if (t.subtasks && t.subtasks.length > 0) {
1472
- lines.push(...renderDebugTaskLines(t.subtasks, indent + 1));
1473
- }
1474
- }
1475
- return lines;
1476
- }
1477
-
1478
- /** Show the proposal dialog using real goal state — no hardcoded text */
1479
- function openDebugProposal(ctx: ExtensionContext): void {
1480
- // Build a fresh debug goal + tasks in memory for the dialog
1481
- debugGoalCounter++;
1482
- const goal = createGoal({
1483
- objective: `=== Goal ===
1484
- Objective: Add collapsible task sections to the goal widget so large task lists are navigable
1485
-
1486
- Success criteria:
1487
- - Tasks are grouped into sections by status (pending, active, complete) with visible section headers
1488
- - Each section header is toggleable — clicking it expands or collapses that section
1489
- - When collapsed, the section shows a header line only with a task count badge
1490
- - When expanded, tasks render with normal indentation and per-line styling
1491
- - Default state: pending section expanded, active and complete sections collapsed
1492
- - Section state is tracked per-render (no persistence needed)
1493
- - All 310 existing tests still pass
1494
-
1495
- Boundaries:
1496
- - In scope: GoalWidgetComponent.render() grouping logic, section header toggling, expand/collapse state per render cycle
1497
- - Out of scope: task reordering, drag-and-drop, keyboard navigation for sections, persistence of section state across pi restarts
1498
- - Out of scope: modifying GoalTask or GoalRecord types
1499
-
1500
- Constraints:
1501
- - Render width must respect the existing width parameter — no hardcoded widths
1502
- - Section collapse state is a render-only map, not stored in goal record
1503
- - Collapse toggle must be keyboard-accessible via existing widget interaction model
1504
- - Do not change the GoalWidgetComponent public API (constructor options, render signature)
1505
- - Section headers must use theme.fg("accent", ...) consistent with existing render patterns
1506
-
1507
- Verification contract:
1508
- - Run npm test and confirm 310/310 pass (0 failures)
1509
- - Read render method and confirm task grouping logic exists
1510
- - Read expand/collapse toggle handler and confirm it inverts section state
1511
- - Confirm collapsed sections only render the header line with task count
1512
- - Confirm expanded sections render tasks with correct indentation and styling`,
1513
- autoContinue: true,
1514
- sisyphus: false,
1515
- });
1516
- goal.id = `debug-${nowIso().replace(/[:.]/g, "-")}-${debugGoalCounter}`;
1517
- goal.createdAt = nowIso();
1518
- goal.updatedAt = nowIso();
1519
-
1520
- const now = nowIso();
1521
- const tasks: GoalTask[] = [
1522
- {
1523
- id: "t1",
1524
- title: "Set up project structure",
1525
- status: "complete",
1526
- completedAt: now,
1527
- subtasks: [
1528
- { id: "t1a", title: "Initialize repo", status: "complete", completedAt: now },
1529
- { id: "t1b", title: "Add build config", status: "pending" },
1530
- ],
1531
- },
1532
- {
1533
- id: "t2",
1534
- title: "Implement core feature",
1535
- status: "pending",
1536
- subtasks: [
1537
- { id: "t2a", title: "Status grouping logic", status: "pending" },
1538
- { id: "t2b", title: "Section header component", status: "pending" },
1539
- { id: "t2c", title: "Expand/collapse state", status: "pending" },
1540
- { id: "t2d", title: "Task count badge", status: "pending" },
1541
- ],
1542
- },
1543
- { id: "t3", title: "Update tests", status: "pending" },
1544
- { id: "t4", title: "Manual TUI verification", status: "pending" },
1545
- ];
1546
- goal.taskList = { tasks, blockCompletion: false, proposedAt: now };
1547
-
1548
- // Build proposal from goal state — exactly like the real flow
1549
- const confirmationText = buildDraftConfirmationText({
1550
- focus: "goal",
1551
- originalTopic: "Refactor the goal widget component to support collapsible task sections",
1552
- objective: goal.objective,
1553
- autoContinue: goal.autoContinue,
1554
- });
1555
-
1556
- // Append task proposal — exactly like propose_task_list would
1557
- const taskLines = renderDebugTaskLines(tasks).map((l) => `│ ${l}`);
1558
- const taskProposal = [
1559
- "",
1560
- "│ Proposed task list:",
1561
- "",
1562
- ...taskLines,
1563
- ].join("\n");
1564
-
1565
- showProposalDialog(ctx, confirmationText + taskProposal, "goal", true);
1566
- }
1567
- }
1568
-
1569
- function sendQueuedContinuation(ctx: ExtensionContext, goalId: string, epoch: number): void {
1570
- continuationTimer = null;
1571
- continuationScheduledFor = null;
1572
- if (epoch !== continuationEpoch) return;
1573
- syncGoalTools();
1574
- if (!isActionableContinuationGoal(goalId)) {
1575
- if (continuationQueuedFor === goalId) continuationQueuedFor = null;
1576
- return;
1577
- }
1578
-
1579
- const settleRemaining = compactionSettleUntil - Date.now();
1580
- if (settleRemaining > 0) {
1581
- continuationScheduledFor = goalId;
1582
- continuationTimer = setTimeout(() => sendQueuedContinuation(ctx, goalId, epoch), settleRemaining);
1583
- continuationTimer.unref?.();
1584
- return;
1585
- }
1586
-
1587
- let ready: boolean;
1588
- try {
1589
- ready = !ctx.hasPendingMessages() && ctx.isIdle();
1590
- } catch {
1591
- if (continuationQueuedFor === goalId) continuationQueuedFor = null;
1592
- return;
1593
- }
1594
-
1595
- if (!ready) {
1596
- continuationScheduledFor = goalId;
1597
- continuationTimer = setTimeout(() => sendQueuedContinuation(ctx, goalId, epoch), CONTINUATION_IDLE_RETRY_MS);
1598
- continuationTimer.unref?.();
1599
- return;
1600
- }
1601
- const goal = state.goal;
1602
- if (!goal) return;
1603
- continuationQueuedFor = goalId;
1604
- const settings = loadGoalSettings(ctx.cwd);
1605
- pi.sendMessage<GoalEventDetails>(
1606
- {
1607
- customType: GOAL_EVENT_ENTRY,
1608
- content: continuationPrompt(goal, settings, { epoch }),
1609
- display: false,
1610
- details: {
1611
- kind: "checkpoint",
1612
- goalId: goal.id,
1613
- status: goal.status,
1614
- objective: goal.objective,
1615
- timestamp: Date.now(),
1616
- continuationEpoch: epoch,
1617
- },
1618
- },
1619
- { triggerTurn: true, deliverAs: "followUp" },
1620
- );
1621
- }
1622
-
1623
-
1624
- function queueContinuation(ctx: ExtensionContext, force = false): void {
1625
- if (confirmationIntent !== null || tweakDraftingFor !== null) return;
1626
- if (!state.goal || state.goal.status !== "active" || !state.goal.autoContinue) return;
1627
- const goalId = state.goal.id;
1628
- if (!force && (continuationQueuedFor === goalId || continuationScheduledFor === goalId)) return;
1629
- clearContinuationTimer();
1630
- let delay = CONTINUATION_IDLE_RETRY_MS;
1631
- try {
1632
- delay = ctx.isIdle() && !ctx.hasPendingMessages() ? 0 : CONTINUATION_IDLE_RETRY_MS;
1633
- } catch {
1634
- return;
1635
- }
1636
- const epoch = continuationEpoch;
1637
- continuationScheduledFor = goalId;
1638
- continuationTimer = setTimeout(() => sendQueuedContinuation(ctx, goalId, epoch), delay);
1639
- continuationTimer.unref?.();
1640
- }
1641
-
1642
- function replaceGoal(config: GoalCreationConfig, ctx: ExtensionContext, startNow = true, verificationContract?: string): void {
1643
- const goal = createGoal(config);
1644
- if (verificationContract) goal.verificationContract = verificationContract;
1645
- setGoal(goal, ctx, true, "created");
1646
- beginAccounting();
1647
- // Reset continuation nudge state — this is a fresh goal.
1648
- resetGetGoalNudgeState(state.goal?.id);
1649
- // A goal was committed — clear pending confirmation intent if any.
1650
- confirmationIntent = null;
1651
- ctx.ui.notify(buildGoalRunningNotification(config), "info");
1652
- if (startNow && state.goal?.autoContinue) queueContinuation(ctx, true);
1653
- // Append ledger event for durable history
1654
- const created = state.goal;
1655
- if (created) {
1656
- try {
1657
- appendGoalEvent(ctx, {
1658
- type: "goal_created",
1659
- goalId: created.id,
1660
- objective: created.objective,
1661
- sisyphus: created.sisyphus,
1662
- autoContinue: created.autoContinue,
1663
- at: created.createdAt,
1664
- });
1665
- } catch {
1666
- // Ledger append failure should not crash creation
1667
- }
1668
- }
1669
- }
1670
-
1671
- async function startGoalTweakDrafting(hint: string, ctx: ExtensionContext): Promise<void> {
1672
- reconcileFocusedGoalFromDisk(ctx);
1673
- invalidateQueuedContinuations();
1674
- clearActiveAccounting();
1675
- if (!state.goal) {
1676
- if (openGoals().length > 0) {
1677
- const selected = await chooseOpenGoal(ctx, "Tweak which open goal?");
1678
- if (!selected) return;
1679
- } else {
1680
- ctx.ui.notify("No goal is set. Use /goals or /sisyphus to discuss, or /goals-set / /sisyphus-set to start immediately.", "warning");
1681
- return;
1682
- }
1683
- }
1684
- const currentGoal = state.goal;
1685
- if (!currentGoal) return;
1686
- if (currentGoal.status === "complete") {
1687
- ctx.ui.notify("Goal is complete. Use /goals to discuss a new one or /goals-set to start immediately.", "warning");
1688
- return;
1689
- }
1690
- syncGoalPromptFromDisk(ctx);
1691
- persist(ctx);
1692
- const trimmed = hint.trim();
1693
- const focused = state.goal;
1694
- if (!focused) return;
1695
- const sisyphusOn = focused.sisyphus;
1696
- const label = sisyphusOn ? "Sisyphus tweak drafting" : "Goal tweak drafting";
1697
- // Activate the tweak edit-gate so propose_goal_tweak is callable.
1698
- tweakDraftingFor = focused.id;
1699
- syncGoalTools();
1700
- ctx.ui.notify(
1701
- `${label} started${trimmed ? `: ${truncateText(trimmed, 60)}` : ""}. The agent will interview you and then propose the revision for you to Confirm.`,
1702
- "info",
1703
- );
1704
- const draftId = `tweak-${focused.id}-${Date.now().toString(36)}`;
1705
- try {
1706
- pi.sendMessage<GoalEventDetails>(
1707
- {
1708
- customType: GOAL_EVENT_ENTRY,
1709
- content: goalTweakDraftingPrompt(focused, trimmed),
1710
- display: false,
1711
- details: {
1712
- kind: "drafting",
1713
- goalId: draftId,
1714
- objective: trimmed,
1715
- focus: sisyphusOn ? "sisyphus" : "goal",
1716
- timestamp: Date.now(),
1717
- },
1718
- },
1719
- { triggerTurn: true, deliverAs: ctx.isIdle() ? "followUp" : "steer" },
1720
- );
1721
- } catch (err) {
1722
- tweakDraftingFor = null;
1723
- syncGoalTools();
1724
- ctx.ui.notify(`Could not start goal tweak: ${(err as Error).message}`, "error");
1725
- }
1726
- }
1727
-
1728
- function startGoalDrafting(topic: string, focus: DraftingFocus, ctx: ExtensionContext): void {
1729
- invalidateQueuedContinuations();
1730
- clearActiveAccounting();
1731
- const trimmed = topic.trim();
1732
- const label = focus === "sisyphus" ? "Sisyphus intent discussion" : "Goal intent discussion";
1733
- const hint = focus === "sisyphus"
1734
- ? "The agent will research or grill the ordered plan as needed, then propose a draft for you to Confirm. No skipping, no rushing."
1735
- : "The agent will clarify, research, or grill assumptions as needed, then propose a draft for you to Confirm.";
1736
- ctx.ui.notify(
1737
- `${label} started${trimmed ? `: ${truncateText(trimmed, 60)}` : ""}. ${hint}`,
1738
- "info",
1739
- );
1740
-
1741
- confirmationIntent = {
1742
- focus,
1743
- originalTopic: trimmed,
1744
- startedAt: Date.now(),
1745
- };
1746
- syncGoalTools();
1747
- try {
1748
- pi.sendUserMessage(goalDraftingPrompt(trimmed, focus), { deliverAs: ctx.isIdle() ? "followUp" : "steer" });
1749
- } catch (err) {
1750
- ctx.ui.notify(`Could not start ${label.toLowerCase()}: ${(err as Error).message}`, "error");
1751
- }
1752
- }
1753
-
1754
- async function chooseOpenGoal(ctx: ExtensionContext, title: string): Promise<GoalRecord | null> {
1755
- reconcileFocusedGoalFromDisk(ctx);
1756
- if (state.goal && state.goal.status !== "complete") return state.goal;
1757
- const open = openGoals();
1758
- if (open.length === 0) return null;
1759
- if (open.length === 1) {
1760
- const only = open[0];
1761
- if (!only) return null;
1762
- setFocusedGoalId(only.id, ctx, "selected");
1763
- return state.goal;
1764
- }
1765
- if (!ctx.hasUI) {
1766
- ctx.ui.notify(buildUnfocusedOpenGoalsSummary(open.length), "warning");
1767
- return null;
1768
- }
1769
- const labels = open.map((item) => goalSelectorLabel(item, focusedGoalId));
1770
- const byLabel = new Map(labels.map((label, index) => [label, open[index]?.id]));
1771
- const selected = await ctx.ui.select(title, labels);
1772
- const selectedId = selected ? byLabel.get(selected) : undefined;
1773
- if (!selectedId) {
1774
- ctx.ui.notify("Goal focus unchanged.", "info");
1775
- return null;
1776
- }
1777
- setFocusedGoalId(selectedId, ctx, "selected");
1778
- return state.goal;
1779
- }
1780
-
1781
- async function focusGoalCommand(ctx: ExtensionContext): Promise<void> {
1782
- const open = openGoals();
1783
- if (open.length === 0) {
1784
- ctx.ui.notify("No open goals. Use /goals or /sisyphus to discuss, or /goals-set / /sisyphus-set to start immediately.", "warning");
1785
- return;
1786
- }
1787
- if (open.length === 1) {
1788
- const only = open[0];
1789
- if (!only) return;
1790
- setFocusedGoalId(only.id, ctx, "selected");
1791
- armFocusedContinuation(ctx);
1792
- ctx.ui.notify(`Focused goal: ${oneLineSummary(only)}`, "info");
1793
- return;
1794
- }
1795
- if (!ctx.hasUI) {
1796
- ctx.ui.notify(buildGoalListText(goalsById, focusedGoalId), "info");
1797
- return;
1798
- }
1799
- const labels = open.map((item) => goalSelectorLabel(item, focusedGoalId));
1800
- const byLabel = new Map(labels.map((label, index) => [label, open[index]?.id]));
1801
- const selected = await ctx.ui.select("Focus open goal", labels);
1802
- const selectedId = selected ? byLabel.get(selected) : undefined;
1803
- if (!selectedId) {
1804
- ctx.ui.notify("Goal focus unchanged.", "info");
1805
- return;
1806
- }
1807
- setFocusedGoalId(selectedId, ctx, "selected");
1808
- armFocusedContinuation(ctx);
1809
- ctx.ui.notify(`Focused goal: ${oneLineSummary(state.goal)}`, "info");
1810
- }
1811
-
1812
- async function handleGoalCommandTopic(rawTopic: string, ctx: ExtensionContext, focus: DraftingFocus, opts: { replace: boolean }): Promise<void> {
1813
- const topic = rawTopic.trim();
1814
- if (opts.replace) {
1815
- const replacementTarget = await chooseOpenGoal(ctx, "Replace which open goal?");
1816
- if (openGoals().length > 0 && !replacementTarget) return;
1817
- archiveCurrentGoal(ctx, "user");
1818
- setGoal(null, ctx, true, "cleared");
1819
- }
1820
- startGoalDrafting(topic, focus, ctx);
1821
- }
1822
-
1823
- function handleDirectGoalSet(rawObjective: string, ctx: ExtensionContext, focus: DraftingFocus): void {
1824
- const raw = rawObjective.trim();
1825
- if (!raw) {
1826
- const command = focus === "sisyphus" ? "/sisyphus-set" : "/goals-set";
1827
- ctx.ui.notify(`No objective provided. Use ${command} <objective>.`, "warning");
1828
- return;
1829
- }
1830
- const { objective, verificationContract } = extractVerificationContract(raw);
1831
- clearContinuationState();
1832
- clearActiveAccounting();
1833
- confirmationIntent = null;
1834
- syncGoalTools();
1835
- replaceGoal({ objective, autoContinue: true, sisyphus: focus === "sisyphus" }, ctx, true, verificationContract);
1836
- }
1837
-
1838
- async function showGoalStatus(ctx: ExtensionContext): Promise<void> {
1839
- reconcileFocusedGoalFromDisk(ctx);
1840
- if (state.goal) syncGoalPromptFromDisk(ctx);
1841
- const view = goalForDisplay() ?? state.goal;
1842
- const otherCount = otherOpenGoalCount(goalsById, focusedGoalId);
1843
- const extra = view && otherCount > 0 ? `\nOther open goals: ${otherCount} (run /goal-list or /goal-focus)` : "";
1844
- const text = view ? `${detailedSummary(view)}${extra}` : openGoals().length > 0 ? buildUnfocusedOpenGoalsSummary(openGoals().length) : detailedSummary(null);
1845
- ctx.ui.notify(text, "info");
1846
- updateUI(ctx);
1847
- }
1848
-
1849
- async function handleGoalPause(ctx: ExtensionContext): Promise<void> {
1850
- reconcileFocusedGoalFromDisk(ctx);
1851
- if (!state.goal) {
1852
- if (openGoals().length > 0) {
1853
- const selected = await chooseOpenGoal(ctx, "Pause which open goal?");
1854
- if (!selected) return;
1855
- } else {
1856
- ctx.ui.notify("No goal is set.", "warning");
1857
- return;
1858
- }
1859
- }
1860
- const currentGoal = state.goal;
1861
- if (!currentGoal) return;
1862
- if (currentGoal.status === "complete") {
1863
- ctx.ui.notify("Goal is complete.", "warning");
1864
- return;
1865
- }
1866
- if (currentGoal.status === "paused") {
1867
- ctx.ui.notify("Goal is already paused. Use /goal-resume to continue.", "info");
1868
- return;
1869
- }
1870
- pauseActiveGoal(ctx);
1871
- }
1872
-
1873
- async function handleGoalResume(ctx: ExtensionContext): Promise<void> {
1874
- reconcileFocusedGoalFromDisk(ctx);
1875
- if (!state.goal && openGoals().length > 0) {
1876
- const selected = await chooseOpenGoal(ctx, "Resume or focus open goal");
1877
- if (!selected) return;
1878
- if (selected.status === "active") {
1879
- armFocusedContinuation(ctx);
1880
- ctx.ui.notify(`Goal focused: ${oneLineSummary(selected)}`, "info");
1881
- return;
1882
- }
1883
- }
1884
- const resumeGate = validateResumeGoal(state.goal);
1885
- if (!resumeGate.ok) {
1886
- const level = resumeGate.message.includes("already running") ? "info" : "warning";
1887
- ctx.ui.notify(resumeGate.message, level);
1888
- return;
1889
- }
1890
- if (!state.goal) throw new Error("Goal disappeared during resume validation.");
1891
- setGoal(
1892
- {
1893
- ...mergeGoalPromptFromDisk(ctx, state.goal),
1894
- status: "active",
1895
- autoContinue: true,
1896
- stopReason: undefined,
1897
- pauseReason: undefined,
1898
- pauseSuggestedAction: undefined,
1899
- },
1900
- ctx,
1901
- );
1902
- beginAccounting();
1903
- resetGetGoalNudgeState(state.goal.id);
1904
- ctx.ui.notify("Goal resumed.", "info");
1905
- queueContinuation(ctx, true);
1906
- // Append ledger event for resumption
1907
- try {
1908
- appendGoalEvent(ctx, {
1909
- type: "goal_resumed",
1910
- goalId: state.goal.id,
1911
- reason: "user",
1912
- at: nowIso(),
1913
- });
1914
- } catch {
1915
- // Ledger append failure should not crash resume
1916
- }
1917
- }
1918
-
1919
- function settingsValue(config: GoalSettings, key: keyof GoalSettings): string {
1920
- if (key === "disabled") return config.disabled === true ? "true" : "false";
1921
- if (key === "disableTasks") return config.disableTasks === true ? "true" : "false";
1922
- if (key === "disableContracts") return config.disableContracts === true ? "true" : "false";
1923
- if (key === "subtaskDepth") return config.subtaskDepth !== undefined ? String(config.subtaskDepth) : "1";
1924
- return config[key] ?? "(default)";
1925
- }
1926
-
1927
- function settingsLines(config: GoalSettings): string[] {
1928
- return [
1929
- `disabled: ${settingsValue(config, "disabled")}`,
1930
- `provider: ${settingsValue(config, "provider")}`,
1931
- `model: ${settingsValue(config, "model")}`,
1932
- `thinking_level: ${settingsValue(config, "thinkingLevel")}`,
1933
- `disableTasks: ${settingsValue(config, "disableTasks")}`,
1934
- `disableContracts: ${settingsValue(config, "disableContracts")}`,
1935
- `subtaskDepth: ${settingsValue(config, "subtaskDepth")}`,
1936
- ];
1937
- }
1938
-
1939
- async function handleSettingsMenu(ctx: ExtensionContext): Promise<void> {
1940
- if (!ctx.hasUI) {
1941
- ctx.ui.notify(`Settings file: ${goalSettingsPath(ctx.cwd)}`, "info");
1942
- return;
1943
- }
1944
- const editorKeys = ["disabled", "provider", "model", "thinking_level", "subtaskDepth"] as const;
1945
- while (true) {
1946
- const config = loadGoalSettingsFileConfig(ctx.cwd);
1947
- const options = settingsLines(config).map((line) => ` ${line}`);
1948
- options.unshift("─── Settings ───");
1949
- options.push("Done");
1950
- const selected = await ctx.ui.select("Goal settings", options);
1951
- if (!selected || selected === "Done" || selected === "─── Settings ───") return;
1952
- // Strip leading spaces from selection
1953
- const selectedTrimmed = selected.trim();
1954
- const colon = selectedTrimmed.indexOf(":");
1955
- if (colon === -1) continue;
1956
- const field = selectedTrimmed.slice(0, colon).trim();
1957
- const editorKey = field === "thinking_level" ? "thinkingLevel" : field;
1958
- if (!(editorKeys as readonly string[]).includes(editorKey)) continue;
1959
- const key = editorKey as keyof GoalSettings;
1960
- if (key === "disabled") {
1961
- const next = { ...config, disabled: !config.disabled };
1962
- saveGoalSettingsFileConfig(ctx.cwd, next);
1963
- ctx.ui.notify(`Settings saved:\n${settingsLines(loadGoalSettingsFileConfig(ctx.cwd)).join("\n")}`, "info");
1964
- continue;
1965
- }
1966
- if (key === "subtaskDepth") {
1967
- const input = await ctx.ui.input("Set subtaskDepth", String(config.subtaskDepth ?? 1));
1968
- if (input === undefined) continue;
1969
- const n = parseInt(input.trim(), 10);
1970
- if (isNaN(n) || n < 1) {
1971
- ctx.ui.notify("subtaskDepth must be a positive integer", "warning");
1972
- continue;
1973
- }
1974
- const next = { ...config, subtaskDepth: n };
1975
- saveGoalSettingsFileConfig(ctx.cwd, next);
1976
- ctx.ui.notify(`Settings saved:\n${settingsLines(loadGoalSettingsFileConfig(ctx.cwd)).join("\n")}`, "info");
1977
- continue;
1978
- }
1979
- const currentValue = settingsValue(config, key);
1980
- const input = await ctx.ui.input(`Set ${field}`, currentValue === "(default)" ? "Leave empty for default" : currentValue);
1981
- if (input === undefined) continue;
1982
- const next: GoalSettings = { ...config };
1983
- const inputTrimmed = input.trim();
1984
- if (!inputTrimmed) {
1985
- delete next[key];
1986
- } else if (key === "thinkingLevel") {
1987
- if (!["off", "minimal", "low", "medium", "high", "xhigh"].includes(inputTrimmed)) {
1988
- ctx.ui.notify("thinking_level must be one of: off, minimal, low, medium, high, xhigh", "warning");
1989
- continue;
1990
- }
1991
- next.thinkingLevel = inputTrimmed as GoalSettings["thinkingLevel"];
1992
- } else if (key === "provider" || key === "model") {
1993
- next[key] = inputTrimmed;
1994
- }
1995
- saveGoalSettingsFileConfig(ctx.cwd, next);
1996
- ctx.ui.notify(`Settings saved:\n${settingsLines(loadGoalSettingsFileConfig(ctx.cwd)).join("\n")}`, "info");
1997
- }
1998
- }
1999
-
2000
- async function handleGoalClear(ctx: ExtensionContext): Promise<void> {
2001
- if (confirmationIntent !== null || tweakDraftingFor !== null) {
2002
- confirmationIntent = null;
2003
- tweakDraftingFor = null;
2004
- syncGoalTools();
2005
- updateUI(ctx);
2006
- ctx.ui.notify(clearGoalCommandMessage({ archived: false, wasDrafting: true }), "info");
2007
- return;
2008
- }
2009
- reconcileFocusedGoalFromDisk(ctx);
2010
- if (!state.goal && openGoals().length > 0) {
2011
- const selected = await chooseOpenGoal(ctx, "Clear which open goal?");
2012
- if (!selected) return;
2013
- }
2014
- const archived = archiveCurrentGoal(ctx, "user");
2015
- const didArchive = !!archived;
2016
- resetGetGoalNudgeState(state.goal?.id);
2017
- setGoal(null, ctx, true, "cleared");
2018
- // Phase 5 D: also abort any in-flight drafting so the agent's next turn
2019
- // doesn't try to propose into a cleared slot.
2020
- const wasDrafting = confirmationIntent !== null;
2021
- confirmationIntent = null;
2022
- syncGoalTools();
2023
- const msg = clearGoalCommandMessage({ archived: didArchive, wasDrafting });
2024
- ctx.ui.notify(msg, didArchive || wasDrafting ? "info" : "warning");
2025
- }
2026
-
2027
- async function handleGoalAbort(ctx: ExtensionContext): Promise<void> {
2028
- if (confirmationIntent !== null || tweakDraftingFor !== null) {
2029
- confirmationIntent = null;
2030
- tweakDraftingFor = null;
2031
- syncGoalTools();
2032
- updateUI(ctx);
2033
- ctx.ui.notify(abortGoalCommandMessage({ archived: false, wasDrafting: true }), "info");
2034
- return;
2035
- }
2036
- reconcileFocusedGoalFromDisk(ctx);
2037
- if (!state.goal && openGoals().length > 0) {
2038
- const selected = await chooseOpenGoal(ctx, "Abort which open goal?");
2039
- if (!selected) return;
2040
- }
2041
- const archived = archiveCurrentGoal(ctx, "user");
2042
- const didArchive = !!archived;
2043
- resetGetGoalNudgeState(state.goal?.id);
2044
- setGoal(null, ctx, true, "aborted");
2045
- const wasDrafting = confirmationIntent !== null;
2046
- confirmationIntent = null;
2047
- syncGoalTools();
2048
- const msg = abortGoalCommandMessage({ archived: didArchive, wasDrafting });
2049
- ctx.ui.notify(msg, didArchive || wasDrafting ? "info" : "warning");
2050
- }
2051
-
2052
- pi.registerMessageRenderer<GoalEventDetails>(GOAL_EVENT_ENTRY, renderGoalEvent);
2053
- pi.registerMessageRenderer<GoalAuditEventDetails>(GOAL_AUDIT_ENTRY, renderGoalAuditEvent);
2054
-
2055
- // /goal and /goal-status: read-only status display.
2056
- const statusCommand = {
2057
- description: "Show the current goal: objective, status, sisyphus mode, usage.",
2058
- handler: async (_rawArgs: string, ctx: ExtensionContext) => {
2059
- await showGoalStatus(ctx);
2060
- },
2061
- };
2062
- pi.registerCommand("goal", {
2063
- description: "Show focused goal status. Discuss with /goals or /sisyphus; direct-start with /goals-set or /sisyphus-set; manage with /goal-list, /goal-focus, /goal-settings, /goal-tweak, /goal-clear, /goal-abort, /goal-pause, /goal-resume.",
2064
- handler: statusCommand.handler,
2065
- });
2066
- pi.registerCommand("goal-status", statusCommand);
2067
- pi.registerCommand("goal-list", {
2068
- description: "List all open pi goals and show which one this session is focused on.",
2069
- handler: async (_rawArgs, ctx) => {
2070
- reconcileFocusedGoalFromDisk(ctx);
2071
- ctx.ui.notify(buildGoalListText(goalsById, focusedGoalId), "info");
2072
- updateUI(ctx);
2073
- },
2074
- });
2075
- pi.registerCommand("goal-focus", {
2076
- description: "Choose which open goal this session should focus on.",
2077
- handler: async (_rawArgs, ctx) => {
2078
- await focusGoalCommand(ctx);
2079
- },
2080
- });
2081
- pi.registerCommand("goal-settings", {
2082
- description: "Open pi-goal settings, including auditor provider/model/thinking_level.",
2083
- handler: async (_rawArgs, ctx) => {
2084
- await handleSettingsMenu(ctx);
2085
- },
2086
- });
2087
-
2088
- // /goals <topic>: discussion/research/grilling -> confirmed normal goal draft.
2089
- pi.registerCommand("goals", {
2090
- description: "Discuss a new goal. The agent clarifies, researches, or grills assumptions, then proposes a draft for confirmation.",
2091
- handler: async (rawArgs, ctx) => {
2092
- await handleGoalCommandTopic(rawArgs, ctx, "goal", { replace: false });
2093
- },
2094
- });
2095
-
2096
- // /sisyphus <topic>: discussion/grilling -> confirmed Sisyphus goal draft.
2097
- pi.registerCommand("sisyphus", {
2098
- description: "Discuss a Sisyphus goal. The agent grills ordered steps, done criteria, blockers, and boundaries before proposing a draft.",
2099
- handler: async (rawArgs: string, ctx: ExtensionContext) => {
2100
- await handleGoalCommandTopic(rawArgs, ctx, "sisyphus", { replace: false });
2101
- },
2102
- });
2103
-
2104
- // /goals-set <objective> and /sisyphus-set <objective>: direct creation, no drafting discussion.
2105
- pi.registerCommand("goals-set", {
2106
- description: "Immediately create and start a normal goal from the supplied objective. No draft discussion.",
2107
- handler: async (rawArgs, ctx) => {
2108
- handleDirectGoalSet(rawArgs, ctx, "goal");
2109
- },
2110
- });
2111
- pi.registerCommand("sisyphus-set", {
2112
- description: "Immediately create and start a Sisyphus goal from the supplied objective. No draft discussion.",
2113
- handler: async (rawArgs, ctx) => {
2114
- handleDirectGoalSet(rawArgs, ctx, "sisyphus");
2115
- },
2116
- });
2117
-
2118
- // /goal-tweak [hint]: drafting on top of the current goal -> edits the active goal file.
2119
- pi.registerCommand("goal-tweak", {
2120
- description: "Refine the current goal via a drafting interview. The agent asks what to change, then edits the active goal file with the revised objective.",
2121
- handler: async (rawArgs, ctx) => {
2122
- await startGoalTweakDrafting(rawArgs, ctx);
2123
- },
2124
- });
2125
-
2126
- // /goal-clear: archive the current goal.
2127
- pi.registerCommand("goal-clear", {
2128
- description: "Archive the current goal.",
2129
- handler: async (_rawArgs, ctx) => {
2130
- await handleGoalClear(ctx);
2131
- },
2132
- });
2133
-
2134
- // /goal-abort: abandon and archive the current goal, or cancel drafting.
2135
- pi.registerCommand("goal-abort", {
2136
- description: "Abort the current goal and archive it, or cancel an in-progress drafting flow.",
2137
- handler: async (_rawArgs, ctx) => {
2138
- await handleGoalAbort(ctx);
2139
- },
2140
- });
2141
-
2142
- // /goal-pause: pause the currently running goal.
2143
- pi.registerCommand("goal-pause", {
2144
- description: "Pause the currently running goal. Esc also pauses while a goal is running.",
2145
- handler: async (_rawArgs, ctx) => {
2146
- await handleGoalPause(ctx);
2147
- },
2148
- });
2149
-
2150
- // /goal-resume: resume a paused goal.
2151
- pi.registerCommand("goal-resume", {
2152
- description: "Resume a paused goal.",
2153
- handler: async (_rawArgs, ctx) => {
2154
- await handleGoalResume(ctx);
2155
- },
2156
- });
2157
-
2158
-
2159
- registerQuestionnaireTools(pi);
2160
-
2161
- pi.registerTool(defineTool({
2162
- name: "get_goal",
2163
- label: "Get Goal",
2164
- description: "Get the current pi goal for this session: objective, status, auto-continue, usage, and local file paths.",
2165
- promptSnippet: "Read the active pi goal state for the current session.",
2166
- promptGuidelines: [
2167
- "Use get_goal when you need the current goal before deciding whether to continue or mark it complete.",
2168
- "Before marking a goal complete, compare every explicit requirement with concrete evidence from the workspace/session.",
2169
- "If the returned goal has sisyphus mode on, you must execute strictly step-by-step in the order written in the objective; do not skip, combine, or rush steps, and stop to ask the user when blocked or unclear.",
2170
- ],
2171
- parameters: Type.Object({}),
2172
- async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
2173
- reconcileFocusedGoalFromDisk(ctx);
2174
- if (state.goal) syncGoalPromptFromDisk(ctx);
2175
- syncGoalTools();
2176
- const view = goalForDisplay() ?? state.goal;
2177
- const otherCount = otherOpenGoalCount(goalsById, focusedGoalId);
2178
- let nudge = "";
2179
- if (view && view.status === "active" && view.id) {
2180
- const prior = activeGetGoalTurnsByGoalId.get(view.id) ?? 0;
2181
- if (prior >= 2) {
2182
- nudge = "\n\n[NUDGE] You have called get_goal multiple times this turn. Prefer concrete work tools (write/read/bash/edit) to advance the goal.";
2183
- }
2184
- }
2185
- const lifecycleHint = view && (view.status === "active" || view.status === "paused")
2186
- ? "\nLifecycle tools: if evidence proves the objective is satisfied, call complete_goal({verificationSummary: \"evidence\"}); if blocked, call pause_goal({reason, suggestedAction?}); if abandoned/obsolete/unsafe, call abort_goal({reason}). For file or shell work, use the normal work tools directly (write/read/bash/edit); do not call get_goal repeatedly just to look for tools."
2187
- : "";
2188
- const text = view
2189
- ? `${detailedSummary(view)}${lifecycleHint}${nudge}${otherCount > 0 ? `\nOther open goals: ${otherCount} (human can run /goal-list or /goal-focus)` : ""}`
2190
- : openGoals().length > 0
2191
- ? buildUnfocusedOpenGoalsSummary(openGoals().length)
2192
- : detailedSummary(null);
2193
- return {
2194
- content: [{ type: "text", text }],
2195
- details: goalDetails(view),
2196
- };
2197
- },
2198
- renderCall(_args, theme) {
2199
- return new Text(theme.fg("toolTitle", "get_goal"), 0, 0);
2200
- },
2201
- renderResult(result, _options, theme) {
2202
- return renderGoalResult(result, theme);
2203
- },
2204
- }));
2205
-
2206
- pi.registerTool(defineTool({
2207
- name: "create_goal",
2208
- label: "Create Goal",
2209
- description: "Create a new active pi goal and focus it. Hidden outside drafting flows; propose_goal_draft is the normal commit path.",
2210
- promptSnippet: "Create a persistent pi goal when the user explicitly asks for one or when a goal-drafting interview has converged.",
2211
- promptGuidelines: [
2212
- "Use create_goal only when the user explicitly asks to start a long-running goal, OR when a /goals or /sisyphus intent discussion has produced a concrete objective.",
2213
- "Creating a new goal focuses it and leaves other open goals untouched. Do not archive or replace existing goals unless the user explicitly asks through a user command.",
2214
- "Pass sisyphus=true only when the goal came out of /sisyphus intent discussion or /sisyphus-set, or when the user explicitly invoked Sisyphus mode.",
2215
- ],
2216
- parameters: Type.Object({
2217
- objective: Type.String({ description: "Concrete objective to pursue. For Sisyphus goals this MUST be the full plan including numbered steps and per-step done criteria." }),
2218
- autoContinue: Type.Optional(Type.Boolean({ description: "Whether pi should keep sending continuation prompts until complete. Defaults to true." })),
2219
- sisyphus: Type.Optional(Type.Boolean({ description: "When true, mark this as a Sisyphus goal: the agent must execute strictly step-by-step, no skipping, no rushing, no improvising. Default false." })),
2220
- }),
2221
- executionMode: "sequential",
2222
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2223
- return {
2224
- content: [{ type: "text", text: "create_goal REJECTED: direct agent creation is disabled. Use /goals or /sisyphus with propose_goal_draft for confirmation, or have the user invoke /goals-set or /sisyphus-set for immediate creation." }],
2225
- details: goalDetails(state.goal),
2226
- };
2227
- },
2228
- renderCall(args, theme) {
2229
- const prefix = args?.sisyphus ? "create_goal sisyphus " : "create_goal ";
2230
- return new Text(theme.fg("toolTitle", prefix) + theme.fg("muted", args?.objective ?? ""), 0, 0);
2231
- },
2232
- renderResult(result, _options, theme) {
2233
- return renderGoalResult(result, theme);
2234
- },
2235
- }));
2236
-
2237
- // Agent's goal-confirmation entry point. Shows the user a full plain-text
2238
- // draft report with two choices: [Confirm] (creates the goal) or
2239
- // [Continue Chatting] (returns control to the agent for more clarification).
2240
- // Schema gates enforce focus-vs-sisyphus consistency; draftId is ignored for
2241
- // one-release compatibility with older prompt residue.
2242
- // In headless mode (no UI), auto-confirms — harness-friendly.
2243
- pi.registerTool(defineTool({
2244
- name: PROPOSE_DRAFT_TOOL_NAME,
2245
- label: "Propose Goal Draft",
2246
- description: "During /goals or /sisyphus intent discussion, propose the goal draft to the user. The user sees a full plain-text confirmation report and chooses Confirm (creates the goal) or Continue Chatting (returns control to you to refine). REPLACES create_goal during discussion-based creation.",
2247
- promptSnippet: "Propose the drafted goal to the user with a full plain-text Confirm / Continue Chatting dialog.",
2248
- promptGuidelines: [
2249
- "Call propose_goal_draft when a /goals or /sisyphus intent discussion has enough information to write a concrete goal. Ask a focused question only when the request is still ambiguous.",
2250
- "If an answer exposes ambiguity, keep interviewing the user — do not propose prematurely.",
2251
- "The user will see a full plain-text draft report plus a [Confirm] / [Continue Chatting] choice. Confirm creates the goal; Continue Chatting returns control to you to ask follow-up questions.",
2252
- "If the tool returns 'continue chatting', ask the user what they want changed. Do NOT propose again immediately with the same content; iterate based on their feedback first.",
2253
- "The sisyphus field must match the user's confirmation focus: /sisyphus -> sisyphus=true, /goals -> sisyphus=false. The schema enforces this; mismatched proposals are REJECTED.",
2254
- "For sisyphus goals, preserve the user's requested ordered style and completion standard. Do not add reconnaissance/preflight steps, merge steps, reorder steps, or change the mode without explicit user confirmation.",
2255
- "create_goal is rejected; propose_goal_draft is the confirmation path. This is intentional — the user wants explicit say in goal creation.",
2256
- "You may include a Verification contract: section in the objective to specify what verification evidence is required before the goal can be completed. This is optional — if omitted, no per-goal contract enforcement applies.",
2257
- ],
2258
- parameters: Type.Object({
2259
- objective: Type.String({ description: "Full goal text. For Sisyphus goals this MUST include the user's numbered steps + per-step done criteria, taken faithfully from the user's input." }),
2260
- autoContinue: Type.Optional(Type.Boolean({ description: "Whether pi should keep sending continuation prompts until complete. Default true." })),
2261
- sisyphus: Type.Optional(Type.Boolean({ description: "Must equal true for /sisyphus discussion, false for /goals discussion. Schema-enforced via B1 gate." })),
2262
- tasks: Type.Optional(Type.Array(Type.Object({
2263
- id: Type.String({ description: "Short stable slug e.g. 'task-1'" }),
2264
- title: Type.String({ description: "Human-readable task title" }),
2265
- verificationContract: Type.Optional(Type.String({ description: "Optional verification contract for this task." })),
2266
- lightweightSubtasks: Type.Optional(Type.Boolean({ description: "If true, subtasks are lightweight (no completion enforcement). Default false." })),
2267
- subtasks: Type.Optional(Type.Any({ description: "Optional recursive array of sub-tasks (same shape as parent)." })),
2268
- }), { description: "Optional task list to confirm together with the goal in a single step. Each task supports recursive subtasks." })),
2269
- draftId: Type.Optional(Type.String({ description: "Deprecated compatibility field. It is accepted but ignored; current goal confirmation no longer depends on hidden draft ids." })),
2270
- }),
2271
- executionMode: "sequential",
2272
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2273
- const validation = validateGoalDraftProposal({
2274
- intent: confirmationIntent,
2275
- hasUnfinishedGoal: !!state.goal && state.goal.status !== "complete",
2276
- objective: params.objective,
2277
- sisyphus: params.sisyphus,
2278
- draftId: params.draftId,
2279
- });
2280
- if (!validation.ok) {
2281
- if (validation.clearDrafting) {
2282
- confirmationIntent = null;
2283
- syncGoalTools();
2284
- }
2285
- return {
2286
- content: [{ type: "text", text: validation.message }],
2287
- details: goalDetails(state.goal),
2288
- };
2289
- }
2290
- const activeIntent = confirmationIntent;
2291
- if (!activeIntent) throw new Error("Goal confirmation intent disappeared during proposal validation.");
2292
-
2293
- // All schema gates passed. Decide how to confirm.
2294
- const objective = validation.objective;
2295
- const autoContinueFlag = params.autoContinue ?? true;
2296
- const sisyphusFlag = validation.expectedSisyphus;
2297
- // Build confirmation text: goal + optional task list
2298
- let taskSummarySection = "";
2299
- let tasksToCreate: GoalTask[] | undefined;
2300
- if (params.tasks && params.tasks.length > 0) {
2301
- tasksToCreate = params.tasks.map((t) => {
2302
- const task: GoalTask = {
2303
- id: (t as Record<string, unknown>).id as string,
2304
- title: (t as Record<string, unknown>).title as string,
2305
- status: "pending",
2306
- verificationContract: (t as Record<string, unknown>).verificationContract as string | undefined,
2307
- lightweightSubtasks: (t as Record<string, unknown>).lightweightSubtasks === true ? true : undefined,
2308
- };
2309
- const rawSubtasks = (t as Record<string, unknown>).subtasks;
2310
- if (Array.isArray(rawSubtasks) && rawSubtasks.length > 0) {
2311
- task.subtasks = rawSubtasks.map((s) => normalizeTaskItem(s as Record<string, unknown>)).filter((s): s is GoalTask => !!s);
2312
- }
2313
- return task;
2314
- });
2315
- // Validate subtask depth BEFORE showing dialog (consistent with propose_task_list)
2316
- const settings = loadGoalSettings(ctx.cwd);
2317
- const depthViolation = findSubtaskDepthViolation(tasksToCreate, settings.subtaskDepth ?? 1);
2318
- if (depthViolation) {
2319
- return {
2320
- content: [{ type: "text", text: depthViolation }],
2321
- details: goalDetails(state.goal),
2322
- };
2323
- }
2324
- const taskLines = renderConfirmationTasks(tasksToCreate, 0);
2325
- taskSummarySection = `\n\n┌─ TASKS ─────────────────────────────────────┐\n${taskLines.join("\n")}\n└──────────────────────────────────────────────┘`;
2326
- }
2327
-
2328
- const draftSummary = buildDraftConfirmationText({
2329
- focus: activeIntent.focus,
2330
- originalTopic: activeIntent.originalTopic,
2331
- // Tasks section appears FIRST in the context so it stays visible
2332
- // even when the dialog caps long context lines.
2333
- objective: taskSummarySection ? `${taskSummarySection}
2334
-
2335
- ${objective}` : objective,
2336
- autoContinue: autoContinueFlag,
2337
- });
2338
-
2339
- const headless = shouldAutoConfirmProposal({ hasUI: hasGoalQuestionnaireUi(ctx), autoConfirmEnv: process.env.PI_GOAL_AUTO_CONFIRM });
2340
-
2341
- let decision: { decision: "confirm" | "continue"; auditorEnabled: boolean };
2342
- const auditorDefault = isAuditorEnabledByDefault(loadGoalSettings(ctx.cwd));
2343
- if (headless) {
2344
- // Headless: auto-confirm (tests and non-TUI sessions).
2345
- decision = { decision: "confirm", auditorEnabled: auditorDefault };
2346
- } else {
2347
- // TUI/browser: show confirmation dialog and emit structured proposal data for non-TUI listeners.
2348
- try {
2349
- const extracted = extractVerificationContract(objective);
2350
- decision = await showStructuredProposalDialog(ctx, {
2351
- id: nextGoalProposalId("goal-draft"),
2352
- kind: "goal-draft",
2353
- focus: activeIntent.focus,
2354
- title: activeIntent.focus === "sisyphus" ? "Confirm Sisyphus Goal Draft" : "Confirm Goal Draft",
2355
- originalTopic: activeIntent.originalTopic,
2356
- objective: extracted.objective,
2357
- autoContinue: autoContinueFlag,
2358
- ...(extracted.verificationContract ? { verificationContract: extracted.verificationContract } : {}),
2359
- ...(tasksToCreate ? { tasks: tasksToCreate } : {}),
2360
- auditorEnabledDefault: auditorDefault,
2361
- }, draftSummary, activeIntent.focus, auditorDefault);
2362
- } catch (err) {
2363
- const message = proposalDialogFailureMessage(err);
2364
- ctx.ui.notify(message, "error");
2365
- return {
2366
- content: [{ type: "text", text: message }],
2367
- details: goalDetails(state.goal),
2368
- };
2369
- }
2370
- }
2371
-
2372
- if (decision.decision === "confirm") {
2373
- // Extract verification contract from objective before creation
2374
- const { objective: cleanedObjective, verificationContract } = extractVerificationContract(objective);
2375
- const config: GoalCreationConfig = {
2376
- objective: cleanedObjective,
2377
- autoContinue: autoContinueFlag,
2378
- sisyphus: sisyphusFlag,
2379
- };
2380
- confirmationIntent = null;
2381
- replaceGoal(config, ctx, false, verificationContract);
2382
-
2383
- // Set skipAuditor on the goal if user toggled auditor off
2384
- if (!decision.auditorEnabled && state.goal) {
2385
- state.goal = { ...state.goal, skipAuditor: true };
2386
- setGoal(state.goal, ctx);
2387
- }
2388
-
2389
- // Set task list if provided
2390
- if (tasksToCreate && tasksToCreate.length > 0 && state.goal) {
2391
- const now = nowIso();
2392
- state.goal = {
2393
- ...state.goal,
2394
- taskList: {
2395
- tasks: tasksToCreate,
2396
- blockCompletion: false,
2397
- proposedAt: now,
2398
- },
2399
- updatedAt: now,
2400
- };
2401
- setGoal(state.goal, ctx);
2402
- // Append ledger event for task list
2403
- try {
2404
- appendGoalEvent(ctx, {
2405
- type: "task_list_set",
2406
- goalId: state.goal.id,
2407
- taskCount: tasksToCreate.length,
2408
- blockCompletion: false,
2409
- at: now,
2410
- });
2411
- } catch {
2412
- // Ledger failure should not block creation
2413
- }
2414
- syncGoalTools();
2415
- updateUI(ctx);
2416
- }
2417
-
2418
- syncGoalTools();
2419
- return {
2420
- content: [{ type: "text", text: buildGoalCreatedReport({ objective, detailedSummary: detailedSummary(state.goal) }) }],
2421
- details: goalDetails(state.goal),
2422
- terminate: true,
2423
- };
2424
- }
2425
- // "continue" — user wants to keep chatting. Drafting state stays armed.
2426
- return {
2427
- content: [{
2428
- type: "text",
2429
- text: "Goal draft refinement requested (Continue Chatting). The goal was not created — drafting remains active. Ask the user what they want changed about the draft (objective, scope, criteria, steps), then revise and call propose_goal_draft again. Do not re-propose the same content — wait for the user's input first.",
2430
- }],
2431
- details: goalDetails(state.goal),
2432
- };
2433
- },
2434
- renderCall(args, theme) {
2435
- const prefix = args?.sisyphus ? "propose_goal_draft sisyphus " : "propose_goal_draft ";
2436
- return new Text(theme.fg("toolTitle", prefix) + theme.fg("muted", truncateText(args?.objective ?? "", 80)), 0, 0);
2437
- },
2438
- renderResult(result, _options, theme) {
2439
- return renderGoalResult(result, theme);
2440
- },
2441
- }));
2442
-
2443
- pi.registerTool(defineTool({
2444
- name: PROPOSE_TWEAK_TOOL_NAME,
2445
- label: "Propose Goal Tweak",
2446
- description: "Propose a goal tweak or auto-start the /goal-tweak drafting flow. When a goal is active or paused and no /goal-tweak flow is active, calling this auto-starts the drafting interview; inside an active flow it presents the revised goal for confirmation.",
2447
- promptSnippet: "Propose the revised goal to the user with a Confirm / Continue Chatting dialog.",
2448
- promptGuidelines: [
2449
- "Always callable when a goal is active or paused. Calling outside a /goal-tweak flow automatically starts one — the tool enters a drafting interview so you can clarify the change before proposing.",
2450
- "newObjective must be the FULL revised objective text, formatted the same way as the original (=== Goal === or === Sisyphus Goal === block). Do NOT pass a diff or partial patch; pass the whole new objective.",
2451
- "For Sisyphus goals: preserve the Sisyphus style and ordered-plan wording unless the user explicitly asks to remove it.",
2452
- "changeSummary is a one-sentence description of WHAT changed (for the confirmation dialog, activity log, and tweak log). When auto-starting a tweak flow, this is used as the hint for the drafting interview.",
2453
- "The user will see a full plain-text report plus a [Confirm] / [Continue Chatting] choice. Confirm applies the tweak; Continue Chatting returns control to you to ask follow-up questions.",
2454
- "If the tool returns 'continue chatting', ask the user what they want changed. Do NOT re-propose the same content immediately; iterate based on their feedback first.",
2455
- "Do NOT use write/edit/bash to modify the active goal file directly. propose_goal_tweak is the only sanctioned channel.",
2456
- "tasks (optional): an array of task objects to REPLACE the current goal's task list. When omitted,",
2457
- " the existing task list is inherited as-is. When provided, the full task list is replaced with",
2458
- " the new tasks — add/remove/change tasks by passing the complete updated list.",
2459
- " Each task has: {id, title, verificationContract?, lightweightSubtasks?, subtasks?}.",
2460
- " Subtasks use the same shape recursively. The task list is displayed in the confirmation",
2461
- " dialog alongside the objective diff, matching propose_goal_draft's rendering format.",
2462
- "Start from the current goal's objective text and task list (the inheritance defaults), then",
2463
- " edit/rewrite them directly rather than composing a goal from scratch.",
2464
- ],
2465
- parameters: Type.Object({
2466
- newObjective: Type.String({ description: "The complete revised objective text. For Sisyphus goals, preserve the Sisyphus style unless the user explicitly changes it." }),
2467
- changeSummary: Type.String({ description: "One-sentence description of what was changed (used in confirmation dialog, activity log, and tweak log)." }),
2468
- tasks: Type.Optional(Type.Array(Type.Object({
2469
- id: Type.String({ description: "Short stable slug e.g. 'task-1'" }),
2470
- title: Type.String({ description: "Human-readable task title" }),
2471
- verificationContract: Type.Optional(Type.String({ description: "Optional verification contract for this task." })),
2472
- lightweightSubtasks: Type.Optional(Type.Boolean({ description: "If true, subtasks are lightweight (no completion enforcement). Default false." })),
2473
- subtasks: Type.Optional(Type.Any({ description: "Optional recursive array of sub-tasks (same shape as parent)." })),
2474
- }), { description: "Optional task list to replace the current goal's tasks. When omitted the existing task list is inherited. Each task supports recursive subtasks." })),
2475
- }),
2476
- executionMode: "sequential",
2477
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2478
- reconcileFocusedGoalFromDisk(ctx);
2479
- if (!state.goal) {
2480
- return {
2481
- content: [{ type: "text", text: "No goal is set; propose_goal_tweak is a no-op." }],
2482
- details: goalDetails(state.goal),
2483
- };
2484
- }
2485
- if (state.goal.status !== "active" && state.goal.status !== "paused") {
2486
- return {
2487
- content: [{ type: "text", text: `Goal is ${statusLabel(state.goal)}; cannot apply a tweak.` }],
2488
- details: goalDetails(state.goal),
2489
- };
2490
- }
2491
- const newObjective = params.newObjective.trim();
2492
- if (!newObjective) throw new Error("propose_goal_tweak requires a non-empty newObjective.");
2493
- const changeSummary = params.changeSummary.trim();
2494
- if (!changeSummary) throw new Error("propose_goal_tweak requires a non-empty changeSummary.");
2495
-
2496
- // Resolve tasks: inherit from current goal if not provided, or normalize/validate the passed tasks.
2497
- let tweakTasks: GoalTask[] | undefined;
2498
- if (params.tasks && Array.isArray(params.tasks) && params.tasks.length > 0) {
2499
- tweakTasks = params.tasks.map((t: Record<string, unknown>) => {
2500
- const task: GoalTask = {
2501
- id: t.id as string,
2502
- title: t.title as string,
2503
- status: "pending",
2504
- verificationContract: t.verificationContract as string | undefined,
2505
- lightweightSubtasks: t.lightweightSubtasks === true ? true : undefined,
2506
- };
2507
- const rawSubtasks = t.subtasks;
2508
- if (Array.isArray(rawSubtasks) && rawSubtasks.length > 0) {
2509
- task.subtasks = rawSubtasks
2510
- .map((s: Record<string, unknown>) => normalizeTaskItem(s))
2511
- .filter((s: GoalTask | undefined): s is GoalTask => !!s);
2512
- }
2513
- return task;
2514
- });
2515
- // Validate task list
2516
- if (tweakTasks.length > 50) {
2517
- return { content: [{ type: "text", text: "Task list cannot exceed 50 tasks." }], details: goalDetails(state.goal) };
2518
- }
2519
- const settings = loadGoalSettings(ctx.cwd);
2520
- const depthViolation = findSubtaskDepthViolation(tweakTasks, settings.subtaskDepth ?? 1);
2521
- if (depthViolation) {
2522
- return { content: [{ type: "text", text: depthViolation }], details: goalDetails(state.goal) };
2523
- }
2524
- } else {
2525
- // Inherit current task list when no tasks parameter provided
2526
- if (state.goal.taskList && state.goal.taskList.tasks.length > 0) {
2527
- tweakTasks = state.goal.taskList.tasks;
2528
- }
2529
- }
2530
-
2531
- // Auto-start the tweak drafting flow if not already active.
2532
- if (tweakDraftingFor !== state.goal.id) {
2533
- await startGoalTweakDrafting(changeSummary, ctx);
2534
- return {
2535
- content: [{
2536
- type: "text",
2537
- text: "Tweak drafting flow auto-started. The drafting interview prompt will arrive in a new turn. " +
2538
- "Ask the user clarifying questions as needed, refine the proposal, then call propose_goal_tweak again with the complete revision.",
2539
- }],
2540
- details: goalDetails(state.goal),
2541
- };
2542
- }
2543
-
2544
- // Build the confirmation dialog text.
2545
- const draftSummary = buildTweakConfirmationText({
2546
- currentObjective: state.goal.objective,
2547
- newObjective,
2548
- changeSummary,
2549
- sisyphus: !!state.goal.sisyphus,
2550
- tasks: tweakTasks,
2551
- });
2552
-
2553
- const headless = shouldAutoConfirmProposal({ hasUI: hasGoalQuestionnaireUi(ctx), autoConfirmEnv: process.env.PI_GOAL_AUTO_CONFIRM });
2554
-
2555
- let decision: { decision: "confirm" | "continue"; auditorEnabled: boolean };
2556
- if (headless) {
2557
- decision = { decision: "confirm", auditorEnabled: !state.goal.skipAuditor };
2558
- } else {
2559
- try {
2560
- const extracted = extractVerificationContract(newObjective);
2561
- const focus = state.goal.sisyphus ? "sisyphus" : "goal";
2562
- decision = await showStructuredProposalDialog(ctx, {
2563
- id: nextGoalProposalId("goal-tweak"),
2564
- kind: "goal-tweak",
2565
- focus,
2566
- title: focus === "sisyphus" ? "Confirm Sisyphus Goal Tweak" : "Confirm Goal Tweak",
2567
- currentObjective: state.goal.objective,
2568
- newObjective: extracted.objective,
2569
- changeSummary,
2570
- ...(extracted.verificationContract ? { verificationContract: extracted.verificationContract } : {}),
2571
- auditorEnabledDefault: !state.goal.skipAuditor,
2572
- }, draftSummary, focus, !state.goal.skipAuditor);
2573
- } catch (err) {
2574
- const message = proposalDialogFailureMessage(err);
2575
- ctx.ui.notify(message, "error");
2576
- return {
2577
- content: [{ type: "text", text: message }],
2578
- details: goalDetails(state.goal),
2579
- };
2580
- }
2581
- }
2582
-
2583
- if (decision.decision === "confirm") {
2584
- // Persist any auditor toggle change
2585
- if (state.goal) {
2586
- state.goal = { ...state.goal, skipAuditor: !decision.auditorEnabled };
2587
- }
2588
- // Extract verification contract from revised objective
2589
- const { objective: cleanedObjective, verificationContract } = extractVerificationContract(newObjective);
2590
- // Apply the tweak: write the new objective to disk authoritatively.
2591
- const next: GoalRecord = {
2592
- ...state.goal,
2593
- objective: cleanedObjective,
2594
- verificationContract: verificationContract,
2595
- updatedAt: nowIso(),
2596
- // Clear any prior agent pause reason — the user has redefined the work.
2597
- pauseReason: undefined,
2598
- pauseSuggestedAction: undefined,
2599
- taskList: tweakTasks && tweakTasks.length > 0
2600
- ? { tasks: tweakTasks, blockCompletion: false, proposedAt: nowIso() }
2601
- : undefined,
2602
- };
2603
- // IMPORTANT: bypass setGoal() / persist() here. persist() calls
2604
- // syncGoalPromptFromDisk() which would RE-READ the stale objective
2605
- // from the still-old goal file on disk and clobber our new objective
2606
- // before writing. propose_goal_tweak is the authoritative source for
2607
- // objective changes — the disk is downstream, not upstream. Do the
2608
- // minimal state update manually:
2609
- // 1) write the new record to disk authoritatively
2610
- // 2) update in-memory `goal` to the canonical post-write record
2611
- // 3) append the state entry and re-sync tools
2612
- // 4) clear the tweak drafting gate so propose_goal_tweak can't be re-used
2613
- state.goal = writeActiveGoalFile(ctx, next);
2614
- invalidateQueuedContinuations();
2615
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
2616
- tweakDraftingFor = null;
2617
- // Reset autoContinue counter — plan changed, agent gets a fresh chain.
2618
- resetGetGoalNudgeState(state.goal.id);
2619
- // Mark turn-stopped so subsequent in-turn tool calls are blocked.
2620
- markTurnStopped(state.goal.id);
2621
- syncGoalTools();
2622
- updateUI(ctx);
2623
- ctx.ui.notify(`Goal tweaked: ${truncateText(changeSummary, 160)}`, "info");
2624
- // Append ledger event for tweak
2625
- try {
2626
- appendGoalEvent(ctx, {
2627
- type: "goal_tweaked",
2628
- goalId: state.goal.id,
2629
- changeSummary,
2630
- at: state.goal.updatedAt,
2631
- });
2632
- } catch {
2633
- // Ledger append failure should not crash tweak
2634
- }
2635
- // Append ledger event for task list change if tasks were provided
2636
- if (params.tasks && Array.isArray(params.tasks) && params.tasks.length > 0) {
2637
- try {
2638
- appendGoalEvent(ctx, {
2639
- type: "task_list_set",
2640
- goalId: state.goal.id,
2641
- taskCount: params.tasks.length,
2642
- blockCompletion: false,
2643
- at: state.goal.updatedAt,
2644
- });
2645
- } catch {
2646
- // Ledger append failure should not crash tweak
2647
- }
2648
- }
2649
- return {
2650
- content: [{
2651
- type: "text",
2652
- text: `Goal tweak applied. ${changeSummary}\nStop now; the next continuation will arrive automatically if the goal is active.`,
2653
- }],
2654
- details: goalDetails(state.goal),
2655
- terminate: true,
2656
- };
2657
- }
2658
-
2659
- // "continue" — user wants to keep chatting. Drafting state stays armed.
2660
- return {
2661
- content: [{
2662
- type: "text",
2663
- text: "Goal tweak refinement requested (Continue Chatting). The tweak was not applied — drafting remains active. Ask the user what they want changed about the revision, then revise and call propose_goal_tweak again. Do not re-propose the same content — wait for the user's input first.",
2664
- }],
2665
- details: goalDetails(state.goal),
2666
- };
2667
- },
2668
- renderCall(args, theme) {
2669
- const summary = typeof args?.changeSummary === "string" ? truncateText(args.changeSummary, 80) : "";
2670
- return new Text(theme.fg("toolTitle", "propose_goal_tweak ") + theme.fg("muted", summary), 0, 0);
2671
- },
2672
- renderResult(result, _options, theme) {
2673
- return renderGoalResult(result, theme);
2674
- },
2675
- }));
2676
-
2677
- pi.registerTool(defineTool({
2678
- name: "complete_goal",
2679
- label: "Complete Goal",
2680
- description: "Mark the current active or paused pi goal complete. Only call this when the goal objective is actually achieved — no required work remains.",
2681
- promptSnippet: "Mark the active or paused pi goal complete — only when every requirement is satisfied.",
2682
- promptGuidelines: [
2683
- "Call complete_goal only when the pi goal objective has actually been achieved and no required work remains.",
2684
- "Before calling complete_goal, you MUST provide a verificationSummary that addresses every success criterion and any verification contract on the goal. Fold all verification evidence (test output, grep results, requirements coverage) into this single field.",
2685
- "The auditor is authoritative: completion is archived only if the auditor report ends with <approved/>. If it ends with <disapproved/> or no approval marker, complete_goal is rejected and the goal remains open.",
2686
- "Do NOT call complete_goal if any work remains, even if substantial progress was made. Do not use it merely because work is stopping, tests passed, or you are blocked.",
2687
- "Do not use complete_goal=complete as an escape hatch when you are blocked. If you are blocked, call pause_goal({reason, suggestedAction?}) instead so the user can intervene.",
2688
- "For sisyphus goals, do not mark complete until every numbered step has been executed and individually verified against its done criterion.",
2689
- "The goal objective is immutable. The agent MUST NOT modify the goal objective on its own initiative. If the user gives requirements, feedback, or corrections that differ from the goal objective, ask the user to run /goal-tweak to revise the goal. Use goal_question to confirm when the change is ambiguous.",
2690
- "If the goal has a verificationContract, your verificationSummary must address every item in the contract. The auditor will cross-check your claims against real artifacts.",
2691
- ],
2692
- parameters: Type.Object({
2693
- status: Type.Optional(StringEnum([COMPLETE_STATUS] as const, { description: "Set to complete only when the objective is achieved." })),
2694
- completionSummary: Type.Optional(Type.String({ description: "Concise completion claim and evidence summary passed to the independent auditor agent." })),
2695
- verificationSummary: Type.String({ description: "Required verification evidence showing what was checked before declaring completion. Must address every success criterion and any verification contract on the goal. Examples: 'Ran npm test (0 failures), re-read requirements and confirmed A1-A3 complete, grepped for remaining STP references (none found).' The exact requirements depend on the specific goal." }),
2696
- confirmBypassAuditor: Type.Optional(Type.Boolean({ description: "Set to true to confirm bypassing the independent auditor when it is disabled in settings." })),
2697
- }, { additionalProperties: false }),
2698
- executionMode: "sequential",
2699
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2700
- reconcileFocusedGoalFromDisk(ctx);
2701
-
2702
- // -- Phase 2: Status validation --
2703
- const effectiveStatus = params.status ?? COMPLETE_STATUS;
2704
- if (effectiveStatus !== COMPLETE_STATUS) {
2705
- throw new Error("complete_goal requires status=complete when marking a goal complete.");
2706
- }
2707
-
2708
- // -- Phase 3: Completion --
2709
- const completionGate = validateGoalCompletion({ goal: state.goal, runningGoalId });
2710
- if (!completionGate.ok) {
2711
- return {
2712
- content: [{ type: "text", text: completionGate.message }],
2713
- details: goalDetails(state.goal),
2714
- };
2715
- }
2716
- if (!state.goal) throw new Error("Goal disappeared during completion validation.");
2717
-
2718
- // Task gate: warn if blockCompletion is enabled and tasks remain pending
2719
- const disableTasksSettings = loadGoalSettings(ctx.cwd).disableTasks;
2720
- if (!disableTasksSettings) {
2721
- const taskWarning = state.goal.taskList ? taskCompletionBlockWarning(state.goal.taskList) : null;
2722
- if (taskWarning) {
2723
- return {
2724
- content: [{ type: "text", text: taskWarning }],
2725
- details: goalDetails(state.goal),
2726
- };
2727
- }
2728
- }
2729
-
2730
- // Verification contract gate: if the goal has a contract, verificationSummary must be non-empty
2731
- const disableContractsSettings = loadGoalSettings(ctx.cwd).disableContracts;
2732
- if (!disableContractsSettings) {
2733
- const contractGate = validateVerificationSummary({
2734
- verificationContract: state.goal.verificationContract,
2735
- verificationSummary: params.verificationSummary,
2736
- });
2737
- if (!contractGate.ok) {
2738
- return {
2739
- content: [{ type: "text", text: contractGate.message }],
2740
- details: goalDetails(state.goal),
2741
- };
2742
- }
2743
- }
2744
-
2745
- const auditTarget = mergeGoalPromptFromDisk(ctx, state.goal);
2746
- // Append ledger: completion requested
2747
- try {
2748
- appendGoalEvent(ctx, {
2749
- type: "completion_requested",
2750
- goalId: auditTarget.id,
2751
- summary: params.completionSummary,
2752
- at: nowIso(),
2753
- });
2754
- } catch {
2755
- // Ledger append failure should not block completion
2756
- }
2757
- const settings = loadGoalSettingsFileConfig(ctx.cwd);
2758
- // Check if auditor is disabled per-goal (user toggled it off during goal confirmation)
2759
- if (auditTarget.skipAuditor) {
2760
- try {
2761
- appendGoalEvent(ctx, {
2762
- type: "audit_skipped",
2763
- goalId: auditTarget.id,
2764
- reason: "disabled",
2765
- provider: settings.provider,
2766
- model: settings.model,
2767
- thinkingLevel: settings.thinkingLevel,
2768
- at: nowIso(),
2769
- });
2770
- } catch {
2771
- // Ledger append failure should not block completion
2772
- }
2773
- accountProgress(ctx);
2774
- auditProgress = null;
2775
- goalWidgetComponent?.invalidate();
2776
- state.goal = {
2777
- ...auditTarget,
2778
- status: "complete",
2779
- stopReason: "agent",
2780
- updatedAt: nowIso(),
2781
- };
2782
- state.goal = writeActiveGoalFile(ctx, state.goal);
2783
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
2784
- markTurnStopped(state.goal?.id);
2785
- resetGetGoalNudgeState(state.goal?.id);
2786
- syncGoalTools();
2787
- updateUI(ctx);
2788
- return {
2789
- content: [{
2790
- type: "text",
2791
- text: buildCompletionReport({
2792
- detailedSummary: detailedSummary(state.goal),
2793
- completionSummary: params.completionSummary,
2794
- auditSkippedReason: "per-goal auditor disabled",
2795
- taskSummary: state.goal?.taskList ? buildTaskSummary(state.goal.taskList) : null,
2796
- }),
2797
- }],
2798
- details: goalDetails(state.goal),
2799
- terminate: true,
2800
- };
2801
- }
2802
-
2803
- // Check if auditor is disabled in settings
2804
- if (settings.disabled === true) {
2805
- if (params.confirmBypassAuditor !== true) {
2806
- return {
2807
- content: [{ type: "text", text: [
2808
- "The completion auditor is disabled in settings.",
2809
- "",
2810
- `Use \`goal_question\` to ask the user: "The independent completion auditor is disabled. Bypass independent verification and mark the goal complete?"`,
2811
- "If the user confirms, call complete_goal again with confirmBypassAuditor: true.",
2812
- ].join("\n") }],
2813
- details: goalDetails(state.goal),
2814
- };
2815
- }
2816
- // Auditor disabled and confirmed — skip audit.
2817
- // Defer archival: set goal complete in-memory + write active file WITHOUT
2818
- // archiving. Archival happens at turn_end so the agent can receive the
2819
- // complete_goal tool result before the goal is archived.
2820
- try {
2821
- appendGoalEvent(ctx, {
2822
- type: "audit_skipped",
2823
- goalId: auditTarget.id,
2824
- reason: "disabled",
2825
- provider: settings.provider,
2826
- model: settings.model,
2827
- thinkingLevel: settings.thinkingLevel,
2828
- at: nowIso(),
2829
- });
2830
- } catch {
2831
- // Ledger append failure should not block completion
2832
- }
2833
- // Set goal complete in memory (defer archival to turn_end)
2834
- accountProgress(ctx);
2835
- auditProgress = null;
2836
- goalWidgetComponent?.invalidate();
2837
- state.goal = {
2838
- ...auditTarget,
2839
- status: "complete",
2840
- stopReason: "agent",
2841
- updatedAt: nowIso(),
2842
- };
2843
- state.goal = writeActiveGoalFile(ctx, state.goal);
2844
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
2845
- markTurnStopped(state.goal?.id);
2846
- resetGetGoalNudgeState(state.goal?.id);
2847
- syncGoalTools();
2848
- updateUI(ctx);
2849
- return {
2850
- content: [{
2851
- type: "text",
2852
- text: buildCompletionReport({
2853
- detailedSummary: detailedSummary(state.goal),
2854
- completionSummary: params.completionSummary,
2855
- auditSkippedReason: "auditor disabled in settings",
2856
- taskSummary: state.goal?.taskList ? buildTaskSummary(state.goal.taskList) : null,
2857
- }),
2858
- }],
2859
- details: goalDetails(state.goal),
2860
- terminate: true,
2861
- };
2862
- }
2863
-
2864
- // Auditor is enabled — run the normal audit flow. The complete_goal
2865
- // tool result is the authoritative user-visible audit report; do not
2866
- // inject audit lifecycle messages into the session, because custom
2867
- // messages can be queued/reordered around active tool execution.
2868
- // Append ledger: audit started
2869
- try {
2870
- appendGoalEvent(ctx, {
2871
- type: "audit_started",
2872
- goalId: auditTarget.id,
2873
- provider: settings.provider,
2874
- model: settings.model,
2875
- thinkingLevel: settings.thinkingLevel,
2876
- at: nowIso(),
2877
- });
2878
- } catch {
2879
- // Ledger append failure should not block completion
2880
- }
2881
- // Set up auditor progress display (before createAgentSession)
2882
- const auditStartedAt = Date.now();
2883
- auditProgress = {
2884
- recentOutput: [],
2885
- phase: "running",
2886
- elapsedMs: 0,
2887
- };
2888
- // Start animation timer for the spinner in the auditor widget
2889
- stopAuditAnimation();
2890
- auditAnimationTimer = setInterval(() => {
2891
- if (!auditProgress) {
2892
- stopAuditAnimation();
2893
- return;
2894
- }
2895
- auditProgress.elapsedMs = Date.now() - auditStartedAt;
2896
- goalWidgetComponent?.invalidate();
2897
- }, 80);
2898
- auditAnimationTimer.unref?.();
2899
-
2900
- // Create a dedicated AbortController for the audit so it can be interrupted via Escape
2901
- auditAbortController?.abort(); // Clean up any stale controller
2902
- auditAbortController = new AbortController();
2903
-
2904
- const auditor = await runGoalCompletionAuditor({
2905
- ctx,
2906
- goal: auditTarget,
2907
- completionSummary: params.completionSummary,
2908
- detailedSummary: detailedSummary(auditTarget),
2909
- verificationSummary: params.verificationSummary,
2910
- settings: loadGoalSettings(ctx.cwd),
2911
- signal: auditAbortController.signal,
2912
- onProgress: (progress) => {
2913
- auditProgress = {
2914
- ...progress,
2915
- elapsedMs: Date.now() - auditStartedAt,
2916
- };
2917
- goalWidgetComponent?.invalidate();
2918
- },
2919
- });
2920
- // Clear abort controller — audit finished on its own
2921
- auditAbortController = null;
2922
- // Clear auditor progress display
2923
- stopAuditAnimation();
2924
-
2925
- // If the audit was aborted by the user (Esc), show a TUI dialog letting
2926
- // the user choose: mark complete without audit, or continue working.
2927
- if (auditor.error === "Auditor aborted.") {
2928
- auditProgress = null;
2929
- goalWidgetComponent?.invalidate();
2930
- updateUI(ctx);
2931
-
2932
- showingEscapeDialog = true;
2933
- const userChoice: EscapeDialogResult = await showEscapeDialog(ctx, auditTarget.objective);
2934
- showingEscapeDialog = false;
2935
-
2936
- if (userChoice === "complete_without_audit") {
2937
- // ── Mark complete without audit ────────────────────────────
2938
- try {
2939
- appendGoalEvent(ctx, {
2940
- type: "audit_skipped",
2941
- goalId: auditTarget.id,
2942
- reason: "user_aborted",
2943
- provider: settings.provider,
2944
- model: settings.model,
2945
- thinkingLevel: settings.thinkingLevel,
2946
- at: nowIso(),
2947
- });
2948
- } catch {
2949
- // Ledger append failure should not block completion
2950
- }
2951
- // Set goal complete in memory (defer archival to turn_end)
2952
- accountProgress(ctx);
2953
- state.goal = {
2954
- ...auditTarget,
2955
- status: "complete",
2956
- stopReason: "agent",
2957
- updatedAt: nowIso(),
2958
- };
2959
- state.goal = writeActiveGoalFile(ctx, state.goal);
2960
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
2961
- markTurnStopped(state.goal?.id);
2962
- resetGetGoalNudgeState(state.goal?.id);
2963
- syncGoalTools();
2964
- updateUI(ctx);
2965
- return {
2966
- content: [{
2967
- type: "text",
2968
- text: [
2969
- "User chose to mark the goal complete (bypassed audit via Escape).",
2970
- "",
2971
- "The goal is complete. Provide a final summary of what was accomplished.",
2972
- ].join("\n"),
2973
- }],
2974
- details: goalDetails(state.goal),
2975
- };
2976
- } else {
2977
- // ── Continue working → pause the goal ──────────────
2978
- pauseActiveGoal(ctx);
2979
- markTurnStopped(state.goal?.id);
2980
- return {
2981
- content: [{ type: "text", text: "Goal paused — user chose to continue working after skipping audit." }],
2982
- details: state.goal ? goalDetails(state.goal) : undefined,
2983
- };
2984
- }
2985
- }
2986
-
2987
- // Show final audit output briefly before clearing
2988
- if (auditProgress && auditor.output) {
2989
- const outputLines = auditor.output.split("\n").slice(0, 8);
2990
- auditProgress = {
2991
- ...auditProgress,
2992
- phase: "done",
2993
- recentOutput: outputLines,
2994
- elapsedMs: Date.now() - auditStartedAt,
2995
- };
2996
- goalWidgetComponent?.invalidate();
2997
- }
2998
- // Append ledger: audit result
2999
- const verdict = auditor.approved ? "approved" : auditor.error ? "error" : "disapproved" as const;
3000
- try {
3001
- appendGoalEvent(ctx, {
3002
- type: "audit_result",
3003
- goalId: auditTarget.id,
3004
- verdict,
3005
- report: auditor.output || "Auditor produced no output.",
3006
- at: nowIso(),
3007
- });
3008
- } catch {
3009
- // Ledger append failure should not block completion
3010
- }
3011
- if (!auditor.approved) {
3012
- // Clear auditor progress to restore normal widget state
3013
- auditProgress = null;
3014
- goalWidgetComponent?.invalidate();
3015
- const rejectionText = [
3016
- "Goal audit rejected.",
3017
- "",
3018
- "Goal completion rejected by independent auditor.",
3019
- auditor.model ? `Auditor model: ${auditor.model}${auditor.thinkingLevel ? `:${auditor.thinkingLevel}` : ""}` : undefined,
3020
- auditor.error ? `Auditor error: ${auditor.error}` : undefined,
3021
- "",
3022
- auditor.output || "Auditor produced no approval marker.",
3023
- ].filter((line): line is string => line !== undefined).join("\n");
3024
- return {
3025
- content: [{ type: "text", text: rejectionText }],
3026
- details: goalDetails(state.goal),
3027
- };
3028
- }
3029
- const approvalText = [
3030
- "Auditor: I approve this completion claim.",
3031
- auditor.model ? `Auditor model: ${auditor.model}${auditor.thinkingLevel ? `:${auditor.thinkingLevel}` : ""}` : undefined,
3032
- "",
3033
- auditor.output || "Auditor approved completion.",
3034
- ].filter((line): line is string => line !== undefined).join("\n");
3035
- // Account for any remaining elapsed time.
3036
- // Defer archival: set goal complete in-memory + write active file WITHOUT
3037
- // archiving. Archival happens at turn_end so the agent can receive the
3038
- // complete_goal approval report before the goal is archived.
3039
- accountProgress(ctx);
3040
- auditProgress = null;
3041
- goalWidgetComponent?.invalidate();
3042
- state.goal = {
3043
- ...auditTarget,
3044
- status: "complete",
3045
- stopReason: "agent",
3046
- updatedAt: nowIso(),
3047
- };
3048
- state.goal = writeActiveGoalFile(ctx, state.goal);
3049
- pi.appendEntry(STATE_ENTRY, goalDetails(state.goal));
3050
- markTurnStopped(state.goal?.id);
3051
- resetGetGoalNudgeState(state.goal?.id);
3052
- syncGoalTools();
3053
- updateUI(ctx);
3054
- return {
3055
- content: [{
3056
- type: "text",
3057
- text: buildCompletionReport({
3058
- detailedSummary: detailedSummary(state.goal),
3059
- completionSummary: params.completionSummary,
3060
- auditorReport: auditor.output,
3061
- taskSummary: state.goal?.taskList ? buildTaskSummary(state.goal.taskList) : null,
3062
- }),
3063
- }],
3064
- details: goalDetails(state.goal),
3065
- terminate: true,
3066
- };
3067
- },
3068
- renderCall(args, theme) {
3069
- const label = args?.status ?? "";
3070
- return new Text(theme.fg("toolTitle", "complete_goal ") + theme.fg("success", label), 0, 0);
3071
- },
3072
- renderResult(result, _options, theme) {
3073
- return renderGoalResult(result, theme);
3074
- },
3075
- }));
3076
-
3077
- pi.registerTool(defineTool({
3078
- name: "pause_goal",
3079
- label: "Pause Goal",
3080
- description: "Pause the active pi goal and report a blocker to the user. The user must /goal-resume, /goal-tweak, or /goal-clear before work continues.",
3081
- promptSnippet: "Pause the active pi goal and report a concrete blocker so the user can intervene.",
3082
- promptGuidelines: [
3083
- "Use pause_goal when you have hit a real blocker that you cannot resolve with one more reasonable next step: missing credentials, ambiguous or contradictory spec, a file or permission you cannot access, a sisyphus step whose precondition is not in the plan, or any irreversible / dangerous operation that requires explicit user approval.",
3084
- "Do NOT use pause_goal to escape a merely hard problem; first try one concrete next step. Do not use pause_goal as a softer substitute for complete_goal \u2014 if the objective is achieved, complete it; if it is not, do not complete it.",
3085
- "Never silently invent a workaround, fake completion, or quietly redefine the objective. Pause and report instead.",
3086
- "Always pass a concrete one-sentence reason. When you know how the user can unblock you, pass suggestedAction (e.g. 'Set FOO_API_KEY env var and /goal-resume', or 'Use /goal-tweak to insert a precondition step before step 3').",
3087
- "After pause_goal returns, stop. Do not call other tools in the same turn.",
3088
- "For sisyphus goals: if any step is unclear, blocked, fails, or seems wrong, pause_goal is the correct action \u2014 do not skip the step or invent a workaround.",
3089
- ],
3090
- parameters: Type.Object({
3091
- reason: Type.String({ description: "One-sentence concrete blocker description. Plain language, not an apology." }),
3092
- suggestedAction: Type.Optional(Type.String({ description: "Optional concrete suggestion for how the user can unblock (e.g. command to run, value to provide, /goal-tweak hint)." })),
3093
- }),
3094
- executionMode: "sequential",
3095
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3096
- reconcileFocusedGoalFromDisk(ctx);
3097
- const reason = params.reason.trim();
3098
- if (!reason) throw new Error("pause_goal requires a non-empty reason.");
3099
- const pauseGate = validatePauseGoal({ goal: state.goal, runningGoalId, reason });
3100
- if (!pauseGate.ok) {
3101
- return {
3102
- content: [{ type: "text", text: pauseGate.message }],
3103
- details: goalDetails(state.goal),
3104
- };
3105
- }
3106
- if (!state.goal) throw new Error("Goal disappeared during pause validation.");
3107
- const suggested = params.suggestedAction?.trim() || undefined;
3108
-
3109
- // Account for any remaining elapsed time before stopping the run.
3110
- accountProgress(ctx);
3111
- state.goal = mergeGoalPromptFromDisk(ctx, state.goal);
3112
- const next = buildPausedByAgentGoal(state.goal, { reason, suggestedAction: suggested, updatedAt: nowIso() });
3113
- setGoal(next, ctx);
3114
- resetGetGoalNudgeState(next.id);
3115
- // C9 fix: mark turn-stopped so subsequent in-turn tool calls are blocked.
3116
- // This is the schema-level closure of "agent kept writing files after pause_goal".
3117
- markTurnStopped(state.goal.id);
3118
-
3119
- const suggestionLine = suggested ? `\nSuggested: ${truncateText(suggested, 160)}` : "";
3120
- ctx.ui.notify(
3121
- `Goal paused by agent.\nReason: ${truncateText(reason, 200)}${suggestionLine}\n\nUse /goal-resume to continue, /goal-tweak to revise, or /goal-clear to abandon.`,
3122
- "warning",
3123
- );
3124
- return {
3125
- content: [{
3126
- type: "text",
3127
- text: `Goal paused. Reason: ${reason}${suggested ? `\nSuggested: ${suggested}` : ""}\nWaiting for user to /goal-resume, /goal-tweak, or /goal-clear. Stop now; do not start another tool call.`,
3128
- }],
3129
- details: goalDetails(state.goal),
3130
- terminate: true,
3131
- };
3132
- },
3133
- renderCall(args, theme) {
3134
- return new Text(theme.fg("toolTitle", "pause_goal ") + theme.fg("warning", truncateText(args?.reason ?? "", 80)), 0, 0);
3135
- },
3136
- renderResult(result, _options, theme) {
3137
- return renderGoalResult(result, theme);
3138
- },
3139
- }));
3140
-
3141
- pi.registerTool(defineTool({
3142
- name: ABORT_GOAL_TOOL_NAME,
3143
- label: "Abort Goal",
3144
- description: "Abort the current active or paused pi goal and archive it without marking it complete.",
3145
- promptSnippet: "Abort the current pi goal only when the user asks to abandon it or the objective is obsolete/impossible.",
3146
- promptGuidelines: [
3147
- "Use abort_goal only when the user explicitly asks to abandon/cancel the current goal, or when the goal is impossible, obsolete, or unsafe to continue and should not be marked complete.",
3148
- "Do not use abort_goal as a substitute for complete_goal. If the objective is achieved, complete it instead.",
3149
- "Do not use abort_goal for ordinary blockers that the user can resolve; use pause_goal({reason, suggestedAction?}) for that case.",
3150
- "Always pass a concrete one-sentence reason. After abort_goal returns, stop and do not call other tools in the same turn.",
3151
- ],
3152
- parameters: Type.Object({
3153
- reason: Type.String({ description: "One-sentence reason for abandoning the current goal. Plain language, not an apology." }),
3154
- }),
3155
- executionMode: "sequential",
3156
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3157
- reconcileFocusedGoalFromDisk(ctx);
3158
- const reason = params.reason.trim();
3159
- if (!reason) throw new Error("abort_goal requires a non-empty reason.");
3160
- const abortGate = validateGoalAbort({ goal: state.goal, runningGoalId, reason });
3161
- if (!abortGate.ok) {
3162
- return {
3163
- content: [{ type: "text", text: abortGate.message }],
3164
- details: goalDetails(state.goal),
3165
- };
3166
- }
3167
- if (!state.goal) throw new Error("Goal disappeared during abort validation.");
3168
- const abortedGoalId = state.goal.id;
3169
-
3170
- // Account for any remaining elapsed time before abandoning the run.
3171
- accountProgress(ctx);
3172
- state.goal = mergeGoalPromptFromDisk(ctx, state.goal);
3173
- state.goal = buildAbortedByAgentGoal(state.goal, { reason, updatedAt: nowIso() });
3174
- const archived = archiveCurrentGoal(ctx, "agent");
3175
- resetGetGoalNudgeState(abortedGoalId);
3176
- setGoal(null, ctx, true, "aborted");
3177
- markTurnStopped(abortedGoalId);
3178
-
3179
- const archiveLine = archived?.archivedPath ? `\nArchive: ${archived.archivedPath}` : "";
3180
- ctx.ui.notify(
3181
- `Goal aborted by agent.\nReason: ${truncateText(reason, 200)}${archiveLine}`,
3182
- "warning",
3183
- );
3184
- // Append ledger event for abort
3185
- try {
3186
- appendGoalEvent(ctx, {
3187
- type: "goal_aborted",
3188
- goalId: abortedGoalId,
3189
- reason,
3190
- archivePath: archived?.archivedPath,
3191
- at: nowIso(),
3192
- });
3193
- } catch {
3194
- // Ledger append failure should not crash abort
3195
- }
3196
- return {
3197
- content: [{
3198
- type: "text",
3199
- text: `Goal aborted. Reason: ${reason}${archiveLine}\nThe goal has been archived and cleared. Stop now; do not start another tool call.`,
3200
- }],
3201
- details: goalDetails(state.goal),
3202
- terminate: true,
3203
- };
3204
- },
3205
- renderCall(args, theme) {
3206
- return new Text(theme.fg("toolTitle", "abort_goal ") + theme.fg("warning", truncateText(args?.reason ?? "", 80)), 0, 0);
3207
- },
3208
- renderResult(result, _options, theme) {
3209
- return renderGoalResult(result, theme);
3210
- },
3211
- }));
3212
-
3213
- pi.registerTool(defineTool({
3214
- name: SISYPHUS_STEP_TOOL_NAME,
3215
- label: "Sisyphus Step Complete (Legacy)",
3216
- description: "Legacy compatibility tool. Current Sisyphus mode is a prompt/criteria style and no longer uses schema-tracked step completion.",
3217
- promptSnippet: "Legacy no-op: Sisyphus no longer requires step_complete.",
3218
- promptGuidelines: [
3219
- "Do not call this in normal operation. Sisyphus mode shares the normal goal lifecycle and completion gate.",
3220
- "Call complete_goal only when the full objective is actually satisfied.",
3221
- ],
3222
- parameters: Type.Object({
3223
- stepIndex: Type.Integer({ minimum: 1, description: "Legacy step index. Ignored." }),
3224
- evidence: Type.String({ description: "Legacy evidence text. Ignored by the schema." }),
3225
- verifyCommand: Type.Optional(Type.String({ description: "Legacy field. Not executed." })),
3226
- }),
3227
- executionMode: "sequential",
3228
- async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
3229
- return {
3230
- content: [{ type: "text", text: "step_complete is no longer required. Sisyphus is now a prompt/criteria style that uses the normal goal lifecycle. Continue working from the objective, or call complete_goal only when the full objective is actually satisfied." }],
3231
- details: goalDetails(state.goal),
3232
- };
3233
- },
3234
- renderCall(args, theme) {
3235
- return new Text(theme.fg("toolTitle", "step_complete legacy ") + theme.fg("muted", `#${args?.stepIndex ?? "?"}`), 0, 0);
3236
- },
3237
- renderResult(result, _options, theme) {
3238
- return renderGoalResult(result, theme);
3239
- },
3240
- }));
3241
-
3242
- // ── propose_task_list ──────────────────────────────────────────────────
3243
- pi.registerTool(defineTool({
3244
- name: PROPOSE_TASK_LIST_TOOL_NAME,
3245
- label: "Propose Task List",
3246
- description: "Propose a structured task list for the current goal. Mirrors the propose_goal_tweak pattern: shows a confirmation dialog and stops the turn.",
3247
- promptSnippet: "Propose a task list with confirmation. Stops the turn after confirmation.",
3248
- promptGuidelines: [
3249
- "Use propose_task_list after a goal is confirmed, on the first continuation turn, if the objective naturally decomposes into trackable milestones.",
3250
- "Do not add a task list for simple, single-step goals.",
3251
- "If a task list already exists on the goal, only call propose_task_list to restructure it when (a) the user explicitly asks for a change, or (b) the goal objective or requirements have structurally changed. Do not restructure the task list autonomously.",
3252
- "Existing tasks with matching IDs preserve their status/evidence/timestamps; new IDs start as pending; removed IDs are gone.",
3253
- "After confirmation the turn stops; the next continuation will arrive automatically.",
3254
- "You may optionally specify a verificationContract per task to define what verification evidence is required before completing that task.",
3255
- ],
3256
- parameters: Type.Object({
3257
- tasks: Type.Array(Type.Object({
3258
- id: Type.String({ description: "Short stable slug e.g. 'task-1'" }),
3259
- title: Type.String({ description: "Human-readable task title" }),
3260
- verificationContract: Type.Optional(Type.String({ description: "Optional verification contract for this task — what evidence is required before marking it complete." })),
3261
- lightweightSubtasks: Type.Optional(Type.Boolean({ description: "If true, subtasks are lightweight (no completion enforcement). Default false (full subtasks)." })),
3262
- subtasks: Type.Optional(Type.Any({ description: "Optional recursive array of sub-tasks (same shape as parent). Nested up to subtaskDepth (default 1, from settings)." })),
3263
- }), { description: "Array of task objects with id, title, optional subtasks" }),
3264
- blockCompletion: Type.Optional(Type.Boolean({ description: "If true, warns when pending tasks remain during complete_goal. Default false." })),
3265
- changeSummary: Type.Optional(Type.String({ description: "Optional summary of the task list proposal" })),
3266
- }),
3267
- executionMode: "sequential",
3268
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3269
- reconcileFocusedGoalFromDisk(ctx);
3270
- if (!state.goal) {
3271
- return {
3272
- content: [{ type: "text", text: "No goal is set; propose_task_list requires an active goal." }],
3273
- details: goalDetails(state.goal),
3274
- };
3275
- }
3276
- // Reject if task lists are disabled via settings
3277
- if (loadGoalSettings(ctx.cwd).disableTasks) {
3278
- return {
3279
- content: [{ type: "text", text: "propose_task_list is disabled by settings (disableTasks: true)." }],
3280
- details: goalDetails(state.goal),
3281
- };
3282
- }
3283
- const settings = loadGoalSettings(ctx.cwd);
3284
- const gate = validateTaskListProposal({ goal: state.goal, tasks: params.tasks as GoalTask[], maxSubtaskDepth: settings.subtaskDepth });
3285
- if (!gate.ok) {
3286
- return {
3287
- content: [{ type: "text", text: gate.message }],
3288
- details: goalDetails(state.goal),
3289
- };
3290
- }
3291
- const blockCompletion = params.blockCompletion === true;
3292
- const now = nowIso();
3293
- const existingTasks = state.goal.taskList?.tasks ?? [];
3294
- const existingById = new Map(existingTasks.map((t) => [t.id, t]));
3295
-
3296
- // Merge: existing tasks with matching IDs preserve status/timestamps
3297
- function mergeTask(input: GoalTask): GoalTask {
3298
- const existing = existingById.get(input.id);
3299
- const base: GoalTask = existing
3300
- ? {
3301
- ...existing,
3302
- title: input.title,
3303
- verificationContract: input.verificationContract ?? existing.verificationContract,
3304
- lightweightSubtasks: input.lightweightSubtasks ?? existing.lightweightSubtasks,
3305
- }
3306
- : {
3307
- id: input.id,
3308
- title: input.title,
3309
- status: "pending" as const,
3310
- verificationContract: input.verificationContract || undefined,
3311
- lightweightSubtasks: input.lightweightSubtasks || undefined,
3312
- };
3313
- if (input.subtasks && input.subtasks.length > 0) {
3314
- base.subtasks = input.subtasks.map((child) => mergeTask(child));
3315
- }
3316
- return base;
3317
- }
3318
- const mergedTasks = params.tasks.map((p) => mergeTask(p as GoalTask));
3319
-
3320
- const taskList: GoalTaskList = {
3321
- tasks: mergedTasks,
3322
- blockCompletion,
3323
- proposedAt: now,
3324
- };
3325
-
3326
- // Show full proposed task list in confirmation dialog (with subtasks)
3327
- function renderTaskLines(tasks: GoalTask[], indent = 0): string[] {
3328
- const prefix = " ".repeat(indent);
3329
- const lines: string[] = [];
3330
- for (const t of tasks) {
3331
- const marker = t.status === "complete" ? "[x]" : t.status === "skipped" ? "[~]" : "[ ]";
3332
- const lw = t.lightweightSubtasks ? " (lightweight)" : "";
3333
- lines.push(`${prefix}${marker} ${t.id}: ${t.title}${lw}`);
3334
- if (t.subtasks && t.subtasks.length > 0) {
3335
- lines.push(...renderTaskLines(t.subtasks, indent + 1));
3336
- }
3337
- }
3338
- return lines;
3339
- }
3340
- const taskLines = renderTaskLines(taskList.tasks);
3341
- const gateLabel = blockCompletion ? " (blockCompletion enabled)" : "";
3342
- const proposalText = [`Proposed task list${gateLabel}:`, "", ...taskLines].join("\n");
3343
-
3344
- const dialogResult = await showStructuredProposalDialog(ctx, {
3345
- id: nextGoalProposalId("task-list"),
3346
- kind: "task-list",
3347
- focus: "goal",
3348
- title: "Confirm Task List",
3349
- currentObjective: state.goal.objective,
3350
- tasks: taskList.tasks,
3351
- blockCompletion,
3352
- auditorEnabledDefault: !state.goal.skipAuditor,
3353
- }, proposalText, "goal", !state.goal.skipAuditor);
3354
- if (dialogResult.decision !== "confirm") {
3355
- return {
3356
- content: [{ type: "text", text: "Task list proposal declined." }],
3357
- details: goalDetails(state.goal),
3358
- };
3359
- }
3360
- // Persist any auditor toggle change
3361
- if (state.goal) {
3362
- state.goal = { ...state.goal, skipAuditor: !dialogResult.auditorEnabled };
3363
- }
3364
-
3365
- // Apply
3366
- state.goal = mergeGoalPromptFromDisk(ctx, state.goal);
3367
- if (!state.goal) {
3368
- return {
3369
- content: [{ type: "text", text: "Goal disappeared during task list proposal." }],
3370
- details: goalDetails(null),
3371
- };
3372
- }
3373
- state.goal = { ...state.goal, taskList, updatedAt: now };
3374
- setGoal(state.goal, ctx);
3375
- markTurnStopped(state.goal.id);
3376
- resetGetGoalNudgeState(state.goal.id);
3377
- syncGoalTools();
3378
- updateUI(ctx);
3379
-
3380
- // Append ledger event
3381
- try {
3382
- appendGoalEvent(ctx, {
3383
- type: "task_list_set",
3384
- goalId: state.goal.id,
3385
- taskCount: taskList.tasks.length,
3386
- blockCompletion,
3387
- at: now,
3388
- });
3389
- } catch {
3390
- // Ledger failure should not block task list proposal
3391
- }
3392
-
3393
- return {
3394
- content: [{ type: "text", text: `Task list proposed and confirmed. ${taskList.tasks.length} task${taskList.tasks.length === 1 ? "" : "s"} set.${gateLabel}` }],
3395
- details: goalDetails(state.goal),
3396
- terminate: true,
3397
- };
3398
- },
3399
- renderCall(args, theme) {
3400
- const summary = args?.changeSummary ? truncateText(args.changeSummary, 80) : `${args?.tasks?.length ?? 0} tasks`;
3401
- return new Text(theme.fg("toolTitle", "propose_task_list ") + theme.fg("muted", summary), 0, 0);
3402
- },
3403
- renderResult(result, _options, theme) {
3404
- return renderGoalResult(result, theme);
3405
- },
3406
- }));
3407
-
3408
- // ── complete_task ─────────────────────────────────────────────────────
3409
- pi.registerTool(defineTool({
3410
- name: COMPLETE_TASK_TOOL_NAME,
3411
- label: "Complete Task",
3412
- description: "Mark a task as complete within the current goal's task list. Does NOT stop the turn — the agent can continue working.",
3413
- promptSnippet: "Mark a task done and continue. Does not stop the turn.",
3414
- promptGuidelines: [
3415
- "Use complete_task to mark a task as complete with optional evidence text (max 200 characters).",
3416
- "The turn does NOT stop after complete_task — you may continue with other work.",
3417
- "If the task has a verificationContract, you MUST provide a verificationSummary that addresses it.",
3418
- ],
3419
- parameters: Type.Object({
3420
- taskId: Type.String({ description: "Task id to mark as complete" }),
3421
- evidence: Type.Optional(Type.String({ description: "Optional evidence note (max 200 characters)" })),
3422
- verificationSummary: Type.Optional(Type.String({ description: "Verification evidence for this task. Required if the task has a verificationContract." })),
3423
- }),
3424
- executionMode: "sequential",
3425
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3426
- reconcileFocusedGoalFromDisk(ctx);
3427
- if (loadGoalSettings(ctx.cwd).disableTasks) {
3428
- return {
3429
- content: [{ type: "text", text: "complete_task is disabled by settings (disableTasks: true)." }],
3430
- details: goalDetails(state.goal),
3431
- };
3432
- }
3433
- const gate = validateTaskCompletion({ goal: state.goal, taskId: params.taskId });
3434
- if (!gate.ok) {
3435
- return {
3436
- content: [{ type: "text", text: gate.message }],
3437
- details: goalDetails(state.goal),
3438
- };
3439
- }
3440
- if (!state.goal?.taskList) throw new Error("Task list disappeared during task completion.");
3441
-
3442
- // Check verification contract for the task (skip if contracts disabled)
3443
- const settings = loadGoalSettings(ctx.cwd);
3444
- const taskToComplete = findTaskInTree(state.goal.taskList.tasks, params.taskId);
3445
- if (!settings.disableContracts) {
3446
- const contractGate = validateVerificationSummary({
3447
- verificationContract: taskToComplete?.verificationContract,
3448
- verificationSummary: params.verificationSummary,
3449
- });
3450
- if (!contractGate.ok) {
3451
- return {
3452
- content: [{ type: "text", text: contractGate.message }],
3453
- details: goalDetails(state.goal),
3454
- };
3455
- }
3456
- }
3457
-
3458
- // Check subtask completion (full subtasks only)
3459
- if (taskToComplete) {
3460
- const subtaskGate = checkSubtasksComplete(taskToComplete);
3461
- if (subtaskGate) {
3462
- return {
3463
- content: [{ type: "text", text: subtaskGate }],
3464
- details: goalDetails(state.goal),
3465
- };
3466
- }
3467
- }
3468
-
3469
- const now = nowIso();
3470
- const evidence = params.evidence?.trim().slice(0, 200) || undefined;
3471
- const updatedTasks = updateTaskInTree(state.goal.taskList.tasks, params.taskId, (t) => ({
3472
- ...t,
3473
- status: "complete" as const,
3474
- completedAt: now,
3475
- evidence,
3476
- }));
3477
- state.goal = mergeGoalPromptFromDisk(ctx, state.goal);
3478
- if (!state.goal || !state.goal.taskList) throw new Error("Goal disappeared during task completion.");
3479
- state.goal = {
3480
- ...state.goal,
3481
- taskList: { ...state.goal.taskList, blockCompletion: state.goal.taskList.blockCompletion, tasks: updatedTasks },
3482
- updatedAt: now,
3483
- };
3484
- setGoal(state.goal, ctx);
3485
- syncGoalTools();
3486
- updateUI(ctx);
3487
-
3488
- // Append ledger event
3489
- try {
3490
- appendGoalEvent(ctx, {
3491
- type: "task_complete",
3492
- goalId: state.goal.id,
3493
- taskId: params.taskId,
3494
- evidence,
3495
- at: now,
3496
- });
3497
- } catch {
3498
- // Ledger failure should not block task completion
3499
- }
3500
-
3501
- const taskSummary = buildTaskSummary(state.goal.taskList!);
3502
- return {
3503
- content: [{ type: "text", text: `${params.taskId} complete. ${taskSummary}.` }],
3504
- details: goalDetails(state.goal),
3505
- };
3506
- },
3507
- renderCall(args, theme) {
3508
- return new Text(theme.fg("toolTitle", "complete_task ") + theme.fg("success", args?.taskId ?? ""), 0, 0);
3509
- },
3510
- renderResult(result, _options, theme) {
3511
- return renderGoalResult(result, theme);
3512
- },
3513
- }));
3514
-
3515
- // ── skip_task ─────────────────────────────────────────────────────────
3516
- pi.registerTool(defineTool({
3517
- name: SKIP_TASK_TOOL_NAME,
3518
- label: "Skip Task",
3519
- description: "Skip a pending task in the current goal's task list. Does NOT stop the turn — the agent can continue working.",
3520
- promptSnippet: "Skip a task with a reason. Does not stop the turn.",
3521
- promptGuidelines: [
3522
- "Use skip_task to mark a task as skipped with a required reason.",
3523
- "The turn does NOT stop after skip_task — you may continue with other work.",
3524
- "Only skip a task when the user explicitly asks you to, or when the task directly contradicts a hard constraint (e.g. an impossible requirement).",
3525
- "Do NOT autonomously skip tasks to avoid work, or because they look optional, inconvenient, or out of scope. When in doubt, ask the user first.",
3526
- "If skip_task is called on an already-skipped task, it toggles back to pending (unskip).",
3527
- ],
3528
- parameters: Type.Object({
3529
- taskId: Type.String({ description: "Task id to skip" }),
3530
- reason: Type.String({ description: "Non-empty reason for skipping this task" }),
3531
- }),
3532
- executionMode: "sequential",
3533
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3534
- reconcileFocusedGoalFromDisk(ctx);
3535
- if (loadGoalSettings(ctx.cwd).disableTasks) {
3536
- return {
3537
- content: [{ type: "text", text: "skip_task is disabled by settings (disableTasks: true)." }],
3538
- details: goalDetails(state.goal),
3539
- };
3540
- }
3541
- const gate = validateTaskSkip({ goal: state.goal, taskId: params.taskId, reason: params.reason });
3542
- if (!gate.ok) {
3543
- return {
3544
- content: [{ type: "text", text: gate.message }],
3545
- details: goalDetails(state.goal),
3546
- };
3547
- }
3548
- if (!state.goal?.taskList) throw new Error("Task list disappeared during task skip.");
3549
- const now = nowIso();
3550
- const wasAlreadySkipped = findTaskInTree(state.goal.taskList.tasks, params.taskId)?.status === "skipped";
3551
-
3552
- const updatedTasks = updateTaskInTree(state.goal.taskList.tasks, params.taskId, (t) => {
3553
- if (t.status === "skipped") {
3554
- // Toggle back to pending — clear skip state, do NOT cascade to subtasks
3555
- const { skippedAt, skipReason, ...rest } = t;
3556
- return { ...rest, status: "pending" as const };
3557
- }
3558
- // First-time skip: cascade to all subtasks (full subtasks only)
3559
- const base = { ...t, status: "skipped" as const, skippedAt: now, skipReason: params.reason.trim() };
3560
- if (t.subtasks && t.subtasks.length > 0 && !t.lightweightSubtasks) {
3561
- return skipAllSubtasks(base, now, params.reason.trim());
3562
- }
3563
- return base;
3564
- });
3565
- state.goal = mergeGoalPromptFromDisk(ctx, state.goal);
3566
- if (!state.goal || !state.goal.taskList) throw new Error("Goal disappeared during task skip.");
3567
- state.goal = {
3568
- ...state.goal,
3569
- taskList: { ...state.goal.taskList, blockCompletion: state.goal.taskList.blockCompletion, tasks: updatedTasks },
3570
- updatedAt: now,
3571
- };
3572
- setGoal(state.goal, ctx);
3573
- syncGoalTools();
3574
- updateUI(ctx);
3575
-
3576
- // Append ledger event
3577
- try {
3578
- if (wasAlreadySkipped) {
3579
- appendGoalEvent(ctx, {
3580
- type: "task_skipped",
3581
- goalId: state.goal.id,
3582
- taskId: params.taskId,
3583
- reason: "unskipped (toggle via skip_task)",
3584
- at: now,
3585
- });
3586
- } else {
3587
- appendGoalEvent(ctx, {
3588
- type: "task_skipped",
3589
- goalId: state.goal.id,
3590
- taskId: params.taskId,
3591
- reason: params.reason.trim(),
3592
- at: now,
3593
- });
3594
- }
3595
- } catch {
3596
- // Ledger failure should not block task skip
3597
- }
3598
-
3599
- const taskSummary = buildTaskSummary(state.goal.taskList!);
3600
- const action = wasAlreadySkipped ? "unsikpped" : "skipped";
3601
- return {
3602
- content: [{ type: "text", text: `${params.taskId} ${action}. ${taskSummary}.` }],
3603
- details: goalDetails(state.goal),
3604
- };
3605
- },
3606
- renderCall(args, theme) {
3607
- return new Text(theme.fg("toolTitle", "skip_task ") + theme.fg("warning", args?.taskId ?? ""), 0, 0);
3608
- },
3609
- renderResult(result, _options, theme) {
3610
- return renderGoalResult(result, theme);
3611
- },
3612
- }));
3613
-
3614
- pi.on("context", async (event): Promise<{ messages: typeof event.messages } | undefined> => {
3615
- let changed = false;
3616
- const latestGoalEventIndex = new Map<string, number>();
3617
- event.messages.forEach((message, index) => {
3618
- const queuedGoalId = goalEventMessageId(message as { customType?: string; details?: unknown; content?: unknown });
3619
- if (queuedGoalId) latestGoalEventIndex.set(queuedGoalId, index);
3620
- });
3621
-
3622
- const messages = event.messages.map((message, index) => {
3623
- const candidate = message as { customType?: string; details?: unknown; content?: unknown };
3624
- const queuedGoalId = goalEventMessageId(candidate);
3625
- if (!queuedGoalId) return message;
3626
- const queuedEpoch = goalEventEpoch(candidate);
3627
- if (
3628
- state.goal?.id === queuedGoalId
3629
- && (state.goal.status === "active")
3630
- && state.goal.autoContinue
3631
- && isCurrentContinuationEpoch(queuedEpoch)
3632
- && latestGoalEventIndex.get(queuedGoalId) === index
3633
- ) return message;
3634
- changed = true;
3635
- if (index === event.messages.length - 1) {
3636
- checkpointGoalId = queuedGoalId;
3637
- checkpointBlocked = true;
3638
- clearContinuationState();
3639
- }
3640
- const details = asRecord(candidate.details) ?? {};
3641
- return {
3642
- ...message,
3643
- content: staleContinuationPrompt(queuedGoalId, state.goal),
3644
- display: false,
3645
- details: {
3646
- ...details,
3647
- kind: "stale",
3648
- goalId: queuedGoalId,
3649
- currentGoalId: state.goal?.id ?? null,
3650
- currentStatus: state.goal?.status ?? null,
3651
- },
3652
- } as typeof message;
619
+ pi.on("agent_settled", (_event, ctx) => {
620
+ const completed = state.goal?.status === "complete" ? state.goal : null;
621
+ if (!completed) return;
622
+ persist(null, ctx);
623
+ publishReceipt({
624
+ kind: "goal_completed",
625
+ level: "info",
626
+ ...goalFields(completed),
627
+ completionSummary: completed.completion?.summary,
628
+ auditorReport: completed.completion?.auditorReport,
629
+ message: "Goal completed.",
630
+ tuiMessage: "Goal completed.",
3653
631
  });
3654
- return changed ? { messages } : undefined;
3655
- });
3656
-
3657
- pi.on("turn_start", async (_event, ctx) => {
3658
- // Per-turn flag resets (#4 + C9 fix).
3659
- advanceTurnSeq();
3660
- goalWorkToolCalledThisTurn = false;
3661
- syncGoalTools();
3662
- beginAccounting();
3663
- updateUI(ctx);
3664
- });
3665
-
3666
- // #4 + C9 fix + Phase 5 C3: gate in-turn tool calls based on lifecycle state.
3667
- pi.on("tool_call", async (event, ctx) => {
3668
- const stoppedGoalId = currentTurnStoppedGoalId();
3669
- // Post-stop in-turn block (C9 0ad8 fix): after pause_goal / abort_goal /
3670
- // complete_goal / propose_goal_tweak fires in this turn, block all subsequent tool calls except
3671
- // read-only inspection. Forces the agent to yield the turn instead of "fixing"
3672
- // the situation by creating extra files etc.
3673
- if (stoppedGoalId !== null && !POST_STOP_ALLOWED_TOOL_SET.has(event.toolName)) {
3674
- return {
3675
- block: true,
3676
- reason: `The goal was already stopped earlier in this turn (goalId=${stoppedGoalId}). ` +
3677
- `Do not call more tools; end the turn with a brief summary and yield to the user.`,
3678
- };
3679
- }
3680
- // Stale checkpoint guard: if the turn was triggered by a queued continuation
3681
- // for a goal that is no longer active/autoContinue, block work tools.
3682
- if (checkpointGoalId !== null && (checkpointBlocked || !isActionableContinuationGoal(checkpointGoalId)) && isStaleCheckpointBlockedToolCall(event.toolName)) {
3683
- // Block the tool call with a stale-checkpoint message.
3684
- return {
3685
- block: true,
3686
- reason: `Cannot call ${event.toolName}: the goal checkpoint that triggered this turn is no longer active. ` +
3687
- `Goal ${checkpointGoalId} has been paused, cleared, or replaced. ` +
3688
- `End the turn with a brief summary and yield to the user.`,
3689
- };
3690
- }
3691
- // Phase 5 soft gate relaxation: active-goal question block and repeated get_goal
3692
- // block are removed. The agent is trusted to prefer work tools; prompts nudge
3693
- // toward concrete work without hard-stopping the turn.
3694
- if (confirmationIntent === null && tweakDraftingFor === null && state.goal?.status === "active") {
3695
- if (event.toolName === "get_goal") {
3696
- const prior = activeGetGoalTurnsByGoalId.get(state.goal.id) ?? 0;
3697
- activeGetGoalTurnsByGoalId.set(state.goal.id, prior + 1);
3698
- // Nudge only: do not hard-block, but warn in tool response via get_goal execute
3699
- }
3700
- }
3701
- // Track for #4 empty-turn gate.
3702
- if (isMeaningfulProgressToolCall(event.toolName, asRecord(event)?.args)) {
3703
- if (state.goal?.id) activeGetGoalTurnsByGoalId.delete(state.goal.id);
3704
- goalWorkToolCalledThisTurn = true;
3705
- }
3706
- return;
3707
- });
3708
-
3709
- pi.on("tool_execution_end", async (_event, ctx) => {
3710
- accountProgress(ctx);
3711
- });
3712
-
3713
- pi.on("turn_end", async (event, ctx) => {
3714
- const message = event.message as AssistantMessageLike;
3715
- if (confirmationIntent !== null || tweakDraftingFor !== null) return;
3716
- const tokens = assistantTurnTokens(message);
3717
- accountProgress(ctx, { completedTurnTokens: tokens });
3718
-
3719
- if (isAbortedAssistantMessage(message)) {
3720
- pauseActiveGoal(ctx);
3721
- clearCheckpointBlock();
3722
- return;
3723
- }
3724
- if (deferAfterCoreContextOverflow(ctx, [message])) {
3725
- clearCheckpointBlock();
3726
- return;
3727
- }
3728
- refreshGoalDisplayFromDisk(ctx);
3729
-
3730
- // Archive a goal that was marked complete by complete_goal but whose archival
3731
- // was deferred so the agent could see/recognize the audit result first.
3732
- // This runs after the agent's turn ends — the agent has now seen the result.
3733
- if (state.goal?.status === "complete" && !state.goal?.archivedPath) {
3734
- const completedGoal = state.goal;
3735
- const archived = archiveGoalFile(ctx, completedGoal);
3736
- resetGetGoalNudgeState(completedGoal.id);
3737
- goalsById.delete(completedGoal.id);
3738
- focusedGoalId = null;
3739
- appendFocusEntry(null, "completed");
3740
- syncGoalTools();
3741
- updateUI(ctx);
3742
- try {
3743
- appendGoalEvent(ctx, {
3744
- type: "goal_completed",
3745
- goalId: completedGoal.id,
3746
- archivePath: archived.archivedPath,
3747
- at: nowIso(),
3748
- });
3749
- } catch {
3750
- // Ledger append failure should not crash completion
3751
- }
3752
- }
3753
-
3754
- // If the assistant ended a turn without queuing more tool calls, push a continuation right away.
3755
- // #4: only queue if some real work was done this turn — otherwise the model is
3756
- // just chatting and we should not keep firing turns on noise.
3757
- if (
3758
- !isToolUseAssistantMessage(message)
3759
- && state.goal?.status === "active"
3760
- && state.goal.autoContinue
3761
- && goalWorkToolCalledThisTurn
3762
- ) {
3763
- if (isLengthAssistantMessage(message)) {
3764
- deferContinuationUntilAfterCompaction(state.goal.id);
3765
- clearCheckpointBlock();
3766
- return;
3767
- }
3768
- queueContinuation(ctx);
3769
- }
3770
- clearCheckpointBlock();
3771
- });
3772
-
3773
- pi.on("message_end", async (event, ctx) => {
3774
- if (isAbortedAssistantMessage(event.message)) pauseActiveGoal(ctx);
3775
- const raw = asRecord(event.message);
3776
- if (raw?.role === "custom" && raw.customType === GOAL_EVENT_ENTRY && raw.display !== false) {
3777
- return { message: { ...event.message, display: false } as typeof event.message };
3778
- }
3779
- });
3780
-
3781
- pi.on("session_start", async (event, ctx) => {
3782
- loadState(ctx);
3783
- syncGoalTools();
3784
- syncTerminalInputPause(ctx);
3785
- if (event.reason === "resume" && !state.goal && openGoals().length > 1 && ctx.hasUI) {
3786
- await focusGoalCommand(ctx);
3787
- }
3788
- // Codex behavior: prompt before reactivating a paused goal on resume.
3789
- if (event.reason === "resume" && state.goal?.status === "paused" && ctx.hasUI) {
3790
- const current = state.goal;
3791
- const shouldResume = await ctx.ui.confirm("Resume paused goal?", `Goal: ${current.objective}`);
3792
- if (shouldResume) {
3793
- setGoal({ ...current, status: "active", autoContinue: true, stopReason: undefined, pauseReason: undefined, pauseSuggestedAction: undefined }, ctx);
3794
- }
3795
- }
3796
- beginAccounting();
3797
- queueContinuation(ctx, true);
3798
- });
3799
-
3800
- pi.on("session_before_compact", async (_event, ctx) => {
3801
- accountProgress(ctx);
3802
- deferContinuationUntilAfterCompaction(
3803
- state.goal?.status === "active" && state.goal.autoContinue ? state.goal.id : null,
3804
- );
3805
- });
3806
-
3807
- pi.on("session_compact", async (event, ctx) => {
3808
- if (confirmationIntent !== null || tweakDraftingFor !== null) return;
3809
- if (state.goal) persist(ctx);
3810
- beginAccounting();
3811
- // Arm a deterministic compaction summary for the next agent turn.
3812
- // This replaces the generic reminder with artifact-backed state.
3813
- if (shouldArmPostCompactReminder(state.goal)) {
3814
- postCompactReminderPending = true;
3815
- }
3816
- const goalId = postCompactionContinuationGoalId;
3817
- deferContinuationUntilAfterCompaction(goalId);
3818
- postCompactionContinuationGoalId = null;
3819
- // Pi core owns the immediate recovery turn. Normal turn_end handling will
3820
- // schedule later goal work if that recovered turn makes meaningful progress.
3821
- // Keep the optional cast until this package's minimum Pi version exposes willRetry.
3822
- if ((event as typeof event & { willRetry?: boolean }).willRetry === true) return;
3823
- if (isActionableContinuationGoal(goalId)) queueContinuation(ctx, true);
3824
- });
3825
-
3826
- pi.on("session_tree", async (_event, ctx) => {
3827
- loadState(ctx);
3828
- syncTerminalInputPause(ctx);
3829
- beginAccounting();
3830
- queueContinuation(ctx, true);
3831
- });
3832
-
3833
- pi.on("before_agent_start", async (event, ctx) => {
3834
- advanceTurnSeq();
3835
- syncGoalTools();
3836
- const currentSystemPrompt = () => ctx.getSystemPrompt?.() || event.systemPrompt;
3837
- const incomingGoalId = extractGoalIdFromInjectedMessage(event.prompt ?? "");
3838
- const incomingEpoch = extractContinuationEpochFromInjectedMessage(event.prompt ?? "");
3839
-
3840
- if (confirmationIntent !== null) {
3841
- checkpointGoalId = null;
3842
- checkpointBlocked = false;
3843
- clearContinuationState();
3844
- clearActiveAccounting();
3845
- runningGoalId = null;
3846
- return { systemPrompt: currentSystemPrompt() };
3847
- }
3848
-
3849
- if (tweakDraftingFor !== null) {
3850
- checkpointGoalId = null;
3851
- checkpointBlocked = false;
3852
- clearContinuationState();
3853
- clearActiveAccounting();
3854
- runningGoalId = null;
3855
- return { systemPrompt: currentSystemPrompt() };
3856
- }
3857
-
3858
- // If this turn was triggered by a hidden goal checkpoint that no longer
3859
- // matches the active goal, abort the whole turn instead of letting the
3860
- // model act on a stale instruction.
3861
- if (incomingGoalId !== null) {
3862
- // Reconcile from disk to pick up any external state changes before
3863
- // evaluating whether the checkpoint is actionable.
3864
- reconcileFocusedGoalFromDisk(ctx);
3865
- checkpointGoalId = incomingGoalId;
3866
- checkpointBlocked = false;
3867
- clearContinuationState();
3868
- if (!isActionableContinuationGoal(incomingGoalId) || !isCurrentContinuationEpoch(incomingEpoch)) {
3869
- checkpointBlocked = true;
3870
- try {
3871
- ctx.abort?.();
3872
- } catch {}
3873
- updateUI(ctx);
3874
- return {
3875
- systemPrompt: `${currentSystemPrompt()}\n\n${staleContinuationPrompt(incomingGoalId, state.goal)}`,
3876
- };
3877
- }
3878
- checkpointGoalId = null;
3879
- checkpointBlocked = false;
3880
- } else if (checkpointBlocked && checkpointGoalId !== null) {
3881
- // The current/latest queued continuation was rewritten by the context
3882
- // hook rather than delivered as the before_agent_start prompt. Keep the
3883
- // tool-call guard armed for this turn and give the model only the terse
3884
- // stale-checkpoint instruction.
3885
- clearContinuationState();
3886
- return {
3887
- systemPrompt: `${currentSystemPrompt()}\n\n${staleContinuationPrompt(checkpointGoalId, state.goal)}`,
3888
- };
3889
- } else {
3890
- // A user-driven turn — clear any queued continuation so we don't
3891
- // double-fire after the user's own message returns. Also reset the
3892
- // autoContinue nudge state so the user always gets a fresh chain.
3893
- clearCheckpointBlock();
3894
- clearContinuationState();
3895
- resetGetGoalNudgeState(state.goal?.id);
3896
- }
3897
-
3898
- if (!state.goal) {
3899
- runningGoalId = null;
3900
- const openCount = openGoals().length;
3901
- if (openCount > 0) {
3902
- return { systemPrompt: `${currentSystemPrompt()}\n\n${unfocusedOpenGoalsPrompt(openCount)}` };
3903
- }
3904
- return;
3905
- }
3906
- reconcileFocusedGoalFromDisk(ctx);
3907
- if (!state.goal) {
3908
- runningGoalId = null;
3909
- const openCount = openGoals().length;
3910
- if (openCount > 0) return { systemPrompt: `${currentSystemPrompt()}\n\n${unfocusedOpenGoalsPrompt(openCount)}` };
3911
- return;
3912
- }
3913
- runningGoalId = state.goal.status === "active" ? state.goal.id : null;
3914
- if (state.goal.status === "complete") return;
3915
- if (state.goal.status === "paused") {
3916
- const current = state.goal;
3917
- const pauseExtras: string[] = [];
3918
- if (current.stopReason === "agent") {
3919
- pauseExtras.push("");
3920
- pauseExtras.push(`Pause reason (you set this in a prior turn via pause_goal): ${current.pauseReason ?? "(unknown)"}`);
3921
- if (current.pauseSuggestedAction) pauseExtras.push(`You suggested: ${current.pauseSuggestedAction}`);
3922
- }
3923
- // Inject durable auditor feedback if available
3924
- let auditorExtra = "";
3925
- try {
3926
- const ledger = readGoalLedger(ctx);
3927
- const auditorResult = latestAuditorResultForGoal(ledger.events, current.id);
3928
- if (auditorResult && auditorResult.verdict === "disapproved") {
3929
- auditorExtra = `\n\n[AUDITOR REJECTION] An independent auditor previously rejected a completion request for this goal. Reason: ${auditorResult.report.slice(0, 300)}\nAddress the auditor's objections before requesting completion again.`;
3930
- }
3931
- } catch {
3932
- // Ledger read failure should not break the prompt
3933
- }
3934
- return {
3935
- systemPrompt: `${currentSystemPrompt()}\n\n[PI GOAL PAUSED goalId=${current.id}]\n${untrustedObjectiveBlock(current)}${pauseExtras.join("\n")}${auditorExtra}\n\nThe goal is paused. Do not autonomously continue substantive work unless the user resumes it with /goal-resume. If the user explicitly asks to finish or abandon the paused goal, or the objective is already satisfied based on available evidence, you may call complete_goal or abort_goal without resuming. Do not call pause_goal again.`,
3936
- };
3937
- }
3938
- const activeGoal = state.goal;
3939
- const settings = loadGoalSettings(ctx.cwd);
3940
- let prompt = goalPrompt(activeGoal, settings);
3941
- // Inject durable auditor feedback if the latest result was a rejection
3942
- try {
3943
- const ledger = readGoalLedger(ctx);
3944
- const auditorResult = latestAuditorResultForGoal(ledger.events, activeGoal.id);
3945
- if (auditorResult && auditorResult.verdict === "disapproved" && ledger.events.some((e) => e.type === "completion_requested" && e.goalId === activeGoal.id)) {
3946
- prompt = `${prompt}\n\n[AUDITOR REJECTION goalId=${activeGoal.id}]\nAn independent auditor previously rejected a completion request for this goal. Reason: ${auditorResult.report.slice(0, 300)}\nAddress the auditor's objections before requesting completion again.`;
3947
- }
3948
- } catch {
3949
- // Ledger read failure should not break the prompt
3950
- }
3951
- if (shouldInjectPostCompactReminder({ pending: postCompactReminderPending, goal: activeGoal })) {
3952
- postCompactReminderPending = false;
3953
- // Use deterministic compaction summary instead of generic reminder
3954
- try {
3955
- const ledger = readGoalLedger(ctx);
3956
- const compaction = buildCompactionSummary({ goalsById, focusedGoalId, ledgerEvents: ledger.events });
3957
- prompt = `${prompt}\n\n[POST-COMPACTION RESYNC goalId=${activeGoal.id}]\n${compaction}`;
3958
- } catch {
3959
- prompt = `${prompt}\n\n[POST-COMPACTION RESYNC goalId=${state.goal.id}]\nThe conversation was just compacted. Re-read the objective and continue from the actual artifacts/state; do not rely on memory of the prior chat.`;
3960
- }
3961
- }
3962
- return { systemPrompt: `${currentSystemPrompt()}\n\n${prompt}` };
3963
- });
3964
-
3965
- pi.on("agent_end", async (event, ctx) => {
3966
- if (confirmationIntent !== null || tweakDraftingFor !== null) return;
3967
- const endedGoalId = runningGoalId;
3968
- runningGoalId = null;
3969
-
3970
- // Account for any tokens from aborted in-flight assistant messages so
3971
- // they are not silently lost (but charge them to the original goal).
3972
- const abortedTokens = event.messages
3973
- .filter(isAbortedAssistantMessage)
3974
- .reduce((sum, message) => sum + assistantTurnTokens(message), 0);
3975
- if (abortedTokens > 0 && endedGoalId && state.goal?.id === endedGoalId) {
3976
- accountProgress(ctx, { completedTurnTokens: abortedTokens });
3977
- }
3978
-
3979
- continuationQueuedFor = null;
3980
- if (!state.goal || state.goal.status !== "active" || !state.goal.autoContinue) return;
3981
- if (endedGoalId && state.goal.id !== endedGoalId) return;
3982
- if (!reconcileFocusedGoalFromDisk(ctx)) return;
3983
- if (hasAbortedAssistantMessage(event.messages) || ctx.signal?.aborted) {
3984
- pauseActiveGoal(ctx);
3985
- return;
3986
- }
3987
- if (deferAfterCoreContextOverflow(ctx, event.messages)) {
3988
- return;
3989
- }
3990
- if (hasLengthAssistantMessage(event.messages)) {
3991
- deferContinuationUntilAfterCompaction(state.goal.id);
3992
- persist(ctx);
3993
- updateUI(ctx);
3994
- return;
3995
- }
3996
- persist(ctx);
3997
- updateUI(ctx);
3998
- queueContinuation(ctx);
3999
632
  });
4000
633
 
4001
- pi.on("session_shutdown", async (_event, ctx) => {
4002
- accountProgress(ctx);
4003
- clearContinuationTimer();
4004
- stopStatusRefresh();
4005
- terminalInputUnsubscribe?.();
4006
- terminalInputUnsubscribe = null;
4007
- if (state.goal) persist(ctx);
634
+ pi.on("session_shutdown", () => {
635
+ cancelContinuation();
636
+ widget = null;
637
+ widgetContext = null;
4008
638
  });
4009
639
  }