4 4 import { complete
as piComplete, StringEnum }
from "@earendil-works/pi-ai";
7 7 DefaultResourceLoader,
9 9 type ExtensionContext,
12 13 }
from "@earendil-works/pi-coding-agent";
20 21 const JUDGE_COMPLETE_FOR_TEST
= Symbol.
for(
21 22 "@bugabinga/pi-ext-goal/completeJudge",
24 +const PLANNER_FOR_TEST
= Symbol.
for(
"@bugabinga/pi-ext-goal/planner");
25 +type PlannerForTest = (payload
: Record<
string,
unknown>)
=> PlannerOutput;
23 26 type GoalTestGlobals = typeof globalThis
& {
24 27 [JUDGE_COMPLETE_FOR_TEST]
?: JudgeComplete;
28 + [PLANNER_FOR_TEST]
?: PlannerForTest;
27 31 function judgeComplete()
: JudgeComplete {
31 35 type GoalStatus = "active" | "paused" | "complete" | "blocked";
32 36 type GoalVerdictLabel = "done" | "blocked" | "continue" | "error";
33 37 type ProbeMode = "direct" | "microtask" | "timeout";
38 +type GoalThinkingLevel = "off" | "low" | "medium" | "high" | "xhigh";
39 +type GoalMode = "plan" | "execute" | "validate" | "recover" | "ask";
35 41 type GoalSettings = {
36 42 judgeModel
?: string;
43 + plannerModel
?: string;
44 + plannerThinkingLevel
: GoalThinkingLevel;
38 46 tokenBudget
?: number;
39 47 timeBudgetSeconds
?: number;
50 59 criteria
: string[];
82 +type EvidenceConfidence = "claim" | "observed" | "verified";
91 +type GoalEvidenceItem = {
94 + confidence
: EvidenceConfidence;
102 + status
: "todo" | "active" | "done" | "blocked" | "skipped";
103 + validationHints
: string[];
106 +type GoalDossier = {
109 + invariants
: string[];
112 + subgoals
: GoalSubgoal[];
113 + currentSubgoalId
?: string;
114 + evidence
: GoalEvidenceItem[];
116 + openQuestions
: string[];
117 + lastPlannerTrigger
?: string;
118 + lastJudgeReason
?: string;
122 +type PlannerOutput = {
125 + subgoals
?: unknown;
127 + openQuestions
?: unknown;
73 130 type TurnEvidence = {
74 131 assistantText
: string;
75 132 stopReason
?: string;
103 160 description: string;
163 +const GOAL_STATE_VERSION
= 2;
164 +const GOAL_DOSSIER_VERSION
= 1;
106 165 const GOAL_STATE_ENTRY
= "goal-state";
166 +const GOAL_DOSSIER_ENTRY
= "goal-dossier";
107 167 const GOAL_JUDGE_ENTRY
= "goal-judge";
108 168 const GOAL_EVENT_ENTRY
= "goal-event";
109 169 const GOAL_DEBUG_ENTRY
= "goal-debug";
112 172 const PROBE_ENTRY
= "goal-probe";
113 173 const PROBE_MESSAGE
= "GOAL_PROBE_CONTINUATION";
114 174 const DEFAULT_TAIL_BYTES
= 4096;
175 +const DEFAULT_PLANNER_THINKING_LEVEL
: GoalThinkingLevel = "high";
176 +const PLANNER_REFRESH_TURNS
= 5;
177 +const MAX_DOSSIER_EVIDENCE
= 40;
178 +const MAX_DOSSIER_LIST
= 12;
115 179 const STATUS_KEY
= "goal";
116 180 const WIDGET_KEY
= "goal";
117 -const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
118 181 const FOOTER_SEGMENT
= { id:
"goal", zone:
"llm", order:
30 }
as const;
119 -type FooterGlobal = typeof globalThis
& {
120 - [FOOTER_KEY]
?: { loaded
?: boolean; version
?: number };
122 182 const JUDGE_ATTEMPTS
= 2;
123 183 const JUDGE_PARSE_FAILURE_LIMIT
= 3;
124 184 const BLOCKED_STREAK_LIMIT
= 3;
129 189 let liveGoalState
: GoalState | undefined;
130 190 let liveGoalMode
: GoalUiMode = "normal";
131 191 let liveGoalWidgetMode
: GoalWidgetMode = "compact";
192 +let goalWidgetRegistered
= false;
132 193 let liveGoalTimer
: 141 202 const GOAL_WIDGET_DEFAULT_WIDTH
= 78;
142 203 const GOAL_WIDGET_LEFT_PADDING
= 0;
143 -const JUDGE_SYSTEM_PROMPT
= `You are a strict /goal completion judge. Be skeptical. Agents lie about completion. 204 +const JUDGE_SYSTEM_PROMPT
= `You are a strict adversarial /goal completion judge. Be skeptical. Agents lie about completion. 206 +Your job is to find concrete reasons the goal is not complete before accepting completion. 145 207 You must independently verify the goal using available tools. 146 208 Use read/grep/find/ls for repo inspection. 147 209 Use bash for inspection and verification commands/tests/checks. 210 +Use dossier evidence and subgoals as hints, not proof. 148 211 Do not modify files, git state, dependencies, config, network state, or external services. 150 213 Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}. 238 301 return Number.
isFinite(parsed)
&& parsed
> 0 ? Math.
trunc(parsed)
: undefined;
304 +function parseThinkingLevel(value
: unknown)
: GoalThinkingLevel {
305 + return value
=== "off" || 307 + value
=== "medium" || 308 + value
=== "high" || 311 + : DEFAULT_PLANNER_THINKING_LEVEL;
241 314 function loadSettings(pi
: ExtensionAPI)
: GoalSettings {
242 315 const all
= (pi
as SettingsAPI).settingsManager?.
getSettings?.();
243 316 const raw
= isRecord(all?.goal)
? all.goal
: {};
246 319 typeof raw.judgeModel
=== "string" && raw.judgeModel.
trim()
247 320 ? raw.judgeModel.
trim()
323 + typeof raw.plannerModel
=== "string" && raw.plannerModel.
trim()
324 + ? raw.plannerModel.
trim()
326 + plannerThinkingLevel:
parseThinkingLevel(raw.plannerThinkingLevel),
249 327 tailBytes:
clampInt(raw.tailBytes, DEFAULT_TAIL_BYTES,
512,
65_536),
251 329 const tokenBudget
= parseBudgetCount(raw.tokenBudget);
307 385 function isGoalState(value
: unknown)
: value
is GoalState {
308 386 if (
!isRecord(value))
return false;
388 + value.schemaVersion
=== GOAL_STATE_VERSION
&& 310 389 typeof value.
id === "string" && 311 390 typeof value.objective
=== "string" && 312 391 Array.
isArray(value.criteria)
&& 345 424 customType
?: string;
350 429 for (
let i
= entries.
length - 1; i
>= 0; i
--) {
351 430 const entry
= entries[i];
361 440 return undefined;
443 +function isGoalDossier(value
: unknown)
: value
is GoalDossier {
444 + if (
!isRecord(value))
return false;
446 + value.
version === GOAL_DOSSIER_VERSION
&& 447 + typeof value.goalId
=== "string" && 448 + Array.
isArray(value.invariants)
&& 449 + value.invariants.
every((x)
=> typeof x
=== "string")
&& 450 + isGoalMode(value.mode)
&& 451 + Array.
isArray(value.plan)
&& 452 + value.plan.
every((x)
=> typeof x
=== "string")
&& 453 + Array.
isArray(value.subgoals)
&& 454 + value.subgoals.
every(isGoalSubgoal)
&& 455 + (value.currentSubgoalId
=== undefined || 456 + typeof value.currentSubgoalId
=== "string")
&& 457 + Array.
isArray(value.evidence)
&& 458 + value.evidence.
every(isGoalEvidenceItem)
&& 459 + Array.
isArray(value.risks)
&& 460 + value.risks.
every((x)
=> typeof x
=== "string")
&& 461 + Array.
isArray(value.openQuestions)
&& 462 + value.openQuestions.
every((x)
=> typeof x
=== "string")
&& 463 + (value.lastPlannerTrigger
=== undefined || 464 + typeof value.lastPlannerTrigger
=== "string")
&& 465 + (value.lastJudgeReason
=== undefined || 466 + typeof value.lastJudgeReason
=== "string")
&& 467 + typeof value.updatedAt
=== "number" 471 +function isGoalMode(value
: unknown)
: value
is GoalMode {
473 + value
=== "plan" || 474 + value
=== "execute" || 475 + value
=== "validate" || 476 + value
=== "recover" || 481 +function isGoalSubgoal(value
: unknown)
: value
is GoalSubgoal {
482 + if (
!isRecord(value))
return false;
484 + typeof value.
id === "string" && 485 + typeof value.
title === "string" && 486 + (value.
status === "todo" || 487 + value.
status === "active" || 488 + value.
status === "done" || 489 + value.
status === "blocked" || 490 + value.
status === "skipped")
&& 491 + Array.
isArray(value.validationHints)
&& 492 + value.validationHints.
every((x)
=> typeof x
=== "string")
496 +function isGoalEvidenceItem(value
: unknown)
: value
is GoalEvidenceItem {
497 + if (
!isRecord(value))
return false;
499 + Number.
isInteger(value.turn)
&& 500 + (value.kind
=== "assistant" || 501 + value.kind
=== "tool" || 502 + value.kind
=== "command" || 503 + value.kind
=== "test" || 504 + value.kind
=== "file" || 505 + value.kind
=== "error")
&& 506 + (value.confidence
=== "claim" || 507 + value.confidence
=== "observed" || 508 + value.confidence
=== "verified")
&& 509 + typeof value.
text === "string" && 510 + typeof value.createdAt
=== "number" 514 +function latestGoalDossier(
515 + ctx
: ExtensionContext,
517 +)
: GoalDossier | undefined {
518 + const entries
= ctx.sessionManager.
getEntries()
as Array<{
520 + customType
?: string;
523 + for (
let i
= entries.
length - 1; i
>= 0; i
--) {
524 + const entry
= entries[i];
526 + entry.
type !== "custom" || 527 + entry.customType
!== GOAL_DOSSIER_ENTRY
|| 528 + !isGoalDossier(entry.
data)
531 + if (entry.
data.goalId
=== goalId)
return entry.
data;
364 536 function appendGoal(pi
: ExtensionAPI, state
: GoalState)
: void {
365 537 pi.
appendEntry(GOAL_STATE_ENTRY, state);
540 +function createGoalState(
542 + settings
: GoalSettings,
543 + sessionId
: string | undefined,
547 + schemaVersion: GOAL_STATE_VERSION,
548 + id: crypto.
randomUUID(),
553 + tokenBudget: settings.tokenBudget,
555 + timeBudgetSeconds: settings.timeBudgetSeconds,
556 + timeUsedSeconds:
0,
368 564 function updateGoal(
369 565 pi
: ExtensionAPI,
370 566 current
: GoalState,
574 +function createInitialDossier(state
: GoalState, now
= Date.
now())
: GoalDossier {
577 + version: GOAL_DOSSIER_VERSION,
579 + "Do not redefine the objective smaller.",
580 + "Preserve user criteria exactly.",
581 + "Verify before claiming completion.",
582 + "Do not complete from assistant claims alone.",
594 +function appendDossier(pi
: ExtensionAPI, dossier
: GoalDossier)
: GoalDossier {
595 + pi.
appendEntry(GOAL_DOSSIER_ENTRY, dossier);
599 +function ensureDossier(
601 + ctx
: ExtensionContext,
605 + latestGoalDossier(ctx, state.
id)
?? 606 + appendDossier(pi,
createInitialDossier(state))
610 +function updateDossier(
612 + current
: GoalDossier,
613 + patch
: Partial<
GoalDossier>,
615 + return appendDossier(pi, {
...current,
...patch, updatedAt:
Date.
now() });
378 618 function showsTurnBudget(state
: GoalState)
: boolean {
379 619 return state.
status === "active" || state.
status === "paused";
437 -function judgeDisplayReason(reason
: string)
: string {
438 - return sanitizeGoalText(reason,
160);
677 +function stringList(
679 + maxItems
= MAX_DOSSIER_LIST,
682 + const raw
= Array.
isArray(value)
? value
: [];
683 + const out
: string[]
= [];
684 + for (
const item
of raw) {
686 + typeof item
=== "string" 688 + : isRecord(item)
&& typeof item.
title === "string" 691 + if (
!text)
continue;
692 + const safe
= sanitizeGoalText(text, max);
693 + if (safe
&& !out.
includes(safe)) out.
push(safe);
694 + if (out.
length >= maxItems)
break;
699 +function judgeDisplayReason(reason
: string | undefined)
: string {
700 + return sanitizeGoalText(reason
|| "no reason",
160);
703 +function normalizeJudgeVerdict(value
: unknown)
: JudgeVerdict {
704 + const verdict
= isRecord(value)
? value
: {};
706 + done:
parseLooseBoolean(verdict.done),
707 + blocked:
parseLooseBoolean(verdict.blocked),
709 + typeof verdict.reason
=== "string" && verdict.reason.
trim()
710 + ? shortText(verdict.reason.
trim(),
160)
441 715 function judgeVerdictLabel(
442 716 verdict
: JudgeVerdict,
443 717 )
: "done" | "blocked" | "continue" {
444 - if (verdict.done)
return "done";
445 - if (verdict.blocked)
return "blocked";
718 + const normalized
= normalizeJudgeVerdict(verdict);
719 + if (normalized.done)
return "done";
720 + if (normalized.blocked)
return "blocked";
446 721 return "continue";
449 724 function isJudgeFailure(verdict
: JudgeVerdict)
: boolean {
450 - return verdict.reason.
startsWith(
"judge failed:");
725 + return normalizeJudgeVerdict(verdict).reason.
startsWith(
"judge failed:");
453 728 function isJudgeParseFailure(verdict
: JudgeVerdict)
: boolean {
729 + const reason
= normalizeJudgeVerdict(verdict).reason;
455 - verdict.reason.
includes(
"judge returned")
|| 456 - verdict.reason.
includes(
"JSON")
|| 457 - verdict.reason.
includes(
"Unexpected")
731 + reason.
includes(
"judge returned")
|| 732 + reason.
includes(
"JSON")
|| 733 + reason.
includes(
"Unexpected")
613 -function hasFooter()
: boolean {
614 - const footer
= (globalThis
as FooterGlobal)[FOOTER_KEY];
615 - return footer?.loaded
=== true && (footer.
version ?? 0)
>= 1;
618 889 function clearFooter(pi
: ExtensionAPI)
: void {
619 890 pi.events.
emit(
"footer:segment", { id: FOOTER_SEGMENT.
id, text:
undefined });
834 1105 ? ` · ${verdictGlyph(state.lastVerdict)} ${sanitizeGoalText(state.lastReason, 48)}` 836 1107 return truncateToWidth(
837 - `◇ ${footerPhaseText(state, mode)} · ${budgetText(state)}${criteria} · ${sanitizeGoalText(state.objective, 160)}${reason}`,
1108 + `◇ ${footerPhaseText(state, mode)} · ctrl+shift+g expand · ${budgetText(state)}${criteria} · ${sanitizeGoalText(state.objective, 160)}${reason}`,
838 1109 Math.
max(
0, width),
843 1114 function updateWidget(ctx
: ExtensionContext)
: void {
844 1115 if (
!liveGoalState) {
845 - ctx.ui.
setWidget(WIDGET_KEY,
undefined);
1116 + if (goalWidgetRegistered) ctx.ui.
setWidget(WIDGET_KEY,
undefined);
1117 + goalWidgetRegistered
= false;
1120 + if (goalWidgetRegistered)
return;
848 1121 ctx.ui.
setWidget(
850 1123 (_tui, theme)
=> ({
864 1137 {
placement:
"aboveEditor" },
1139 + goalWidgetRegistered
= true;
868 1142 function updateFooter(
869 1143 pi
: ExtensionAPI,
870 1144 ctx
: ExtensionContext,
871 - state
: GoalState | undefined,
1145 + _state
: GoalState | undefined,
1146 + _mode
: GoalUiMode,
874 - if (
!hasFooter()) {
878 - state
&& (mode
=== "judging" || mode
=== "queued")
879 - ? footerPhaseText(state, mode)
880 - : statusText(state),
884 1148 ctx.ui.
setStatus(STATUS_KEY,
undefined);
885 - const shown
= widgetState(state);
890 - const phase
= footerPhaseText(shown, mode);
892 - shown.criteria.
length === 0 ? "" : ` · ${shown.criteria.length}c`;
893 - const reason
= shown.lastReason
894 - ? ` · ${shortText(shown.lastReason, 36)}` 896 - pi.events.
emit(
"footer:segment", {
898 - text:
`${phase} · ${budgetText(shown)}${criteria}${reason}`,
899 - variants: [phase, shown.
status],
900 - color:
goalTone(shown, mode),
904 1152 function updateHeartbeat(
1026 -function activeGoalPrompt(state
: GoalState)
: string {
1027 - return `\n\nActive /goal:\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
1274 +function goalControlBlock(dossier
: GoalDossier | undefined)
: string {
1275 + if (
!dossier)
return "";
1276 + const active
= dossier.subgoals.
find(
1277 + (x)
=> x.
id === dossier.currentSubgoalId,
1280 + `Mode: ${dossier.mode}`,
1281 + active
? `Current subgoal: ${escapeXmlText(active.title)}` : undefined,
1282 + dossier.invariants.
length 1283 + ? `Invariants:\n${dossier.invariants.map((x) => `- ${escapeXmlText(x)}`).join("\n")}` 1285 + dossier.plan.
length 1286 + ? `Plan:\n${dossier.plan.map((x, i) => `${i + 1}. ${escapeXmlText(x)}`).join("\n")}` 1288 + dossier.risks.
length 1289 + ? `Risks:\n${dossier.risks.map((x) => `- ${escapeXmlText(x)}`).join("\n")}` 1291 + active?.validationHints.
length 1292 + ? `Validation hints:\n${active.validationHints.map((x) => `- ${escapeXmlText(x)}`).join("\n")}` 1297 + return parts
? `\n\n<goal_control_data>\n${parts}\n</goal_control_data>` : "";
1030 -function continuationPrompt(state
: GoalState)
: string {
1031 - return `Continue working toward this standing goal.\n\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Call update_goal with status "complete" only after verifying success. Call update_goal with status "blocked" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.`;
1300 +function activeGoalPrompt(
1302 + dossier
: GoalDossier | undefined = undefined,
1304 + return `\n\nActive /goal:\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}${goalControlBlock(dossier)}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
1307 +function continuationPrompt(
1309 + dossier
: GoalDossier | undefined = undefined,
1311 + return `Continue working toward this standing goal.\n\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}${goalControlBlock(dossier)}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Follow goal_control_data when present. Call update_goal with status "complete" only after verifying success. Call update_goal with status "blocked" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.`;
1034 1314 function kickoffPrompt(state
: GoalState)
: string {
1112 1392 return Buffer.
from(text).
subarray(
-tailBytes).
toString();
1395 +function evidenceFromTurn(
1397 + evidence
: TurnEvidence | undefined,
1398 + tailBytes
: number,
1399 +)
: GoalEvidenceItem[] {
1400 + if (
!evidence)
return [];
1401 + const now
= Date.
now();
1402 + const items
: GoalEvidenceItem[]
= [];
1403 + if (evidence.assistantText.
trim()) {
1406 + kind:
"assistant",
1407 + confidence:
"claim",
1408 + text:
sanitizeGoalText(
tailText(evidence.assistantText, tailBytes),
240),
1412 + if (evidence.errorMessage) {
1416 + confidence:
"observed",
1417 + text:
sanitizeGoalText(evidence.errorMessage,
240),
1421 + for (
const call
of evidence.toolCalls) {
1424 + kind:
toolEvidenceKind(call.
name, call.args),
1425 + confidence:
"observed",
1426 + text:
sanitizeGoalText(
1427 + `${call.name} ${JSON.stringify(call.args ?? {})}`,
1433 + for (
const result
of evidence.toolResults) {
1436 + kind: result.isError
? "error" : toolEvidenceKind(result.toolName),
1437 + confidence: result.isError
? "observed" : toolEvidenceConfidence(result),
1438 + text:
sanitizeGoalText(
1439 + `${result.toolName}: ${tailText(result.text, tailBytes)}`,
1445 + return items.
filter((item)
=> item.
text.
length > 0);
1448 +function toolEvidenceKind(name
: string, args
?: unknown)
: EvidenceKind {
1449 + if (name
=== "bash") {
1450 + const command
= isRecord(args)
? String(args.command
?? "")
: "";
1451 + return /\b(test|vitest|jest|check|lint|ci|build)\b/iu.
test(command)
1455 + if (name
=== "read" || name
=== "grep" || name
=== "find" || name
=== "ls")
1460 +function toolEvidenceConfidence(
1461 + result
: TurnEvidence[
"toolResults"][
number],
1462 +)
: EvidenceConfidence {
1464 + result.toolName
=== "bash" && 1465 + /\b(0 passed|passed|OK|All checks passed)\b/iu.
test(result.
text)
1467 + return "verified";
1468 + return "observed";
1471 +function appendTurnEvidenceToDossier(
1473 + dossier
: GoalDossier,
1475 + evidence
: TurnEvidence | undefined,
1476 + settings
: GoalSettings,
1478 + const items
= evidenceFromTurn(turn, evidence, settings.tailBytes);
1479 + if (items.
length === 0)
return dossier;
1480 + return updateDossier(pi, dossier, {
1481 + evidence: [
...dossier.evidence,
...items].
slice(
-MAX_DOSSIER_EVIDENCE),
1115 1485 function parseModelRef(ref
: string)
: { provider
: string; model
: string } {
1116 1486 const i
= ref.
indexOf(
"/");
1117 1487 if (i
<= 0 || i
=== ref.
length - 1)
1119 1489 return { provider: ref.
slice(
0, i), model: ref.
slice(i
+ 1) };
1122 -function resolveJudgeModel(ctx
: ExtensionContext, settings
: GoalSettings) {
1123 - if (
!settings.judgeModel)
return ctx.model;
1124 - const { provider, model }
= parseModelRef(settings.judgeModel);
1492 +function resolveConfiguredModel(
1493 + ctx
: ExtensionContext,
1494 + modelRef
: string | undefined,
1497 + if (
!modelRef)
return ctx.model;
1498 + const { provider, model }
= parseModelRef(modelRef);
1125 1499 const found
= ctx.modelRegistry.
find(provider, model);
1127 - throw new Error(
`Goal judge model not found: ${settings.judgeModel}`);
1500 + if (
!found)
throw new Error(
`Goal ${kind} model not found: ${modelRef}`);
1504 +function resolveJudgeModel(ctx
: ExtensionContext, settings
: GoalSettings) {
1505 + return resolveConfiguredModel(ctx, settings.judgeModel,
"judge");
1508 +function resolvePlannerModel(ctx
: ExtensionContext, settings
: GoalSettings) {
1509 + return resolveConfiguredModel(ctx, settings.plannerModel,
"planner");
1131 1512 function parseLooseBoolean(value
: unknown)
: boolean {
1132 1513 if (value
=== true || value
=== 1)
return true;
1133 1514 if (value
=== false || value
=== 0)
return false;
1154 1535 function parseJudge(raw
: string)
: JudgeVerdict {
1155 1536 const parsed
= JSON.
parse(
extractJsonObject(raw));
1156 1537 if (
!isRecord(parsed))
throw new Error(
"judge returned non-object JSON");
1538 + return normalizeJudgeVerdict(parsed);
1541 +function dossierPayload(
1542 + dossier
: GoalDossier | undefined,
1543 +)
: Record<
string,
unknown>
| undefined {
1544 + if (
!dossier)
return undefined;
1158 - done:
parseLooseBoolean(parsed.done),
1159 - blocked:
parseLooseBoolean(parsed.blocked),
1161 - typeof parsed.reason
=== "string" && parsed.reason.
trim()
1162 - ? shortText(parsed.reason.
trim(),
160)
1546 + mode: dossier.mode,
1547 + invariants: dossier.invariants,
1548 + plan: dossier.plan,
1549 + subgoals: dossier.subgoals,
1550 + currentSubgoalId: dossier.currentSubgoalId,
1551 + evidenceTail: dossier.evidence.
slice(
-12),
1552 + risks: dossier.risks,
1553 + openQuestions: dossier.openQuestions,
1554 + lastPlannerTrigger: dossier.lastPlannerTrigger,
1555 + lastJudgeReason: dossier.lastJudgeReason,
1559 +function plannerPayload(
1561 + dossier
: GoalDossier,
1563 +)
: Record<
string,
unknown> {
1566 + objective: state.objective,
1567 + criteria: state.criteria,
1568 + turn: state.turnsUsed,
1569 + dossier:
dossierPayload(dossier),
1573 +function plannerUserPrompt(payload
: Record<
string,
unknown>)
: string {
1574 + return `Create or refresh the internal /goal execution plan. 1576 +Use the existing dossier as current control state. Preserve useful plan/subgoals. Only change what new evidence justifies. Never reduce, reinterpret, or complete the goal. Prefer concrete subgoals and validation hints. Some goals are subjective; for those, suggest observable progress and human confirmation points. 1578 +Return only JSON: {"mode":"plan|execute|validate|recover|ask","plan":["..."],"subgoals":[{"title":"...","status":"todo|active|done|blocked|skipped","validationHints":["..."]}],"risks":["..."],"openQuestions":["..."]}. 1580 +${JSON.stringify(payload, null, 2)}`;
1583 +function applyPlannerOutput(
1584 + dossier
: GoalDossier,
1585 + output
: PlannerOutput,
1588 + const existingByTitle
= new Map(
1589 + dossier.subgoals.
map((subgoal)
=> [subgoal.
title.
toLowerCase(), subgoal]),
1591 + const rawSubgoals
= Array.
isArray(output.subgoals)
? output.subgoals
: [];
1592 + const subgoals
= rawSubgoals
1593 + .
slice(
0, MAX_DOSSIER_LIST)
1594 + .
flatMap((raw, index)
=> {
1595 + const title
= isRecord(raw)
1596 + ? typeof raw.
title === "string" 1599 + : typeof raw
=== "string" 1602 + const safeTitle
= title
? sanitizeGoalText(title,
160)
: "";
1603 + if (
!safeTitle)
return [];
1604 + const existing
= existingByTitle.
get(safeTitle.
toLowerCase());
1606 + isRecord(raw)
&& isSubgoalStatus(raw.
status)
1611 + const validationHints
= isRecord(raw)
1612 + ? stringList(raw.validationHints,
6,
160)
1616 + id: existing?.
id ?? `sg-${index + 1}`,
1623 + const nextSubgoals
= subgoals.
length > 0 ? subgoals
: dossier.subgoals;
1625 + nextSubgoals.
find((x)
=> x.
status === "active")
?? 1626 + nextSubgoals.
find((x)
=> x.
status === "todo");
1629 + mode:
isGoalMode(output.mode)
? output.mode
: dossier.mode,
1630 + plan:
stringList(output.plan, MAX_DOSSIER_LIST,
160),
1631 + subgoals: nextSubgoals,
1632 + currentSubgoalId: active?.
id,
1633 + risks:
stringList(output.risks, MAX_DOSSIER_LIST,
160),
1634 + openQuestions:
stringList(output.openQuestions,
8,
160),
1635 + lastPlannerTrigger: trigger,
1636 + updatedAt:
Date.
now(),
1640 +function isSubgoalStatus(value
: unknown)
: GoalSubgoal[
"status"]
| undefined {
1641 + return value
=== "todo" || 1642 + value
=== "active" || 1643 + value
=== "done" || 1644 + value
=== "blocked" || 1645 + value
=== "skipped" 1167 1650 function judgePayload(
1168 1651 ctx
: ExtensionContext,
1169 1652 state
: GoalState,
1170 1653 settings
: GoalSettings,
1171 1654 evidence
: TurnEvidence | undefined,
1655 + dossier
?: GoalDossier,
1172 1656 )
: Record<
string,
unknown> {
1174 1658 objective: state.objective,
1185 1669 text:
tailText(result.
text, settings.tailBytes),
1671 + dossier:
dossierPayload(dossier),
1196 1681 ${
JSON.
stringify(payload,
null,
2)}
`; 1684 +async function runPlanner( 1685 + ctx: ExtensionContext, 1687 + dossier: GoalDossier, 1688 + settings: GoalSettings, 1690 +): Promise<GoalDossier> { 1691 + const testPlanner = (globalThis as GoalTestGlobals)[PLANNER_FOR_TEST]; 1692 + const payload = plannerPayload(state, dossier, trigger); 1694 + return applyPlannerOutput(dossier, testPlanner(payload), trigger); 1695 + const model = resolvePlannerModel(ctx, settings); 1696 + if (!model) return dossier; 1697 + const loader = new DefaultResourceLoader(judgeResourceLoaderOptions(ctx)); 1698 + await loader.reload(); 1699 + const { session } = await createAgentSession({ 1702 + modelRegistry: ctx.modelRegistry, 1703 + resourceLoader: loader, 1704 + sessionManager: SessionManager.inMemory(ctx.cwd), 1705 + tools: ["read", "grep", "find", "ls", "bash"], 1706 + thinkingLevel: settings.plannerThinkingLevel, 1710 + const unsubscribe = session.subscribe((event) => { 1711 + if (event.type !== "message_end" || event.message.role !== "assistant") 1713 + raw = textFromContent(event.message.content); 1716 + await session.prompt(plannerUserPrompt(payload), { source: "extension" }); 1720 + if (!raw.trim()) raw = textFromContent(session.messages.at(-1)?.content); 1721 + const parsed = JSON.parse(extractJsonObject(raw)); 1722 + return applyPlannerOutput(dossier, isRecord(parsed) ? parsed : {}, trigger); 1724 + session.dispose(); 1728 +function shouldRefreshPlanner( 1730 + dossier: GoalDossier, 1731 + verdict: JudgeVerdict, 1732 +): string | undefined { 1733 + if (dossier.subgoals.length === 0) return "empty-plan"; 1734 + if (state.turnsUsed > 0 && state.turnsUsed % PLANNER_REFRESH_TURNS === 0) 1735 + return "periodic"; 1736 + if (state.blockedStreak && state.blockedStreak.count >= 2) 1737 + return "blocked-risk"; 1739 + /\b(no proof|verify|unclear|vague|not enough|missing)\b/iu.test( 1743 + return "weak-proof"; 1747 +function refreshPlannerInBackground( 1749 + ctx: ExtensionContext, 1751 + dossier: GoalDossier, 1754 + const globals = globalThis as GoalTestGlobals; 1756 + (process.env.VITEST || globals[JUDGE_COMPLETE_FOR_TEST]) && 1757 + !globals[PLANNER_FOR_TEST] 1760 + void runPlanner(ctx, state, dossier, loadSettings(pi), trigger) 1763 + const latest = latestGoalDossier(ctx, state.id) ?? dossier; 1764 + appendDossier(pi, { 1766 + evidence: latest.evidence, 1767 + lastJudgeReason: latest.lastJudgeReason ?? next.lastJudgeReason, 1768 + updatedAt: Date.now(), 1771 + if (!isStaleContextError(error)) throw error; 1774 + .catch((error) => { 1776 + debugGoal(pi, "planner-failed", { 1779 + reason: error instanceof Error ? error.message : String(error), 1781 + } catch (debugError) { 1782 + if (!isStaleContextError(debugError)) throw debugError; 1199 1787 function appendJudge( 1200 1788 pi: ExtensionAPI, 1201 1789 ctx: ExtensionContext, 1233 1821 state: GoalState,
1234 1822 settings: GoalSettings,
1235 1823 evidence: TurnEvidence
| undefined,
1824 + dossier: GoalDossier
| undefined,
1236 1825 ):
Promise<JudgeVerdict
> {
1237 1826 const model
= resolveJudgeModel(ctx, settings);
1238 1827 if (!model) return {
done:
false,
blocked:
false,
reason:
"no judge model" };
1253 1842 type:
"text" as const,
1254 - text:
judgeUserPrompt(
judgePayload(ctx, state, settings, evidence)),
1843 + text:
judgeUserPrompt(
1844 + judgePayload(ctx, state, settings, evidence, dossier),
1257 1848 timestamp:
Date.
now(),
1287 1878 throw lastError;
1881 +function judgeResourceLoaderOptions(ctx
: ExtensionContext) {
1884 + agentDir:
getAgentDir(),
1885 + systemPromptOverride: ()
=> JUDGE_SYSTEM_PROMPT,
1290 1889 async function judgeGoalWithAgent(
1291 1890 ctx
: ExtensionContext,
1292 1891 state
: GoalState,
1293 1892 settings
: GoalSettings,
1294 1893 evidence
: TurnEvidence | undefined,
1894 + dossier
: GoalDossier | undefined,
1295 1895 )
: Promise<
JudgeVerdict> {
1296 1896 const model
= resolveJudgeModel(ctx, settings);
1297 1897 if (
!model)
return { done:
false, blocked:
false, reason:
"no judge model" };
1298 - const loader
= new DefaultResourceLoader({
1300 - systemPromptOverride: ()
=> JUDGE_SYSTEM_PROMPT,
1898 + const loader
= new DefaultResourceLoader(
judgeResourceLoaderOptions(ctx));
1302 1899 await loader.
reload();
1303 1900 const { session }
= await createAgentSession({
1320 1917 await session.
prompt(
1321 - judgeUserPrompt(
judgePayload(ctx, state, settings, evidence)),
1918 + judgeUserPrompt(
judgePayload(ctx, state, settings, evidence, dossier)),
1322 1919 { source:
"extension" },
1336 1933 state: GoalState,
1337 1934 settings: GoalSettings,
1338 1935 evidence: TurnEvidence
| undefined,
1936 + dossier: GoalDossier
| undefined,
1339 1937 ):
Promise<JudgeVerdict
> {
1340 1938 if ((globalThis as GoalTestGlobals)[JUDGE_COMPLETE_FOR_TEST])
1341 - return
judgeGoalWithDirectComplete(ctx, state, settings, evidence);
1939 + return
judgeGoalWithDirectComplete(ctx, state, settings, evidence, dossier);
1940 + if (process.env.VITEST) throw new
Error(
"test judge unavailable");
1342 1941 let lastError: unknown;
1343 1942 for (let attempt
= 0; attempt
< JUDGE_ATTEMPTS; attempt
++) {
1345 - return await
judgeGoalWithAgent(ctx, state, settings, evidence);
1944 + return await
judgeGoalWithAgent(ctx, state, settings, evidence, dossier);
1346 1945 }
catch (error) {
1347 1946 lastError
= error;
2078 + const dossier
= latestGoalDossier(ctx, latest.
id);
1479 2079 pi.
sendMessage(
1481 2081 customType: GOAL_CONTINUATION_ENTRY,
1482 - content:
continuationPrompt(latest),
2082 + content:
continuationPrompt(latest, dossier),
1483 2083 display:
false,
1484 2084 details: { goalId: latest.
id, turn: latest.turnsUsed
+ 1 },
1627 2227 pi.
on(
"session_start", (_event, ctx)
=> {
1628 2228 state
= latestGoalState(ctx);
2229 + if (state
&& state.
status === "active")
ensureDossier(pi, ctx, state);
1629 2230 continuation.queued
= false;
1630 2231 continuation.scheduled
= false;
1631 2232 removeTerminalInput?.();
1660 2261 lastReason:
`steering added as criterion: ${shortText(text)}`,
1662 2263 appendGoalEvent(pi, ctx,
"steering-added", state, { text });
2264 + refreshPlannerInBackground(
2268 + ensureDossier(pi, ctx, state),
1663 2271 renderGoalUi(ctx, state);
1665 2273 pi.
sendMessage(
1682 2290 const objective
= extractStandingGoalObjective(
event.
prompt);
1683 2291 if (objective) {
1684 2292 const settings
= loadSettings(pi);
1685 - const now
= Date.
now();
1687 - id: crypto.
randomUUID(),
1692 - tokenBudget: settings.tokenBudget,
1694 - timeBudgetSeconds: settings.timeBudgetSeconds,
1695 - timeUsedSeconds:
0,
1697 - sessionId:
currentSessionId(ctx),
2293 + state
= createGoalState(objective, settings,
currentSessionId(ctx));
1701 2294 appendGoal(pi, state);
2295 + const dossier
= appendDossier(pi,
createInitialDossier(state));
2296 + refreshPlannerInBackground(pi, ctx, state, dossier,
"adopted-goal");
1702 2297 renderGoalUi(ctx, state);
1703 2298 syncUpdateGoalTool();
1706 2301 if (
!state
|| state.
status !== "active" || !ownsGoal(ctx, state))
return;
1707 - return { systemPrompt:
event.systemPrompt
+ activeGoalPrompt(state) };
2302 + const dossier
= ensureDossier(pi, ctx, state);
2304 + systemPrompt:
event.systemPrompt
+ activeGoalPrompt(state, dossier),
1710 2308 pi.
on(
"context", (event)
=> {
1780 2378 syncUpdateGoalTool();
1781 2379 if (
!state
|| state.
status !== "active" || !ownsGoal(ctx, state))
return;
1782 2380 const evidence
= lastTurnEvidence;
2381 + const settings
= loadSettings(pi);
2382 + let dossier
= ensureDossier(pi, ctx, state);
2383 + dossier
= appendTurnEvidenceToDossier(
2386 + state.turnsUsed
+ 1,
1784 2391 evidence?.stopReason
=== "aborted" || 1785 2392 evidence?.stopReason
=== "error" 1827 2434 renderGoalUi(ctx, judged,
"judging");
1828 2435 let verdict
: JudgeVerdict;
1830 - verdict
= await judgeGoal(ctx, judged,
loadSettings(pi), evidence);
2437 + verdict
= normalizeJudgeVerdict(
2438 + await judgeGoal(ctx, judged, settings, evidence, dossier),
1831 2440 }
catch (err) {
2442 + err
instanceof Error && err.message
? err.message
: String(err);
1834 2445 blocked:
false,
1835 - reason:
`judge failed: ${(err as Error).message}`,
2446 + reason:
`judge failed: ${message}`,
1838 2449 if (state
!== judged
|| state.
status !== "active")
return;
2450 + dossier
= updateDossier(pi,
latestGoalDossier(ctx, judged.
id)
?? dossier, {
2451 + lastJudgeReason: verdict.reason,
1839 2453 appendJudge(pi, ctx,
"verdict", judged, verdict);
1840 2454 const commonPatch
: Partial<
GoalState>
= {
1841 2455 lastReason: verdict.reason,
1862 2476 appendGoalEvent(pi, ctx,
"paused", state, { reason: verdict.reason });
1864 2478 ctx.ui.
notify(
`Goal paused — ${verdict.reason}`,
"warning");
1865 - }
else scheduleContinuation(pi, ctx, state, continuation);
2480 + refreshPlannerInBackground(pi, ctx, state, dossier,
"judge-failed");
2481 + scheduleContinuation(pi, ctx, state, continuation);
1868 2485 if (verdict.done) {
1897 2514 appendGoalEvent(pi, ctx,
"blocked", state, { reason: verdict.reason });
1899 2516 ctx.ui.
notify(
`Goal blocked: ${verdict.reason}`,
"warning");
1900 - }
else scheduleContinuation(pi, ctx, state, continuation);
2518 + if (blockedStreak.count
>= 2)
2519 + refreshPlannerInBackground(pi, ctx, state, dossier,
"blocked-risk");
2520 + scheduleContinuation(pi, ctx, state, continuation);
1903 2524 const turnsUsed
= judged.turnsUsed
+ 1;
1935 2556 renderGoalUi(ctx, state);
1936 2557 syncUpdateGoalTool();
2559 + const trigger
= shouldRefreshPlanner(state, dossier, verdict);
2560 + if (trigger)
refreshPlannerInBackground(pi, ctx, state, dossier, trigger);
1937 2562 scheduleContinuation(pi, ctx, state, continuation);
2014 2639 errorRetries:
0,
2015 2640 sessionId:
currentSessionId(ctx),
2642 + const dossier
= ensureDossier(pi, ctx, state);
2643 + refreshPlannerInBackground(pi, ctx, state, dossier,
"resume");
2017 2644 renderGoalUi(ctx, state);
2018 2645 syncUpdateGoalTool();
2110 2737 const settings
= loadSettings(pi);
2112 - id: crypto.
randomUUID(),
2117 - tokenBudget: settings.tokenBudget,
2119 - timeBudgetSeconds: settings.timeBudgetSeconds,
2120 - timeUsedSeconds:
0,
2122 - sessionId:
currentSessionId(ctx),
2123 - createdAt:
Date.
now(),
2124 - updatedAt:
Date.
now(),
2738 + state
= createGoalState(input, settings,
currentSessionId(ctx));
2126 2739 appendGoal(pi, state);
2740 + const dossier
= appendDossier(pi,
createInitialDossier(state));
2741 + refreshPlannerInBackground(pi, ctx, state, dossier,
"new-goal");
2127 2742 renderGoalUi(ctx, state);
2128 2743 syncUpdateGoalTool();
2129 2744 ctx.ui.
notify(
"Goal set",
"info");
2152 2767 export const GOAL_PROBE_MESSAGE
= PROBE_MESSAGE;
2153 2768 export const GOAL_STATE_CUSTOM_TYPE
= GOAL_STATE_ENTRY;
2769 +export const GOAL_DOSSIER_CUSTOM_TYPE
= GOAL_DOSSIER_ENTRY;
2154 2770 function setCompleteJudgeForTest(fn
: JudgeComplete) {
2155 2771 (globalThis
as GoalTestGlobals)[JUDGE_COMPLETE_FOR_TEST]
= fn;
2172 2788 latestAssistantTail,
2173 2789 latestGoalState,
2790 + latestGoalDossier,
2792 + createInitialDossier,
2793 + applyPlannerOutput,
2797 + appendTurnEvidenceToDossier,
2174 2798 buildTurnEvidence,
2175 2799 mergeTurnEvidence,
2205 2829 isJudgeParseFailure,
2206 2830 judgeVerdictLabel,
2207 2831 goalVerdictLabel,
2832 + judgeResourceLoaderOptions,
2208 2833 showsTurnBudget,
2209 2834 showsPersistentStatus,
2210 2835 wrapVisibleWords,