@fractaal/pi-goal-x 0.28.10 → 0.29.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.
@@ -11,7 +11,7 @@ import {
11
11
  type ExtensionContext,
12
12
  type ResourceLoader,
13
13
  } from "@earendil-works/pi-coding-agent";
14
- import type { Goal } from "./goal-contract.ts";
14
+ import { GOAL_RECEIPT_ENTRY, type Goal } from "./goal-contract.ts";
15
15
 
16
16
  export interface GoalAuditorResult {
17
17
  approved: boolean;
@@ -20,7 +20,19 @@ export interface GoalAuditorResult {
20
20
  error?: string;
21
21
  }
22
22
 
23
+ /** What the auditor judges against, beyond the objective and the executor's claim. */
24
+ export interface GoalAuditContext {
25
+ /** The system prompt the executor worked under, which carries the user's and project's directives. */
26
+ executorInstructions?: string;
27
+ userMessages: string[];
28
+ priorRejections: string[];
29
+ bashAvailable?: boolean;
30
+ snapshotPath?: string;
31
+ }
32
+
23
33
  const GOAL_AUDIT_SNAPSHOT_MARKER = "pi-goal-audit-snapshot-v1";
34
+ // Keeps a pasted log from crowding out the rest; the full message stays in the snapshot.
35
+ const AUDIT_USER_MESSAGE_MAX_LENGTH = 4_000;
24
36
 
25
37
  interface GoalAuditSnapshot {
26
38
  directory: string;
@@ -54,30 +66,117 @@ function createGoalAuditSnapshot(ctx: ExtensionContext): GoalAuditSnapshot {
54
66
  }
55
67
  }
56
68
 
69
+ export type GoalReviewVerdict = "approved" | "approved_with_notes" | "disapproved";
70
+
71
+ /** The verdict marker on the report's final non-empty line, or null when there is none. */
72
+ export function reviewVerdict(output: string): GoalReviewVerdict | null {
73
+ const last = output.split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
74
+ if (last === "<approved/>") return "approved";
75
+ if (last === "<approved_with_notes/>") return "approved_with_notes";
76
+ if (last === "<disapproved/>") return "disapproved";
77
+ return null;
78
+ }
79
+
57
80
  export function parseAuditorDecision(output: string): boolean {
58
- const lines = output.split("\n").map((line) => line.trim()).filter(Boolean);
59
- return lines.at(-1) === "<approved/>";
81
+ const verdict = reviewVerdict(output);
82
+ return verdict === "approved" || verdict === "approved_with_notes";
83
+ }
84
+
85
+ function messageText(content: unknown): string {
86
+ if (typeof content === "string") return content;
87
+ if (!Array.isArray(content)) return "";
88
+ return content
89
+ .filter((part): part is { type: "text"; text: string } => part?.type === "text" && typeof part.text === "string")
90
+ .map((part) => part.text)
91
+ .join("\n");
92
+ }
93
+
94
+ /** The user's own words on this branch and the earlier review rejections of this Goal. */
95
+ export function collectGoalAuditHistory(branch: readonly unknown[], goalId: string): Pick<GoalAuditContext, "userMessages" | "priorRejections"> {
96
+ const userMessages: string[] = [];
97
+ const priorRejections: string[] = [];
98
+ for (const item of branch) {
99
+ const entry = item as {
100
+ type?: string;
101
+ customType?: string;
102
+ message?: { role?: string; content?: unknown };
103
+ data?: { kind?: string; goalId?: string; auditorReport?: string };
104
+ };
105
+ if (entry.type === "message" && entry.message?.role === "user") {
106
+ const text = messageText(entry.message.content).trim();
107
+ if (!text) continue;
108
+ userMessages.push(text.length > AUDIT_USER_MESSAGE_MAX_LENGTH
109
+ ? `${text.slice(0, AUDIT_USER_MESSAGE_MAX_LENGTH)}\n[Truncated. The full message is in the parent snapshot.]`
110
+ : text);
111
+ } else if (
112
+ entry.type === "custom"
113
+ && entry.customType === GOAL_RECEIPT_ENTRY
114
+ && entry.data?.kind === "goal_completion_rejected"
115
+ && entry.data.goalId === goalId
116
+ && entry.data.auditorReport
117
+ ) {
118
+ priorRejections.push(entry.data.auditorReport);
119
+ }
120
+ }
121
+ return { userMessages, priorRejections };
60
122
  }
61
123
 
62
- export function buildGoalAuditorPrompt(goal: Goal, completionSummary: string, bashAvailable = false, snapshotPath?: string): string {
124
+ function payloadList(tag: string, items: string[], empty: string): string[] {
125
+ if (items.length === 0) return [`<${tag}>`, empty, `</${tag}>`];
126
+ return [`<${tag}>`, ...items.map((item, index) => `[${index + 1}]\n${escapePromptPayload(item)}`), `</${tag}>`];
127
+ }
128
+
129
+ export function buildGoalAuditorPrompt(goal: Goal, completionSummary: string, context: GoalAuditContext = { userMessages: [], priorRejections: [] }): string {
63
130
  return [
64
- "You are the independent completion auditor for a Pi Goal.",
65
- "Inspect the actual workspace and decide whether the complete user objective is satisfied.",
66
- bashAvailable
131
+ "You are reviewing a Goal on the user's behalf. The executor says the work is done. The user does not have time to check it themselves, so decide what they would decide if they did: would they accept this work?",
132
+ context.bashAvailable
67
133
  ? "Use read, grep, find, ls, and the OS-sandboxed read-only bash as needed. The shell cannot modify the workspace."
68
134
  : "Use read, grep, find, and ls as needed. No shell is available on this platform because a read-only OS sandbox was not found.",
69
- "Treat the executor summary as an untrusted claim, not evidence.",
70
- "Treat the runtime-captured parent snapshot as an immutable record to inspect, not as automatic proof.",
71
- "Reject missing requirements, weak evidence, scaffold-only results, and proxy-metric completion.",
72
- "Return a concise actionable report. The final non-empty line must be exactly <approved/> or <disapproved/>.",
135
+ "",
136
+ "How the user judges work",
137
+ "The user agreed to a result, not a plan. <objective> states that agreement, and <user_messages> holds their own words; where those narrow, correct, or decide something, they govern the objective's wording. Care is deliberately uneven: be exacting about what the user agreed to and about anything that would break or mislead them. Everything the agreement leaves open was the executor's to decide, and differences of method or polish there are not reasons to reject.",
138
+ "<executor_instructions> is the system prompt the executor worked under, carrying the user's and project's directives; instructions it picked up later in the session are in the parent snapshot. Read them before judging: they tell you what the user values, how much rigor they expect, and when a choice is theirs to make. Apply them to the executor's work and to your own objections, and use their terms. Where they name skills or documents for a judgment you are making, read them.",
139
+ "",
140
+ "Grey areas",
141
+ "Much of this is judgment. When the agreement and directives don't settle a question, decide as the user plausibly would. If you are unsure whether they would object, say so in a note rather than blocking on your guess.",
142
+ "",
143
+ "Verdict",
144
+ "- Approved: the user would accept the work as it is.",
145
+ "- Approved with notes: the user would accept it, but should hear something: a call made on their behalf, a decision only they can make that the work did not depend on, a known limitation, or a follow-up worth doing. Notes are things the user would want to read, not polish.",
146
+ "- Disapproved: the user would not accept it yet. The result they agreed to is missing, broken, or unverified; a constraint they set or a standard in their directives is violated, including doing more than they support; or the work depends on a decision only they can make. Each blocking finding names its consequence for the user and what would resolve it.",
147
+ "",
148
+ "Decisions made without the user",
149
+ "List the judgment calls the executor made on the user's behalf that they would want to hear about, whether or not the executor reported them: what was decided and why, in plain language. These are notes unless a call changed what the user agreed to.",
150
+ "",
151
+ "Evidence",
152
+ "<executor_summary> tells you where to look; it is not proof. Verify what matters in the workspace or the parent snapshot, where the runtime recorded every tool call and its result, so those show what actually ran and what it printed. Don't require evidence to be written into the workspace, and accept a report or plan the user asked for when it is delivered in the conversation or the summary. A recorded check is stale only if a later change could plausibly alter its result.",
153
+ "",
154
+ "Earlier reviews",
155
+ "<prior_reviews> holds earlier rejections of this Goal. They are earlier judgments, not requirements, and may have been wrong. Recheck the objections that still meet the standard above. When the executor disputes one, test its reasons against the evidence and the user's words, and uphold it only if the reasons fail.",
156
+ "",
157
+ "Report",
158
+ "Write for the user: plain and brief. Blocking findings first, then notes. The final non-empty line must be exactly <approved/>, <approved_with_notes/>, or <disapproved/>.",
159
+ "",
160
+ "<executor_instructions>",
161
+ context.executorInstructions?.trim()
162
+ ? escapePromptPayload(context.executorInstructions)
163
+ : "The executor's instructions are unavailable. Judge against the objective and the user's messages.",
164
+ "</executor_instructions>",
73
165
  "",
74
166
  "<objective>",
75
167
  escapePromptPayload(goal.objective),
76
168
  "</objective>",
77
169
  "",
170
+ ...payloadList("user_messages", context.userMessages, "No user messages are recorded on this branch."),
171
+ "",
172
+ ...payloadList("prior_reviews", context.priorRejections, "This is the first review of this Goal."),
173
+ "",
78
174
  "<parent_snapshot>",
79
- snapshotPath
80
- ? `Inspect the immutable runtime-captured current parent branch JSONL at: ${escapePromptPayload(snapshotPath)}`
175
+ context.snapshotPath
176
+ ? [
177
+ `Inspect the immutable runtime-captured current parent branch JSONL at: ${escapePromptPayload(context.snapshotPath)}`,
178
+ "Each line is one entry. Tool calls appear as toolCall parts in assistant messages; their results are messages with role toolResult.",
179
+ ].join("\n")
81
180
  : "No runtime-captured parent branch snapshot is available. Do not treat the executor summary as evidence.",
82
181
  "</parent_snapshot>",
83
182
  "",
@@ -94,7 +193,7 @@ function emptyResourceLoader(): ResourceLoader {
94
193
  getPrompts: () => ({ prompts: [], diagnostics: [] }),
95
194
  getThemes: () => ({ themes: [], diagnostics: [] }),
96
195
  getAgentsFiles: () => ({ agentsFiles: [] }),
97
- getSystemPrompt: () => "You are a read-only completion auditor. Inspect real evidence and never modify the workspace.",
196
+ getSystemPrompt: () => "You review finished work on a user's behalf. You can inspect anything you need, but never modify the workspace.",
98
197
  getSystemPromptSource: () => undefined,
99
198
  getAppendSystemPrompt: () => [],
100
199
  getAppendSystemPromptSources: () => [],
@@ -152,7 +251,7 @@ export async function runGoalCompletionAuditor(args: {
152
251
  createSession?: typeof createAgentSession;
153
252
  }): Promise<GoalAuditorResult> {
154
253
  const model = args.ctx.model;
155
- if (!model) return { approved: false, output: "", error: "No active model is available for the completion auditor." };
254
+ if (!model) return { approved: false, output: "", error: "No active model is available for the Goal review." };
156
255
  const output: string[] = [];
157
256
  let nestedSession: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
158
257
  let snapshot: GoalAuditSnapshot | undefined;
@@ -195,7 +294,12 @@ export async function runGoalCompletionAuditor(args: {
195
294
  args.signal?.addEventListener("abort", abort, { once: true });
196
295
  try {
197
296
  if (args.signal?.aborted) throw new DOMException("Auditor aborted", "AbortError");
198
- await session.prompt(buildGoalAuditorPrompt(args.goal, args.completionSummary, auditorBash !== null, snapshot.path));
297
+ await session.prompt(buildGoalAuditorPrompt(args.goal, args.completionSummary, {
298
+ executorInstructions: args.ctx.getSystemPrompt(),
299
+ ...collectGoalAuditHistory(args.ctx.sessionManager.getBranch(), args.goal.id),
300
+ bashAvailable: auditorBash !== null,
301
+ snapshotPath: snapshot.path,
302
+ }));
199
303
  } finally {
200
304
  args.signal?.removeEventListener("abort", abort);
201
305
  unsubscribe();
@@ -10,6 +10,13 @@ export const GOAL_PROPOSAL_EVENT = "pi-goal:proposal";
10
10
  export const GOAL_AUDIT_EVENT = "pi-goal:audit";
11
11
  export const GOAL_AUDIT_EVENT_VERSION = 1 as const;
12
12
  export const GOAL_CONTINUATION_MESSAGE = "pi-goal-continuation-v1";
13
+ // Pi delivers custom messages in the user role, so the constant text must say it is not from the user.
14
+ export const GOAL_CONTINUATION_TEXT = [
15
+ "<system_message source=\"goal_extension\">",
16
+ "Automatic reprompt from the Goal extension, not a message from the user. It does not answer anything you asked the user, approve anything, or give permission; any decision you put to the user is still pending.",
17
+ "Continue the Goal.",
18
+ "</system_message>",
19
+ ].join("\n");
13
20
  // A model-chosen wake lives in its own entry so the Goal state shape never changes.
14
21
  export const GOAL_WAKE_ENTRY = "pi-goal-wake-v1";
15
22
  export const GOAL_WAIT_MIN_SECONDS = 60;
@@ -33,6 +40,8 @@ export const GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH = 12_000;
33
40
  export const GOAL_COMPLETION_SUMMARY_MAX_LENGTH = 4_000;
34
41
  export const GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH = 12_000;
35
42
  export const GOAL_PROPOSAL_COMMENT_MAX_LENGTH = 4_000;
43
+ // A proposed objective must stay readable at a glance; stored state keeps the larger bound so older Goals still load.
44
+ export const GOAL_PROPOSED_OBJECTIVE_MAX_LENGTH = 2_000;
36
45
 
37
46
  export const GoalUsageSchema = Type.Object({
38
47
  tokensUsed: Type.Number({ minimum: 0 }),
@@ -25,7 +25,7 @@ export class GoalWidget implements Component {
25
25
  if (!goal) return [];
26
26
  const blocked = goal.status === "paused" && isGoalBlockedPause(goal.pause);
27
27
  const status = this.isAuditing()
28
- ? { icon: "◌", label: "auditing", color: "warning" as const }
28
+ ? { icon: "◌", label: "reviewing", color: "warning" as const }
29
29
  : goal.status === "complete"
30
30
  ? { icon: "✓", label: "complete", color: "success" as const }
31
31
  : goal.status === "paused"
@@ -41,7 +41,7 @@ export class GoalWidget implements Component {
41
41
  if (goal.pause.suggestedAction) lines.push(`${this.theme.fg("dim", blocked ? "unblock" : "next")} ${this.theme.fg("muted", goal.pause.suggestedAction)}`);
42
42
  }
43
43
  if (goal.lastAuditRejection) {
44
- lines.push(`${this.theme.fg("warning", "audit")} ${this.theme.fg("muted", goal.lastAuditRejection.report.replace(/\s+/g, " ").trim())}`);
44
+ lines.push(`${this.theme.fg("warning", "review")} ${this.theme.fg("muted", goal.lastAuditRejection.report.replace(/\s+/g, " ").trim())}`);
45
45
  }
46
46
  return lines.map((line) => truncateToWidth(line, Math.max(1, width), "…"));
47
47
  }
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { Type } from "@earendil-works/pi-ai";
3
3
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
4
4
  import { Text } from "@earendil-works/pi-tui";
5
- import { runGoalCompletionAuditor } from "./goal-auditor.ts";
5
+ import { reviewVerdict, runGoalCompletionAuditor } from "./goal-auditor.ts";
6
6
  import {
7
7
  GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH,
8
8
  GOAL_BLOCKER_MAX_LENGTH,
@@ -11,8 +11,10 @@ import {
11
11
  GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH,
12
12
  GOAL_COMPLETION_SUMMARY_MAX_LENGTH,
13
13
  GOAL_CONTINUATION_MESSAGE,
14
+ GOAL_CONTINUATION_TEXT,
14
15
  GOAL_OBJECTIVE_MAX_LENGTH,
15
16
  GOAL_PROPOSAL_COMMENT_MAX_LENGTH,
17
+ GOAL_PROPOSED_OBJECTIVE_MAX_LENGTH,
16
18
  GOAL_PAUSE_REASON_MAX_LENGTH,
17
19
  GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH,
18
20
  GOAL_UNBLOCK_CONDITION_MAX_LENGTH,
@@ -58,7 +60,6 @@ export * from "./goal-contract.ts";
58
60
  export * from "./goal-transcript-events.ts";
59
61
  export * from "./legacy-migration.ts";
60
62
 
61
- const GOAL_CONTINUATION_TEXT = "Continue the Goal.";
62
63
  const REQUIRED_PI_CODING_AGENT_VERSION = "0.84.1";
63
64
 
64
65
  type IdleExtensionContext = ExtensionContext & {
@@ -89,6 +90,16 @@ function boundedOptionalText(value: string | undefined, label: string, maxLength
89
90
  return trimmed;
90
91
  }
91
92
 
93
+ const PROPOSED_OBJECTIVE_DESCRIPTION = "What the user agreed to, in their own terms: the result they want, what they expect to see, and any constraints they insisted on. A few short paragraphs they can read at a glance, at most 2,000 characters. Leave out your plan, method, and verification steps; decide those as you work. Markdown is allowed.";
94
+
95
+ function proposedObjective(value: string): string {
96
+ const objective = boundedRequiredText(value, "Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
97
+ if (objective.length > GOAL_PROPOSED_OBJECTIVE_MAX_LENGTH) {
98
+ throw new Error(`Goal objective is ${objective.length.toLocaleString("en-US")} characters; the limit is ${GOAL_PROPOSED_OBJECTIVE_MAX_LENGTH.toLocaleString("en-US")}. State only what the user agreed to, in their terms: the result they want and the constraints they insisted on. Move plan, method, and verification detail out of the objective.`);
99
+ }
100
+ return objective;
101
+ }
102
+
92
103
  function emptyState(): GoalState {
93
104
  return { schemaVersion: GOAL_SCHEMA_VERSION, revision: 0, goal: null };
94
105
  }
@@ -166,12 +177,15 @@ function renderGoalSystemPrompt(state: GoalState): string {
166
177
  "<goal_objective>",
167
178
  goal.objective.replace(/<\/?goal_objective>/gi, (tag) => tag.replaceAll("<", "&lt;").replaceAll(">", "&gt;")),
168
179
  "</goal_objective>",
180
+ "The objective is what the user agreed to. Everything it leaves open is yours to decide as you work, guided by the user's directives and the conversation. Bring a choice to the user only when it would change what they agreed to or is one they would clearly want to make. While you wait for their answer, continue any work that does not depend on it. When you settle something the user might want a say in, such as dropping, keeping, or reinterpreting part of the work, say so plainly in your reply at the time, with your reason.",
181
+ "\"Continue the Goal.\" messages are automatic reprompts from the Goal extension, not from the user. They never answer your questions, approve anything, or give permission; a decision you put to the user stays pending until the user replies.",
169
182
  ];
170
183
  if (goal.status === "active") {
171
184
  lines.push("An active Goal continues by default. Do not stop at a progress report: if any safe, in-scope action can materially advance any part of the objective, take it.");
172
185
  lines.push("When the only remaining progress depends on external state that takes time, call wait_goal instead of polling or stopping.");
186
+ lines.push("If nothing else can advance the Goal until the user answers, call wait_goal.");
173
187
  lines.push("set_goal_blocked is an exceptional factual claim that autonomous progress is currently impossible. It is not a way to defer work, request review, or hand back an unfinished objective.");
174
- lines.push("Call abandon_goal only when the Goal should be abandoned, or complete_goal only after the objective is genuinely complete.");
188
+ lines.push("Call complete_goal when you believe the user would accept the work as done, or abandon_goal only when the Goal should be abandoned.");
175
189
  } else if (goal.status === "paused" && isGoalBlockedPause(goal.pause)) {
176
190
  lines.push("The Goal is blocked. Do not resume substantive Goal work until resume_goal is called.");
177
191
  lines.push(goal.pause?.reason ?? "No block proof recorded.");
@@ -180,12 +194,43 @@ function renderGoalSystemPrompt(state: GoalState): string {
180
194
  lines.push(`The Goal is paused by the user: ${goal.pause?.reason ?? "no reason recorded"}. Do not resume substantive Goal work until resume_goal is called.`);
181
195
  if (goal.pause?.suggestedAction) lines.push(`Suggested resume action: ${goal.pause.suggestedAction}`);
182
196
  } else {
183
- lines.push("The Goal passed its independent audit. Write one normal final response now and do not call tools.");
197
+ lines.push("The Goal's review approved it. Write one normal final response now and do not call tools.");
184
198
  }
185
- if (goal.lastAuditRejection) lines.push(`Latest auditor objection: ${goal.lastAuditRejection.report}`);
199
+ if (goal.lastAuditRejection) lines.push(`Latest review objection (fix it, dispute it in your next complete_goal summary, or ask the user): ${goal.lastAuditRejection.report}`);
186
200
  return lines.join("\n");
187
201
  }
188
202
 
203
+ function reviewRejectionText(report: string): string {
204
+ return [
205
+ "Goal review: not done yet. The Goal stays active.",
206
+ "",
207
+ "<review>",
208
+ report,
209
+ "</review>",
210
+ "",
211
+ "The reviewer stands in for the user but can be wrong. For each objection:",
212
+ "- If you agree, fix it.",
213
+ "- If it misreads what the user agreed to or their directives, asks for work they would not want, or rests on wrong facts, leave the work as it is and say why in your next complete_goal summary. The next review sees this report and your reasons.",
214
+ "- If it turns on a decision only the user can make, ask the user and call wait_goal.",
215
+ ].join("\n");
216
+ }
217
+
218
+ function reviewApprovalText(report: string, withNotes: boolean): string {
219
+ return [
220
+ `Goal review: approved${withNotes ? " with notes" : ""}.`,
221
+ "",
222
+ "<review>",
223
+ report,
224
+ "</review>",
225
+ "",
226
+ `Write one normal final response now: what was done, what changed, how it was verified, and the final state.${withNotes ? " Pass on the reviewer's notes: they are things the user should know or decide." : ""} End with "Decided without you": one or two plain sentences per judgment call you or the reviewer identified, saying what was decided and why, tied to what the user said, and ask the user to say if any is wrong. Leave that section out if there were none. Do not call tools.`,
227
+ ].join("\n");
228
+ }
229
+
230
+ function completionMessage(goal: Goal): string {
231
+ return goal.completion && reviewVerdict(goal.completion.auditorReport) === "approved_with_notes" ? "Goal completed with notes." : "Goal completed.";
232
+ }
233
+
189
234
  function stateText(state: GoalState): string {
190
235
  const goal = state.goal;
191
236
  if (!goal) return "No Goal is active on this branch.";
@@ -194,7 +239,7 @@ function stateText(state: GoalState): string {
194
239
  const lines = [`Goal ${status}: ${goal.objective}`, `Revision: ${state.revision}`, `Auto-continue: ${goal.autoContinue ? "on" : "off"}`];
195
240
  if (goal.pause) lines.push(`${blocked ? "Block proof" : "Pause reason"}: ${goal.pause.reason}`);
196
241
  if (goal.pause?.suggestedAction) lines.push(`${blocked ? "Unblock condition" : "Suggested action"}: ${goal.pause.suggestedAction}`);
197
- if (goal.lastAuditRejection) lines.push(`Latest audit rejection: ${goal.lastAuditRejection.report}`);
242
+ if (goal.lastAuditRejection) lines.push(`Latest review objection: ${goal.lastAuditRejection.report}`);
198
243
  return lines.join("\n");
199
244
  }
200
245
 
@@ -504,15 +549,18 @@ export default function goalExtension(
504
549
  pi.registerTool({
505
550
  name: "propose_goal",
506
551
  label: "Propose Goal",
507
- description: "Propose one Goal after ordinary conversation has made the objective clear. User confirmation creates and starts it.",
508
- promptSnippet: "Propose one confirmed Goal from an aligned objective.",
509
- promptGuidelines: ["Use Markdown to create your Goal proposal.", "Use propose_goal only after normal conversation has made a concrete objective clear enough for user confirmation."],
510
- parameters: Type.Object({ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH, description: "The complete Goal contract. Markdown is allowed." }) }, { additionalProperties: false }),
552
+ description: "Propose a Goal once the conversation has settled what the user wants. The user reads and confirms it; confirmation starts autonomous work toward it.",
553
+ promptSnippet: "Propose a Goal stating what the user agreed to.",
554
+ promptGuidelines: [
555
+ "Propose a Goal only after the conversation has settled what the user wants.",
556
+ "The objective is the user's agreement, not your plan. The user confirms it by reading it, and the reviewer later judges the work against it, so anything you add becomes a requirement they never asked for.",
557
+ ],
558
+ parameters: Type.Object({ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH, description: PROPOSED_OBJECTIVE_DESCRIPTION }) }, { additionalProperties: false }),
511
559
  executionMode: "sequential",
512
560
  async execute(_id, params, _signal, _update, ctx) {
513
561
  requireIdleSupport(ctx);
514
562
  if (state.goal) throw new Error("A Goal already exists. Use tweak_goal, set_goal_blocked, abandon_goal, or complete_goal.");
515
- const objective = boundedRequiredText(params.objective, "Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
563
+ const objective = proposedObjective(params.objective);
516
564
  setProposal("create", objective);
517
565
  let decision: GoalProposalDecision;
518
566
  try {
@@ -533,15 +581,15 @@ export default function goalExtension(
533
581
  pi.registerTool({
534
582
  name: "tweak_goal",
535
583
  label: "Tweak Goal",
536
- description: "Propose a complete revised objective for the current Goal. The revision applies only after user confirmation.",
537
- promptSnippet: "Propose a confirmed revision to the current Goal objective.",
538
- promptGuidelines: ["Use Markdown to create your Goal proposal.", "Use tweak_goal when user feedback changes the current Goal contract; pass the complete revised objective, not a patch."],
539
- parameters: Type.Object({ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH }) }, { additionalProperties: false }),
584
+ description: "Propose a revised objective when the user changes what they want. It applies only after the user confirms it, which also resumes a blocked or paused Goal.",
585
+ promptSnippet: "Propose a revision when the user changes what they agreed to.",
586
+ promptGuidelines: ["Use tweak_goal when the user changes what they agreed to, not when your plan changes. Pass the complete revised objective in the same short form as propose_goal."],
587
+ parameters: Type.Object({ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH, description: PROPOSED_OBJECTIVE_DESCRIPTION }) }, { additionalProperties: false }),
540
588
  executionMode: "sequential",
541
589
  async execute(_id, params, _signal, _update, ctx) {
542
590
  requireIdleSupport(ctx);
543
591
  const goal = currentGoal("paused-or-active");
544
- const objective = boundedRequiredText(params.objective, "Goal objective", GOAL_OBJECTIVE_MAX_LENGTH);
592
+ const objective = proposedObjective(params.objective);
545
593
  setProposal("tweak", objective, goal.objective);
546
594
  let decision: GoalProposalDecision;
547
595
  try {
@@ -550,12 +598,20 @@ export default function goalExtension(
550
598
  clearProposal();
551
599
  }
552
600
  if (!decision.confirmed) return { content: [{ type: "text", text: proposalResultText("Goal revision declined. The current Goal is unchanged.", decision.comment) }], details: state };
553
- const { lastAuditRejection: _lastAuditRejection, ...revisedGoal } = goal;
554
- const next: Goal = { ...revisedGoal, objective, updatedAt: nowIso() };
601
+ // The user's confirmation of the revised contract is also the go-ahead, so a blocked or paused Goal resumes.
602
+ const resumed = goal.status !== "active";
603
+ const { lastAuditRejection: _lastAuditRejection, pause: _pause, ...revisedGoal } = goal;
604
+ const next: Goal = { ...revisedGoal, objective, status: "active", autoContinue: true, updatedAt: nowIso() };
555
605
  persist(next, ctx);
556
- publishReceipt({ kind: "goal_updated", level: "info", ...goalFields(next), changeSummary: "Goal objective revised with user confirmation.", tuiMessage: "Goal updated." });
557
- if (next.status === "active") requestContinuation(ctx);
558
- return { content: [{ type: "text", text: proposalResultText("Goal revision confirmed.", decision.comment) }], details: state, terminate: true };
606
+ publishReceipt({
607
+ kind: "goal_updated",
608
+ level: "info",
609
+ ...goalFields(next),
610
+ changeSummary: resumed ? "Goal objective revised with user confirmation; the Goal resumed." : "Goal objective revised with user confirmation.",
611
+ tuiMessage: resumed ? "Goal updated and resumed." : "Goal updated.",
612
+ });
613
+ requestContinuation(ctx);
614
+ return { content: [{ type: "text", text: proposalResultText("Goal revision confirmed. Autonomous continuation is active.", decision.comment) }], details: state, terminate: true };
559
615
  },
560
616
  });
561
617
 
@@ -587,7 +643,7 @@ export default function goalExtension(
587
643
  description: `Choose when the active Goal next continues, from ${GOAL_WAIT_MIN_SECONDS} to ${GOAL_WAIT_MAX_SECONDS} seconds from now, instead of continuing immediately. The Goal stays active; any user message or event before then wakes you sooner.`,
588
644
  promptSnippet: "Wait for external state before the Goal continues.",
589
645
  promptGuidelines: [
590
- "Use wait_goal only when no safe, in-scope action can advance the Goal until external state changes, such as a build, deploy, review, or long-running process. It is not a way to defer work that can be done now.",
646
+ "Use wait_goal only when no safe, in-scope action can advance the Goal until external state changes, such as a build, deploy, review, long-running process, or the user's reply to a decision you put to them. It is not a way to defer work that can be done now.",
591
647
  "Match delaySeconds to what you are waiting for: one check when it should be done beats many short polls. If it is still not ready when you wake, wait again.",
592
648
  ],
593
649
  parameters: Type.Object({
@@ -641,10 +697,10 @@ export default function goalExtension(
641
697
  pi.registerTool({
642
698
  name: "complete_goal",
643
699
  label: "Complete Goal",
644
- description: "Request independent audit of the active, blocked, or human-paused Goal. Approval permits one final prose response, then archival.",
645
- promptSnippet: "Submit genuinely complete Goal work for independent audit.",
646
- promptGuidelines: ["Use complete_goal only when the complete Goal objective is satisfied; the summary is an audit claim, not proof."],
647
- parameters: Type.Object({ summary: Type.String({ minLength: 1, maxLength: GOAL_COMPLETION_SUMMARY_MAX_LENGTH, description: "Concise completion claim and available verification evidence." }) }, { additionalProperties: false }),
700
+ description: "Ask for the active, blocked, or human-paused Goal to be reviewed as done. A reviewer judges the work on the user's behalf against what they agreed to; approval permits one final response, then the Goal is archived.",
701
+ promptSnippet: "Submit Goal work for review when the user would accept it as done.",
702
+ promptGuidelines: ["The reviewer reads the conversation and inspects the workspace. Your complete_goal summary tells it where to look; it is not proof."],
703
+ parameters: Type.Object({ summary: Type.String({ minLength: 1, maxLength: GOAL_COMPLETION_SUMMARY_MAX_LENGTH, description: "What you did and how you know it works, pointing to where the evidence is, and the judgment calls you made on the user's behalf. If you dispute an earlier review objection, say which one and why." }) }, { additionalProperties: false }),
648
704
  executionMode: "sequential",
649
705
  async execute(_id, params, signal, _update, ctx) {
650
706
  const target = structuredClone(currentGoal("paused-or-active"));
@@ -657,18 +713,18 @@ export default function goalExtension(
657
713
  emitAuditState(false, target.id);
658
714
  }
659
715
  })();
660
- 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.");
716
+ if (state.goal?.id !== target.id || state.goal.updatedAt !== target.updatedAt) throw new Error("The Goal changed while it was being reviewed; the review result was discarded.");
661
717
  if (!auditor.approved) {
662
718
  const report = boundedRequiredText(
663
- auditor.output.trim() || auditor.error || "The independent auditor did not approve completion.",
719
+ auditor.output.trim() || auditor.error || "The Goal review did not approve completion.",
664
720
  "Goal audit rejection report",
665
721
  GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH,
666
722
  );
667
723
  const { pause: _pause, ...rejectedGoal } = target;
668
724
  const next: Goal = { ...rejectedGoal, status: "active", autoContinue: true, updatedAt: nowIso(), lastAuditRejection: { rejectedAt: nowIso(), report } };
669
725
  persist(next, ctx);
670
- 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}` });
671
- return { content: [{ type: "text", text: `Goal completion rejected. Address these objections before retrying:\n\n${report}` }], details: state };
726
+ publishReceipt({ kind: "goal_completion_rejected", level: auditor.error ? "error" : "warning", ...goalFields(next), reason: auditor.error ?? "Not approved by the Goal review.", auditorReport: report, message: "Goal review: not done yet.", tuiMessage: `Goal review: not done yet.\n${report}` });
727
+ return { content: [{ type: "text", text: reviewRejectionText(report) }], details: state };
672
728
  }
673
729
  const auditorReport = boundedRequiredText(auditor.output, "Goal completion auditor report", GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH);
674
730
  const { pause: _pause, lastAuditRejection: _lastAuditRejection, ...auditedGoal } = target;
@@ -681,7 +737,7 @@ export default function goalExtension(
681
737
  };
682
738
  persist(completed, ctx);
683
739
  return {
684
- 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.` }],
740
+ content: [{ type: "text", text: reviewApprovalText(auditorReport, reviewVerdict(auditorReport) === "approved_with_notes") }],
685
741
  details: state,
686
742
  };
687
743
  },
@@ -821,8 +877,8 @@ export default function goalExtension(
821
877
  ...goalFields(completed),
822
878
  completionSummary: completed.completion?.summary,
823
879
  auditorReport: completed.completion?.auditorReport,
824
- message: "Goal completed.",
825
- tuiMessage: "Goal completed.",
880
+ message: completionMessage(completed),
881
+ tuiMessage: completionMessage(completed),
826
882
  });
827
883
  });
828
884
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractaal/pi-goal-x",
3
- "version": "0.28.10",
3
+ "version": "0.29.0",
4
4
  "description": "Portable single-goal runtime for Pi",
5
5
  "license": "MIT",
6
6
  "author": "pi-goal-x contributors",