Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI] Keep goal token accounting monotonic across summary context rebuilds (#2215)

Seth Karten215e7a7409b2
diff --git a/packages/coding-agent/.changes/eng-6081-goal-token-monotonicity.md b/packages/coding-agent/.changes/eng-6081-goal-token-monotonicity.md
new file mode 100644
index 0000000000..70c25b91d9
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-6081-goal-token-monotonicity.md
@@ -0,0 +1 @@
+- Fixed goal token accounting regressing across compaction context rebuilds: the same goal's usage counter can no longer move backwards when a summary navigation reloads a stale persisted state, and a stale active snapshot can no longer revive a goal whose budget gate already fired.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index d5351155ae..7a854eb064 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -1945,8 +1945,25 @@ export class AgentSession {
return true;
}
- private _reloadGoalStateFromBranch(): void {
- this._goalState = this._loadPersistedGoalState();
+ private _reloadGoalStateFromBranch(options: { monotonicTokens?: boolean } = {}): void {
+ const previous = this._goalState;
+ const reloaded = this._loadPersistedGoalState();
+ if (options.monotonicTokens && reloaded.goalId !== undefined && reloaded.goalId === previous.goalId) {
+ // A context rebuild continues the same timeline, but the rebuilt branch's
+ // last persisted goal entry can lag the in-memory state (queue/flush
+ // races; child-usage attribution landing late). Neither the accounting
+ // counters nor an already-fired gate (budget limit, pause, completion)
+ // for the same logical goal may regress across the cold boundary. Tree
+ // navigation keeps faithful branch semantics by calling without the flag.
+ this._goalState = {
+ ...previous,
+ tokensUsed: Math.max(previous.tokensUsed, reloaded.tokensUsed),
+ continuationsUsed: Math.max(previous.continuationsUsed, reloaded.continuationsUsed),
+ timeUsedSeconds: Math.max(previous.timeUsedSeconds, reloaded.timeUsedSeconds),
+ };
+ } else {
+ this._goalState = reloaded;
+ }
this._goalAccountingStartedAt = this._goalState.status === "active" ? Date.now() : undefined;
this._emitGoalUpdate();
}
@@ -12993,8 +13010,11 @@ export class AgentSession {
this._mergeUnpersistedOutcomes(this.agent.state.messages);
this._restoreLateIpythonSentAgentMessages();
// Context rebuild = cold boundary: refresh the digest like resume.
+ // Summary navigation continues the same timeline (compaction), so the
+ // same goal's accounting must never regress; a plain branch move is
+ // time travel and keeps faithful branch semantics.
this._ensureHarnessDigestContext();
- this._reloadGoalStateFromBranch();
+ this._reloadGoalStateFromBranch({ monotonicTokens: Boolean(summaryText) });
this._reloadRlmMaxDepthFromBranch();
this._invalidateQueuedPromptPreparation();
diff --git a/packages/coding-agent/test/suite/agent-session-goal.test.ts b/packages/coding-agent/test/suite/agent-session-goal.test.ts
index 969cf111dc..79cfce57e4 100644
--- a/packages/coding-agent/test/suite/agent-session-goal.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-goal.test.ts
@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { AgentSession } from "../../src/core/agent-session.js";
import { AuthStorage } from "../../src/core/auth-storage.js";
import type { ExtensionFactory } from "../../src/core/extensions/types.js";
-import type { GoalHostResponse } from "../../src/core/goals.js";
+import { GOAL_STATE_CUSTOM_TYPE, type GoalHostResponse } from "../../src/core/goals.js";
import { ModelRegistry } from "../../src/core/model-registry.js";
import { SessionManager } from "../../src/core/session-manager.js";
import { SettingsManager } from "../../src/core/settings-manager.js";
@@ -476,6 +476,142 @@ describe("AgentSession goals", () => {
});
});
+ it("keeps goal token accounting monotonic across summary context rebuilds", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.session.handleGoalHostRequest("goal.create", { objective: "do work" });
+
+ const goalId = harness.session.goalState.goalId;
+ expect(harness.session.goalState.status).toBe("active");
+
+ // Bill usage to the active goal through the same path a real assistant
+ // message_end uses.
+ const billed = assistantWithUsage("working", { input: 40, output: 10, totalTokens: 50 });
+ const accounted = (
+ harness.session as unknown as {
+ _accountGoalUsageForAssistantMessage(message: AssistantMessage): boolean;
+ }
+ )._accountGoalUsageForAssistantMessage(billed);
+ // The method returns true only when accounting hits the token budget;
+ // normal accounting returns false.
+ expect(accounted).toBe(false);
+ expect(harness.session.goalState.tokensUsed).toBeGreaterThanOrEqual(50);
+
+ // Simulate a stale persisted snapshot for the SAME goal: an older
+ // accounting entry re-persisted after newer usage (queue/flush race,
+ // or child-usage attribution landing after the branch was written).
+ harness.sessionManager.appendCustomEntry(GOAL_STATE_CUSTOM_TYPE, {
+ ...harness.session.goalState,
+ tokensUsed: 1,
+ continuationsUsed: 0,
+ timeUsedSeconds: 0,
+ });
+
+ const reload = (options?: { monotonicTokens?: boolean }) =>
+ (
+ harness.session as unknown as {
+ _reloadGoalStateFromBranch(options?: { monotonicTokens?: boolean }): void;
+ }
+ )._reloadGoalStateFromBranch(options);
+
+ // Summary navigation (compaction) continues the same timeline: the same
+ // goal's accounting must not regress to the stale snapshot.
+ reload({ monotonicTokens: true });
+ expect(harness.session.goalState.status).toBe("active");
+ expect(harness.session.goalState.goalId).toBe(goalId);
+ expect(harness.session.goalState.tokensUsed).toBeGreaterThanOrEqual(50);
+
+ // Plain branch moves are time travel and stay faithful to the branch's
+ // last persisted entry, even when it is lower.
+ reload();
+ expect(harness.session.goalState.tokensUsed).toBe(1);
+ });
+
+ it("keeps a fired budget gate monotonic across summary context rebuilds", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.session.handleGoalHostRequest("goal.create", { objective: "do work", token_budget: 100 });
+
+ const goalId = harness.session.goalState.goalId;
+
+ // Bill usage until the budget gate fires.
+ const billed = assistantWithUsage("working", { input: 60, output: 50, totalTokens: 110 });
+ const accounted = (
+ harness.session as unknown as {
+ _accountGoalUsageForAssistantMessage(message: AssistantMessage): boolean;
+ }
+ )._accountGoalUsageForAssistantMessage(billed);
+ expect(accounted).toBe(true);
+ expect(harness.session.goalState.status).toBe("budget_limited");
+
+ // Stale branch snapshot for the same goal predates the budget gate.
+ harness.sessionManager.appendCustomEntry(GOAL_STATE_CUSTOM_TYPE, {
+ ...harness.session.goalState,
+ status: "active",
+ active: true,
+ tokensUsed: 10,
+ });
+
+ const reload = (options?: { monotonicTokens?: boolean }) =>
+ (
+ harness.session as unknown as {
+ _reloadGoalStateFromBranch(options?: { monotonicTokens?: boolean }): void;
+ }
+ )._reloadGoalStateFromBranch(options);
+
+ // A summary rebuild continues the same timeline: the gate that already
+ // fired must survive, and the counter must not regress.
+ reload({ monotonicTokens: true });
+ expect(harness.session.goalState.status).toBe("budget_limited");
+ expect(harness.session.goalState.goalId).toBe(goalId);
+ expect(harness.session.goalState.tokensUsed).toBeGreaterThanOrEqual(110);
+ });
+
+ it("treats an empty extension summary as a plain branch move for goal accounting", async () => {
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("session_before_tree", async () => ({ summary: { summary: "" } }));
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.session.handleGoalHostRequest("goal.create", { objective: "do work" });
+
+ const goalId = harness.session.goalState.goalId;
+ // Append the entry to navigate to directly so no goal continuation turn
+ // runs; the goal stays active with only the billed usage.
+ harness.sessionManager.appendMessage({
+ role: "user",
+ content: [{ type: "text", text: "do something" }],
+ timestamp: Date.now(),
+ });
+
+ const billed = assistantWithUsage("working", { input: 40, output: 10, totalTokens: 50 });
+ (
+ harness.session as unknown as {
+ _accountGoalUsageForAssistantMessage(message: AssistantMessage): boolean;
+ }
+ )._accountGoalUsageForAssistantMessage(billed);
+ expect(harness.session.goalState.status).toBe("active");
+ expect(harness.session.goalState.tokensUsed).toBeGreaterThanOrEqual(50);
+
+ // The extension returns an empty summary string, so no summary branch is
+ // created: the navigation is a plain branch move and must reload the
+ // branch's own goal state instead of clamping counters.
+ const userEntry = harness.sessionManager
+ .getEntries()
+ .find((entry) => entry.type === "message" && entry.message.role === "user");
+ expect(userEntry).toBeDefined();
+ const result = await harness.session.navigateTree(userEntry!.id, { summarize: true });
+
+ expect(result.cancelled).toBe(false);
+ expect(result.summaryEntry).toBeUndefined();
+ expect(harness.session.goalState.status).toBe("active");
+ expect(harness.session.goalState.goalId).toBe(goalId);
+ expect(harness.session.goalState.tokensUsed).toBe(0);
+ });
+
it("normalizes queued goal context text and images", async () => {
const harness = await createGoalHarness();
const image = { type: "image" as const, data: "image-data", mimeType: "image/png" };