From d58eaba2cfec1d48c872e7240c8a0055bb7068d7 Mon Sep 17 00:00:00 2001 From: Phil Date: Thu, 26 Nov 2026 18:40:35 +0100 Subject: [PATCH 01/12] fix(restored-task): follow the active provider profile on restore Restoring a task re-activated the profile pinned in HistoryItem.apiConfigName even when the user had switched to a different profile while the task was stopped, so the resumed task and the task header kept the old provider's context window and the usage bar could exceed 100% (issue #970). The restore path now resolves the decision through resolveRestoreProfileActivation: an existing pin equal to the active profile is re-applied as before; a pin differing from the active profile is treated as stale, the active profile stays in effect, and the history item is re-pinned to it. A deleted pin falls back to the active profile when one resolves, and no active profile preserves the legacy fallback. Spec: docs/architecture/tla/RestoreProfileDecision (TLC pass 15 states; sabotage violates FollowActive at 9 states). Tests: ClineProvider.restore-follows-active-profile (red-verified on the pre-fix restore path) and restore-provider-profile decision table. --- .../tla/RestoreProfileDecision.Sabotage.cfg | 7 + .../tla/RestoreProfileDecision.cfg | 6 + .../tla/RestoreProfileDecision.tla | 78 ++++++ .../tla/RestoreProfileDecisionMC.tla | 12 + ...der.restore-follows-active-profile.spec.ts | 226 ++++++++++++++++++ src/core/webview/ClineProvider.ts | 45 +++- .../restore-provider-profile.spec.ts | 88 +++++++ src/core/webview/restore-provider-profile.ts | 67 ++++++ 8 files changed, 517 insertions(+), 12 deletions(-) create mode 100644 docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg create mode 100644 docs/architecture/tla/RestoreProfileDecision.cfg create mode 100644 docs/architecture/tla/RestoreProfileDecision.tla create mode 100644 docs/architecture/tla/RestoreProfileDecisionMC.tla create mode 100644 src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts create mode 100644 src/core/webview/__tests__/restore-provider-profile.spec.ts create mode 100644 src/core/webview/restore-provider-profile.ts diff --git a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg new file mode 100644 index 00000000000..3299de5c8b9 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg @@ -0,0 +1,7 @@ +\* Sabotage check. The stale-pin guard is removed. FollowActive must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Decide <- DecideAlwaysPin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback diff --git a/docs/architecture/tla/RestoreProfileDecision.cfg b/docs/architecture/tla/RestoreProfileDecision.cfg new file mode 100644 index 00000000000..84f61a1227d --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.cfg @@ -0,0 +1,6 @@ +\* RestoreProfileDecision.cfg — the decision must satisfy every invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla new file mode 100644 index 00000000000..1813d7dca6d --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -0,0 +1,78 @@ +---- MODULE RestoreProfileDecision ---- +\* Models src/core/webview/restore-provider-profile.ts resolveRestoreProfileActivation. +\* Source: HistoryItem.apiConfigName (the pin) and the currentApiConfigName global, +\* resolved against the profile list by ClineProvider.createTaskWithHistoryItemUnlocked. +\* Sink: the decision record (reactivateProfileName, refreshedApiConfigName) consumed by +\* the same method: reactivate calls activateProviderProfile, refresh rewrites the pin +\* through updateTaskHistory and the Task constructor. +\* Failure: restore re-activates a stale pinned profile, so the resumed task and the +\* task header keep the old provider's context window (issue #970). +\* Invariants (first version written before the fix): +\* FollowActive. With an existing pin and a resolvable active profile different from +\* it, the decision must not reactivate the pinned profile. +\* PinNamesEffect. A refresh names exactly the active profile, and a reactivation +\* never also refreshes. +\* LegacyFallback. With no resolvable active profile, an existing pin is reactivated. +\* Run each config on RestoreProfileDecisionMC.tla. The MC module holds the sabotage. +\* Expected before the run: all invariants hold in the model; the sabotage run fails +\* FollowActive only. +\* Result: TypeOK, FollowActive, PinNamesEffect and LegacyFallback hold in the model in +\* 15 distinct states. The sabotage run violates FollowActive at 9 states; no other +\* invariant breaks. +\* Not modeled: the profile list (pinnedProfileExists is an oracle the caller computes), +\* the activateProviderProfile and updateTaskHistory side effects, and the CLI runtime +\* skip flag (checked before the decision runs). +\* Cost: TLC finishes in under 1 second per config. + +CONSTANT NoActive \* sentinel: no resolvable active profile at restore time + +VARIABLES input, decision + +vars == <> + +NoProfile == "absent" \* decision marker: reactivate nothing +Keep == "keep" \* decision marker: preserve the stored pin + +Input == [pin: {"p1", "p2", "absent"}, active: {"p1", "p2", NoActive}, pinExists: BOOLEAN] + +\* The caller never passes an existing flag for an absent pin. +Valid(inp) == (inp.pin = "absent") => (~inp.pinExists) + +\* Mirrors resolveRestoreProfileActivation rule for rule. +Decide(inp) == + IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF ~inp.pinExists THEN + IF inp.active # NoActive THEN [r |-> NoProfile, f |-> inp.active] + ELSE [r |-> NoProfile, f |-> Keep] + ELSE IF inp.active = NoActive THEN [r |-> inp.pin, f |-> Keep] + ELSE IF inp.active = inp.pin THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> inp.active] + +Init == + /\ input = [pin |-> "absent", active |-> NoActive, pinExists |-> FALSE] + /\ decision = Decide(input) + +Next == + \E inp \in Input : + /\ Valid(inp) + /\ input' = inp + /\ decision' = Decide(inp) + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ decision.r \in {"p1", "p2", "absent"} + /\ decision.f \in {"p1", "p2", "keep"} + +FollowActive == + (input.pin # "absent" /\ input.pinExists /\ input.active # NoActive /\ input.active # input.pin) + => decision.r = NoProfile + +PinNamesEffect == + /\ (decision.f # Keep) => decision.f = input.active + /\ (decision.r # NoProfile) => decision.f = Keep + +LegacyFallback == + (input.pin # "absent" /\ input.pinExists /\ input.active = NoActive) => decision.r = input.pin + +==== diff --git a/docs/architecture/tla/RestoreProfileDecisionMC.tla b/docs/architecture/tla/RestoreProfileDecisionMC.tla new file mode 100644 index 00000000000..9588a1abd72 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecisionMC.tla @@ -0,0 +1,12 @@ +---- MODULE RestoreProfileDecisionMC ---- +\* Model-checking settings for RestoreProfileDecision. +EXTENDS RestoreProfileDecision + +\* Sabotage: the stale-pin guard is removed. The pin is always re-activated when it +\* exists (the pre-fix behavior) and the pin is never refreshed. +DecideAlwaysPin(inp) == + IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF inp.pinExists THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> Keep] + +==== diff --git a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts new file mode 100644 index 00000000000..9ac4c87f30b --- /dev/null +++ b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts @@ -0,0 +1,226 @@ +// npx vitest run __tests__/ClineProvider.restore-follows-active-profile.spec.ts +// +// Issue #970: the task header's context window stays on the old provider after a +// stop -> switch provider -> restore flow, and the usage bar can exceed 100%. +// Root cause on this path: ClineProvider.createTaskWithHistoryItemUnlocked +// re-activates the profile pinned in HistoryItem.apiConfigName even when the user +// has switched to a different profile while the task was stopped, so the restored +// task and the header keep the old provider's context window. +// +// Failure sentences these tests prevent: +// 1. Restoring a task re-activates a stale pinned profile that differs from the +// user's active profile, so the resumed task keeps the old provider's limits. +// 2. The history item keeps pinning a profile that is not in effect for the +// restored task, so every later restore flips the configuration back. +// 3. A restore whose pinned profile no longer exists loses the re-pin to the +// profile that is actually in effect. +// +// Red-verify: tests 1 and 3 fail on pre-fix code because the restore block +// activates the stale pin unconditionally. + +import { describe, it, expect, vi, beforeEach } from "vitest" +import { providerIdentifiers } from "@roo-code/types" +import type { HistoryItem } from "@roo-code/types" + +/* vscode mock for Task/Provider imports */ +vi.mock("vscode", () => { + const window = { + createTextEditorDecorationType: vi.fn(() => ({ dispose: vi.fn() })), + showErrorMessage: vi.fn(), + onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), + } + const workspace = { + getConfiguration: vi.fn(() => ({ + get: vi.fn((_key: string, defaultValue: unknown) => defaultValue), + update: vi.fn(), + })), + workspaceFolders: [], + } + const env = { machineId: "test-machine", uriScheme: "vscode", appName: "VSCode", language: "en", sessionId: "sess" } + const Uri = { file: (p: string) => ({ fsPath: p, toString: () => p }) } + const commands = { executeCommand: vi.fn() } + const ExtensionMode = { Development: 2 } + const version = "1.0.0-test" + return { window, workspace, env, Uri, commands, ExtensionMode, version } +}) + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + captureTaskCompleted: vi.fn(), + }, + }, +})) + +vi.mock("../core/task-persistence/taskMessages", () => ({ + readTaskMessages: vi.fn().mockResolvedValue([]), +})) + +vi.mock("../core/task-persistence", async (importOriginal) => { + const real = await importOriginal() + return { + ...real, + readApiMessages: vi.fn().mockResolvedValue([]), + saveApiMessages: vi.fn(async ({ messages }: { messages: unknown[] }) => messages), + saveTaskMessages: vi.fn(async ({ messages }: { messages: unknown[] }) => messages), + } +}) + +// The tail of createTaskWithHistoryItemUnlocked constructs a real Task. Replace it +// with a recording double so the test can observe the history item the restored +// task is built from without booting the whole task runtime. +vi.mock("../core/task/Task", async (importOriginal) => { + const real = await importOriginal() + // A regular (non-arrow) function so `new Task(...)` constructs the double. + const TaskDouble = vi.fn(function TaskDoubleMock(this: Record, _options: unknown) { + this.taskId = "restored-task" + this.instanceId = "instance-1" + this.parentTask = undefined + this.abortTask = vi.fn(async () => {}) + this.emit = vi.fn() + this.clineMessages = [] + this.apiConversationHistory = [] + }) + return { ...real, Task: TaskDouble } +}) + +import { ClineProvider } from "../core/webview/ClineProvider" +import { Task } from "../core/task/Task" +import { makeProviderStub } from "./helpers/provider-stub" + +function makeHistoryItem(apiConfigName: string): HistoryItem { + return { + id: "task-1", + number: 1, + ts: 1700000000000, + task: "summarize the repository", + tokensIn: 100, + tokensOut: 20, + totalCost: 0.01, + apiConfigName, + } satisfies HistoryItem +} + +type ProfileEntry = { name: string; apiProvider?: string } + +function makeRestoreHarness(options: { profiles: ProfileEntry[]; activeProfileName: string | undefined }) { + const listConfig = vi.fn(async () => options.profiles) + const getGlobalState = vi.fn((key: string) => + key === "currentApiConfigName" ? options.activeProfileName : undefined, + ) + const activateProviderProfile = vi.fn(async () => {}) + const updateTaskHistory = vi.fn(async () => []) + + const provider = makeProviderStub({ contextProxy: { globalStorageUri: { fsPath: "/tmp" } } }) + + Object.assign(provider, { + getState: vi.fn(async () => ({ + apiConfiguration: { apiProvider: providerIdentifiers.openrouter }, + enableCheckpoints: false, + checkpointTimeout: 10, + experiments: {}, + diffFuzzyThreshold: 0.8, + })), + updateGlobalState: vi.fn(async () => {}), + getGlobalState, + activateProviderProfile, + updateTaskHistory, + providerSettingsManager: { listConfig }, + addClineToStack: vi.fn(async () => {}), + getPendingEditOperation: vi.fn(() => undefined), + taskCreationCallback: vi.fn(), + getCurrentTask: vi.fn(() => undefined), + evictCurrentTask: vi.fn(async () => {}), + }) + + const createTaskWithHistoryItemUnlocked = ( + ClineProvider.prototype as unknown as { + createTaskWithHistoryItemUnlocked: ( + this: unknown, + historyItem: HistoryItem, + options?: { startTask?: boolean }, + ) => Promise + } + ).createTaskWithHistoryItemUnlocked + + const runRestore = (historyItem: HistoryItem) => + createTaskWithHistoryItemUnlocked.call(provider, historyItem, { startTask: false }) + + return { runRestore, activateProviderProfile, updateTaskHistory, listConfig, getGlobalState } +} + +function constructedHistoryItem(): HistoryItem | undefined { + const firstCall = vi.mocked(Task).mock.calls[0]?.[0] as { historyItem?: HistoryItem } | undefined + return firstCall?.historyItem +} + +describe("ClineProvider restore follows the active profile", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("keeps the active profile when it differs from the stale pin and re-pins the task to it", async () => { + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfile).not.toHaveBeenCalled() + expect(harness.updateTaskHistory).toHaveBeenCalledWith( + expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), + ) + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + }) + + it("re-activates the pinned profile when it is still the active one", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: "provider-1", + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfile).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + ) + expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + }) + + it("re-pins to the active profile when the pinned profile no longer exists", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + }) + + await harness.runRestore(makeHistoryItem("deleted-profile")) + + expect(harness.activateProviderProfile).not.toHaveBeenCalled() + expect(harness.updateTaskHistory).toHaveBeenCalledWith( + expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), + ) + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + }) + + it("re-activates the pin when no resolvable active profile exists", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: undefined, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfile).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + ) + expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + }) +}) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 542e6bb7682..68542b2091a 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -25,6 +25,8 @@ import { beginExplicitRecovery, } from "./webviewRecoveryPolicy" +import { resolveRestoreProfileActivation } from "./restore-provider-profile" + import { type TaskProviderLike, type TaskProviderEvents, @@ -1608,19 +1610,29 @@ export class ClineProvider // Keep global state/UI in sync with latest profiles for parity with mode restoration above. await this.updateGlobalState("listApiConfigMeta", listApiConfig) const profile = listApiConfig.find(({ name }) => name === historyItem.apiConfigName) + // The profile active at restore time is the user's latest choice; a pin naming a + // different profile is stale (the task saved it before the switch). Resolving the + // active name against the profile list keeps a dangling pointer out of the decision. + const currentApiConfigName = this.getGlobalState("currentApiConfigName") + const activeProfileName = listApiConfig.some(({ name }) => name === currentApiConfigName) + ? currentApiConfigName + : undefined + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName: historyItem.apiConfigName, + activeProfileName, + pinnedProfileExists: !!profile, + }) - if (profile?.name) { + if (decision.reactivateProfileName && profile?.name && profile.apiProvider) { try { - if (profile.apiProvider) { - await this.activateProviderProfile( - { name: profile.name }, - { - persistModeConfig: false, - persistTaskHistory: false, - expectedCurrentTaskId: historyItem.id, - }, - ) - } + await this.activateProviderProfile( + { name: profile.name }, + { + persistModeConfig: false, + persistTaskHistory: false, + expectedCurrentTaskId: historyItem.id, + }, + ) } catch (error) { // Log the error but continue with task restoration. this.log( @@ -1629,7 +1641,16 @@ export class ClineProvider }. Continuing with current configuration.`, ) } - } else { + } else if (decision.refreshedApiConfigName) { + // The pin names a profile that is not in effect at restore time. Keep the user's + // active profile (and its context window) and re-pin the task to it, so later + // restores do not flip the configuration back to the stale profile. + this.log( + `Restoring task ${historyItem.id} with active profile '${decision.refreshedApiConfigName}' instead of stale pinned profile '${historyItem.apiConfigName}'.`, + ) + historyItem.apiConfigName = decision.refreshedApiConfigName + await this.updateTaskHistory({ ...historyItem, apiConfigName: decision.refreshedApiConfigName }) + } else if (!decision.reactivateProfileName) { // Profile no longer exists, log warning but continue this.log( `Provider profile '${historyItem.apiConfigName}' from history no longer exists. Using current configuration.`, diff --git a/src/core/webview/__tests__/restore-provider-profile.spec.ts b/src/core/webview/__tests__/restore-provider-profile.spec.ts new file mode 100644 index 00000000000..1d06b084a65 --- /dev/null +++ b/src/core/webview/__tests__/restore-provider-profile.spec.ts @@ -0,0 +1,88 @@ +// npx vitest run core/webview/__tests__/restore-provider-profile.spec.ts +// +// Decision-table tests for resolveRestoreProfileActivation, the pure decision at +// the heart of the issue #970 fix ("restore follows the active profile"). +// +// Invariants (one per failure sentence): +// - FollowActive: with an existing pin and a resolvable active profile that +// differs from it, the decision must not reactivate the pinned profile. +// - PinNamesEffect: a refresh must name exactly the active profile, and a +// decision that reactivates must never also refresh. +// - LegacyFallback: with no resolvable active profile, an existing pinned +// profile is reactivated exactly as before the fix. + +import { describe, it, expect } from "vitest" + +import { resolveRestoreProfileActivation } from "../restore-provider-profile" + +describe("resolveRestoreProfileActivation", () => { + it.each([ + { + name: "no pin: nothing to reactivate and nothing to refresh", + pinnedApiConfigName: undefined, + activeProfileName: "provider-2", + pinnedProfileExists: false, + expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, + }, + { + name: "existing pin with no resolvable active profile: legacy fallback reactivates the pin", + pinnedApiConfigName: "provider-1", + activeProfileName: undefined, + pinnedProfileExists: true, + expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, + }, + { + name: "existing pin equal to the active profile: reactivation only, pin preserved", + pinnedApiConfigName: "provider-1", + activeProfileName: "provider-1", + pinnedProfileExists: true, + expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, + }, + { + name: "existing pin that differs from the active profile: follow the active profile", + pinnedApiConfigName: "provider-1", + activeProfileName: "provider-2", + pinnedProfileExists: true, + expected: { reactivateProfileName: undefined, refreshedApiConfigName: "provider-2" }, + }, + { + name: "deleted pin with no resolvable active profile: leave the configuration untouched", + pinnedApiConfigName: "deleted-profile", + activeProfileName: undefined, + pinnedProfileExists: false, + expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, + }, + { + name: "deleted pin with a resolvable active profile: re-pin to the active profile", + pinnedApiConfigName: "deleted-profile", + activeProfileName: "provider-2", + pinnedProfileExists: false, + expected: { reactivateProfileName: undefined, refreshedApiConfigName: "provider-2" }, + }, + ])("$name", ({ pinnedApiConfigName, activeProfileName, pinnedProfileExists, expected }) => { + expect( + resolveRestoreProfileActivation({ + pinnedApiConfigName, + activeProfileName, + pinnedProfileExists, + }), + ).toStrictEqual(expected) + }) + + it("never returns a refresh together with a reactivation", () => { + const decisions = [ + { pinnedApiConfigName: undefined, activeProfileName: undefined, pinnedProfileExists: false }, + { pinnedApiConfigName: "provider-1", activeProfileName: undefined, pinnedProfileExists: true }, + { pinnedApiConfigName: "provider-1", activeProfileName: "provider-1", pinnedProfileExists: true }, + { pinnedApiConfigName: "provider-1", activeProfileName: "provider-2", pinnedProfileExists: true }, + { pinnedApiConfigName: "deleted-profile", activeProfileName: undefined, pinnedProfileExists: false }, + { pinnedApiConfigName: "deleted-profile", activeProfileName: "provider-2", pinnedProfileExists: false }, + ].map(resolveRestoreProfileActivation) + + for (const decision of decisions) { + const combined = + decision.reactivateProfileName !== undefined && decision.refreshedApiConfigName !== undefined + expect(combined).toBe(false) + } + }) +}) diff --git a/src/core/webview/restore-provider-profile.ts b/src/core/webview/restore-provider-profile.ts new file mode 100644 index 00000000000..710d7c8e2fe --- /dev/null +++ b/src/core/webview/restore-provider-profile.ts @@ -0,0 +1,67 @@ +// Restore-profile decision for task restore (issue #970). +// +// When a stopped task is restored, its HistoryItem.apiConfigName pins the provider +// profile the task last ran under. If the user switched to a different profile +// while the task was stopped, blindly re-activating that pin reverts the user's +// choice: the restored task and the task header keep the old provider's context +// window, and the usage bar can exceed 100%. +// +// Invariants (first version written before the fix; see +// docs/architecture/tla/RestoreProfileDecision.tla): +// - FollowActive: with an existing pin and a resolvable active profile that +// differs from it, restore must not reactivate the pinned profile. +// - PinNamesEffect: a pin refresh must name exactly the active profile, and a +// decision that reactivates must never also refresh. +// - LegacyFallback: with no resolvable active profile, an existing pinned +// profile is reactivated exactly as before the change. + +/** A profile to re-activate, or undefined to leave the active configuration untouched. */ +export interface RestoreProfileDecision { + /** Profile to re-activate before constructing the restored task; undefined leaves the current configuration in place. */ + reactivateProfileName: string | undefined + /** Replacement pin for the history item; undefined keeps the stored pin unchanged. */ + refreshedApiConfigName: string | undefined +} + +export interface RestoreProfileInput { + /** The pin recorded on the history item at last save; undefined when absent. */ + pinnedApiConfigName: string | undefined + /** The profile active at restore time (currentApiConfigName); undefined when none resolves. */ + activeProfileName: string | undefined + /** Whether the pinned profile still exists in the profile list. */ + pinnedProfileExists: boolean +} + +/** + * Decide how a task restore treats the profile pin stored on its history item. + * + * Rules: + * - No pin: nothing to do; the active configuration stays untouched. + * - Pin exists and no active profile resolves: legacy fallback re-activates the pin. + * - Pin exists and equals the active profile: re-activate it (idempotent re-apply + * of the saved profile settings, unchanged behavior for restores without a switch). + * - Pin exists and differs from the active profile: keep the user's active profile + * and refresh the stale pin to it. + * - Pin no longer exists: keep the active configuration; refresh the pin to the + * active profile when one resolves. + */ +export function resolveRestoreProfileActivation(input: RestoreProfileInput): RestoreProfileDecision { + const { pinnedApiConfigName, activeProfileName, pinnedProfileExists } = input + + if (!pinnedApiConfigName) { + return { reactivateProfileName: undefined, refreshedApiConfigName: undefined } + } + + if (!pinnedProfileExists) { + // The pinned profile is gone; the active configuration (if any) is what runs. + return { reactivateProfileName: undefined, refreshedApiConfigName: activeProfileName } + } + + if (!activeProfileName || activeProfileName === pinnedApiConfigName) { + // No switch happened since the save: re-apply the saved profile settings as before. + return { reactivateProfileName: pinnedApiConfigName, refreshedApiConfigName: undefined } + } + + // The user switched profiles while the task was stopped; their choice wins. + return { reactivateProfileName: undefined, refreshedApiConfigName: activeProfileName } +} From bd9eb7d820644b6d7b559cf21368419b69632847 Mon Sep 17 00:00:00 2001 From: Phil Date: Thu, 26 Nov 2026 22:14:45 +0100 Subject: [PATCH 02/12] fix(restored-task): persist the re-pin through a copy and survive pin-write failures Review round on d58eaba2c (CodeRabbit, 3 findings): - ClineProvider.ts:1651 (Persistence Integrity): build the re-pinned record as a copy instead of mutating the store-owned cached HistoryItem; an in-place mutation makes the store's delta compare drop apiConfigName, so the stale pin survives on disk and the cache reverts after the write. The restore steps below read the copy. - ClineProvider.ts:1652 (Stability): catch and log a rejected pin write and continue the restore - the previous task is already evicted at that point, so an escaping rejection aborts the resume. - spec harness: getState now returns per-profile provider/model settings and follows activation; the retained-active and reactivated-saved cases assert the complete Task configuration. New tests: the pin-write rejection regression, the missing-profile (ghost currentApiConfigName) proof case, and a real-TaskHistoryStore persistence test reading history_item.json back (red-verified on the pre-fix code: both fail there, the other five pass). TLA ratchet on RestoreProfileDecision: +RefreshPersists (distinct- record input rule) and +WriteFailureRestores, with CacheAlias.cfg and WriteAbort.cfg sabotage runs (each violates exactly its own invariant); review counts 1 covered / 2 added / 1 gap. --- .../tla/RestoreProfileDecision.CacheAlias.cfg | 10 + .../tla/RestoreProfileDecision.Sabotage.cfg | 2 +- .../tla/RestoreProfileDecision.WriteAbort.cfg | 9 + .../tla/RestoreProfileDecision.tla | 72 +++++-- .../tla/RestoreProfileDecisionMC.tla | 9 + ...der.restore-follows-active-profile.spec.ts | 193 ++++++++++++++++-- src/core/webview/ClineProvider.ts | 21 +- 7 files changed, 282 insertions(+), 34 deletions(-) create mode 100644 docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg create mode 100644 docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg diff --git a/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg new file mode 100644 index 00000000000..b6b140e2be4 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.CacheAlias.cfg — sabotage: the refresh write aliases the +\* store-cached record (in-place mutation of the cached HistoryItem), so the store's +\* delta compare drops apiConfigName and the stale pin survives on disk. +\* RefreshPersists must be the violated invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Valid <- ValidAliased +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores diff --git a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg index 3299de5c8b9..43f842c63a7 100644 --- a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg @@ -4,4 +4,4 @@ CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Decide <- DecideAlwaysPin -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores diff --git a/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg new file mode 100644 index 00000000000..3586e1a5fa2 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg @@ -0,0 +1,9 @@ +\* RestoreProfileDecision.WriteAbort.cfg — sabotage: the restore aborts when the +\* refresh pin write rejects (the un-caught await before the Task constructor). +\* WriteFailureRestores must be the violated invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Proceed <- ProceedAbort +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla index 1813d7dca6d..3a5758f1a33 100644 --- a/docs/architecture/tla/RestoreProfileDecision.tla +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -4,7 +4,8 @@ \* resolved against the profile list by ClineProvider.createTaskWithHistoryItemUnlocked. \* Sink: the decision record (reactivateProfileName, refreshedApiConfigName) consumed by \* the same method: reactivate calls activateProviderProfile, refresh rewrites the pin -\* through updateTaskHistory and the Task constructor. +\* through updateTaskHistory (persisted to the task file) and hands the record to the +\* Task constructor. \* Failure: restore re-activates a stale pinned profile, so the resumed task and the \* task header keep the old provider's context window (issue #970). \* Invariants (first version written before the fix): @@ -13,30 +14,44 @@ \* PinNamesEffect. A refresh names exactly the active profile, and a reactivation \* never also refreshes. \* LegacyFallback. With no resolvable active profile, an existing pin is reactivated. +\* Added in the PR 2649 review ratchet (CodeRabbit round on d58eaba2c): +\* RefreshPersists. A refresh whose pin write succeeds leaves the persisted pin +\* naming the active profile. The caller must hand the store a record distinct from +\* the cached one (input rule in Valid); mutating the cached record in place makes +\* the store's delta compare drop apiConfigName, so the stale pin survives on disk +\* (CR thread on ClineProvider.ts:1651). +\* WriteFailureRestores. The restore reaches Task construction even when the refresh +\* pin write rejects (CR thread on ClineProvider.ts:1652). \* Run each config on RestoreProfileDecisionMC.tla. The MC module holds the sabotage. -\* Expected before the run: all invariants hold in the model; the sabotage run fails -\* FollowActive only. -\* Result: TypeOK, FollowActive, PinNamesEffect and LegacyFallback hold in the model in -\* 15 distinct states. The sabotage run violates FollowActive at 9 states; no other -\* invariant breaks. +\* Expected: Spec.cfg passes every invariant; Sabotage.cfg fails FollowActive; +\* CacheAlias.cfg fails RefreshPersists; WriteAbort.cfg fails WriteFailureRestores. +\* Result: Spec.cfg holds all six invariants in 132 distinct states. CacheAlias.cfg +\* violates RefreshPersists (21 states), Sabotage.cfg violates FollowActive (29 +\* states), WriteAbort.cfg violates WriteFailureRestores (15 states); no other +\* invariant breaks in any run. \* Not modeled: the profile list (pinnedProfileExists is an oracle the caller computes), -\* the activateProviderProfile and updateTaskHistory side effects, and the CLI runtime +\* the activateProviderProfile side effects, mode restoration, and the CLI runtime \* skip flag (checked before the decision runs). \* Cost: TLC finishes in under 1 second per config. +\* Review (PR 2649, round on d58eaba2c): 1 covered (LegacyFallback - the missing-profile +\* proof case of the Regression Evidence check), 2 added (RefreshPersists + the +\* distinct-record input rule, CR thread ClineProvider.ts:1651; WriteFailureRestores, +\* CR thread ClineProvider.ts:1652), 1 gap (CR thread +\* ClineProvider.restore-follows-active-profile.spec.ts:123 - test-harness settings; +\* the model has no test doubles, the harness assertions pin it directly). CONSTANT NoActive \* sentinel: no resolvable active profile at restore time -VARIABLES input, decision +VARIABLES input, decision, storedPin, restored -vars == <> +vars == <> NoProfile == "absent" \* decision marker: reactivate nothing Keep == "keep" \* decision marker: preserve the stored pin -Input == [pin: {"p1", "p2", "absent"}, active: {"p1", "p2", NoActive}, pinExists: BOOLEAN] - -\* The caller never passes an existing flag for an absent pin. -Valid(inp) == (inp.pin = "absent") => (~inp.pinExists) +Input == + [pin: {"p1", "p2", "absent"}, active: {"p1", "p2", NoActive}, + pinExists: BOOLEAN, pinWriteOk: BOOLEAN, distinctRecord: BOOLEAN] \* Mirrors resolveRestoreProfileActivation rule for rule. Decide(inp) == @@ -48,21 +63,45 @@ Decide(inp) == ELSE IF inp.active = inp.pin THEN [r |-> inp.pin, f |-> Keep] ELSE [r |-> NoProfile, f |-> inp.active] +\* A refresh-shaped input is one whose decision carries a new pin. +Refreshes(inp) == Decide(inp).f # Keep + +\* Caller rules: no existing flag for an absent pin, and a refresh write is built +\* from a record distinct from the store-cached one (a copy), never the cached +\* record itself. +Valid(inp) == + /\ ((inp.pin = "absent") => (~inp.pinExists)) + /\ (Refreshes(inp) => inp.distinctRecord) + +\* The restore reaches Task construction even after a failed refresh write. +Proceed(dec, inp) == TRUE + Init == - /\ input = [pin |-> "absent", active |-> NoActive, pinExists |-> FALSE] + /\ input = [pin |-> "absent", active |-> NoActive, pinExists |-> FALSE, + pinWriteOk |-> TRUE, distinctRecord |-> TRUE] /\ decision = Decide(input) + /\ storedPin = input.pin + /\ restored = TRUE Next == \E inp \in Input : /\ Valid(inp) /\ input' = inp /\ decision' = Decide(inp) + \* An aliased write (the cached record handed back to the store) makes the + \* delta compare omit apiConfigName, so the stale pin survives on disk. + /\ storedPin' = IF decision'.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord + THEN decision'.f + ELSE storedPin + /\ restored' = Proceed(decision', inp) Spec == Init /\ [][Next]_vars TypeOK == /\ decision.r \in {"p1", "p2", "absent"} /\ decision.f \in {"p1", "p2", "keep"} + /\ storedPin \in {"p1", "p2", "absent"} + /\ restored \in BOOLEAN FollowActive == (input.pin # "absent" /\ input.pinExists /\ input.active # NoActive /\ input.active # input.pin) @@ -75,4 +114,9 @@ PinNamesEffect == LegacyFallback == (input.pin # "absent" /\ input.pinExists /\ input.active = NoActive) => decision.r = input.pin +RefreshPersists == + (decision.f # Keep /\ input.pinWriteOk) => storedPin = decision.f + +WriteFailureRestores == restored + ==== diff --git a/docs/architecture/tla/RestoreProfileDecisionMC.tla b/docs/architecture/tla/RestoreProfileDecisionMC.tla index 9588a1abd72..0f79b27843b 100644 --- a/docs/architecture/tla/RestoreProfileDecisionMC.tla +++ b/docs/architecture/tla/RestoreProfileDecisionMC.tla @@ -9,4 +9,13 @@ DecideAlwaysPin(inp) == ELSE IF inp.pinExists THEN [r |-> inp.pin, f |-> Keep] ELSE [r |-> NoProfile, f |-> Keep] +\* Sabotage: the refresh write aliases the store-cached record (the restore mutates +\* the cached item in place before updateTaskHistory), so the store's delta compare +\* drops apiConfigName and the stale pin survives on disk. RefreshPersists must fail. +ValidAliased(inp) == (inp.pin = "absent") => (~inp.pinExists) + +\* Sabotage: the restore aborts when the refresh write rejects (the un-caught await +\* before the Task constructor). WriteFailureRestores must fail. +ProceedAbort(dec, inp) == (dec.f = Keep) \/ inp.pinWriteOk + ==== diff --git a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts index 9ac4c87f30b..7acf83a90f0 100644 --- a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts +++ b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts @@ -14,11 +14,25 @@ // restored task, so every later restore flips the configuration back. // 3. A restore whose pinned profile no longer exists loses the re-pin to the // profile that is actually in effect. +// 4. The restored task is built with settings that do not follow the profile in +// effect after activation (a stale provider/model would keep the old context +// window even with a correct pin). +// 5. A restore whose currentApiConfigName does not resolve in the profile list +// loses the legacy reactivation of the still-existing pinned profile. +// 6. A failed pin write aborts the restore after the previous task was already +// evicted, so the task cannot be resumed at all. +// 7. The re-pinned record mutates the store-owned cached item, so the store's +// delta compare drops apiConfigName and the stale pin survives on disk. // // Red-verify: tests 1 and 3 fail on pre-fix code because the restore block -// activates the stale pin unconditionally. +// activates the stale pin unconditionally. Test 6 fails because the rejected +// updateTaskHistory await escapes before the Task is constructed. Test 7 fails +// because the mutated cache makes the store persist the old pin. import { describe, it, expect, vi, beforeEach } from "vitest" +import { mkdtemp, readFile, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" import { providerIdentifiers } from "@roo-code/types" import type { HistoryItem } from "@roo-code/types" @@ -67,8 +81,9 @@ vi.mock("../core/task-persistence", async (importOriginal) => { }) // The tail of createTaskWithHistoryItemUnlocked constructs a real Task. Replace it -// with a recording double so the test can observe the history item the restored -// task is built from without booting the whole task runtime. +// with a recording double so the test can observe the history item and the API +// configuration the restored task is built from without booting the whole task +// runtime. vi.mock("../core/task/Task", async (importOriginal) => { const real = await importOriginal() // A regular (non-arrow) function so `new Task(...)` constructs the double. @@ -86,6 +101,7 @@ vi.mock("../core/task/Task", async (importOriginal) => { import { ClineProvider } from "../core/webview/ClineProvider" import { Task } from "../core/task/Task" +import { TaskHistoryStore } from "../core/task-persistence/TaskHistoryStore" import { makeProviderStub } from "./helpers/provider-stub" function makeHistoryItem(apiConfigName: string): HistoryItem { @@ -103,28 +119,52 @@ function makeHistoryItem(apiConfigName: string): HistoryItem { type ProfileEntry = { name: string; apiProvider?: string } -function makeRestoreHarness(options: { profiles: ProfileEntry[]; activeProfileName: string | undefined }) { +interface RestoreHarnessOptions { + profiles: ProfileEntry[] + /** Value reported for the currentApiConfigName global (may be absent from `profiles`). */ + activeProfileName: string | undefined + /** Real store to read history through and to persist with the real updateTaskHistory. */ + taskHistoryStore?: TaskHistoryStore +} + +function makeRestoreHarness(options: RestoreHarnessOptions) { const listConfig = vi.fn(async () => options.profiles) const getGlobalState = vi.fn((key: string) => key === "currentApiConfigName" ? options.activeProfileName : undefined, ) - const activateProviderProfile = vi.fn(async () => {}) - const updateTaskHistory = vi.fn(async () => []) - - const provider = makeProviderStub({ contextProxy: { globalStorageUri: { fsPath: "/tmp" } } }) - - Object.assign(provider, { - getState: vi.fn(async () => ({ - apiConfiguration: { apiProvider: providerIdentifiers.openrouter }, + // Activation switches the settings getState observes, mirroring the real + // contract: after activateProviderProfile, getState reports the activated + // profile's provider and model. + let effectiveProfile = options.activeProfileName + const activateProviderProfile = vi.fn(async ({ name }: { name: string }) => { + effectiveProfile = name + }) + const log = vi.fn() + const updateTaskHistoryMock = vi.fn(async () => []) + const getState = vi.fn(async () => { + const settings = options.profiles.find((profile) => profile.name === effectiveProfile) + return { + apiConfiguration: { + apiProvider: settings?.apiProvider ?? providerIdentifiers.openrouter, + apiModelId: settings ? `model-of-${settings.name}` : "model-of-unresolved", + }, enableCheckpoints: false, checkpointTimeout: 10, experiments: {}, diffFuzzyThreshold: 0.8, - })), + } + }) + + const provider = makeProviderStub({ contextProxy: { globalStorageUri: { fsPath: "/tmp" } } }) + + Object.assign(provider, { + getState, + log, updateGlobalState: vi.fn(async () => {}), getGlobalState, activateProviderProfile, - updateTaskHistory, + updateTaskHistory: options.taskHistoryStore ? ClineProvider.prototype.updateTaskHistory : updateTaskHistoryMock, + taskHistoryStore: options.taskHistoryStore ?? { get: () => undefined, invalidate: async () => {} }, providerSettingsManager: { listConfig }, addClineToStack: vi.fn(async () => {}), getPendingEditOperation: vi.fn(() => undefined), @@ -146,12 +186,25 @@ function makeRestoreHarness(options: { profiles: ProfileEntry[]; activeProfileNa const runRestore = (historyItem: HistoryItem) => createTaskWithHistoryItemUnlocked.call(provider, historyItem, { startTask: false }) - return { runRestore, activateProviderProfile, updateTaskHistory, listConfig, getGlobalState } + return { + runRestore, + activateProviderProfile, + updateTaskHistory: updateTaskHistoryMock, + listConfig, + getGlobalState, + log, + } +} + +function constructedTaskConfig(): + { historyItem?: HistoryItem; apiConfiguration?: Record } | undefined { + const firstCall = vi.mocked(Task).mock.calls[0]?.[0] as + { historyItem?: HistoryItem; apiConfiguration?: Record } | undefined + return firstCall } function constructedHistoryItem(): HistoryItem | undefined { - const firstCall = vi.mocked(Task).mock.calls[0]?.[0] as { historyItem?: HistoryItem } | undefined - return firstCall?.historyItem + return constructedTaskConfig()?.historyItem } describe("ClineProvider restore follows the active profile", () => { @@ -175,6 +228,12 @@ describe("ClineProvider restore follows the active profile", () => { expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), ) expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + // The restored task must run on the active profile's settings, not the stale + // pin's provider/model. + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-provider-2", + }) }) it("re-activates the pinned profile when it is still the active one", async () => { @@ -191,6 +250,12 @@ describe("ClineProvider restore follows the active profile", () => { ) expect(harness.updateTaskHistory).not.toHaveBeenCalled() expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + // After the re-activation the restored task must run on the activated + // profile's provider and model. + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-of-provider-1", + }) }) it("re-pins to the active profile when the pinned profile no longer exists", async () => { @@ -206,6 +271,10 @@ describe("ClineProvider restore follows the active profile", () => { expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), ) expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-provider-2", + }) }) it("re-activates the pin when no resolvable active profile exists", async () => { @@ -222,5 +291,95 @@ describe("ClineProvider restore follows the active profile", () => { ) expect(harness.updateTaskHistory).not.toHaveBeenCalled() expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + // The activation must be what the observed settings follow: with no active + // profile at restore time only the re-activated pin can supply provider/model. + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-of-provider-1", + }) + }) + + it("re-activates the existing pinned profile when currentApiConfigName is absent from the profile list", async () => { + // Regression-evidence case: the active name is a dangling pointer, the pin + // still exists. Legacy fallback re-activates the pin and must not write. + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: "ghost-profile", + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfile).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + ) + expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-of-provider-1", + }) + }) + + it("continues the restore when the pin write rejects", async () => { + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + }) + harness.updateTaskHistory.mockRejectedValueOnce(new Error("simulated pin-write failure")) + + // The previous task is already evicted at this point; the restore must not + // fail, and the task must still be constructed with the refreshed pin and + // the active configuration. + await expect(harness.runRestore(makeHistoryItem("provider-1"))).resolves.toBeDefined() + + expect(vi.mocked(Task).mock.calls.length).toBe(1) + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-provider-2", + }) + expect(harness.log).toHaveBeenCalledWith( + expect.stringContaining("Failed to persist re-pinned profile 'provider-2'"), + ) + }) + + it("persists the refreshed pin through the real TaskHistoryStore", async () => { + // Persistence-integrity case: the restore must re-pin the STORE-OWNED record + // without mutating the cached item in place (an in-place mutation would make + // the store's delta compare drop apiConfigName, leaving the stale pin on + // disk). The disk file is the oracle. + const storageRoot = await mkdtemp(join(tmpdir(), "zoo-970-store-")) + try { + const store = new TaskHistoryStore(storageRoot) + await store.upsert(makeHistoryItem("provider-1")) + // Route the store-cached object through the restore, exactly as the + // history-navigation callers do. + const cached = store.get("task-1") + expect(cached?.apiConfigName).toBe("provider-1") + + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + taskHistoryStore: store, + }) + + await harness.runRestore(cached as HistoryItem) + + const disk = JSON.parse( + await readFile(join(storageRoot, "tasks", "task-1", "history_item.json"), "utf8"), + ) as HistoryItem + expect(disk.apiConfigName).toBe("provider-2") + // The cache is updated by the store's own write path, not by the restore. + expect(store.get("task-1")?.apiConfigName).toBe("provider-2") + } finally { + await rm(storageRoot, { recursive: true, force: true }) + } }) }) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 68542b2091a..d0c092b5440 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -1648,8 +1648,25 @@ export class ClineProvider this.log( `Restoring task ${historyItem.id} with active profile '${decision.refreshedApiConfigName}' instead of stale pinned profile '${historyItem.apiConfigName}'.`, ) - historyItem.apiConfigName = decision.refreshedApiConfigName - await this.updateTaskHistory({ ...historyItem, apiConfigName: decision.refreshedApiConfigName }) + // Re-pin through a copy: historyItem is the store-owned cached record, and + // mutating it in place would make the store's delta compare treat apiConfigName + // as unchanged, so the stale pin would survive on disk. The store updates its + // cache only through its own write path; the restore steps below read the + // refreshed pin from this copy. + const repinnedHistoryItem = { ...historyItem, apiConfigName: decision.refreshedApiConfigName } + try { + await this.updateTaskHistory(repinnedHistoryItem) + } catch (error) { + // The previous task is already evicted here; a failed pin write must not + // abort the restore. Continue with the active configuration and the + // refreshed in-memory pin. + this.log( + `Failed to persist re-pinned profile '${decision.refreshedApiConfigName}' for task ${historyItem.id}: ${ + error instanceof Error ? error.message : String(error) + }. Continuing restore with the active configuration.`, + ) + } + historyItem = repinnedHistoryItem } else if (!decision.reactivateProfileName) { // Profile no longer exists, log warning but continue this.log( From 6ca11ea04cfc7b311697b9b25d8b95ec32d84145 Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 27 Nov 2026 04:54:01 +0100 Subject: [PATCH 03/12] fix(restored-task): check all six invariants in the base cfg and pin the surviving mutants CodeRabbit round on bd9eb7d82 (PR #2649): - RestoreProfileDecision.cfg now checks RefreshPersists and WriteFailureRestores in the passing run, matching the spec header's six-invariant claim (CR thread RestoreProfileDecision.cfg:6). A rejected-write regression that leaves restored=FALSE is now caught by the passing run instead of only by the WriteAbort sabotage. - Kill the two reachable mutation-diff survivors on ClineProvider.ts: the re-pin log line is pinned by an exact log assertion, and the deleted-profile else-if guard is pinned by a new test (a pinned profile that exists without configured provider settings must not trigger the deleted-profile warning). - The OptionalChaining survivor on profile?.name is an equivalent mutant: resolveRestoreProfileActivation returns a reactivation only when pinnedProfileExists holds, which the caller computes as !!profile. Documented with a Stryker disable comment. Gates: TLC base cfg passes all six invariants (132 states), CacheAlias/WriteAbort/Sabotage variants fail with exactly RefreshPersists/WriteFailureRestores/FollowActive; scoped vitest 15/15; tsc --noEmit clean; eslint --max-warnings=0 clean; prettier unchanged. Mutation kills red-verified by sabotage. --- .../tla/RestoreProfileDecision.cfg | 2 +- .../tla/RestoreProfileDecision.tla | 12 ++++++++-- ...der.restore-follows-active-profile.spec.ts | 24 +++++++++++++++++++ src/core/webview/ClineProvider.ts | 1 + 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/docs/architecture/tla/RestoreProfileDecision.cfg b/docs/architecture/tla/RestoreProfileDecision.cfg index 84f61a1227d..105c396940c 100644 --- a/docs/architecture/tla/RestoreProfileDecision.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.cfg @@ -3,4 +3,4 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla index 3a5758f1a33..d397c7a151b 100644 --- a/docs/architecture/tla/RestoreProfileDecision.tla +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -25,8 +25,8 @@ \* Run each config on RestoreProfileDecisionMC.tla. The MC module holds the sabotage. \* Expected: Spec.cfg passes every invariant; Sabotage.cfg fails FollowActive; \* CacheAlias.cfg fails RefreshPersists; WriteAbort.cfg fails WriteFailureRestores. -\* Result: Spec.cfg holds all six invariants in 132 distinct states. CacheAlias.cfg -\* violates RefreshPersists (21 states), Sabotage.cfg violates FollowActive (29 +\* Result: Spec.cfg checks and holds all six invariants in 132 distinct states. +\* CacheAlias.cfg violates RefreshPersists (21 states), Sabotage.cfg violates FollowActive (29 \* states), WriteAbort.cfg violates WriteFailureRestores (15 states); no other \* invariant breaks in any run. \* Not modeled: the profile list (pinnedProfileExists is an oracle the caller computes), @@ -39,6 +39,14 @@ \* CR thread ClineProvider.ts:1652), 1 gap (CR thread \* ClineProvider.restore-follows-active-profile.spec.ts:123 - test-harness settings; \* the model has no test doubles, the harness assertions pin it directly). +\* Review (PR 2649, round on bd9eb7d82): 1 covered (RefreshPersists + +\* WriteFailureRestores were already modeled; the defect was the passing cfg +\* checking only four of the six invariants - all six are checked now, CR thread +\* RestoreProfileDecision.cfg:6), 3 gap (mutation-diff survivors on bd9eb7d82: +\* the re-pin log text and the deleted-profile else-if guard are log/branch-level, +\* pinned by unit tests in ClineProvider.restore-follows-active-profile.spec.ts; +\* the defensive profile?.name chain is an equivalent mutant documented beside +\* the condition in ClineProvider.ts). CONSTANT NoActive \* sentinel: no resolvable active profile at restore time diff --git a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts index 7acf83a90f0..35924ab8585 100644 --- a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts +++ b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts @@ -23,6 +23,8 @@ // evicted, so the task cannot be resumed at all. // 7. The re-pinned record mutates the store-owned cached item, so the store's // delta compare drops apiConfigName and the stale pin survives on disk. +// 8. A restore whose pinned profile exists but carries no configured provider +// settings logs the deleted-profile warning, so the log misreports the state. // // Red-verify: tests 1 and 3 fail on pre-fix code because the restore block // activates the stale pin unconditionally. Test 6 fails because the rejected @@ -228,6 +230,11 @@ describe("ClineProvider restore follows the active profile", () => { expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), ) expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + // The re-pin decision must be visible in the log with both names: the + // active profile that stays in effect and the stale pin it replaces. + expect(harness.log).toHaveBeenCalledWith( + "Restoring task task-1 with active profile 'provider-2' instead of stale pinned profile 'provider-1'.", + ) // The restored task must run on the active profile's settings, not the stale // pin's provider/model. expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ @@ -382,4 +389,21 @@ describe("ClineProvider restore follows the active profile", () => { await rm(storageRoot, { recursive: true, force: true }) } }) + + it("does not warn about a deleted profile when the pinned profile exists without a configured provider", async () => { + // The pinned profile exists but carries no apiProvider settings: the + // reactivation branch skips activation, and the restore must fall through + // without the deleted-profile warning. That warning is reserved for a pin + // whose profile is absent from the list. + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1" }], + activeProfileName: undefined, + }) + + await expect(harness.runRestore(makeHistoryItem("provider-1"))).resolves.toBeDefined() + + expect(harness.activateProviderProfile).not.toHaveBeenCalled() + expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(harness.log).not.toHaveBeenCalledWith(expect.stringContaining("no longer exists")) + }) }) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index d0c092b5440..d65fa64326e 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -1623,6 +1623,7 @@ export class ClineProvider pinnedProfileExists: !!profile, }) + // Stryker disable next-line OptionalChaining: profile is always defined here; resolveRestoreProfileActivation returns a reactivation only when pinnedProfileExists holds, and the caller computes that flag as !!profile, so no reachable input distinguishes profile?.name from profile.name if (decision.reactivateProfileName && profile?.name && profile.apiProvider) { try { await this.activateProviderProfile( From ea2d69b75c6659cfbd41fea3133098fbfbbef48a Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 27 Nov 2026 05:43:07 +0100 Subject: [PATCH 04/12] fix(restored-task): assert the exact fall-through settings on the settings-less-pin restore CodeRabbit round on 6ca11ea04 (thread 4715539880): the warning-free fall-through test only checked the restore resolved to something defined. The restored task must be constructed exactly once from the unresolved settings snapshot (openrouter / model-of-unresolved); the assertion is placed first so a dropped profile.apiProvider guard fails on the config diff (model-of-provider-1), red-verified by sabotage. RestoreProfileDecision.tla header records the round as a caller-guard gap; TLC re-run: base passes (132 states), CacheAlias/WriteAbort/Sabotage fail with the pinned invariant each. --- .../tla/RestoreProfileDecision.tla | 6 ++++++ ...ider.restore-follows-active-profile.spec.ts | 18 ++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla index d397c7a151b..42d200ceead 100644 --- a/docs/architecture/tla/RestoreProfileDecision.tla +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -47,6 +47,12 @@ \* pinned by unit tests in ClineProvider.restore-follows-active-profile.spec.ts; \* the defensive profile?.name chain is an equivalent mutant documented beside \* the condition in ClineProvider.ts). +\* Review (PR 2649, round on 6ca11ea04): 1 gap (CR thread on +\* ClineProvider.restore-follows-active-profile.spec.ts:403 - the fall-through +\* restore must construct the task from the exact unresolved-settings snapshot; +\* expressing it would mean modeling the caller's profile.apiProvider activation +\* guard, which sits outside the decision record like the activation side +\* effects above; pinned by the strengthened exact-config unit assertion). CONSTANT NoActive \* sentinel: no resolvable active profile at restore time diff --git a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts index 35924ab8585..7ccd1c81fa6 100644 --- a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts +++ b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts @@ -29,7 +29,11 @@ // Red-verify: tests 1 and 3 fail on pre-fix code because the restore block // activates the stale pin unconditionally. Test 6 fails because the rejected // updateTaskHistory await escapes before the Task is constructed. Test 7 fails -// because the mutated cache makes the store persist the old pin. +// because the mutated cache makes the store persist the old pin. Test 8's +// exact-settings assertion fails when the caller's profile.apiProvider guard +// is dropped (activation then reports 'model-of-provider-1') or when the +// fall-through skips Task construction; a bare resolves-defined check passed +// both (review round on 6ca11ea04). import { describe, it, expect, vi, beforeEach } from "vitest" import { mkdtemp, readFile, rm } from "node:fs/promises" @@ -400,7 +404,17 @@ describe("ClineProvider restore follows the active profile", () => { activeProfileName: undefined, }) - await expect(harness.runRestore(makeHistoryItem("provider-1"))).resolves.toBeDefined() + await harness.runRestore(makeHistoryItem("provider-1")) + + // The fall-through must still construct the task from the settings snapshot + // getState reports after no activation ran: the unresolved-profile fallback. + // A wrongly re-activated settings-less pin surfaces 'model-of-provider-1' + // here, and a restore that skips Task construction leaves no call to read. + expect(vi.mocked(Task).mock.calls.length).toBe(1) + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-unresolved", + }) expect(harness.activateProviderProfile).not.toHaveBeenCalled() expect(harness.updateTaskHistory).not.toHaveBeenCalled() From 5456f54f4dea15bd45f4187f6da32fad41e5ae1e Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 27 Nov 2026 12:19:25 +0100 Subject: [PATCH 05/12] fix(restored-task): keep the modeled persisted pin aligned with the selected input CodeRabbit round on ea2d69b75 (CR thread RestoreProfileDecision.tla:109): the no-write sink path kept the previous modeled pin instead of the pin the history item carried in, so the model diverged from the persisted pin on every admitted input whose pin differed from the prior step's outcome. - Factor the sink as PersistedPin(dec, inp, prev); the fall-through now persists the selected input's pin, and successful distinct-record refresh writes still store decision.f. - Add NoWritePreservesPin (red-verified: the base cfg failed on the unfixed model) and list it in all five configs. - Add RestoreProfileDecision.StalePin.cfg + MC PersistedPinStale so the stale fallback stays a must-fail sabotage (NoWritePreservesPin is its violation). Gates: Spec.cfg passes all seven invariants (48 states); Sabotage.cfg fails FollowActive (27), CacheAlias.cfg fails RefreshPersists (21), WriteAbort.cfg fails WriteFailureRestores (15), StalePin.cfg fails NoWritePreservesPin (13); no other invariant breaks in any run. Scoped vitest 381/381 (ClineProvider + restore suites), tsc --noEmit clean, eslint --max-warnings=0 clean, prettier clean. --- .../tla/RestoreProfileDecision.CacheAlias.cfg | 2 +- .../tla/RestoreProfileDecision.Sabotage.cfg | 2 +- .../tla/RestoreProfileDecision.StalePin.cfg | 10 +++++++ .../tla/RestoreProfileDecision.WriteAbort.cfg | 2 +- .../tla/RestoreProfileDecision.cfg | 2 +- .../tla/RestoreProfileDecision.tla | 29 ++++++++++++++----- .../tla/RestoreProfileDecisionMC.tla | 5 ++++ 7 files changed, 41 insertions(+), 11 deletions(-) create mode 100644 docs/architecture/tla/RestoreProfileDecision.StalePin.cfg diff --git a/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg index b6b140e2be4..500ab8b041d 100644 --- a/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg @@ -7,4 +7,4 @@ CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Valid <- ValidAliased -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin diff --git a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg index 43f842c63a7..9a5a8005ebe 100644 --- a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg @@ -4,4 +4,4 @@ CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Decide <- DecideAlwaysPin -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin diff --git a/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg b/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg new file mode 100644 index 00000000000..1d8aaa03063 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.StalePin.cfg — sabotage: the no-write path keeps the +\* previous modeled pin instead of the pin the selected input carried in, so the +\* modeled pin diverges from the persisted history-item pin. +\* NoWritePreservesPin must be the violated invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + PersistedPin <- PersistedPinStale +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin diff --git a/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg index 3586e1a5fa2..cbeec399df3 100644 --- a/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg @@ -6,4 +6,4 @@ CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Proceed <- ProceedAbort -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin diff --git a/docs/architecture/tla/RestoreProfileDecision.cfg b/docs/architecture/tla/RestoreProfileDecision.cfg index 105c396940c..5a51f4846af 100644 --- a/docs/architecture/tla/RestoreProfileDecision.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.cfg @@ -3,4 +3,4 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla index 42d200ceead..a388443b41e 100644 --- a/docs/architecture/tla/RestoreProfileDecision.tla +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -24,10 +24,12 @@ \* pin write rejects (CR thread on ClineProvider.ts:1652). \* Run each config on RestoreProfileDecisionMC.tla. The MC module holds the sabotage. \* Expected: Spec.cfg passes every invariant; Sabotage.cfg fails FollowActive; -\* CacheAlias.cfg fails RefreshPersists; WriteAbort.cfg fails WriteFailureRestores. -\* Result: Spec.cfg checks and holds all six invariants in 132 distinct states. -\* CacheAlias.cfg violates RefreshPersists (21 states), Sabotage.cfg violates FollowActive (29 -\* states), WriteAbort.cfg violates WriteFailureRestores (15 states); no other +\* CacheAlias.cfg fails RefreshPersists; WriteAbort.cfg fails WriteFailureRestores; +\* StalePin.cfg fails NoWritePreservesPin. +\* Result: Spec.cfg checks and holds all seven invariants in 48 distinct states. +\* CacheAlias.cfg violates RefreshPersists (21 states), Sabotage.cfg violates +\* FollowActive (27 states), WriteAbort.cfg violates WriteFailureRestores (15 +\* states), StalePin.cfg violates NoWritePreservesPin (13 states); no other \* invariant breaks in any run. \* Not modeled: the profile list (pinnedProfileExists is an oracle the caller computes), \* the activateProviderProfile side effects, mode restoration, and the CLI runtime @@ -53,6 +55,10 @@ \* expressing it would mean modeling the caller's profile.apiProvider activation \* guard, which sits outside the decision record like the activation side \* effects above; pinned by the strengthened exact-config unit assertion). +\* Review (PR 2649, round on ea2d69b75): 1 added (NoWritePreservesPin + the sink +\* fallback it pins: the no-write path now persists the selected input's pin, +\* factored as PersistedPin so StalePin.cfg sabotages the stale form; CR thread +\* RestoreProfileDecision.tla:109), 0 covered, 0 gap. CONSTANT NoActive \* sentinel: no resolvable active profile at restore time @@ -80,6 +86,12 @@ Decide(inp) == \* A refresh-shaped input is one whose decision carries a new pin. Refreshes(inp) == Decide(inp).f # Keep +\* The sink: the pin persisted after one restore. A refresh whose write succeeds on +\* a record distinct from the store-cached one rewrites the pin; every other path +\* writes nothing, so the pin the history item carried in stays persisted. +PersistedPin(dec, inp, prev) == + IF dec.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord THEN dec.f ELSE inp.pin + \* Caller rules: no existing flag for an absent pin, and a refresh write is built \* from a record distinct from the store-cached one (a copy), never the cached \* record itself. @@ -104,9 +116,7 @@ Next == /\ decision' = Decide(inp) \* An aliased write (the cached record handed back to the store) makes the \* delta compare omit apiConfigName, so the stale pin survives on disk. - /\ storedPin' = IF decision'.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord - THEN decision'.f - ELSE storedPin + /\ storedPin' = PersistedPin(decision', inp, storedPin) /\ restored' = Proceed(decision', inp) Spec == Init /\ [][Next]_vars @@ -131,6 +141,11 @@ LegacyFallback == RefreshPersists == (decision.f # Keep /\ input.pinWriteOk) => storedPin = decision.f +\* No write landed (no refresh, a failed refresh write, or an aliased record the +\* store's delta compare drops): the persisted pin is the one the input carried in. +NoWritePreservesPin == + (~(decision.f # Keep /\ input.pinWriteOk /\ input.distinctRecord)) => storedPin = input.pin + WriteFailureRestores == restored ==== diff --git a/docs/architecture/tla/RestoreProfileDecisionMC.tla b/docs/architecture/tla/RestoreProfileDecisionMC.tla index 0f79b27843b..333f256eec0 100644 --- a/docs/architecture/tla/RestoreProfileDecisionMC.tla +++ b/docs/architecture/tla/RestoreProfileDecisionMC.tla @@ -18,4 +18,9 @@ ValidAliased(inp) == (inp.pin = "absent") => (~inp.pinExists) \* before the Task constructor). WriteFailureRestores must fail. ProceedAbort(dec, inp) == (dec.f = Keep) \/ inp.pinWriteOk +\* Sabotage: the no-write path keeps the previous modeled pin instead of the pin +\* the selected input carried in (the pre-round fallback). NoWritePreservesPin must fail. +PersistedPinStale(dec, inp, prev) == + IF dec.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord THEN dec.f ELSE prev + ==== From 9afd156a7a3f968216ee5eaf8185a7554cc84638 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 11:43:31 +0100 Subject: [PATCH 06/12] fix(restored-task): own the restore pin per origin and through the store write path - the read -> decide -> activate -> settings-capture sequence runs inside the provider-profile mutation queue, so a concurrent profile switch cannot pin one profile name while the task is built from another's settings - delegated children restore their own task-local pin (restoredProfileOriginOf) and are never refreshed to the global active profile - a profile that exists on disk but fails schema validation keeps its saved pin with a dedicated warning instead of the deleted-profile overwrite - the refresh re-pins through repinTaskProfilePin via the store's atomic patch: only apiConfigName changes, so newer token counts survive and the cancel-rehydrate lineage references are never serialized - the old task's pin is synced to the refreshed record before its abort, so its final save cannot restore the old profile name - deleting the active profile activates the fallback's settings, closing the name-changed-settings-did-not gap --- src/core/config/ProviderSettingsManager.ts | 21 ++ src/core/task-persistence/index.ts | 3 + src/core/task-persistence/taskLifecycle.ts | 23 ++ src/core/webview/ClineProvider.ts | 249 ++++++++++++++----- src/core/webview/restore-provider-profile.ts | 23 +- 5 files changed, 249 insertions(+), 70 deletions(-) diff --git a/src/core/config/ProviderSettingsManager.ts b/src/core/config/ProviderSettingsManager.ts index 79a9d67c794..068460e6add 100644 --- a/src/core/config/ProviderSettingsManager.ts +++ b/src/core/config/ProviderSettingsManager.ts @@ -414,6 +414,27 @@ export class ProviderSettingsManager { } } + /** + * True when a config with this name exists in the raw settings file, including + * entries that schema validation drops from listConfig on load. + */ + public async hasRawConfigName(name: string): Promise { + try { + return await this.lock(async () => { + const content = await this.context.secrets.get(this.secretsKey) + if (!content) { + return false + } + const parsed = JSON.parse(content) as { apiConfigs?: Record } + return !!parsed.apiConfigs && Object.prototype.hasOwnProperty.call(parsed.apiConfigs, name) + }) + } catch { + // An unreadable or unparsable file resolves nothing; the caller keeps the + // saved pin rather than treating the profile as recoverable. + return false + } + } + /** * Save a config with the given name. * Preserves the ID from the input 'config' object if it exists, diff --git a/src/core/task-persistence/index.ts b/src/core/task-persistence/index.ts index 0baf9ce57e6..86d87738055 100644 --- a/src/core/task-persistence/index.ts +++ b/src/core/task-persistence/index.ts @@ -21,7 +21,10 @@ export { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + repinTaskProfilePin, + restoredProfileOriginOf, settleRejectedCreateSubtaskAction, type HistoryItemStatus, + type RestoreProfileOrigin, VALID_TASK_STATUS_TRANSITIONS, } from "./taskLifecycle" diff --git a/src/core/task-persistence/taskLifecycle.ts b/src/core/task-persistence/taskLifecycle.ts index b8a5e571f03..ffabb39694f 100644 --- a/src/core/task-persistence/taskLifecycle.ts +++ b/src/core/task-persistence/taskLifecycle.ts @@ -130,3 +130,26 @@ export function abandonDelegatedChild( }, } } + +/** + * Ownership of a restored task's provider-profile pin: the user's global profile + * choice governs a root task, while a delegated child keeps the task-local pin + * delegation assigned it (delegation never changes the global profile). + */ +export type RestoreProfileOrigin = "user" | "delegated-child" + +export function restoredProfileOriginOf(record: Pick): RestoreProfileOrigin { + return record.parentTaskId ? "delegated-child" : "user" +} + +/** + * The one sanctioned way to rewrite a persisted task's profile pin: a copy that + * patches only apiConfigName. A refresh routed through this reducer cannot revert + * newer token counts or timestamps, and cannot serialize the live rootTask/ + * parentTask references the cancel-rehydrate path attaches to history items. + * An absent or empty name keeps the record unchanged, so applying a decision + * without a refresh is a no-op on the persisted record. + */ +export function repinTaskProfilePin(record: HistoryItem, apiConfigName: string | undefined): HistoryItem { + return apiConfigName ? { ...record, apiConfigName } : record +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index d65fa64326e..dfb385ee841 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -154,6 +154,8 @@ import { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + repinTaskProfilePin, + restoredProfileOriginOf, } from "../task-persistence" import { readTaskMessages } from "../task-persistence/taskMessages" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" @@ -1602,78 +1604,131 @@ export class ClineProvider } } + // Settings snapshot for the Task constructor. On the profile-restore path it is + // captured inside the provider-profile mutation queue, right after the decision's + // activation, so no interleaved user profile switch can leave the task built from + // settings that do not match the decided profile. + let restoredStateSnapshot: Awaited> | undefined + // If the history item has a saved API config name (provider profile), restore it. // This overrides any mode-based config restoration above, because the task's // specific provider profile takes precedence over mode defaults. + // + // The read -> decide -> activate -> settings-capture sequence runs inside the + // provider-profile mutation queue, so a user profile switch cannot interleave + // between the profile snapshot, the decision, and the settings capture (the + // decision would otherwise pin one profile name while the task is built from + // another profile's settings). if (historyItem.apiConfigName && !skipProfileRestoreFromHistory) { - const listApiConfig = await this.providerSettingsManager.listConfig() - // Keep global state/UI in sync with latest profiles for parity with mode restoration above. - await this.updateGlobalState("listApiConfigMeta", listApiConfig) - const profile = listApiConfig.find(({ name }) => name === historyItem.apiConfigName) - // The profile active at restore time is the user's latest choice; a pin naming a - // different profile is stale (the task saved it before the switch). Resolving the - // active name against the profile list keeps a dangling pointer out of the decision. - const currentApiConfigName = this.getGlobalState("currentApiConfigName") - const activeProfileName = listApiConfig.some(({ name }) => name === currentApiConfigName) - ? currentApiConfigName - : undefined - const decision = resolveRestoreProfileActivation({ - pinnedApiConfigName: historyItem.apiConfigName, - activeProfileName, - pinnedProfileExists: !!profile, - }) + // The narrowed pin, captured before the queue closure: historyItem is + // reassigned on the refresh path, so its narrowing does not survive into + // the callback. + const pinnedApiConfigName: string = historyItem.apiConfigName + const restoreOutcome = await this.enqueueProviderProfileMutation( + async (signal) => { + const listApiConfig = await this.providerSettingsManager.listConfig() + // Keep global state/UI in sync with latest profiles for parity with mode restoration above. + await this.updateGlobalState("listApiConfigMeta", listApiConfig) + const profile = listApiConfig.find(({ name }) => name === pinnedApiConfigName) + // The profile active at restore time is the user's latest choice; a pin naming a + // different profile is stale (the task saved it before the switch). Resolving the + // active name against the profile list keeps a dangling pointer out of the decision. + const currentApiConfigName = this.getGlobalState("currentApiConfigName") + const activeProfileName = listApiConfig.some(({ name }) => name === currentApiConfigName) + ? currentApiConfigName + : undefined + // A pinned profile missing from the validated list may still exist in the + // settings file with a schema validation failure; listConfig drops such + // entries, which would make a recoverable profile look deleted. + const pinnedProfileOnDisk = !profile + ? await this.providerSettingsManager.hasRawConfigName(pinnedApiConfigName) + : false + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName, + activeProfileName, + pinnedProfileExists: !!profile, + // A delegated child carries its own task-local profile (delegation never + // changes the global profile), so the global active profile must not win. + profileOrigin: restoredProfileOriginOf(historyItem), + }) - // Stryker disable next-line OptionalChaining: profile is always defined here; resolveRestoreProfileActivation returns a reactivation only when pinnedProfileExists holds, and the caller computes that flag as !!profile, so no reachable input distinguishes profile?.name from profile.name - if (decision.reactivateProfileName && profile?.name && profile.apiProvider) { - try { - await this.activateProviderProfile( - { name: profile.name }, - { - persistModeConfig: false, - persistTaskHistory: false, - expectedCurrentTaskId: historyItem.id, - }, - ) - } catch (error) { - // Log the error but continue with task restoration. - this.log( - `Failed to restore API configuration '${historyItem.apiConfigName}' for task: ${ - error instanceof Error ? error.message : String(error) - }. Continuing with current configuration.`, - ) - } - } else if (decision.refreshedApiConfigName) { - // The pin names a profile that is not in effect at restore time. Keep the user's - // active profile (and its context window) and re-pin the task to it, so later - // restores do not flip the configuration back to the stale profile. - this.log( - `Restoring task ${historyItem.id} with active profile '${decision.refreshedApiConfigName}' instead of stale pinned profile '${historyItem.apiConfigName}'.`, - ) - // Re-pin through a copy: historyItem is the store-owned cached record, and - // mutating it in place would make the store's delta compare treat apiConfigName - // as unchanged, so the stale pin would survive on disk. The store updates its - // cache only through its own write path; the restore steps below read the - // refreshed pin from this copy. - const repinnedHistoryItem = { ...historyItem, apiConfigName: decision.refreshedApiConfigName } - try { - await this.updateTaskHistory(repinnedHistoryItem) - } catch (error) { - // The previous task is already evicted here; a failed pin write must not - // abort the restore. Continue with the active configuration and the - // refreshed in-memory pin. - this.log( - `Failed to persist re-pinned profile '${decision.refreshedApiConfigName}' for task ${historyItem.id}: ${ - error instanceof Error ? error.message : String(error) - }. Continuing restore with the active configuration.`, - ) - } - historyItem = repinnedHistoryItem - } else if (!decision.reactivateProfileName) { - // Profile no longer exists, log warning but continue - this.log( - `Provider profile '${historyItem.apiConfigName}' from history no longer exists. Using current configuration.`, - ) - } + if (signal.aborted) { + return { decision, pinnedProfileOnDisk, state: await this.getState() } + } + + // Stryker disable next-line OptionalChaining: resolveRestoreProfileActivation returns a reactivation only when pinnedProfileExists holds, and the caller computes that flag as !!profile, so no reachable input distinguishes profile?.name from profile.name + if (decision.reactivateProfileName && profile?.name && profile.apiProvider) { + try { + // Already inside the mutation queue: call the unlocked activation + // directly so the restore does not wait behind itself. + await this.activateProviderProfileUnlocked( + { name: profile.name }, + { + persistModeConfig: false, + persistTaskHistory: false, + expectedCurrentTaskId: historyItem.id, + }, + signal, + ) + } catch (error) { + // Log the error but continue with task restoration. + this.log( + `Failed to restore API configuration '${historyItem.apiConfigName}' for task: ${ + error instanceof Error ? error.message : String(error) + }. Continuing with current configuration.`, + ) + } + } else if (decision.refreshedApiConfigName) { + if (pinnedProfileOnDisk) { + // The pinned profile exists in the settings file but failed validation + // on load, so it is absent from the profile list. Keep the saved name + // and warn instead of overwriting a pin the user may still recover. + this.log( + `Provider profile '${historyItem.apiConfigName}' exists but failed to load. Keeping the saved profile and using the current configuration.`, + ) + } else { + // The pin names a profile that is not in effect at restore time. Keep the user's + // active profile (and its context window) and re-pin the task to it, so later + // restores do not flip the configuration back to the stale profile. + this.log( + `Restoring task ${historyItem.id} with active profile '${decision.refreshedApiConfigName}' instead of stale pinned profile '${historyItem.apiConfigName}'.`, + ) + try { + // Re-pin through the store's own write path: an atomic patch of only + // apiConfigName on the current record, so the refresh can neither + // revert newer token counts with the stale snapshot nor serialize + // the live rootTask/parentTask references the cancel-rehydrate + // path attaches to historyItem. + await this.repinTaskProfile(historyItem.id, decision.refreshedApiConfigName) + } catch (error) { + // The previous task is already evicted here; a failed pin write must not + // abort the restore. Continue with the active configuration and the + // refreshed in-memory pin. + this.log( + `Failed to persist re-pinned profile '${decision.refreshedApiConfigName}' for task ${historyItem.id}: ${ + error instanceof Error ? error.message : String(error) + }. Continuing restore with the active configuration.`, + ) + } + // Local copy for the Task construction only; the store record was + // already re-pinned through repinTaskProfile. + historyItem = { ...historyItem, apiConfigName: decision.refreshedApiConfigName } + } + } else if (!decision.reactivateProfileName) { + // Nothing to reactivate or refresh: warn but continue with the + // current configuration. + this.log( + pinnedProfileOnDisk + ? `Provider profile '${historyItem.apiConfigName}' exists but failed to load. Keeping the saved profile and using the current configuration.` + : `Provider profile '${historyItem.apiConfigName}' from history no longer exists. Using current configuration.`, + ) + } + + return { decision, pinnedProfileOnDisk, state: await this.getState() } + }, + { runToCompletion: true }, + ) + restoredStateSnapshot = restoreOutcome.state } else if (historyItem.apiConfigName && skipProfileRestoreFromHistory) { this.log( `Skipping restore of provider profile '${historyItem.apiConfigName}' for task ${historyItem.id} in CLI runtime.`, @@ -1681,7 +1736,7 @@ export class ClineProvider } const { apiConfiguration, enableCheckpoints, checkpointTimeout, experiments, diffFuzzyThreshold } = - await this.getState() + restoredStateSnapshot ?? (await this.getState()) const task = new Task({ provider: this, apiConfiguration, @@ -1715,6 +1770,13 @@ export class ClineProvider } if (oldTask) { + // The old task's final save writes its own pin (saveClineMessages persists + // _taskApiConfigName). Sync it to the restored record's pin first, so the + // abort cannot write the stale profile name back over a refresh that has + // already landed. + if (historyItem.apiConfigName) { + oldTask.setTaskApiConfigName(historyItem.apiConfigName) + } // Abort the old task to stop running processes and mark as abandoned try { await oldTask.abortTask(true) @@ -2501,9 +2563,10 @@ export class ClineProvider async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { const globalSettings = this.contextProxy.getValues() + const deletedWasActive = profileToDelete.name === globalSettings.currentApiConfigName let profileToActivate: string | undefined = globalSettings.currentApiConfigName - if (profileToDelete.name === profileToActivate) { + if (deletedWasActive) { profileToActivate = this.getProviderProfileEntries().find(({ name }) => name !== profileToDelete.name)?.name } @@ -2519,6 +2582,22 @@ export class ClineProvider listApiConfigMeta: entries, }) + if (deletedWasActive) { + // Deleting the active profile must leave the active name naming the settings + // in effect. Activate the fallback the same way the webview delete path does, + // so a later task restore cannot pin a name whose settings were never loaded + // and run the deleted profile's settings under the new name. + try { + await this.activateProviderProfile({ name: profileToActivate }) + } catch (error) { + this.log( + `Failed to activate profile '${profileToActivate}' after deleting '${profileToDelete.name}': ${ + error instanceof Error ? error.message : String(error) + }. The active name changed but its settings were not loaded.`, + ) + } + } + await this.postStateToWebview() } @@ -3785,6 +3864,38 @@ export class ClineProvider * @param options.broadcast Whether to broadcast the updated history to the webview (default: true) * @returns The updated task history array */ + /** + * Re-pin a task's provider profile through the store's own write path: an atomic + * read-update-write under the store lock that patches only `apiConfigName` on the + * current record. A refresh therefore cannot revert newer token counts or + * timestamps with the caller's stale snapshot, and it cannot serialize the live + * `rootTask`/`parentTask` references that the cancel-rehydrate path attaches to + * the history item copy. The missing-record error, the recent-tasks cache clear + * and the webview update are handled here. + */ + private async repinTaskProfile(taskId: string, apiConfigName: string): Promise { + const patchPin = (current: HistoryItem) => repinTaskProfilePin(current, apiConfigName) + try { + await this.taskHistoryStore.atomicReadAndUpdate(taskId, patchPin) + } catch (error) { + const notCached = + error instanceof Error && + error.message === `[TaskHistoryStore] atomicReadAndUpdate: task ${taskId} not found in cache` + if (!notCached) throw error + // The cache lost the record (an invalidation raced the restore): reload once. + await this.taskHistoryStore.invalidate(taskId) + if (!this.taskHistoryStore.get(taskId)) throw error + await this.taskHistoryStore.atomicReadAndUpdate(taskId, patchPin) + } + this.recentTasksCache = undefined + if (this.isViewLaunched) { + const updatedItem = this.taskHistoryStore.get(taskId) + if (updatedItem) { + await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem }) + } + } + } + async updateTaskHistory(item: HistoryItem, options: { broadcast?: boolean } = {}): Promise { const { broadcast = true } = options diff --git a/src/core/webview/restore-provider-profile.ts b/src/core/webview/restore-provider-profile.ts index 710d7c8e2fe..2e0c10a2615 100644 --- a/src/core/webview/restore-provider-profile.ts +++ b/src/core/webview/restore-provider-profile.ts @@ -14,6 +14,12 @@ // decision that reactivates must never also refresh. // - LegacyFallback: with no resolvable active profile, an existing pinned // profile is reactivated exactly as before the change. +// - ChildPinStable: a delegated child's restore never refreshes the child's +// task-local pin to the global active profile and never overwrites it. + +import type { RestoreProfileOrigin } from "../task-persistence/taskLifecycle" + +export type { RestoreProfileOrigin } /** A profile to re-activate, or undefined to leave the active configuration untouched. */ export interface RestoreProfileDecision { @@ -30,6 +36,8 @@ export interface RestoreProfileInput { activeProfileName: string | undefined /** Whether the pinned profile still exists in the profile list. */ pinnedProfileExists: boolean + /** Whether the pinned task runs a delegated child's task-local profile or the user's global choice. */ + profileOrigin: RestoreProfileOrigin } /** @@ -37,6 +45,9 @@ export interface RestoreProfileInput { * * Rules: * - No pin: nothing to do; the active configuration stays untouched. + * - Delegated child: the child's own task-local profile (selected at delegation by + * selectHandoffExecutionContext) is authoritative; the child is never re-pinned + * to the global active profile and its saved profile is never overwritten. * - Pin exists and no active profile resolves: legacy fallback re-activates the pin. * - Pin exists and equals the active profile: re-activate it (idempotent re-apply * of the saved profile settings, unchanged behavior for restores without a switch). @@ -46,12 +57,22 @@ export interface RestoreProfileInput { * active profile when one resolves. */ export function resolveRestoreProfileActivation(input: RestoreProfileInput): RestoreProfileDecision { - const { pinnedApiConfigName, activeProfileName, pinnedProfileExists } = input + const { pinnedApiConfigName, activeProfileName, pinnedProfileExists, profileOrigin } = input if (!pinnedApiConfigName) { return { reactivateProfileName: undefined, refreshedApiConfigName: undefined } } + if (profileOrigin === "delegated-child") { + // Delegation never changes the global profile, so the active global profile is + // not the user's choice for this child: restore the child's own pin (the + // legacy behavior) and never refresh it to the global profile. + if (!pinnedProfileExists) { + return { reactivateProfileName: undefined, refreshedApiConfigName: undefined } + } + return { reactivateProfileName: pinnedApiConfigName, refreshedApiConfigName: undefined } + } + if (!pinnedProfileExists) { // The pinned profile is gone; the active configuration (if any) is what runs. return { reactivateProfileName: undefined, refreshedApiConfigName: activeProfileName } From a5f0d771b8acf3dff3e829db93000f1e41548ba0 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 11:43:57 +0100 Subject: [PATCH 07/12] test(restored-task): pin every review-round restore behavior at its lowest layer - the restore harness binds the real queue machinery and the repin reducer, and the concurrent-switch test enqueues the switch while the restore is in flight (timeline order proves the serialization) - new regressions: the delegated child keeps its task-local pin, a validation-failed profile keeps its saved pin, the refresh patches only apiConfigName (newer token counts survive), the cancel-rehydrate circular lineage write still lands, the old task's pin syncs before its abort, and deleting the active profile loads the fallback settings - the decision spec gains the exhaustive property test over the whole input domain (origin included) in place of the duplicated table test --- ...der.restore-follows-active-profile.spec.ts | 455 ++++++++++++++++-- .../__tests__/taskLifecycle.spec.ts | 30 ++ .../restore-provider-profile.spec.ts | 129 ++++- 3 files changed, 560 insertions(+), 54 deletions(-) diff --git a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts index 7ccd1c81fa6..d6de86cb138 100644 --- a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts +++ b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts @@ -25,6 +25,26 @@ // delta compare drops apiConfigName and the stale pin survives on disk. // 8. A restore whose pinned profile exists but carries no configured provider // settings logs the deleted-profile warning, so the log misreports the state. +// 9. A delegated child is restored onto the global active profile and its saved +// task-local pin is overwritten with it (PR 2649 human review, +// restore-provider-profile.ts:66; delegation never changes the global profile). +// 10. A restore whose pinned profile failed schema validation on load (so +// listConfig drops it) overwrites the pin as if the profile were deleted +// (PR 2649 human review, restore-provider-profile.ts:57). +// 11. A user profile switch interleaves between the restore's profile snapshot, +// its decision and the settings capture, so the task is pinned to one profile +// name and built from another profile's settings (PR 2649 human review, +// ClineProvider.ts:1620; the decision now runs in the provider-profile +// mutation queue). +// 12. The re-pin write serializes the caller's stale full copy, so newer token +// counts or timestamps are reverted, or the live rootTask/parentTask +// references attached by the cancel-rehydrate path fail the write with +// "Converting circular structure to JSON" (PR 2649 human review, +// ClineProvider.ts:1657/1659; the re-pin patches only apiConfigName on the +// current store record). +// 13. During a rehydrate of the current task, the old task's final save runs +// after the re-pin and restores the old profile name (PR 2649 human review, +// ClineProvider.ts:1670; the old task's pin is synced before its abort). // // Red-verify: tests 1 and 3 fail on pre-fix code because the restore block // activates the stale pin unconditionally. Test 6 fails because the rejected @@ -33,7 +53,12 @@ // exact-settings assertion fails when the caller's profile.apiProvider guard // is dropped (activation then reports 'model-of-provider-1') or when the // fall-through skips Task construction; a bare resolves-defined check passed -// both (review round on 6ca11ea04). +// both (review round on 6ca11ea04). Test 9 fails on the pre-review code because +// the stale child pin is refreshed to the global profile. Test 10 fails because +// the pin is overwritten through the deleted-profile branch. Test 11 fails +// without the queue because the switch interleaves before the settings capture. +// Test 12 fails because the full-copy write regresses the tokens and rejects on +// the circular lineage. Test 13 fails because the old task's pin is never synced. import { describe, it, expect, vi, beforeEach } from "vitest" import { mkdtemp, readFile, rm } from "node:fs/promises" @@ -108,9 +133,10 @@ vi.mock("../core/task/Task", async (importOriginal) => { import { ClineProvider } from "../core/webview/ClineProvider" import { Task } from "../core/task/Task" import { TaskHistoryStore } from "../core/task-persistence/TaskHistoryStore" +import type { ProviderSettingsEntry } from "@roo-code/types" import { makeProviderStub } from "./helpers/provider-stub" -function makeHistoryItem(apiConfigName: string): HistoryItem { +function makeHistoryItem(apiConfigName: string, extra: Partial = {}): HistoryItem { return { id: "task-1", number: 1, @@ -120,6 +146,7 @@ function makeHistoryItem(apiConfigName: string): HistoryItem { tokensOut: 20, totalCost: 0.01, apiConfigName, + ...extra, } satisfies HistoryItem } @@ -129,25 +156,61 @@ interface RestoreHarnessOptions { profiles: ProfileEntry[] /** Value reported for the currentApiConfigName global (may be absent from `profiles`). */ activeProfileName: string | undefined - /** Real store to read history through and to persist with the real updateTaskHistory. */ + /** Whether the pinned profile exists in the raw settings file despite missing from `profiles`. */ + pinnedProfileOnDisk?: boolean + /** Reject the atomic re-pin write once with this error. */ + failRepinWith?: Error + /** Real store to read history through and to persist with the real write path. */ taskHistoryStore?: TaskHistoryStore + /** Tasks pre-seeded into the provider's real TaskRegistry (stack order). */ + tasks?: Task[] + /** Hook fired when the restore reads the profile list, while it is in flight. */ + onListConfig?: () => void } function makeRestoreHarness(options: RestoreHarnessOptions) { - const listConfig = vi.fn(async () => options.profiles) + const timeline: string[] = [] + const listConfig = vi.fn(async () => { + timeline.push("listConfig") + options.onListConfig?.() + return options.profiles + }) + const hasRawConfigName = vi.fn(async () => options.pinnedProfileOnDisk ?? false) const getGlobalState = vi.fn((key: string) => key === "currentApiConfigName" ? options.activeProfileName : undefined, ) // Activation switches the settings getState observes, mirroring the real // contract: after activateProviderProfile, getState reports the activated - // profile's provider and model. + // profile's provider and model. The restore runs the unlocked variant inside + // the provider-profile mutation queue, so the double replaces that method. let effectiveProfile = options.activeProfileName - const activateProviderProfile = vi.fn(async ({ name }: { name: string }) => { + const activateProviderProfileUnlocked = vi.fn(async ({ name }: { name: string }) => { + timeline.push(`activate:${name}`) effectiveProfile = name }) const log = vi.fn() const updateTaskHistoryMock = vi.fn(async () => []) + // In-memory record store for the atomic re-pin patch. The updater receives the + // current record and its result becomes the stored record, mirroring the real + // store's read-update-write under one lock. + const records = new Map() + const atomicReadAndUpdate = vi.fn( + async (taskId: string, updater: (current: HistoryItem) => HistoryItem): Promise => { + timeline.push("repin") + if (options.failRepinWith) { + throw options.failRepinWith + } + const current = records.get(taskId) + if (!current) { + throw new Error(`[TaskHistoryStore] atomicReadAndUpdate: task ${taskId} not found in cache`) + } + const updated = updater(current) + records.set(taskId, updated) + return [updated] + }, + ) const getState = vi.fn(async () => { + timeline.push("getState") const settings = options.profiles.find((profile) => profile.name === effectiveProfile) return { apiConfiguration: { @@ -161,17 +224,33 @@ function makeRestoreHarness(options: RestoreHarnessOptions) { } }) - const provider = makeProviderStub({ contextProxy: { globalStorageUri: { fsPath: "/tmp" } } }) + const provider = makeProviderStub({ + contextProxy: { globalStorageUri: { fsPath: "/tmp" } }, + tasks: options.tasks, + }) Object.assign(provider, { getState, log, updateGlobalState: vi.fn(async () => {}), getGlobalState, - activateProviderProfile, + ["activateProviderProfileUnlocked"]: activateProviderProfileUnlocked, + // The real queue machinery, bound to the stub so the restore's serialization + // semantics (and the concurrent-switch ordering) are exercised for real. + enqueueProviderProfileMutation: ClineProvider.prototype["enqueueProviderProfileMutation"], + withProviderProfileMutationTimeout: ClineProvider.prototype["withProviderProfileMutationTimeout"], + activateProviderProfile: ClineProvider.prototype["activateProviderProfile"], + repinTaskProfile: ClineProvider.prototype["repinTaskProfile"], updateTaskHistory: options.taskHistoryStore ? ClineProvider.prototype.updateTaskHistory : updateTaskHistoryMock, - taskHistoryStore: options.taskHistoryStore ?? { get: () => undefined, invalidate: async () => {} }, - providerSettingsManager: { listConfig }, + taskHistoryStore: options.taskHistoryStore ?? { + get: () => undefined, + invalidate: async () => {}, + atomicReadAndUpdate, + }, + providerSettingsManager: { listConfig, hasRawConfigName }, + providerProfileMutationQueue: Promise.resolve(), + isViewLaunched: false, + postMessageToWebview: vi.fn(async () => {}), addClineToStack: vi.fn(async () => {}), getPendingEditOperation: vi.fn(() => undefined), taskCreationCallback: vi.fn(), @@ -179,26 +258,25 @@ function makeRestoreHarness(options: RestoreHarnessOptions) { evictCurrentTask: vi.fn(async () => {}), }) - const createTaskWithHistoryItemUnlocked = ( - ClineProvider.prototype as unknown as { - createTaskWithHistoryItemUnlocked: ( - this: unknown, - historyItem: HistoryItem, - options?: { startTask?: boolean }, - ) => Promise - } - ).createTaskWithHistoryItemUnlocked + // Bracket notation for the private method, as the typed-test rules in + // AGENTS.md ask; element access keeps the real signature without a cast. + const createTaskWithHistoryItemUnlocked = ClineProvider.prototype["createTaskWithHistoryItemUnlocked"] const runRestore = (historyItem: HistoryItem) => createTaskWithHistoryItemUnlocked.call(provider, historyItem, { startTask: false }) return { runRestore, - activateProviderProfile, + provider, + activateProviderProfileUnlocked, updateTaskHistory: updateTaskHistoryMock, + repin: atomicReadAndUpdate, + records, + hasRawConfigName, listConfig, getGlobalState, log, + timeline, } } @@ -226,13 +304,14 @@ describe("ClineProvider restore follows the active profile", () => { ], activeProfileName: "provider-2", }) + harness.records.set("task-1", makeHistoryItem("provider-1")) await harness.runRestore(makeHistoryItem("provider-1")) - expect(harness.activateProviderProfile).not.toHaveBeenCalled() - expect(harness.updateTaskHistory).toHaveBeenCalledWith( - expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), - ) + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + // The re-pin patches only apiConfigName on the current store record. + expect(harness.repin).toHaveBeenCalledWith("task-1", expect.any(Function)) + expect(harness.records.get("task-1")?.apiConfigName).toBe("provider-2") expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") // The re-pin decision must be visible in the log with both names: the // active profile that stays in effect and the stale pin it replaces. @@ -255,11 +334,12 @@ describe("ClineProvider restore follows the active profile", () => { await harness.runRestore(makeHistoryItem("provider-1")) - expect(harness.activateProviderProfile).toHaveBeenCalledWith( + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( { name: "provider-1" }, expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), ) - expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") // After the re-activation the restored task must run on the activated // profile's provider and model. @@ -274,13 +354,13 @@ describe("ClineProvider restore follows the active profile", () => { profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], activeProfileName: "provider-2", }) + harness.records.set("task-1", makeHistoryItem("deleted-profile")) await harness.runRestore(makeHistoryItem("deleted-profile")) - expect(harness.activateProviderProfile).not.toHaveBeenCalled() - expect(harness.updateTaskHistory).toHaveBeenCalledWith( - expect.objectContaining({ id: "task-1", apiConfigName: "provider-2" }), - ) + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.repin).toHaveBeenCalledWith("task-1", expect.any(Function)) + expect(harness.records.get("task-1")?.apiConfigName).toBe("provider-2") expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ apiProvider: providerIdentifiers.openrouter, @@ -296,11 +376,12 @@ describe("ClineProvider restore follows the active profile", () => { await harness.runRestore(makeHistoryItem("provider-1")) - expect(harness.activateProviderProfile).toHaveBeenCalledWith( + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( { name: "provider-1" }, expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), ) - expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") // The activation must be what the observed settings follow: with no active // profile at restore time only the re-activated pin can supply provider/model. @@ -320,11 +401,12 @@ describe("ClineProvider restore follows the active profile", () => { await harness.runRestore(makeHistoryItem("provider-1")) - expect(harness.activateProviderProfile).toHaveBeenCalledWith( + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( { name: "provider-1" }, expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), ) - expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ apiProvider: providerIdentifiers.anthropic, @@ -332,15 +414,15 @@ describe("ClineProvider restore follows the active profile", () => { }) }) - it("continues the restore when the pin write rejects", async () => { + it("continues the restore when the re-pin write rejects", async () => { const harness = makeRestoreHarness({ profiles: [ { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, ], activeProfileName: "provider-2", + failRepinWith: new Error("simulated pin-write failure"), }) - harness.updateTaskHistory.mockRejectedValueOnce(new Error("simulated pin-write failure")) // The previous task is already evicted at this point; the restore must not // fail, and the task must still be constructed with the refreshed pin and @@ -416,8 +498,305 @@ describe("ClineProvider restore follows the active profile", () => { apiModelId: "model-of-unresolved", }) - expect(harness.activateProviderProfile).not.toHaveBeenCalled() - expect(harness.updateTaskHistory).not.toHaveBeenCalled() + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() expect(harness.log).not.toHaveBeenCalledWith(expect.stringContaining("no longer exists")) }) + + it("keeps a delegated child on its own task-local profile and never re-pins it to the global profile", async () => { + // Delegation assigns the child its own profile (selectHandoffExecutionContext) + // and never changes the global profile, so the global active profile is not + // the user's choice for this child: the child's own pin is reactivated and + // never overwritten with the global profile. + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + }) + + await harness.runRestore(makeHistoryItem("provider-1", { parentTaskId: "parent-1", rootTaskId: "root-1" })) + + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), + ) + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + expect(harness.log).not.toHaveBeenCalledWith(expect.stringContaining("stale pinned profile")) + }) + + it("keeps the configuration when a delegated child's pin no longer exists instead of re-pinning to the global profile", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + }) + + await harness.runRestore(makeHistoryItem("deleted-profile", { parentTaskId: "parent-1" })) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("deleted-profile") + expect(harness.log).toHaveBeenCalledWith(expect.stringContaining("no longer exists")) + }) + + it("keeps the saved pin when the pinned profile exists on disk but fails validation on load", async () => { + // listConfig drops a profile that fails schema validation, which makes a + // recoverable profile look deleted. The restore must keep the saved name and + // warn instead of overwriting the pin (PR 2649 human review, + // restore-provider-profile.ts:57). + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + pinnedProfileOnDisk: true, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.repin).not.toHaveBeenCalled() + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + expect(harness.log).toHaveBeenCalledWith(expect.stringContaining("exists but failed to load")) + }) + + it("re-pins to the active profile when the pinned profile is genuinely absent from disk", async () => { + // Companion to the validation-failure case: without the on-disk entry the + // deleted-profile re-pin still applies, so the issue #970 contract holds. + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + pinnedProfileOnDisk: false, + }) + harness.records.set("task-1", makeHistoryItem("deleted-profile")) + + await harness.runRestore(makeHistoryItem("deleted-profile")) + + expect(harness.hasRawConfigName).toHaveBeenCalledWith("deleted-profile") + expect(harness.repin).toHaveBeenCalledWith("task-1", expect.any(Function)) + expect(harness.records.get("task-1")?.apiConfigName).toBe("provider-2") + }) + + it("serializes the decision, activation and settings capture against a concurrent profile switch", async () => { + // The whole read -> decide -> activate -> settings-capture sequence runs + // inside the provider-profile mutation queue: a user switch enqueued before + // the restore finishes must run only after the restore captured its settings, + // so the task cannot be pinned to one profile and built from another's + // settings (PR 2649 human review, ClineProvider.ts:1620). + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: "provider-1", + // The user switch arrives while the restore is in flight (right after its + // profile snapshot): the real public method enqueues on the same + // provider-profile mutation queue, so it can only run after the restore's + // queue entry completes, which is after getState captured the settings. + onListConfig: () => { + void harness.provider.activateProviderProfile({ name: "provider-1" }) + }, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.timeline).toStrictEqual(["listConfig", "activate:provider-1", "getState", "activate:provider-1"]) + }) + + it("patches only apiConfigName so a newer token count survives the re-pin", async () => { + // The caller's snapshot is stale: a concurrent save advanced the stored token + // counts after the restore read its copy. The atomic patch must keep the + // newer counts and change only the pin (PR 2649 human review, + // ClineProvider.ts:1659). + const storageRoot = await mkdtemp(join(tmpdir(), "zoo-970-repin-")) + try { + const store = new TaskHistoryStore(storageRoot) + await store.upsert(makeHistoryItem("provider-1")) + const staleSnapshot = store.get("task-1") + // The concurrent save: newer token counts land after the snapshot was read. + await store.upsert(makeHistoryItem("provider-1", { tokensIn: 500, tokensOut: 90 })) + + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + taskHistoryStore: store, + }) + + await harness.runRestore(staleSnapshot as HistoryItem) + + const disk = JSON.parse( + await readFile(join(storageRoot, "tasks", "task-1", "history_item.json"), "utf8"), + ) as HistoryItem + expect(disk.apiConfigName).toBe("provider-2") + expect(disk.tokensIn).toBe(500) + expect(disk.tokensOut).toBe(90) + } finally { + await rm(storageRoot, { recursive: true, force: true }) + } + }) + + it("persists the re-pin even when the cancel-rehydrate copy carries circular task lineage", async () => { + // cancelTaskInternal rehydrates with the LIVE rootTask/parentTask attached to + // the history item ({ ...historyItem, rootTask, parentTask }). A full-copy + // write of that record rejects with "Converting circular structure to JSON", + // so the re-pin silently failed for subtasks. The atomic patch writes the + // store's own record and must not touch the live references (PR 2649 human + // review, ClineProvider.ts:1657). + const storageRoot = await mkdtemp(join(tmpdir(), "zoo-970-cycle-")) + try { + const store = new TaskHistoryStore(storageRoot) + await store.upsert(makeHistoryItem("provider-1")) + const cached = store.get("task-1") + + const rootTask: Record = { taskId: "root-1" } + const parentTask: Record = { taskId: "parent-1" } + // The live Task objects reference each other and themselves. + rootTask["parent"] = parentTask + parentTask["root"] = rootTask + rootTask["self"] = rootTask + const enriched = { ...cached, rootTask, parentTask } as HistoryItem & { + rootTask: unknown + parentTask: unknown + } + + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + taskHistoryStore: store, + }) + + await harness.runRestore(enriched) + + const disk = JSON.parse( + await readFile(join(storageRoot, "tasks", "task-1", "history_item.json"), "utf8"), + ) as HistoryItem + expect(disk.apiConfigName).toBe("provider-2") + // The constructed task still receives the live lineage. + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + } finally { + await rm(storageRoot, { recursive: true, force: true }) + } + }) + + it("syncs the refreshed pin into the old task before its final save during a rehydrate", async () => { + // During a restore of the current task the old task is stopped after the + // re-pin write; its final save carries its own pin and would put the old + // profile name back. The old task's pin must be synced to the refreshed pin + // before the abort (PR 2649 human review, ClineProvider.ts:1670). + const oldTask = { + taskId: "task-1", + instanceId: "old-instance", + setTaskApiConfigName: vi.fn(), + abortTask: vi.fn(async () => {}), + emit: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + } + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + // Seed the real TaskRegistry with the old task so the rehydrate branch's + // in-place replace runs; the double provides only the members the + // rehydrate path touches (taskId, instanceId, abortTask, emit, + // setTaskApiConfigName, message arrays). + tasks: [oldTask as unknown as Task], + }) + harness.records.set("task-1", makeHistoryItem("provider-1")) + Object.assign(harness.provider, { + getCurrentTask: vi.fn(() => oldTask), + taskEventListeners: new WeakMap(), + performPreparationTasks: vi.fn(async () => {}), + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(oldTask.setTaskApiConfigName).toHaveBeenCalledWith("provider-2") + // The sync must land before the abort, whose save would otherwise run last. + expect(oldTask.setTaskApiConfigName.mock.invocationCallOrder[0]).toBeLessThan( + oldTask.abortTask.mock.invocationCallOrder[0], + ) + }) +}) + +describe("ClineProvider deleteProviderProfile loads the fallback profile's settings", () => { + // Failure sentences these tests prevent: + // 1. Deleting the active profile changes the active name but not the settings, + // so a later task restore pins the new name and runs the deleted profile's + // settings (PR 2649 human review, ClineProvider.ts:1617). + // 2. Deleting a profile that is not active re-loads settings for no reason. + function makeDeleteHarness(currentApiConfigName: string | undefined) { + const setValues = vi.fn(async () => {}) + const log = vi.fn() + const activateProviderProfileUnlocked = vi.fn(async () => {}) + const provider = makeProviderStub({ + log, + contextProxy: { + globalStorageUri: { fsPath: "/tmp" }, + getValues: vi.fn(() => ({ currentApiConfigName })), + setValues, + }, + }) + Object.assign(provider, { + getProviderProfileEntries: vi.fn(() => [ + { id: "entry-1", name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { id: "entry-2", name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ]), + updateGlobalState: vi.fn(async () => {}), + activateProviderProfileUnlocked, + activateProviderProfile: ClineProvider.prototype["activateProviderProfile"], + enqueueProviderProfileMutation: ClineProvider.prototype["enqueueProviderProfileMutation"], + withProviderProfileMutationTimeout: ClineProvider.prototype["withProviderProfileMutationTimeout"], + providerProfileMutationQueue: Promise.resolve(), + postStateToWebview: vi.fn(async () => {}), + }) + const deleteProviderProfile = ClineProvider.prototype["deleteProviderProfile"] + return { + setValues, + activateProviderProfileUnlocked, + log, + run: (entry: ProviderSettingsEntry) => deleteProviderProfile.call(provider, entry), + } + } + + it("activates the fallback profile when the deleted profile was active", async () => { + const harness = makeDeleteHarness("provider-1") + + await harness.run({ id: "entry-1", name: "provider-1" }) + + // The stored active name and the loaded settings must move together: the + // fallback activation runs after the store write. + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-2" }, + undefined, + expect.any(AbortSignal), + ) + expect(harness.setValues.mock.invocationCallOrder[0]).toBeLessThan( + harness.activateProviderProfileUnlocked.mock.invocationCallOrder[0], + ) + }) + + it("does not activate anything when the deleted profile was not active", async () => { + const harness = makeDeleteHarness("provider-2") + + await harness.run({ id: "entry-1", name: "provider-1" }) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.setValues).toHaveBeenCalledWith(expect.objectContaining({ currentApiConfigName: "provider-2" })) + }) + + it("keeps the deletion when the fallback activation rejects", async () => { + const harness = makeDeleteHarness("provider-1") + harness.activateProviderProfileUnlocked.mockRejectedValueOnce(new Error("activation failed")) + + await expect(harness.run({ id: "entry-1", name: "provider-1" })).resolves.toBeUndefined() + + expect(harness.log).toHaveBeenCalledWith(expect.stringContaining("Failed to activate profile 'provider-2'")) + }) }) diff --git a/src/core/task-persistence/__tests__/taskLifecycle.spec.ts b/src/core/task-persistence/__tests__/taskLifecycle.spec.ts index 5d3129e0237..e15d61b8f2d 100644 --- a/src/core/task-persistence/__tests__/taskLifecycle.spec.ts +++ b/src/core/task-persistence/__tests__/taskLifecycle.spec.ts @@ -6,6 +6,8 @@ import { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + repinTaskProfilePin, + restoredProfileOriginOf, settleRejectedCreateSubtaskAction, } from "../taskLifecycle" @@ -185,3 +187,31 @@ describe("settleRejectedCreateSubtaskAction", () => { ) }) }) + +describe("restored task profile pin", () => { + it("derives the delegation ownership origin from the record lineage", () => { + expect(restoredProfileOriginOf(item("root"))).toBe("user") + expect(restoredProfileOriginOf(item("child", { parentTaskId: "root" }))).toBe("delegated-child") + }) + + it("patches only apiConfigName and returns a fresh record", () => { + const record = item("task-1", { + tokensIn: 500, + tokensOut: 90, + ts: 1700000000000, + apiConfigName: "provider-1", + }) + + const repinned = repinTaskProfilePin(record, "provider-2") + + expect(repinned).not.toBe(record) + expect(repinned).toStrictEqual({ ...record, apiConfigName: "provider-2" }) + }) + + it("keeps the record unchanged when a decision carries no refresh", () => { + const record = item("task-1", { apiConfigName: "provider-1" }) + + expect(repinTaskProfilePin(record, undefined)).toBe(record) + expect(repinTaskProfilePin(record, "")).toBe(record) + }) +}) diff --git a/src/core/webview/__tests__/restore-provider-profile.spec.ts b/src/core/webview/__tests__/restore-provider-profile.spec.ts index 1d06b084a65..fc43c7103aa 100644 --- a/src/core/webview/__tests__/restore-provider-profile.spec.ts +++ b/src/core/webview/__tests__/restore-provider-profile.spec.ts @@ -10,18 +10,35 @@ // decision that reactivates must never also refresh. // - LegacyFallback: with no resolvable active profile, an existing pinned // profile is reactivated exactly as before the fix. +// - ChildPinStable: a delegated child is never refreshed to the global active +// profile; the child's own task-local pin is the only profile a child +// restore reactivates (PR 2649 human review, restore-provider-profile.ts:66). import { describe, it, expect } from "vitest" -import { resolveRestoreProfileActivation } from "../restore-provider-profile" +import { + resolveRestoreProfileActivation, + type RestoreProfileDecision, + type RestoreProfileOrigin, +} from "../restore-provider-profile" + +interface DecisionCase { + name: string + pinnedApiConfigName: string | undefined + activeProfileName: string | undefined + pinnedProfileExists: boolean + profileOrigin: RestoreProfileOrigin + expected: RestoreProfileDecision +} describe("resolveRestoreProfileActivation", () => { - it.each([ + it.each([ { name: "no pin: nothing to reactivate and nothing to refresh", pinnedApiConfigName: undefined, activeProfileName: "provider-2", pinnedProfileExists: false, + profileOrigin: "user", expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, }, { @@ -29,6 +46,7 @@ describe("resolveRestoreProfileActivation", () => { pinnedApiConfigName: "provider-1", activeProfileName: undefined, pinnedProfileExists: true, + profileOrigin: "user", expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, }, { @@ -36,6 +54,7 @@ describe("resolveRestoreProfileActivation", () => { pinnedApiConfigName: "provider-1", activeProfileName: "provider-1", pinnedProfileExists: true, + profileOrigin: "user", expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, }, { @@ -43,6 +62,7 @@ describe("resolveRestoreProfileActivation", () => { pinnedApiConfigName: "provider-1", activeProfileName: "provider-2", pinnedProfileExists: true, + profileOrigin: "user", expected: { reactivateProfileName: undefined, refreshedApiConfigName: "provider-2" }, }, { @@ -50,6 +70,7 @@ describe("resolveRestoreProfileActivation", () => { pinnedApiConfigName: "deleted-profile", activeProfileName: undefined, pinnedProfileExists: false, + profileOrigin: "user", expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, }, { @@ -57,32 +78,108 @@ describe("resolveRestoreProfileActivation", () => { pinnedApiConfigName: "deleted-profile", activeProfileName: "provider-2", pinnedProfileExists: false, + profileOrigin: "user", expected: { reactivateProfileName: undefined, refreshedApiConfigName: "provider-2" }, }, - ])("$name", ({ pinnedApiConfigName, activeProfileName, pinnedProfileExists, expected }) => { + { + name: "delegated child with its own pin: reactivate the child pin only, never refresh", + pinnedApiConfigName: "provider-1", + activeProfileName: "provider-2", + pinnedProfileExists: true, + profileOrigin: "delegated-child", + expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, + }, + { + name: "delegated child whose pin no longer exists: keep the configuration, never re-pin to the global profile", + pinnedApiConfigName: "deleted-profile", + activeProfileName: "provider-2", + pinnedProfileExists: false, + profileOrigin: "delegated-child", + expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, + }, + ])("$name", ({ pinnedApiConfigName, activeProfileName, pinnedProfileExists, profileOrigin, expected }) => { expect( resolveRestoreProfileActivation({ pinnedApiConfigName, activeProfileName, pinnedProfileExists, + profileOrigin, }), ).toStrictEqual(expected) }) - it("never returns a refresh together with a reactivation", () => { - const decisions = [ - { pinnedApiConfigName: undefined, activeProfileName: undefined, pinnedProfileExists: false }, - { pinnedApiConfigName: "provider-1", activeProfileName: undefined, pinnedProfileExists: true }, - { pinnedApiConfigName: "provider-1", activeProfileName: "provider-1", pinnedProfileExists: true }, - { pinnedApiConfigName: "provider-1", activeProfileName: "provider-2", pinnedProfileExists: true }, - { pinnedApiConfigName: "deleted-profile", activeProfileName: undefined, pinnedProfileExists: false }, - { pinnedApiConfigName: "deleted-profile", activeProfileName: "provider-2", pinnedProfileExists: false }, - ].map(resolveRestoreProfileActivation) + // Property test over the whole input domain (the TLA rules ask for a property + // test from the same invariant sentence; the domain is small enough to check + // exhaustively, which is stronger than sampling). Every combination of pin, + // active profile, existence flag and origin must satisfy the invariant set. + const pins = [undefined, "provider-1", "provider-2", "deleted-profile"] as const + const actives = [undefined, "provider-1", "provider-2"] as const + const exists = [true, false] as const + const origins = ["user", "delegated-child"] as const - for (const decision of decisions) { - const combined = - decision.reactivateProfileName !== undefined && decision.refreshedApiConfigName !== undefined - expect(combined).toBe(false) + it("satisfies the invariant set for every input in the domain", () => { + const failures: string[] = [] + + for (const pinnedApiConfigName of pins) { + for (const activeProfileName of actives) { + for (const pinnedProfileExists of exists) { + for (const profileOrigin of origins) { + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName, + activeProfileName, + pinnedProfileExists, + profileOrigin, + }) + const label = `pin=${String(pinnedApiConfigName)} active=${String(activeProfileName)} exists=${String(pinnedProfileExists)} origin=${profileOrigin}` + const refreshes = decision.refreshedApiConfigName !== undefined + const reactivates = decision.reactivateProfileName !== undefined + + // PinNamesEffect holds for both origins: a refresh names exactly the + // active profile, and a reactivation never also refreshes. + if (refreshes && decision.refreshedApiConfigName !== activeProfileName) { + failures.push(`${label}: refresh does not name the active profile`) + } + if (refreshes && reactivates) { + failures.push(`${label}: refresh and reactivation combined`) + } + + if (profileOrigin === "user") { + // FollowActive: an existing pin differing from the resolvable active + // profile is never reactivated. + if ( + pinnedApiConfigName !== undefined && + pinnedProfileExists && + activeProfileName !== undefined && + activeProfileName !== pinnedApiConfigName && + reactivates + ) { + failures.push(`${label}: stale pin reactivated over the active profile`) + } + // LegacyFallback: an existing pin with no resolvable active profile + // is reactivated exactly as before the fix. + if ( + pinnedApiConfigName !== undefined && + pinnedProfileExists && + activeProfileName === undefined && + decision.reactivateProfileName !== pinnedApiConfigName + ) { + failures.push(`${label}: legacy fallback lost the pin reactivation`) + } + } else { + // ChildPinStable: a delegated child is never refreshed to the global + // profile and only ever reactivates its own pin. + if (refreshes) { + failures.push(`${label}: delegated child refreshed to the global profile`) + } + if (reactivates && decision.reactivateProfileName !== pinnedApiConfigName) { + failures.push(`${label}: delegated child reactivated a foreign profile`) + } + } + } + } + } } + + expect(failures).toStrictEqual([]) }) }) From cfe7b46dc338de8ffe519bae2be057ec17374ca5 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 11:44:25 +0100 Subject: [PATCH 08/12] model(task-lifecycle): explore restore-repin delegation and persistence ownership The restore-repin action applies the production resolveRestoreProfileActivation and repinTaskProfilePin under every delegation interleaving. New invariants: ChildPinStable (a child's pin is never refreshed to the global profile), UserPinFollowsActive, RepinPatchesOnlyPin (a repin changes only apiConfigName, so a stale caller copy cannot revert newer fields), slot isolation, and the completed-record repin exemption bounded to apiConfigName. The child-restore-keeps-pin witness must stay reachable. 2934 reachable states, 7/7 actions, 7/7 witnesses, depth <= 12. --- scripts/check-task-lifecycle.ts | 100 +++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 2 deletions(-) diff --git a/scripts/check-task-lifecycle.ts b/scripts/check-task-lifecycle.ts index bf05ad68e96..f3c6f565b4c 100644 --- a/scripts/check-task-lifecycle.ts +++ b/scripts/check-task-lifecycle.ts @@ -7,8 +7,11 @@ import { completeDelegatedChild, delegateTaskToChild, interruptDelegatedChild, + repinTaskProfilePin, + restoredProfileOriginOf, settleRejectedCreateSubtaskAction, } from "../src/core/task-persistence/taskLifecycle" +import { resolveRestoreProfileActivation } from "../src/core/webview/restore-provider-profile" const taskIds = ["parent", "child-a", "child-b"] as const type TaskId = (typeof taskIds)[number] @@ -20,6 +23,7 @@ interface Transition { delegation?: { parentId: TaskId } completion?: { childId: TaskId; pendingActionId?: string } settlement?: { taskId: TaskId; actionId: string } + restore?: { taskId: TaskId; activeProfileName: string | undefined; pinnedProfileExists: boolean } } interface TraceStep { @@ -36,7 +40,15 @@ interface WitnessContext { const MAX_DEPTH = 12 const MAX_STATES = 10_000 const actionIds = ["action-1", "action-2"] as const -const expectedActions = ["delegate", "interrupt", "complete", "abandon", "stage", "settle-rejected"] as const +const expectedActions = [ + "delegate", + "interrupt", + "complete", + "abandon", + "stage", + "settle-rejected", + "restore-repin", +] as const const semanticLandmarks = { "interrupted-child-redelegation": (state: ModelState) => state.parent?.status === "delegated" && @@ -99,6 +111,14 @@ const semanticWitnesses = { canonicalTask(after.pendingAction) === canonicalTask(beforeAction) ) }, + // A delegated child's restore keeps the child's task-local pin (never refreshed + // to the global active profile) while the restore transition still ran. + "child-restore-keeps-pin": ({ prev, next, transition }: WitnessContext) => { + if (transition.restore === undefined) return false + const before = prev[transition.restore.taskId] + const after = next[transition.restore.taskId] + return !!before?.parentTaskId && !!before.apiConfigName && after?.apiConfigName === before.apiConfigName + }, } satisfies Record boolean> function task(id: TaskId, parentTaskId?: TaskId): HistoryItem { @@ -114,6 +134,9 @@ function task(id: TaskId, parentTaskId?: TaskId): HistoryItem { parentTaskId, rootTaskId: parentTaskId ? "parent" : undefined, childIds: [], + // Every task carries the task-local pin a save persists; delegation assigns + // children their own task-local profile pin. + apiConfigName: "pin-a", } } @@ -221,6 +244,34 @@ function transitions(state: ModelState): Transition[] { }) } } + // Restore: the provider-profile decision for a task whose pin the history item + // carries. The environment inputs are the restore-time profile list state: the + // resolvable active profile and whether the pinned profile still exists. The + // decision is the production resolveRestoreProfileActivation; the persisted + // mutation goes through the production repinTaskProfilePin reducer. + const restoreInputs = [ + { activeProfileName: undefined, pinnedProfileExists: true }, + { activeProfileName: "pin-a", pinnedProfileExists: true }, + { activeProfileName: "pin-b", pinnedProfileExists: true }, + { activeProfileName: "pin-b", pinnedProfileExists: false }, + ] as const + for (const id of taskIds) { + const record = state[id] + if (!record?.apiConfigName) continue + for (const input of restoreInputs) { + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName: record.apiConfigName, + activeProfileName: input.activeProfileName, + pinnedProfileExists: input.pinnedProfileExists, + profileOrigin: restoredProfileOriginOf(record), + }) + result.push({ + name: `restore-repin(${id}, active=${String(input.activeProfileName)}, exists=${String(input.pinnedProfileExists)})`, + next: replace(state, repinTaskProfilePin(record, decision.refreshedApiConfigName)), + restore: { taskId: id, ...input }, + }) + } + } return result } @@ -292,7 +343,52 @@ function checkTransitionInvariants(previous: ModelState, transition: Transition) const before = previous[id] const after = transition.next[id] if (before?.status === "completed" && canonicalTask(before) !== canonicalTask(after)) { - violations.push(`${id}: completed task changed after ${transition.name}`) + // A restore may re-pin a completed record (reopening a finished task from + // history), but only through the patch-only reducer: apiConfigName is the + // only field a restore-repin may change on a completed task. + const repinOnly = + transition.restore?.taskId === id && + canonicalTask({ ...before, apiConfigName: after?.apiConfigName }) === canonicalTask(after) + if (!repinOnly) { + violations.push(`${id}: completed task changed after ${transition.name}`) + } + } + } + + const restore = transition.restore + if (restore) { + const before = previous[restore.taskId] + const after = transition.next[restore.taskId] + if (!before || !after) { + violations.push(`${restore.taskId}: restore-repin touched a missing record`) + } else { + const origin = restoredProfileOriginOf(before) + // ChildPinStable: a delegated child's restore never re-pins the child to + // the global active profile; the task-local pin survives every restore. + if (origin === "delegated-child" && after.apiConfigName !== before.apiConfigName) { + violations.push(`${restore.taskId}: delegated child's pin was refreshed to the global active profile`) + } + // UserPinFollowsActive: a user restore keeps the pin or re-pins it to the + // active profile exactly. + if ( + origin === "user" && + after.apiConfigName !== before.apiConfigName && + after.apiConfigName !== restore.activeProfileName + ) { + violations.push(`${restore.taskId}: restore re-pinned to a profile that is not the active one`) + } + // RepinPatchesOnlyPin: the persisted mutation changes only apiConfigName, + // so a stale caller copy cannot revert newer token counts or timestamps. + const repinned = { ...before, apiConfigName: after.apiConfigName } + if (canonicalTask(repinned) !== canonicalTask(after)) { + violations.push(`${restore.taskId}: restore-repin changed fields other than apiConfigName`) + } + for (const otherId of taskIds) { + if (otherId === restore.taskId) continue + if (canonicalTask(previous[otherId]) !== canonicalTask(transition.next[otherId])) { + violations.push(`${otherId}: restore-repin of ${restore.taskId} changed an unrelated record`) + } + } } } From ebb34892f0d2a3c78cff663a29906194cb638963 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 11:44:26 +0100 Subject: [PATCH 09/12] spec(tla): model profile origin, the stale copy and the concurrent switch RestoreProfileDecision grows the origin, savedPin, switchActive and withinTimeout inputs so Proceed is no longer constant and the review round's gaps are modeled: ChildPinStable (restore-provider-profile.ts:66), RefreshNamesEffectiveActive + the queue rule in Valid (ClineProvider.ts:1620), and NoWritePreservesPin now pinning the persisted record's own pin instead of the caller's history copy (ClineProvider.ts:1657/1659). WriteFailureRestores becomes a real constraint: Proceed must not read the write outcome. Spec.cfg passes all nine invariants (648 states); every sabotage cfg violates exactly its named invariant: Sabotage FollowActive (385), CacheAlias RefreshPersists (205), WriteAbort WriteFailureRestores (205), StalePin NoWritePreservesPin (4), ChildRestore ChildPinStable (199), NoQueue RefreshNamesEffectiveActive (589). --- .../tla/RestoreProfileDecision.CacheAlias.cfg | 2 +- .../RestoreProfileDecision.ChildRestore.cfg | 10 ++ .../tla/RestoreProfileDecision.NoQueue.cfg | 10 ++ .../tla/RestoreProfileDecision.Sabotage.cfg | 2 +- .../tla/RestoreProfileDecision.StalePin.cfg | 12 +- .../tla/RestoreProfileDecision.WriteAbort.cfg | 8 +- .../tla/RestoreProfileDecision.cfg | 2 +- .../tla/RestoreProfileDecision.tla | 124 +++++++++++++----- .../tla/RestoreProfileDecisionMC.tla | 44 +++++-- 9 files changed, 158 insertions(+), 56 deletions(-) create mode 100644 docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg create mode 100644 docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg diff --git a/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg index 500ab8b041d..6fb26260845 100644 --- a/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg @@ -7,4 +7,4 @@ CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Valid <- ValidAliased -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg b/docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg new file mode 100644 index 00000000000..f1e447f2340 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.ChildRestore.cfg — sabotage: the delegated-child origin is +\* ignored, so a child's restore is decided like a user restore and the child is +\* refreshed to the global active profile. ChildPinStable must be the violated +\* invariant (PR 2649 human review, restore-provider-profile.ts:66). +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Decide <- DecideIgnoresOrigin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg b/docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg new file mode 100644 index 00000000000..27a3c722f1a --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.NoQueue.cfg — sabotage: the decision runs outside the +\* provider-profile mutation queue, so a user switch can interleave between the +\* decision's snapshot and the write. RefreshNamesEffectiveActive must be the +\* violated invariant (PR 2649 human review, ClineProvider.ts:1620). +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Valid <- ValidUnqueued +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg index 9a5a8005ebe..a08441c7266 100644 --- a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg @@ -4,4 +4,4 @@ CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Decide <- DecideAlwaysPin -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg b/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg index 1d8aaa03063..9864e2d5a68 100644 --- a/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg @@ -1,10 +1,10 @@ -\* RestoreProfileDecision.StalePin.cfg — sabotage: the no-write path keeps the -\* previous modeled pin instead of the pin the selected input carried in, so the -\* modeled pin diverges from the persisted history-item pin. -\* NoWritePreservesPin must be the violated invariant. +\* RestoreProfileDecision.StalePin.cfg — sabotage: a full-copy write persists the +\* caller's history-copy pin even when no write landed, so a stale copy overwrites +\* the persisted record's newer pin. NoWritePreservesPin must be the violated +\* invariant. SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" - PersistedPin <- PersistedPinStale -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin + PersistedPin <- PersistedPinFullCopy +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg index cbeec399df3..0890cd67eab 100644 --- a/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg @@ -1,9 +1,9 @@ -\* RestoreProfileDecision.WriteAbort.cfg — sabotage: the restore aborts when the -\* refresh pin write rejects (the un-caught await before the Task constructor). -\* WriteFailureRestores must be the violated invariant. +\* RestoreProfileDecision.WriteAbort.cfg — sabotage: Proceed reads the write outcome, +\* so the restore aborts when the refresh pin write rejects (the un-caught await +\* before the Task constructor). WriteFailureRestores must be the violated invariant. SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" Proceed <- ProceedAbort -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.cfg b/docs/architecture/tla/RestoreProfileDecision.cfg index 5a51f4846af..f99b401589c 100644 --- a/docs/architecture/tla/RestoreProfileDecision.cfg +++ b/docs/architecture/tla/RestoreProfileDecision.cfg @@ -3,4 +3,4 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS NoActive = "none" -INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla index a388443b41e..2b50f70247c 100644 --- a/docs/architecture/tla/RestoreProfileDecision.tla +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -4,13 +4,13 @@ \* resolved against the profile list by ClineProvider.createTaskWithHistoryItemUnlocked. \* Sink: the decision record (reactivateProfileName, refreshedApiConfigName) consumed by \* the same method: reactivate calls activateProviderProfile, refresh rewrites the pin -\* through updateTaskHistory (persisted to the task file) and hands the record to the -\* Task constructor. +\* through the repinTaskProfilePin reducer (persisted to the task file) and hands the +\* record to the Task constructor. \* Failure: restore re-activates a stale pinned profile, so the resumed task and the \* task header keep the old provider's context window (issue #970). \* Invariants (first version written before the fix): \* FollowActive. With an existing pin and a resolvable active profile different from -\* it, the decision must not reactivate the pinned profile. +\* it, a user restore must not reactivate the pinned profile. \* PinNamesEffect. A refresh names exactly the active profile, and a reactivation \* never also refreshes. \* LegacyFallback. With no resolvable active profile, an existing pin is reactivated. @@ -20,20 +20,39 @@ \* the cached one (input rule in Valid); mutating the cached record in place makes \* the store's delta compare drop apiConfigName, so the stale pin survives on disk \* (CR thread on ClineProvider.ts:1651). -\* WriteFailureRestores. The restore reaches Task construction even when the refresh -\* pin write rejects (CR thread on ClineProvider.ts:1652). +\* WriteFailureRestores. The restore reaches Task construction with the reachability +\* it would have had if the write had succeeded: Proceed must not read the write +\* outcome, because a failed refresh write is caught (CR thread on +\* ClineProvider.ts:1652). +\* Added in the PR 2649 human review round (edelauna, 2026-11-30): +\* ChildPinStable. A delegated child's restore never refreshes and reactivates only +\* the child's own task-local pin (thread on restore-provider-profile.ts:66; +\* delegation never changes the global profile, so the global active profile is not +\* the user's choice for the child). +\* RefreshNamesEffectiveActive. A refresh names the profile active at write time. +\* The input rule switchActive = active in Valid models the provider-profile +\* mutation queue: a user switch cannot interleave between the decision's snapshot +\* and the write (thread on ClineProvider.ts:1620; RestoreProfileDecision.NoQueue.cfg +\* sabotages the rule away). +\* NoWritePreservesPin. When no write lands, the persisted record keeps its own +\* current pin (input.savedPin), not the pin on the caller's possibly stale history +\* copy (input.pin) - the old-history-copy ownership (threads on ClineProvider.ts +\* :1657/1659; a full-copy write would revert newer fields). StalePin.cfg now +\* sabotages a full-copy write. +\* Proceed is inp.withinTimeout, no longer a constant: the queue timeout is the one +\* modeled stopper, so restored varies across reachable states and +\* WriteFailureRestores has content (thread on RestoreProfileDecision.tla:103). \* Run each config on RestoreProfileDecisionMC.tla. The MC module holds the sabotage. \* Expected: Spec.cfg passes every invariant; Sabotage.cfg fails FollowActive; \* CacheAlias.cfg fails RefreshPersists; WriteAbort.cfg fails WriteFailureRestores; -\* StalePin.cfg fails NoWritePreservesPin. -\* Result: Spec.cfg checks and holds all seven invariants in 48 distinct states. -\* CacheAlias.cfg violates RefreshPersists (21 states), Sabotage.cfg violates -\* FollowActive (27 states), WriteAbort.cfg violates WriteFailureRestores (15 -\* states), StalePin.cfg violates NoWritePreservesPin (13 states); no other -\* invariant breaks in any run. +\* StalePin.cfg fails NoWritePreservesPin; ChildRestore.cfg fails ChildPinStable; +\* NoQueue.cfg fails RefreshNamesEffectiveActive. +\* Result: Spec.cfg checks and holds all nine invariants; each sabotage cfg violates +\* the invariant it names (state counts in the check log, see the commit message). \* Not modeled: the profile list (pinnedProfileExists is an oracle the caller computes), -\* the activateProviderProfile side effects, mode restoration, and the CLI runtime -\* skip flag (checked before the decision runs). +\* the activateProviderProfile settings side effects, mode restoration, and the CLI +\* runtime skip flag (checked before the decision runs). The settings capture after the +\* activation is modeled only through the serialization rule in Valid. \* Cost: TLC finishes in under 1 second per config. \* Review (PR 2649, round on d58eaba2c): 1 covered (LegacyFallback - the missing-profile \* proof case of the Regression Evidence check), 2 added (RefreshPersists + the @@ -59,6 +78,15 @@ \* fallback it pins: the no-write path now persists the selected input's pin, \* factored as PersistedPin so StalePin.cfg sabotages the stale form; CR thread \* RestoreProfileDecision.tla:109), 0 covered, 0 gap. +\* Review (PR 2649, human round 1, edelauna 2026-11-30): 3 added (ChildPinStable + +\* the origin input, thread restore-provider-profile.ts:66; RefreshNamesEffectiveActive +\* + the switchActive input and the queue rule in Valid, thread ClineProvider.ts:1620; +\* the savedPin input making NoWritePreservesPin pin the persisted record's own pin +\* instead of the caller's copy, threads ClineProvider.ts:1657/1659), 1 changed +\* (Proceed is inp.withinTimeout instead of TRUE so WriteFailureRestores is a real +\* constraint; WriteAbort.cfg still fails it, thread RestoreProfileDecision.tla:103), +\* 1 covered (FollowActive and LegacyFallback were already the stale-pin and +\* missing-profile behavior the round's other threads restate). CONSTANT NoActive \* sentinel: no resolvable active profile at restore time @@ -71,11 +99,17 @@ Keep == "keep" \* decision marker: preserve the stored pin Input == [pin: {"p1", "p2", "absent"}, active: {"p1", "p2", NoActive}, - pinExists: BOOLEAN, pinWriteOk: BOOLEAN, distinctRecord: BOOLEAN] + pinExists: BOOLEAN, pinWriteOk: BOOLEAN, distinctRecord: BOOLEAN, + origin: {"user", "child"}, savedPin: {"p1", "p2", "absent"}, + switchActive: {"p1", "p2", NoActive}, withinTimeout: BOOLEAN] -\* Mirrors resolveRestoreProfileActivation rule for rule. +\* Mirrors resolveRestoreProfileActivation rule for rule, origin included: a +\* delegated child's own task-local pin is authoritative and never refreshed. Decide(inp) == IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF inp.origin = "child" THEN + IF inp.pinExists THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> Keep] ELSE IF ~inp.pinExists THEN IF inp.active # NoActive THEN [r |-> NoProfile, f |-> inp.active] ELSE [r |-> NoProfile, f |-> Keep] @@ -87,27 +121,34 @@ Decide(inp) == Refreshes(inp) == Decide(inp).f # Keep \* The sink: the pin persisted after one restore. A refresh whose write succeeds on -\* a record distinct from the store-cached one rewrites the pin; every other path -\* writes nothing, so the pin the history item carried in stays persisted. +\* a record distinct from the store-cached one patches the pin on the store's current +\* record; every other path writes nothing, so the persisted record keeps its own +\* current pin - never the pin on the caller's possibly stale history copy. PersistedPin(dec, inp, prev) == - IF dec.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord THEN dec.f ELSE inp.pin + IF dec.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord THEN dec.f ELSE inp.savedPin -\* Caller rules: no existing flag for an absent pin, and a refresh write is built -\* from a record distinct from the store-cached one (a copy), never the cached -\* record itself. +\* Caller rules: no existing flag for an absent pin; a refresh write is built from a +\* record distinct from the store-cached one (a copy), never the cached record; and +\* the mutation queue serializes the restore, so no user switch can interleave +\* between the decision's profile snapshot and the write. Valid(inp) == /\ ((inp.pin = "absent") => (~inp.pinExists)) /\ (Refreshes(inp) => inp.distinctRecord) + /\ inp.switchActive = inp.active -\* The restore reaches Task construction even after a failed refresh write. -Proceed(dec, inp) == TRUE +\* The queue timeout is the one modeled stopper: with runToCompletion a failed +\* refresh write is caught and the restore still reaches Task construction, while a +\* timeout rejects the caller before it. Not a constant, so restored varies. +Proceed(dec, inp) == inp.withinTimeout Init == /\ input = [pin |-> "absent", active |-> NoActive, pinExists |-> FALSE, - pinWriteOk |-> TRUE, distinctRecord |-> TRUE] + pinWriteOk |-> TRUE, distinctRecord |-> TRUE, + origin |-> "user", savedPin |-> "absent", + switchActive |-> NoActive, withinTimeout |-> TRUE] /\ decision = Decide(input) - /\ storedPin = input.pin - /\ restored = TRUE + /\ storedPin = input.savedPin + /\ restored = Proceed(Decide(input), input) Next == \E inp \in Input : @@ -128,24 +169,41 @@ TypeOK == /\ restored \in BOOLEAN FollowActive == - (input.pin # "absent" /\ input.pinExists /\ input.active # NoActive /\ input.active # input.pin) - => decision.r = NoProfile + (input.pin # "absent" /\ input.origin = "user" /\ input.pinExists + /\ input.active # NoActive /\ input.active # input.pin) => decision.r = NoProfile PinNamesEffect == /\ (decision.f # Keep) => decision.f = input.active /\ (decision.r # NoProfile) => decision.f = Keep LegacyFallback == - (input.pin # "absent" /\ input.pinExists /\ input.active = NoActive) => decision.r = input.pin + (input.pin # "absent" /\ input.origin = "user" /\ input.pinExists + /\ input.active = NoActive) => decision.r = input.pin RefreshPersists == (decision.f # Keep /\ input.pinWriteOk) => storedPin = decision.f \* No write landed (no refresh, a failed refresh write, or an aliased record the -\* store's delta compare drops): the persisted pin is the one the input carried in. +\* store's delta compare drops): the persisted record keeps its own current pin, so +\* the caller's stale history copy cannot overwrite a newer one. NoWritePreservesPin == - (~(decision.f # Keep /\ input.pinWriteOk /\ input.distinctRecord)) => storedPin = input.pin - -WriteFailureRestores == restored + (~(decision.f # Keep /\ input.pinWriteOk /\ input.distinctRecord)) => storedPin = input.savedPin + +\* A delegated child is never refreshed to the global profile and reactivates only +\* its own task-local pin. +ChildPinStable == + (input.origin = "child") => + /\ decision.f = Keep + /\ (decision.r # NoProfile) => decision.r = input.pin + +\* The queue serialized the restore, so a refresh names the profile active at write +\* time - the same profile the decision snapshotted. +RefreshNamesEffectiveActive == + (decision.f # Keep) => decision.f = input.switchActive + +\* The restore reaches Task construction with the reachability it would have had if +\* the refresh write had succeeded: Proceed must not read the write outcome. +WriteFailureRestores == + restored = Proceed(decision, [input EXCEPT !.pinWriteOk = TRUE]) ==== diff --git a/docs/architecture/tla/RestoreProfileDecisionMC.tla b/docs/architecture/tla/RestoreProfileDecisionMC.tla index 333f256eec0..c075724b4a4 100644 --- a/docs/architecture/tla/RestoreProfileDecisionMC.tla +++ b/docs/architecture/tla/RestoreProfileDecisionMC.tla @@ -3,24 +3,48 @@ EXTENDS RestoreProfileDecision \* Sabotage: the stale-pin guard is removed. The pin is always re-activated when it -\* exists (the pre-fix behavior) and the pin is never refreshed. +\* exists (the pre-fix behavior) and the pin is never refreshed. FollowActive must fail. DecideAlwaysPin(inp) == IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] ELSE IF inp.pinExists THEN [r |-> inp.pin, f |-> Keep] ELSE [r |-> NoProfile, f |-> Keep] +\* Sabotage: the delegated-child origin is ignored, so a child's restore is decided +\* like a user restore and the child is refreshed to the global active profile. +\* ChildPinStable must fail. The user rules are inlined (a cfg override of Decide +\* substitutes every occurrence, including inside this operator's own body). +DecideIgnoresOrigin(inp) == + IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF ~inp.pinExists THEN + IF inp.active # NoActive THEN [r |-> NoProfile, f |-> inp.active] + ELSE [r |-> NoProfile, f |-> Keep] + ELSE IF inp.active = NoActive THEN [r |-> inp.pin, f |-> Keep] + ELSE IF inp.active = inp.pin THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> inp.active] + \* Sabotage: the refresh write aliases the store-cached record (the restore mutates -\* the cached item in place before updateTaskHistory), so the store's delta compare -\* drops apiConfigName and the stale pin survives on disk. RefreshPersists must fail. -ValidAliased(inp) == (inp.pin = "absent") => (~inp.pinExists) +\* the cached item in place before the write), so the store's delta compare +\* drops apiConfigName and the stale pin survives on disk. Only the distinct-record +\* rule is dropped, so RefreshPersists is the violated invariant. +ValidAliased(inp) == + /\ ((inp.pin = "absent") => (~inp.pinExists)) + /\ inp.switchActive = inp.active + +\* Sabotage: the decision runs outside the provider-profile mutation queue, so a user +\* switch can interleave between the decision's snapshot and the write. +\* RefreshNamesEffectiveActive must fail. +ValidUnqueued(inp) == + /\ ((inp.pin = "absent") => (~inp.pinExists)) + /\ (Refreshes(inp) => inp.distinctRecord) -\* Sabotage: the restore aborts when the refresh write rejects (the un-caught await -\* before the Task constructor). WriteFailureRestores must fail. +\* Sabotage: the restore aborts when the refresh write rejects (Proceed reads the +\* write outcome). WriteFailureRestores must fail. ProceedAbort(dec, inp) == (dec.f = Keep) \/ inp.pinWriteOk -\* Sabotage: the no-write path keeps the previous modeled pin instead of the pin -\* the selected input carried in (the pre-round fallback). NoWritePreservesPin must fail. -PersistedPinStale(dec, inp, prev) == - IF dec.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord THEN dec.f ELSE prev +\* Sabotage: a full-copy write persists the caller's history-copy pin even when no +\* write landed, so a stale copy overwrites the persisted record's newer pin. +\* NoWritePreservesPin must fail. +PersistedPinFullCopy(dec, inp, prev) == + IF dec.f # Keep /\ inp.pinWriteOk THEN dec.f ELSE inp.pin ==== From 9059bf9d45a9c86ac862b7600d391a20f4b1c5d1 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 12:31:24 +0100 Subject: [PATCH 10/12] test(restored-task): spy the sticky-profile restore at the queued activation seam The review round serialized the restore decision, its activation and the settings capture into one provider-profile mutation queue slot. Re-entering the public activateProviderProfile from inside that slot would enqueue behind itself and deadlock, so the restore path activates through activateProviderProfileUnlocked. The two sticky-profile restore tests still spied the public wrapper, saw zero calls, and let the real unlocked activation run unmocked. Point their spies at the unlocked seam (same profile, same options, plus the queue's AbortSignal) and record both seams in the mode-vs-task ordering test. No production behaviour change. --- .../ClineProvider.sticky-profile.spec.ts | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 60b5cde8fd7..6aa965b8216 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -583,9 +583,17 @@ describe("ClineProvider - Sticky Provider Profile", () => { apiConfigName: "saved-profile", // Saved provider profile } - // Mock activateProviderProfile to track calls + // The restore decision runs serialized inside the provider-profile mutation + // queue, so activation goes through activateProviderProfileUnlocked: routing + // it through the public activateProviderProfile would enqueue behind itself + // and deadlock the queue (see restore-provider-profile.ts). const activateProviderProfileSpy = vi - .spyOn(provider, "activateProviderProfile") + .spyOn( + provider as unknown as { + activateProviderProfileUnlocked: ClineProvider["activateProviderProfile"] + }, + "activateProviderProfileUnlocked", + ) .mockResolvedValue(undefined) // Mock providerSettingsManager.listConfig @@ -596,10 +604,12 @@ describe("ClineProvider - Sticky Provider Profile", () => { // Initialize task with history item await provider.createTaskWithHistoryItem(historyItem) - // Verify provider profile was restored via activateProviderProfile (restore-only: don't persist mode config) + // Verify provider profile was restored via activateProviderProfileUnlocked + // (restore-only: don't persist mode config; the queue passes its AbortSignal) expect(activateProviderProfileSpy).toHaveBeenCalledWith( { name: "saved-profile" }, { persistModeConfig: false, persistTaskHistory: false, expectedCurrentTaskId: historyItem.id }, + expect.any(AbortSignal), ) }) @@ -783,13 +793,26 @@ describe("ClineProvider - Sticky Provider Profile", () => { apiConfigName: "task-specific-profile", // Task's actual profile } - // Track all activateProviderProfile calls + // Track all profile activations. The mode-based path activates through the + // public activateProviderProfile, while the task's apiConfigName restore + // activates through activateProviderProfileUnlocked inside the provider-profile + // mutation queue, so both seams must be recorded in call order. const activateCalls: string[] = [] vi.spyOn(provider, "activateProviderProfile").mockImplementation(async (args) => { if ("name" in args) { activateCalls.push(args.name) } }) + vi.spyOn( + provider as unknown as { + activateProviderProfileUnlocked: ClineProvider["activateProviderProfile"] + }, + "activateProviderProfileUnlocked", + ).mockImplementation(async (args) => { + if ("name" in args) { + activateCalls.push(args.name) + } + }) // Mock providerSettingsManager methods vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-config-id") From dcc742a3e2264343aed96b7ae3ecc311c7f8e1c4 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 12:52:13 +0100 Subject: [PATCH 11/12] ci: re-run after a base-side timing flake on windows platform-unit-test (windows-latest) failed once in core/task/__tests__/empty-response-history.spec.ts (issue 2691, added by merged PR #2701) inside a vi.waitFor cancellation race; this branch touches neither that spec nor Task.ts, ubuntu passed the same merge commit, and the same test passed on windows for all recently merged PR heads. Re-running the job via the API needs actions:write on upstream, so this empty commit re-triggers the matrix. From 414e8fc983a692c87414a6c3ae60bbb3a0c25d42 Mon Sep 17 00:00:00 2001 From: Phil Date: Tue, 1 Dec 2026 13:10:46 +0100 Subject: [PATCH 12/12] test(sticky-profile): spy the queued activation by bracket assignment Access the private activateProviderProfileUnlocked with bracket notation and a typed vi.fn, as the typed-test rules in AGENTS.md ask, instead of a double cast. --- .../ClineProvider.sticky-profile.spec.ts | 25 +++++++------------ 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 6aa965b8216..ee99c027e73 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -588,13 +588,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { // it through the public activateProviderProfile would enqueue behind itself // and deadlock the queue (see restore-provider-profile.ts). const activateProviderProfileSpy = vi - .spyOn( - provider as unknown as { - activateProviderProfileUnlocked: ClineProvider["activateProviderProfile"] - }, - "activateProviderProfileUnlocked", - ) + .fn() .mockResolvedValue(undefined) + provider["activateProviderProfileUnlocked"] = activateProviderProfileSpy // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ @@ -803,16 +799,13 @@ describe("ClineProvider - Sticky Provider Profile", () => { activateCalls.push(args.name) } }) - vi.spyOn( - provider as unknown as { - activateProviderProfileUnlocked: ClineProvider["activateProviderProfile"] - }, - "activateProviderProfileUnlocked", - ).mockImplementation(async (args) => { - if ("name" in args) { - activateCalls.push(args.name) - } - }) + provider["activateProviderProfileUnlocked"] = vi + .fn() + .mockImplementation(async (args) => { + if ("name" in args) { + activateCalls.push(args.name) + } + }) // Mock providerSettingsManager methods vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-config-id")