@narumitw/pi-goal 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@ import {
9
9
  import type { GoalStatus } from "./prompts.js";
10
10
 
11
11
  const GOAL_STATE_ENTRY_TYPE = "goal-state";
12
+ const LEGACY_GOALS_STATE_ENTRY_TYPE = "goals-state";
12
13
  const STATE_FILE = join(
13
14
  process.env.PI_CODING_AGENT_DIR ?? join(process.env.HOME ?? ".", ".pi", "agent"),
14
15
  "pi-goal-state.json",
@@ -28,25 +29,180 @@ export interface ActiveGoal {
28
29
  activeStartedAt?: number;
29
30
  }
30
31
 
32
+ export type PendingQueueAction =
33
+ | {
34
+ kind: "prioritize";
35
+ objective: string;
36
+ tokenBudget?: number;
37
+ }
38
+ | {
39
+ kind: "advance";
40
+ goalId: string;
41
+ reason: "complete" | "skip";
42
+ completedText: string;
43
+ };
44
+
31
45
  export interface GoalStateEntryData {
32
46
  goal: ActiveGoal | null;
47
+ queue?: ActiveGoal[];
48
+ pendingAction?: PendingQueueAction;
49
+ }
50
+
51
+ export interface LoadedGoalState {
52
+ goal: ActiveGoal | undefined;
53
+ queue: ActiveGoal[];
54
+ pendingAction: PendingQueueAction | undefined;
55
+ hasExperimentalQueueState: boolean;
56
+ source: "none" | "canonical" | "legacy-goals";
57
+ }
58
+
59
+ interface SessionEntry {
60
+ type?: string;
61
+ customType?: string;
62
+ data?: unknown;
33
63
  }
34
64
 
35
65
  interface SessionContext {
36
66
  sessionManager?: {
37
- getBranch?: () => Array<{ type?: string; customType?: string; data?: unknown }>;
38
- getEntries?: () => Array<{ type?: string; customType?: string; data?: unknown }>;
67
+ getBranch?: () => SessionEntry[];
68
+ getEntries?: () => SessionEntry[];
39
69
  };
40
70
  }
41
71
 
42
- export function loadGoalFromSession(ctx: SessionContext): ActiveGoal | undefined {
72
+ export function serializeGoalState(
73
+ goal: ActiveGoal | undefined,
74
+ queue: readonly ActiveGoal[],
75
+ pendingAction: PendingQueueAction | undefined,
76
+ ): GoalStateEntryData {
77
+ return {
78
+ goal: goal ?? null,
79
+ ...(queue.length > 0 ? { queue: [...queue] } : {}),
80
+ ...(pendingAction ? { pendingAction } : {}),
81
+ };
82
+ }
83
+
84
+ export function loadGoalStateFromSession(ctx: SessionContext): LoadedGoalState {
43
85
  const entries = ctx.sessionManager?.getBranch?.() ?? ctx.sessionManager?.getEntries?.() ?? [];
44
- const entry = entries
86
+ const canonicalEntry = entries
45
87
  .filter((entry) => entry.type === "custom" && entry.customType === GOAL_STATE_ENTRY_TYPE)
46
88
  .pop();
47
- const data = entry?.data as GoalStateEntryData | undefined;
48
- if (!isGoal(data?.goal) || data.goal.status === "complete") return undefined;
49
- return normalizeLoadedGoal(data.goal);
89
+ if (canonicalEntry) return loadCanonicalGoalState(canonicalEntry.data);
90
+
91
+ const legacyEntry = entries
92
+ .filter(
93
+ (entry) => entry.type === "custom" && entry.customType === LEGACY_GOALS_STATE_ENTRY_TYPE,
94
+ )
95
+ .pop();
96
+ return legacyEntry ? loadLegacyGoalsState(legacyEntry.data) : emptyGoalState("none");
97
+ }
98
+
99
+ export function loadGoalFromSession(ctx: SessionContext): ActiveGoal | undefined {
100
+ const loaded = loadGoalStateFromSession(ctx);
101
+ if (loaded.hasExperimentalQueueState || loaded.goal?.status === "complete") return undefined;
102
+ return loaded.goal;
103
+ }
104
+
105
+ function loadCanonicalGoalState(data: unknown): LoadedGoalState {
106
+ if (!isRecord(data)) return emptyGoalState("canonical");
107
+ const rawGoal = data.goal;
108
+ if (rawGoal !== null && !isGoal(rawGoal)) return emptyGoalState("canonical");
109
+ const rawQueue = Object.hasOwn(data, "queue") ? data.queue : [];
110
+ if (!Array.isArray(rawQueue) || !rawQueue.every(isQueueGoal)) {
111
+ return emptyGoalState("canonical");
112
+ }
113
+ const pendingAction = normalizePendingQueueAction(data.pendingAction);
114
+ if (Object.hasOwn(data, "pendingAction") && !pendingAction) {
115
+ return emptyGoalState("canonical");
116
+ }
117
+
118
+ const queue = rawQueue.map(normalizeQueuedGoal);
119
+ let goal = rawGoal === null ? undefined : normalizeLoadedGoal(rawGoal);
120
+ if (goal?.status === "complete" && !pendingAction) goal = undefined;
121
+ if (!goal && (queue.length > 0 || pendingAction)) return emptyGoalState("canonical");
122
+ return {
123
+ goal,
124
+ queue,
125
+ pendingAction,
126
+ hasExperimentalQueueState:
127
+ goal?.status === "queued" || queue.length > 0 || pendingAction !== undefined,
128
+ source: "canonical",
129
+ };
130
+ }
131
+
132
+ function loadLegacyGoalsState(data: unknown): LoadedGoalState {
133
+ if (!isRecord(data)) return emptyGoalState("legacy-goals");
134
+ let rawGoals: ActiveGoal[];
135
+ if (Array.isArray(data.goals)) {
136
+ if (!data.goals.every(isGoal)) return emptyGoalState("legacy-goals");
137
+ rawGoals = data.goals.filter((goal) => goal.status !== "complete");
138
+ } else if (isGoal(data.goal) && data.goal.status !== "complete") {
139
+ rawGoals = [data.goal];
140
+ } else {
141
+ rawGoals = [];
142
+ }
143
+ const goals = rawGoals.map((goal, index) =>
144
+ index === 0 ? normalizeLoadedGoal(goal) : normalizeQueuedGoal(goal),
145
+ );
146
+ const pendingAction = normalizeLegacyPendingPrioritize(data.pendingUnshift);
147
+ if (goals.length === 0) return emptyGoalState("legacy-goals");
148
+ return {
149
+ goal: goals[0],
150
+ queue: goals.slice(1),
151
+ pendingAction,
152
+ hasExperimentalQueueState:
153
+ goals[0]?.status === "queued" || goals.length > 1 || pendingAction !== undefined,
154
+ source: "legacy-goals",
155
+ };
156
+ }
157
+
158
+ function normalizePendingQueueAction(value: unknown): PendingQueueAction | undefined {
159
+ if (!isRecord(value)) return undefined;
160
+ if (value.kind === "prioritize") {
161
+ if (!validObjective(value.objective)) return undefined;
162
+ return {
163
+ kind: "prioritize",
164
+ objective: value.objective,
165
+ tokenBudget: normalizeTokenBudget(value.tokenBudget),
166
+ };
167
+ }
168
+ if (value.kind === "advance") {
169
+ if (
170
+ typeof value.goalId !== "string" ||
171
+ !value.goalId ||
172
+ value.goalId !== value.goalId.trim() ||
173
+ (value.reason !== "complete" && value.reason !== "skip") ||
174
+ !validObjective(value.completedText)
175
+ ) {
176
+ return undefined;
177
+ }
178
+ return {
179
+ kind: "advance",
180
+ goalId: value.goalId,
181
+ reason: value.reason,
182
+ completedText: value.completedText,
183
+ };
184
+ }
185
+ return undefined;
186
+ }
187
+
188
+ function normalizeLegacyPendingPrioritize(value: unknown): PendingQueueAction | undefined {
189
+ if (!isRecord(value) || !validObjective(value.objective)) return undefined;
190
+ return {
191
+ kind: "prioritize",
192
+ objective: value.objective,
193
+ tokenBudget: normalizeTokenBudget(value.tokenBudget),
194
+ };
195
+ }
196
+
197
+ function validObjective(value: unknown): value is string {
198
+ return typeof value === "string" && Boolean(value.trim()) && value.length <= 4_000;
199
+ }
200
+
201
+ function normalizeQueuedGoal(goal: ActiveGoal): ActiveGoal {
202
+ const normalized = normalizeLoadedGoal(goal);
203
+ return normalized.status === "active"
204
+ ? { ...normalized, status: "queued", activeStartedAt: undefined }
205
+ : { ...normalized, activeStartedAt: undefined };
50
206
  }
51
207
 
52
208
  export function normalizeLoadedGoal(goal: ActiveGoal): ActiveGoal {
@@ -85,20 +241,45 @@ function readState(): Record<string, unknown> {
85
241
  }
86
242
 
87
243
  function isGoal(value: unknown): value is ActiveGoal {
88
- if (!value || typeof value !== "object") return false;
89
- const goal = value as Partial<ActiveGoal>;
244
+ if (!isRecord(value)) return false;
90
245
  return (
91
- typeof goal.id === "string" &&
92
- typeof goal.text === "string" &&
93
- ["active", "paused", "blocked", "usage_limited", "budget_limited", "complete"].includes(
94
- String(goal.status),
95
- ) &&
96
- typeof goal.startedAt === "number" &&
97
- typeof goal.updatedAt === "number" &&
98
- typeof goal.iteration === "number" &&
99
- typeof goal.tokensUsed === "number" &&
100
- typeof goal.timeUsedSeconds === "number" &&
101
- typeof goal.baselineTokens === "number" &&
102
- (goal.activeStartedAt === undefined || typeof goal.activeStartedAt === "number")
246
+ typeof value.id === "string" &&
247
+ Boolean(value.id) &&
248
+ value.id === value.id.trim() &&
249
+ validObjective(value.text) &&
250
+ [
251
+ "active",
252
+ "queued",
253
+ "paused",
254
+ "blocked",
255
+ "usage_limited",
256
+ "budget_limited",
257
+ "complete",
258
+ ].includes(String(value.status)) &&
259
+ typeof value.startedAt === "number" &&
260
+ typeof value.updatedAt === "number" &&
261
+ typeof value.iteration === "number" &&
262
+ typeof value.tokensUsed === "number" &&
263
+ typeof value.timeUsedSeconds === "number" &&
264
+ typeof value.baselineTokens === "number" &&
265
+ (value.activeStartedAt === undefined || typeof value.activeStartedAt === "number")
103
266
  );
104
267
  }
268
+
269
+ function isQueueGoal(value: unknown): value is ActiveGoal {
270
+ return isGoal(value) && value.status !== "complete";
271
+ }
272
+
273
+ function isRecord(value: unknown): value is Record<string, unknown> {
274
+ return typeof value === "object" && value !== null && !Array.isArray(value);
275
+ }
276
+
277
+ function emptyGoalState(source: LoadedGoalState["source"]): LoadedGoalState {
278
+ return {
279
+ goal: undefined,
280
+ queue: [],
281
+ pendingAction: undefined,
282
+ hasExperimentalQueueState: false,
283
+ source,
284
+ };
285
+ }
package/src/prompts.ts CHANGED
@@ -2,6 +2,7 @@ import { formatTokenCount } from "./accounting.js";
2
2
 
3
3
  export type GoalStatus =
4
4
  | "active"
5
+ | "queued"
5
6
  | "paused"
6
7
  | "blocked"
7
8
  | "usage_limited"
@@ -23,22 +24,28 @@ export interface GoalPromptContext {
23
24
  }
24
25
 
25
26
  export function buildGoalPrompt(goal: GoalPromptContext) {
26
- const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatTokenCount(goal.tokenBudget)}.`;
27
+ const budgetLine =
28
+ goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatTokenCount(goal.tokenBudget)}.`;
27
29
  return `Goal mode is active. Complete this goal fully:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalModeRules("this goal")}`;
28
30
  }
29
31
 
30
32
  export function buildObjectiveUpdatedPrompt(goal: GoalPromptContext) {
31
- const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
33
+ const budgetLine =
34
+ goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
32
35
  return `The active /goal objective was updated. The updated objective supersedes every previous goal objective. Avoid continuing work that only served the previous objective unless it also advances the updated objective:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalModeRules("the updated goal")}`;
33
36
  }
34
37
 
35
38
  export function buildResumePrompt(goal: GoalPromptContext, stoppedStatus: GoalStatus) {
36
- const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
39
+ const budgetLine =
40
+ goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
37
41
  return `The user explicitly resumed the ${stoppedStatusLabel(stoppedStatus)} /goal. Continue working toward this goal:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalModeRules("this goal")}`;
38
42
  }
39
43
 
40
44
  export function buildGoalSystemPrompt(goal: GoalPromptContext) {
41
- const budgetLine = goal.tokenBudget === undefined ? "" : `\n- Respect the goal token budget (${formatBudget(goal)} used).`;
45
+ const budgetLine =
46
+ goal.tokenBudget === undefined
47
+ ? ""
48
+ : `\n- Respect the goal token budget (${formatBudget(goal)} used).`;
42
49
  return `Active /goal:\n${goalContextBlock(goal)}\n\n${goalModeRules("the active goal")}${budgetLine}`;
43
50
  }
44
51
 
package/src/queue.ts ADDED
@@ -0,0 +1,96 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { checkpointGoalActiveTime } from "./accounting.js";
3
+ import type { ActiveGoal } from "./persistence.js";
4
+
5
+ export interface GoalQueueResult {
6
+ goal: ActiveGoal | undefined;
7
+ queue: ActiveGoal[];
8
+ }
9
+
10
+ export interface DropLastGoalResult extends GoalQueueResult {
11
+ removed: ActiveGoal | undefined;
12
+ }
13
+
14
+ export function createQueuedGoal(
15
+ text: string,
16
+ tokenBudget: number | undefined,
17
+ now = Date.now(),
18
+ ): ActiveGoal {
19
+ return {
20
+ id: randomUUID(),
21
+ text,
22
+ status: "queued",
23
+ startedAt: now,
24
+ updatedAt: now,
25
+ iteration: 0,
26
+ tokenBudget,
27
+ tokensUsed: 0,
28
+ timeUsedSeconds: 0,
29
+ baselineTokens: 0,
30
+ };
31
+ }
32
+
33
+ export function appendGoal(queue: readonly ActiveGoal[], goal: ActiveGoal): ActiveGoal[] {
34
+ return [...queue, goal];
35
+ }
36
+
37
+ export function prioritizeGoal(
38
+ currentGoal: ActiveGoal,
39
+ queue: readonly ActiveGoal[],
40
+ prioritizedGoal: ActiveGoal,
41
+ now = Date.now(),
42
+ ): GoalQueueResult {
43
+ return {
44
+ goal: prioritizedGoal,
45
+ queue: [shelveGoal(currentGoal, now), ...queue],
46
+ };
47
+ }
48
+
49
+ export function dropLastGoal(
50
+ currentGoal: ActiveGoal,
51
+ queue: readonly ActiveGoal[],
52
+ ): DropLastGoalResult {
53
+ if (queue.length === 0) {
54
+ return { goal: undefined, queue: [], removed: currentGoal };
55
+ }
56
+ return {
57
+ goal: currentGoal,
58
+ queue: queue.slice(0, -1),
59
+ removed: queue.at(-1),
60
+ };
61
+ }
62
+
63
+ export function skipGoal(queue: readonly ActiveGoal[]): GoalQueueResult {
64
+ return { goal: queue[0], queue: queue.slice(1) };
65
+ }
66
+
67
+ export function shelveGoal(goal: ActiveGoal, now = Date.now()): ActiveGoal {
68
+ if (goal.status !== "active") return { ...goal, activeStartedAt: undefined, updatedAt: now };
69
+ const shelved = { ...goal, status: "queued" as const, updatedAt: now };
70
+ checkpointGoalActiveTime(shelved, now, false);
71
+ return shelved;
72
+ }
73
+
74
+ export function activateQueuedGoal(
75
+ goal: ActiveGoal,
76
+ currentTokenTotal: number,
77
+ now = Date.now(),
78
+ ): ActiveGoal {
79
+ const rebased = {
80
+ ...goal,
81
+ baselineTokens: Math.max(0, currentTokenTotal - goal.tokensUsed),
82
+ activeStartedAt: undefined,
83
+ updatedAt: now,
84
+ };
85
+ if (goal.status !== "queued") return rebased;
86
+ const activated = {
87
+ ...rebased,
88
+ id: randomUUID(),
89
+ status: "active" as const,
90
+ };
91
+ checkpointGoalActiveTime(activated, now, true);
92
+ if (activated.tokenBudget !== undefined && activated.tokensUsed >= activated.tokenBudget) {
93
+ return { ...activated, status: "budget_limited", activeStartedAt: undefined };
94
+ }
95
+ return activated;
96
+ }