A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(goals): refresh queued continuation accounting at delivery (#2224)
Seth Karten9bd6a9bc0fbc
diff --git a/packages/coding-agent/.changes/eng-6089-goal-continuation-delivery-refresh.md b/packages/coding-agent/.changes/eng-6089-goal-continuation-delivery-refresh.mdnew file mode 100644index 0000000000..d19bd8be16--- /dev/null+++ b/packages/coding-agent/.changes/eng-6089-goal-continuation-delivery-refresh.md@@ -0,0 +1 @@+- Fixed goal continuation prompts delivering a stale accounting snapshot taken when the continuation was queued; usage numbers now refresh at delivery time so long-queued continuations report the current budget state.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 39f4bf3ce4..e185a12793 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -159,6 +159,7 @@ import {GOAL_CONTEXT_PREVIEW_LABEL,GOAL_SKILL_NAME,GOAL_STATE_CUSTOM_TYPE,+ type GoalContextDetails,type GoalHostResponse,type GoalState,type GoalStatus,@@ -2680,6 +2681,40 @@ export class AgentSession {}}+ /**+ * Queued goal continuations snapshot goal accounting at queue time, but+ * delivery can lag arbitrarily (a threshold compaction, admission pauses,+ * other queued work) while usage keeps accruing. A continuation's whole+ * purpose is "here is the current goal state — keep working", so stale+ * numbers misreport the budget and can mislead the model into stopping+ * early or ignoring limits. Refresh the frozen content in place at+ * delivery, preserving the message identity every queue/dedup marker+ * (post-compaction continuation tracking, threshold dedup) matches on.+ * Budget-limit steers are excluded: they are created immediately after the+ * accounting event they report, and `objective_updated` carries the+ * objective snapshot that was the event.+ */+ private _refreshGoalContextMessageAtDelivery(message: AgentMessage): void {+ if (message.role !== "custom" || message.customType !== GOAL_CONTEXT_CUSTOM_TYPE) return;+ const custom = message as CustomMessage<GoalContextDetails | undefined>;+ const details = custom.details;+ if (details?.kind !== "continuation" || details.goalId === undefined) return;+ if (+ this._goalState.status !== "active" ||+ this._goalState.goalId !== details.goalId ||+ !this._goalState.objective+ ) {+ return;+ }+ const images = Array.isArray(custom.content)+ ? custom.content.filter((block): block is ImageContent => block.type === "image")+ : undefined;+ const fresh = createGoalContextMessage(this._goalState, "continuation", images);+ custom.content = fresh.content;+ custom.details = fresh.details;+ custom.timestamp = fresh.timestamp;+ }+private _runOrQueueGoalContext(kind: "continuation" | "objective_updated", images?: ImageContent[]): void {if (!this._goalState.objective) return;this._ensureGoalRuntimeActive();@@ -6725,6 +6760,11 @@ export class AgentSession {);const firstPrimaryIndex = turns[0].payload.records.indexOf(primaryDeliveryRecord(turns[0]));turns[0].payload.records.splice(firstPrimaryIndex, 0, ...contextRecords);+ for (const action of turns) {+ // Queued continuations must report goal accounting as of delivery,+ // not as of queue time (see refresh rationale).+ this._refreshGoalContextMessageAtDelivery(primaryDeliveryRecord(action).message);+ }const preparedMessages: AgentMessage[] = turns.flatMap((action) =>action.payload.records.map((record) => record.message),);diff --git a/packages/coding-agent/test/goal-continuation-refresh.test.ts b/packages/coding-agent/test/goal-continuation-refresh.test.tsnew file mode 100644index 0000000000..c52b956faf--- /dev/null+++ b/packages/coding-agent/test/goal-continuation-refresh.test.ts@@ -0,0 +1,119 @@+import type { AgentMessage } from "@earendil-works/pi-agent-core";+import { describe, expect, it } from "vitest";+import { AgentSession } from "../src/core/agent-session.js";+import { createGoalContextMessage, type GoalContextKind, type GoalState } from "../src/core/goals.js";+import type { CustomMessage } from "../src/core/messages.js";++type Harness = {+ _goalState: GoalState;+};++const refresh = Reflect.get(AgentSession.prototype, "_refreshGoalContextMessageAtDelivery") as (+ this: Harness,+ message: AgentMessage,+) => void;++function goalState(overrides: Partial<GoalState> = {}): GoalState {+ return {+ active: true,+ goalId: "goal-1",+ objective: "ship the artifact",+ status: "active",+ tokensUsed: 1_000,+ timeUsedSeconds: 10,+ continuationsUsed: 1,+ createdAt: 1_757_500_000_000,+ updatedAt: 1_757_500_000_000,+ ...overrides,+ };+}++function frozenMessage(at: GoalState, kind: GoalContextKind): CustomMessage {+ // Build with the real constructor so the wire format is exercised.+ return createGoalContextMessage(at, kind) as unknown as CustomMessage;+}++function textOf(message: CustomMessage): string {+ return typeof message.content === "string"+ ? message.content+ : message.content+ .filter((block) => block.type === "text")+ .map((block) => (block as { text: string }).text)+ .join("\n");+}++describe("goal continuation delivery-time refresh", () => {+ it("refreshes stale accounting in place, preserving message identity", () => {+ const mode: Harness = { _goalState: goalState({ tokensUsed: 401_869, continuationsUsed: 4 }) };+ const frozen = frozenMessage(goalState({ tokensUsed: 358_712, continuationsUsed: 3 }), "continuation");+ expect(textOf(frozen)).toContain("tokens used: 358712");++ refresh.call(mode, frozen as unknown as AgentMessage);++ expect(textOf(frozen)).toContain("tokens used: 401869");+ expect(textOf(frozen)).not.toContain("tokens used: 358712");+ expect((frozen.details as { continuationsUsed: number }).continuationsUsed).toBe(4);+ });++ it("keeps images from the queued message while refreshing the text", () => {+ const mode: Harness = { _goalState: goalState({ tokensUsed: 9_000 }) };+ const image = { type: "image", data: "aW1hZ2U=", mimeType: "image/png" } as const;+ const frozen = createGoalContextMessage(goalState({ tokensUsed: 1_000 }), "continuation", [+ image as never,+ ]) as unknown as CustomMessage;++ refresh.call(mode, frozen as unknown as AgentMessage);++ const blocks = frozen.content as Array<{ type: string }>;+ expect(blocks.some((block) => block.type === "image")).toBe(true);+ expect(textOf(frozen)).toContain("tokens used: 9000");+ });++ it("leaves the message untouched when the goal id no longer matches", () => {+ const mode: Harness = { _goalState: goalState({ goalId: "goal-2", tokensUsed: 9_000 }) };+ const frozen = frozenMessage(goalState({ tokensUsed: 1_000 }), "continuation");++ refresh.call(mode, frozen as unknown as AgentMessage);++ expect(textOf(frozen)).toContain("tokens used: 1000");+ });++ it("leaves the message untouched when the goal is no longer active", () => {+ const mode: Harness = { _goalState: goalState({ status: "paused", active: false }) };+ const frozen = frozenMessage(goalState({ tokensUsed: 1_000 }), "continuation");++ refresh.call(mode, frozen as unknown as AgentMessage);++ expect(textOf(frozen)).toContain("tokens used: 1000");+ });++ it("never refreshes budget_limit or objective_updated kinds", () => {+ const mode: Harness = { _goalState: goalState({ tokensUsed: 9_000 }) };+ const budget = frozenMessage(goalState({ tokensUsed: 1_000 }), "budget_limit");+ const updated = frozenMessage(+ goalState({ tokensUsed: 1_000, objective: "older objective" }),+ "objective_updated",+ );++ refresh.call(mode, budget as unknown as AgentMessage);+ refresh.call(mode, updated as unknown as AgentMessage);++ expect(textOf(budget)).toContain("1000");+ expect(textOf(updated)).toContain("1000");+ expect(textOf(updated)).toContain("older objective");+ });++ it("ignores non-goal-context messages", () => {+ const mode: Harness = { _goalState: goalState() };+ const other: CustomMessage = {+ role: "custom",+ customType: "unrelated_type",+ content: "frozen",+ display: true,+ timestamp: 1,+ };++ expect(() => refresh.call(mode, other as unknown as AgentMessage)).not.toThrow();+ expect(other.content).toBe("frozen");+ });+});