diff --git a/docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg b/docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg new file mode 100644 index 0000000000..011da41a68 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg @@ -0,0 +1,7 @@ +\* A sweep without the backup write clears the only copy of the blob. +\* expect-fail:ClearRequiresBackup +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + BackupEnabled <- NoBackupEnabled +INVARIANTS TypeOK ClearRequiresBackup diff --git a/docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg b/docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg new file mode 100644 index 0000000000..d0ec6a7691 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg @@ -0,0 +1,8 @@ +\* The clear has no compare-before-clear guard: an entry a downgrade +\* appended while the sweep awaited is deleted unverified. +\* expect-fail:AppendedEntryNeverLost +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CompareGuardEnabled <- NoCompareGuardEnabled +INVARIANTS TypeOK AppendedEntryNeverLost diff --git a/docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg b/docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg new file mode 100644 index 0000000000..17a9931afa --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg @@ -0,0 +1,7 @@ +\* The pre-fix behavior: no sweep runs, so the verified blob stays forever. +\* expect-fail:SweptWhenVerifiable +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SweepEnabled <- NoSweepEnabled +INVARIANTS TypeOK SweptWhenVerifiable diff --git a/docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg b/docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg new file mode 100644 index 0000000000..fc2289ab42 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg @@ -0,0 +1,7 @@ +\* A sweep without the store-verification guard deletes unverified history. +\* expect-fail:ClearRequiresVerification +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + VerifyEnabled <- NoVerifyEnabled +INVARIANTS TypeOK ClearRequiresVerification diff --git a/docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg b/docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg new file mode 100644 index 0000000000..9c739dd09f --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg @@ -0,0 +1,8 @@ +\* A peer sweep overwrites the shared backup with only what it saw, so +\* an entry only an earlier sweep backed up is lost. +\* expect-fail:ClearRequiresBackup +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PeerMergeEnabled <- PeerOverwriteEnabled +INVARIANTS TypeOK ClearRequiresBackup diff --git a/docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg b/docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg new file mode 100644 index 0000000000..0b04a350f7 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg @@ -0,0 +1,7 @@ +\* A stale in-memory array written back after a peer clear fills the blob. +\* expect-fail:PeerClearedStaysCleared +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ResurrectEnabled <- StaleResurrectEnabled +INVARIANTS TypeOK PeerClearedStaysCleared diff --git a/docs/architecture/tla/TaskHistoryMigration.cfg b/docs/architecture/tla/TaskHistoryMigration.cfg new file mode 100644 index 0000000000..2e915d8965 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK SweptWhenVerifiable ClearRequiresVerification ClearRequiresBackup PeerClearedStaysCleared AppendedEntryNeverLost diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla new file mode 100644 index 0000000000..25c6d5e439 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -0,0 +1,418 @@ +---- MODULE TaskHistoryMigration ---- +(***************************************************************************) +(* Source: ClineProvider.initializeTaskHistoryStore reads the legacy *) +(* globalState "taskHistory" array and sets the *) +(* taskHistoryMigratedToFiles marker after TaskHistoryStore migration. *) +(* Sink: globalState.update("taskHistory", undefined) after a verified *) +(* migration, and the uninitialized getTaskHistoryItem fallback read. *) +(* *) +(* Failure: the legacy taskHistory blob survives a startup that completed *) +(* a verified migration, so it weighs globalState down forever. *) +(* Invariant: SweptWhenVerifiable. *) +(* *) +(* Other failures this spec guards: *) +(* - A sweep clears the blob while a blob entry whose task directory *) +(* exists is not held by the file store. Unverified history must never *) +(* be deleted. Invariant: ClearRequiresVerification. *) +(* - A sweep clears the blob before a backup holds its full content. *) +(* Invariant: ClearRequiresBackup. *) +(* - A stale in-memory array is written back after a peer window cleared *) +(* the shared blob. Invariant: PeerClearedStaysCleared. *) +(* - An entry that a downgrade appended and whose change notification has *) +(* reached this window's cache during the sweep is deleted. The clear *) +(* must compare the cached blob with the array the sweep read and keep *) +(* the blob when they differ. Invariant: AppendedEntryNeverLost. *) +(* (CR 2873 thread 4814458162, added.) *) +(* *) +(* Model: a startup runs initialize and migration in one action. The *) +(* sweep is a chain of separate actions - SweepRead via A1 and *) +(* RetrySweep, VerifyEntries, BackupWrite, ReadBackCheck, ClearRequest, *) +(* ClearCommit - because the code awaits between them, and the storage *) +(* write of the delete request lands later still. The compare and the *) +(* delete request run in one synchronous sequence, so they are one *) +(* action (ClearRequest). The globalState *) +(* key is modeled as two variables: `shared` is the shared storage all *) +(* windows write, `blob` is this window's cached view that `get` *) +(* returns (VS Code extHostMemento). SyncCache models the change *) +(* notification that copies shared into the cache, with a delay. *) +(* DowngradeAppend writes shared only; until SyncCache runs, the sweep *) +(* cannot see the entry. PeerClear is a peer window's own verified *) +(* sweep: it deletes shared and merges what it saw into the shared *) +(* backup file. BackupWrite runs read-merge-write as one atomic step *) +(* (safeWriteJson merge callback under the advisory lock), so a peer *) +(* sweep cannot erase entries an earlier backup holds. BackupWrite and *) +(* ReadBackCheck also explore an io-failure outcome that keeps the blob. *) +(* ClearCommit also explores a rejected clear write: shared keeps the *) +(* blob, clearFailed marks the retained verified state, and a later *) +(* startup re-sweeps it (RetrySweep re-runs the whole chain). *) +(* *) +(* Residual race (documented, not fixable at this API level): an entry *) +(* that reaches shared storage while the delete request is in flight - *) +(* between ClearRequest and ClearCommit - is removed without a backup, *) +(* whether it arrived before the compare (hidden by the stale cache) or *) +(* in the request window. VS Code Memento has no compare-and-delete *) +(* primitive (extHostMemento.ts: update schedules an unconditional write), *) +(* so the guard can only cover entries whose notification reached the cache *) +(* before the compare. The window is the smallest the API allows, and a *) +(* later startup's fresh cache re-reads shared and sweeps anything that *) +(* arrived later. *) +(* *) +(* Constants: SweepEnabled, VerifyEnabled, BackupEnabled, *) +(* CompareGuardEnabled and PeerMergeEnabled guard the fix. *) +(* ResurrectEnabled enables a stale write-back for the sabotage check. *) +(* MaxStartups bounds the retries. readHappened marks that a sweep read *) +(* ran, so the beyond-snapshot escape of SweptWhenVerifiable cannot hide *) +(* the pre-fix behavior. *) +(* *) +(* Replay: ClineProvider.taskHistory.spec.ts sweeps the blob after a *) +(* verified migration and keeps it on an unverified entry, on a backup *) +(* failure, when the cached blob changed during the sweep, and after a *) +(* peer clear. The uninitialized fallback reads the sweep backup and *) +(* retries a transient read error. The sweep tests fail on the pre-fix *) +(* code. legacyTaskHistoryBlob.spec.ts is the property test of the pure *) +(* sweep decision and the backup merge. *) +(* *) +(* Result: fixed holds. NoSweep, the pre-fix behavior, fails *) +(* SweptWhenVerifiable. NoVerify fails ClearRequiresVerification. *) +(* NoBackup fails ClearRequiresBackup. StaleResurrect fails *) +(* PeerClearedStaysCleared. NoCompareGuard fails AppendedEntryNeverLost. *) +(* PeerOverwrite fails ClearRequiresBackup. Each variant run violates its *) +(* named invariant only. State counts are in the PR evidence. *) +(* Cost: about 2 minutes for all seven configs on 4 cores. *) +(* Review ratchet (CR 2873 round 2): 1 covered, 3 added, 2 gap. *) +(* Added: 4814652338 (DowngradeAppend at MaxStartups), 4814651913 (cached *) +(* view vs shared storage with delayed notification), 4814653507 (backup *) +(* read-merge-write under the advisory lock, modeled atomic). Covered: *) +(* 4814651541 (test-side *) +(* precision fixes; the behavior they pin is already modeled by the *) +(* ReadBackCheck failure outcome and the BackupWrite ordering). Gap: *) +(* the documented residual race above (no CAS primitive on Memento), *) +(* 4814458155 (test-suite setup, no modeled behavior), 4814458167 *) +(* (fallback read retry is a read-resilience path outside the sweep *) +(* machine; a regression test pins it). *) +(* Review ratchet (CR 2873 round 3): 1 covered, 1 added, 1 gap. Added: *) +(* 4814856207 + 4814856220 (the scheduled storage write is its own *) +(* ClearCommit step, with the request-window append). Covered: 4814856631 *) +(* two-sweep interleaving (BackupWrite's atomic locked merge already *) +(* covers it; a regression test lands in the same commit). Gap: *) +(* 4814856631 non-array backup content (the model's backup is a set of *) +(* ids; the content-type check lives in the code plus a regression test). *) +(* Review ratchet (CR 2873 round 4): 2 covered, 2 added, 2 gap. Added: *) +(* 4814737817 (ClearCommit failure branch + the clearFailed escape in *) +(* SweptWhenVerifiable; the escape reads a variable set only by that *) +(* branch, so it cannot hold vacuously), 4814936082 (lateArrivals and *) +(* clearFailed join vars, so [][Next]_vars constrains every declared *) +(* variable during stuttering) and 4815042563 (RetrySweep blocked while *) +(* sweepPhase = "requested"; the code awaits the delete, so a startup *) +(* cannot overlap a pending clear write). Covered: 4814737827 (the backup *) +(* read-merge-write already runs inside safeWriteJson's advisory lock via *) +(* the merge callback - commit 57fd66ebd closed it before this round; the *) +(* model has described BackupWrite as one atomic locked step since round *) +(* 2), 4814936085 (test-side: the doubles must use the real writer via *) +(* vi.importActual; the pinned behavior is already modeled by the *) +(* BackupWrite and ReadBackCheck failure outcomes). Gap: 4814737822 (the *) +(* id-less multiplicity of the backup array sits below the set-of-ids *) +(* abstraction; mergeLegacyBackup now matches identical id-less records *) +(* one-for-one and regression tests pin the repeated merge), 4815042571 *) +(* (the fallback lookup cache is a read path outside the sweep machine; *) +(* getLegacyBackupItem now re-reads after a cached miss, regression test *) +(* pins it). *) +(* Review ratchet (CR 2873 round 5): 1 covered, 1 added, 4 gap. Added: *) +(* 4816587007 (the input domain admits marker = TRUE at startup: Init *) +(* draws the marker and A1 skips the migration update, so the model also *) +(* checks the keep-when-unverified order on already-migrated inputs). *) +(* Covered: 4816471340 (Windows drive-anchor normalization of the test *) +(* fixture root; the model has no path strings, and the harness fix landed *) +(* in commit 73475ef88 with the platform jobs green). Gap: 4816587009 *) +(* (the custom storage root is a setting read outside the sweep machine; *) +(* the backup root is resolved per access and a regression test pins the *) +(* runtime change), 4816587011 (interrupted-replacement recovery is the *) +(* writer's domain; getLegacyBackupItem reads through *) +(* readFileWithMissingRetry and a recovery-file regression test pins it), *) +(* 4816587015 (mode/profile persistence writes a full-item snapshot *) +(* outside the sweep machine; the store-held path updates the field under *) +(* the store lock and regression tests pin the preserved cost), 4816587019 *) +(* (the fallback authority recheck is a read-ordering rule outside the *) +(* sweep machine; a regression test pins it). *) +(***************************************************************************) +EXTENDS Integers + +MaxStartups == 2 +SweepEnabled == TRUE +VerifyEnabled == TRUE +BackupEnabled == TRUE +CompareGuardEnabled == TRUE +PeerMergeEnabled == TRUE +ResurrectEnabled == FALSE + +Ids == {"t1", "t2"} + +VARIABLES shared, blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts, sweepPhase, readSnapshot, clearedSet, appendedAfterRead, backupOk, compareOk, readHappened, lateArrivals, clearFailed +vars == <> + +Held(ids, storeSet) == (ids \cap dirs) \subseteq storeSet + +Init == + /\ shared \in SUBSET Ids + /\ blob = shared + /\ store \in SUBSET Ids + /\ dirs \in SUBSET Ids + /\ backup = {} + /\ marker \in BOOLEAN + /\ initialized = FALSE + /\ cleared = FALSE + /\ verifiedAtClear = FALSE + /\ peerCleared = FALSE + /\ attempts = 0 + /\ sweepPhase = "none" + /\ readSnapshot = {} + /\ clearedSet = {} + /\ appendedAfterRead = {} + /\ backupOk = TRUE + /\ compareOk = TRUE + /\ readHappened = FALSE + /\ lateArrivals = {} + /\ clearFailed = FALSE + +(* First startup: initialize the store, migrate entries whose task + directories exist, set the marker, then open the sweep with a read + of the cached blob. A provider can also start with the marker + already set; migration is skipped and the store stays empty, so the + sweep keeps the unverified blob (CR 2873 thread 4816587007). *) +A1 == + /\ attempts < MaxStartups + /\ ~initialized + /\ attempts' = attempts + 1 + /\ marker' = TRUE + /\ initialized' = TRUE + /\ store' = (IF marker THEN store ELSE store \cup (blob \cap dirs)) + /\ (IF SweepEnabled /\ blob # {} + THEN /\ sweepPhase' = "read" + /\ readSnapshot' = blob + /\ readHappened' = TRUE + ELSE /\ sweepPhase' = "none" + /\ readSnapshot' = readSnapshot + /\ readHappened' = readHappened) + /\ UNCHANGED <> + +(* A startup whose migration fails. The marker stays unset, the blob + stays, and the next startup retries. *) +A1MigrationFails == + /\ attempts < MaxStartups + /\ ~initialized + /\ attempts' = attempts + 1 + /\ UNCHANGED <> + +(* A later startup with the marker already set. Migration is skipped and + the sweep opens with a fresh read of the cached blob, so entries an + earlier sweep kept become visible to verification. A fresh cache in a + new window sees shared as it is. A startup cannot run while a clear + write is pending: the code awaits the delete inside the startup flow, + so RetrySweep is blocked while sweepPhase = "requested" and the + pending request cannot be dropped by an interleaved retry (CR 2873 + thread 4815042563). *) +RetrySweep == + /\ attempts < MaxStartups + /\ initialized + /\ marker + /\ sweepPhase # "requested" + /\ attempts' = attempts + 1 + /\ store' = store + /\ blob' = shared + /\ (IF SweepEnabled /\ blob' # {} + THEN /\ sweepPhase' = "read" + /\ readSnapshot' = blob' + /\ appendedAfterRead' = {} + /\ clearedSet' = {} + /\ readHappened' = TRUE + ELSE /\ sweepPhase' = "none" + /\ readSnapshot' = readSnapshot + /\ appendedAfterRead' = appendedAfterRead + /\ clearedSet' = clearedSet + /\ readHappened' = readHappened) + /\ UNCHANGED <> + +(* The change notification catches this window's cache up with the + shared storage. It can run at any time, with any delay. An entry + that becomes visible while the sweep is still before its compare is + one the guard protects; after the delete request it is part of the + documented residual race, so it is not flagged. *) +SyncCache == + /\ blob # shared + /\ blob' = shared + /\ appendedAfterRead' = (IF sweepPhase # "none" /\ sweepPhase # "requested" THEN appendedAfterRead \cup (shared \ blob) ELSE appendedAfterRead) + /\ UNCHANGED <> + +(* Sweep step 2: verify every read entry against the file store. An + unconfirmed entry stops the sweep and keeps the blob. *) +VerifyEntries == + /\ sweepPhase = "read" + /\ sweepPhase' = (IF ~VerifyEnabled \/ Held(readSnapshot, store) THEN "verified" ELSE "none") + /\ UNCHANGED <> + +(* Sweep step 3: write the backup. The read-merge-write runs as one + atomic step under the advisory lock (safeWriteJson merge callback), + so a concurrent sweep cannot merge against the same old content. The + write merges the existing backup content, so entries only an earlier + backup holds survive. The write can fail; the blob stays and a later + startup retries. *) +BackupWrite == + /\ sweepPhase = "verified" + /\ \E ok \in BOOLEAN : + (IF ok + THEN /\ backup' = (IF BackupEnabled THEN backup \cup readSnapshot ELSE backup) + /\ sweepPhase' = "backed" + /\ backupOk' = backupOk + ELSE /\ backup' = backup + /\ sweepPhase' = "none" + /\ backupOk' = FALSE) + /\ UNCHANGED <> + +(* Sweep step 4: read the backup back and compare its content. Without + the backup requirement the check passes by design; a failed read or a + content mismatch keeps the blob. *) +ReadBackCheck == + /\ sweepPhase = "backed" + /\ \E ok \in BOOLEAN : + (IF ~BackupEnabled \/ (ok /\ readSnapshot \subseteq backup) + THEN /\ sweepPhase' = "checked" + /\ backupOk' = TRUE + ELSE /\ sweepPhase' = "none" + /\ backupOk' = FALSE) + /\ UNCHANGED <> + +(* Sweep step 5: compare the cached blob and REQUEST the delete. The + code runs both in one synchronous sequence, so no action interleaves + between them; update() also flips this window's cache at once. *) +ClearRequest == + /\ sweepPhase = "checked" + /\ LET ok == (~CompareGuardEnabled \/ blob = readSnapshot) + IN /\ compareOk' = ok + /\ (IF ok + THEN /\ blob' = {} + /\ cleared' = TRUE + /\ clearedSet' = blob + /\ verifiedAtClear' = Held(blob, store) + /\ sweepPhase' = "requested" + ELSE /\ blob' = blob + /\ cleared' = cleared + /\ clearedSet' = clearedSet + /\ verifiedAtClear' = verifiedAtClear + /\ sweepPhase' = "none") + /\ UNCHANGED <> + +(* Sweep step 6: the scheduled write reaches shared storage. VS Code + schedules the storage write, so a downgrade append can land in + shared between the request and this step; such an entry is removed + without a backup. That is the documented residual race: an append + that only ever lives in shared between the request and the commit is + invisible to this window's cache, so no compare can protect it and + Memento offers no compare-and-delete primitive. The next startup's + fresh cache re-reads shared and sweeps anything that arrives later + (a cleared entry re-appended by the downgrade is backed up again by + the merge). *) +ClearCommit == + /\ sweepPhase = "requested" + /\ \E ok \in BOOLEAN : + (IF ok + THEN /\ shared' = {} + /\ clearFailed' = clearFailed + ELSE /\ shared' = shared + /\ clearFailed' = TRUE) + /\ sweepPhase' = "none" + /\ UNCHANGED <> + +(* A peer window completed its own verified sweep between our actions. + It deletes the shared blob and merges what it saw into the shared + backup file. This window's cache stays stale until SyncCache. *) +PeerClear == + /\ marker + /\ shared # {} + /\ shared' = {} + /\ backup' = (IF PeerMergeEnabled THEN backup \cup shared ELSE shared) + /\ peerCleared' = TRUE + /\ UNCHANGED <> + +(* An old build re-writes the legacy list in shared storage while the + marker is set. Its entries were never migrated, so they are not held + by the store. This window's cache learns of it only via SyncCache; an + entry that arrives during a sweep window is tracked in + appendedAfterRead. *) +DowngradeAppend == + /\ marker + /\ ~peerCleared + /\ \E id \in Ids \ shared : + /\ shared' = shared \cup {id} + /\ lateArrivals' = lateArrivals \cup {id} + /\ UNCHANGED <> + +(* Sabotage only: a buggy variant writes a stale in-memory array back + after a peer cleared the shared blob. *) +Resurrect == + /\ ResurrectEnabled + /\ peerCleared + /\ shared' = Ids + /\ blob' = Ids + /\ UNCHANGED <> + +Next == + A1 \/ A1MigrationFails \/ RetrySweep \/ SyncCache \/ VerifyEntries \/ BackupWrite + \/ ReadBackCheck \/ ClearRequest \/ ClearCommit \/ PeerClear \/ DowngradeAppend \/ Resurrect + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ shared \subseteq Ids + /\ blob \subseteq Ids + /\ store \subseteq Ids + /\ dirs \subseteq Ids + /\ backup \subseteq Ids + /\ marker \in BOOLEAN + /\ initialized \in BOOLEAN + /\ cleared \in BOOLEAN + /\ verifiedAtClear \in BOOLEAN + /\ peerCleared \in BOOLEAN + /\ attempts \leq MaxStartups + /\ sweepPhase \in {"none", "read", "verified", "backed", "checked", "requested"} + /\ readSnapshot \subseteq Ids + /\ clearedSet \subseteq Ids + /\ appendedAfterRead \subseteq Ids + /\ backupOk \in BOOLEAN + /\ compareOk \in BOOLEAN + /\ readHappened \in BOOLEAN + /\ lateArrivals \subseteq Ids + /\ clearFailed \in BOOLEAN + +(* No startup that finished a verified migration leaves the blob behind + without a reason, judged on the shared storage. A blob that survives + is unverified, or the sweep kept it because the cached blob changed + after the read, or the last backup cycle failed. *) +SweptWhenVerifiable == + (initialized /\ attempts >= MaxStartups /\ backupOk /\ sweepPhase = "none") => + (\/ shared = {} + \/ ~Held(shared, store) + \/ (shared # readSnapshot /\ readHappened) + \/ shared \subseteq lateArrivals + \/ clearFailed) \* CR 2873 thread 4814737817: the clear write failed; the blob stays for a later startup. + +(* A sweep only clears after every entry with a task directory is held + by the file store. *) +ClearRequiresVerification == cleared => verifiedAtClear + +(* A sweep only clears after the backup holds the full content it + removes from this window's view. *) +ClearRequiresBackup == cleared => clearedSet \subseteq backup + +(* After a peer cleared the shared blob, no stale write-back fills it. *) +PeerClearedStaysCleared == ~( + peerCleared /\ shared # {}) + +(* No entry whose change notification reached this window's cache during + the sweep is ever cleared. The compare guard must run before the + delete. An entry that is still only in shared storage at delete time + is the documented residual race; SyncCache brings it into the cache + of a later startup, which then sweeps it safely. *) +AppendedEntryNeverLost == + appendedAfterRead \cap clearedSet = {} + +==== diff --git a/docs/architecture/tla/TaskHistoryMigrationMC.tla b/docs/architecture/tla/TaskHistoryMigrationMC.tla new file mode 100644 index 0000000000..6c46b658cf --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigrationMC.tla @@ -0,0 +1,10 @@ +---- MODULE TaskHistoryMigrationMC ---- +\* Sabotage operator values for the variant configs. +EXTENDS TaskHistoryMigration +NoSweepEnabled == FALSE +NoVerifyEnabled == FALSE +NoBackupEnabled == FALSE +StaleResurrectEnabled == TRUE +NoCompareGuardEnabled == FALSE +PeerOverwriteEnabled == FALSE +==== diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index e0bb54998c..8e7afcfdb4 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -1311,6 +1311,26 @@ export class TaskHistoryStore { // ────────────────────────────── Private: Path helpers ────────────────────────────── + /** + * Check whether a task directory exists without reading its files. + */ + async hasTaskDir(taskId: string): Promise { + const tasksDir = await this.getTasksDir() + try { + await fs.access(path.join(tasksDir, taskId)) + return true + } catch (error) { + // Absence makes the entry an orphan. Any other failure (e.g. + // EACCES, EIO) must not make the sweep treat an existing + // directory as gone, so the caller keeps the blob instead. + const code = getErrorCode(error) + if (code === "ENOENT" || code === "ENOTDIR") { + return false + } + throw error + } + } + /** * Get the tasks base directory path, resolving custom storage paths. */ diff --git a/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts new file mode 100644 index 0000000000..af46b5a83c --- /dev/null +++ b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from "vitest" +import type { HistoryItem } from "@roo-code/types" +import { mergeLegacyBackup, planLegacyBlobSweep } from "../legacyTaskHistoryBlob" + +// pnpm --filter zoo-code test core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts + +/** + * Deterministic LCG so a failure reproduces with the same scenario set. + */ +function makeRng(seed: number) { + let s = seed >>> 0 + return () => { + s = (s * 1664525 + 1013904223) >>> 0 + return s / 4294967296 + } +} + +const IDS = ["t1", "t2", "t3"] + +const makeEntries = (rng: () => number): HistoryItem[] => + IDS.filter(() => rng() < 0.5).map((id) => ({ number: 1, ts: 1, id, task: id }) as HistoryItem) + +const pickSet = (rng: () => number): Set => new Set(IDS.filter(() => rng() < 0.5)) + +describe("planLegacyBlobSweep", () => { + it("clears only when every non-orphan entry is held and a backup exists", () => { + const rng = makeRng(20261206) + for (let i = 0; i < 500; i++) { + const entries = makeEntries(rng) + const held = pickSet(rng) + const orphans = pickSet(rng) + const backupWritten = rng() < 0.5 + const decision = planLegacyBlobSweep(entries, held, orphans, backupWritten) + const nonOrphans = entries.map((entry) => entry.id!).filter((id) => !orphans.has(id)) + const allHeld = nonOrphans.every((id) => held.has(id)) + const scenario = JSON.stringify({ + entries: entries.map((e) => e.id), + nonOrphans, + held: [...held], + orphans: [...orphans], + backupWritten, + }) + if (decision.action === "clear") { + expect(backupWritten, scenario).toBe(true) + expect(allHeld, scenario).toBe(true) + } else if (!allHeld) { + expect(decision.reason, scenario).toBe("unverified-entries") + expect(decision.unverifiedIds.sort(), scenario).toStrictEqual( + nonOrphans.filter((id) => !held.has(id)).sort(), + ) + } else { + expect(decision.reason, scenario).toBe(backupWritten ? undefined : "backup-unwritten") + } + } + }) + + it("keeps with the unverified ids listed when a directory-backed entry is missing", () => { + const entries = [{ id: "t1" }, { id: "t2" }] as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(), true) + expect(decision).toStrictEqual({ action: "keep", reason: "unverified-entries", unverifiedIds: ["t2"] }) + }) + + it("keeps with backup-unwritten before the backup write even when everything is held", () => { + const entries = [{ id: "t1" }] as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(), false) + expect(decision).toStrictEqual({ action: "keep", reason: "backup-unwritten", unverifiedIds: [] }) + }) + + it("clears orphans too once they are backed up", () => { + const entries = [{ id: "t1" }, { id: "t2" }] as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(["t2"]), true) + expect(decision).toStrictEqual({ action: "clear" }) + }) + + it("ignores id-less entries like orphans", () => { + const entries = [{ id: "t1" }, { task: "no-id" }] as unknown as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(), true) + expect(decision).toStrictEqual({ action: "clear" }) + }) +}) + +describe("mergeLegacyBackup", () => { + it("keeps prior-only entries behind the current array", () => { + const current = [{ id: "t1" }, { id: "t2" }] as HistoryItem[] + const prior = [{ id: "t1" }, { id: "t9" }] as HistoryItem[] + expect(mergeLegacyBackup(current, prior)).toStrictEqual([{ id: "t1" }, { id: "t2" }, { id: "t9" }]) + }) + + it("lets the current array win on an id clash", () => { + const current = [{ id: "t1", task: "fresh" }] as HistoryItem[] + const prior = [{ id: "t1", task: "stale" }, { id: "t8" }] as HistoryItem[] + expect(mergeLegacyBackup(current, prior)).toStrictEqual([{ id: "t1", task: "fresh" }, { id: "t8" }]) + }) + + it("keeps id-less prior entries like any other backup content", () => { + const current = [{ id: "t1" }] as HistoryItem[] + const prior = [{ task: "no-id" }] as HistoryItem[] + expect(mergeLegacyBackup(current, prior)).toStrictEqual([{ id: "t1" }, { task: "no-id" }]) + }) + + it("returns the current array unchanged when the prior backup is empty", () => { + const current = [{ id: "t1" }] as HistoryItem[] + expect(mergeLegacyBackup(current, [])).toStrictEqual([{ id: "t1" }]) + }) + + it("keeps the backup stable across repeated deferred sweeps with ID-less entries", () => { + const orphan = { task: "no-id" } as unknown as HistoryItem + const itemA = { id: "t1" } as HistoryItem + // Sweep 1 retains the blob, so sweep 2 reads the same current + // array and merges against the backup written before. + const first = mergeLegacyBackup([orphan, itemA], [orphan]) + expect(first).toStrictEqual([orphan, itemA]) + const second = mergeLegacyBackup([orphan, itemA], first) + expect(second).toStrictEqual([orphan, itemA]) + }) + + it("preserves the prior-only multiplicity of identical ID-less records", () => { + const orphan = { task: "no-id" } as unknown as HistoryItem + // The current array holds one copy; a second prior copy survives. + expect(mergeLegacyBackup([orphan] as HistoryItem[], [orphan, orphan])).toStrictEqual([orphan, orphan]) + // A distinct ID-less record never collapses into a matching one. + const distinct = { task: "other" } as unknown as HistoryItem + expect(mergeLegacyBackup([{ id: "t1" } as HistoryItem, orphan], [orphan, distinct])).toStrictEqual([ + { id: "t1" } as HistoryItem, + orphan, + distinct, + ]) + }) +}) diff --git a/src/core/task-persistence/legacyTaskHistoryBlob.ts b/src/core/task-persistence/legacyTaskHistoryBlob.ts new file mode 100644 index 0000000000..ec761ba810 --- /dev/null +++ b/src/core/task-persistence/legacyTaskHistoryBlob.ts @@ -0,0 +1,74 @@ +import type { HistoryItem } from "@roo-code/types" + +export const LEGACY_TASK_HISTORY_BACKUP_FILE = "legacy-task-history.backup.json" + +export type LegacyBlobSweepDecision = + { action: "keep"; reason: "unverified-entries" | "backup-unwritten"; unverifiedIds: string[] } | { action: "clear" } + +/** + * Decide whether the legacy globalState taskHistory blob can be removed. + * + * The file-backed store must hold every entry whose task directory still + * exists, and a backup must hold the full array before the delete. Entries + * without an id were never migrated, so they count like orphans here. + */ +export function planLegacyBlobSweep( + entries: HistoryItem[], + storeHeldIds: ReadonlySet, + orphanIds: ReadonlySet, + backupWritten: boolean, +): LegacyBlobSweepDecision { + const unverifiedIds = entries + .map((item) => item?.id) + .filter((id): id is string => Boolean(id)) + .filter((id) => !orphanIds.has(id) && !storeHeldIds.has(id)) + + if (unverifiedIds.length > 0) { + return { action: "keep", reason: "unverified-entries", unverifiedIds } + } + + if (!backupWritten) { + return { action: "keep", reason: "backup-unwritten", unverifiedIds: [] } + } + + return { action: "clear" } +} + +/** + * Merge the current legacy array with an earlier sweep's backup. + * + * Entries only the earlier backup holds (e.g. orphans with no task + * directory) must survive the write; current entries win on an id clash. + * Identical ID-less records match one-for-one, so a repeated deferred + * sweep does not duplicate them; unmatched prior-only records keep their + * existing multiplicity. + */ +export function mergeLegacyBackup(current: HistoryItem[], prior: HistoryItem[]): HistoryItem[] { + const currentIds = new Set(current.map((item) => item?.id).filter((id): id is string => Boolean(id))) + // An ID-less entry has no merge key, so the id filter below would + // append the prior copy again on every deferred sweep and grow the + // backup. Match identical ID-less records one-for-one and keep only + // the prior excess (CR 2873 thread 4814737822). + const currentIdless = new Map() + for (const item of current) { + if (!item?.id) { + const key = JSON.stringify(item) + currentIdless.set(key, (currentIdless.get(key) ?? 0) + 1) + } + } + const keptPrior: HistoryItem[] = [] + for (const item of prior) { + if (!item?.id) { + const key = JSON.stringify(item) + const matched = currentIdless.get(key) ?? 0 + if (matched > 0) { + currentIdless.set(key, matched - 1) + continue + } + } else if (currentIds.has(item.id)) { + continue + } + keptPrior.push(item) + } + return [...current, ...keptPrior] +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 78ad36cd97..fff0594c88 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -153,8 +153,16 @@ import { interruptDelegatedChild, LifecycleTransitionError, } from "../task-persistence" +import { + LEGACY_TASK_HISTORY_BACKUP_FILE, + mergeLegacyBackup, + planLegacyBlobSweep, +} from "../task-persistence/legacyTaskHistoryBlob" +import { getErrorCode } from "../../utils/errorCode" import { readTaskMessages } from "../task-persistence/taskMessages" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" +import deepEqual from "fast-deep-equal" +import { safeWriteJson } from "../../utils/safeWriteJson" import { TaskTitleService } from "../task-title/TaskTitleService" import { getNonce } from "./getNonce" import { getUri } from "./getUri" @@ -330,8 +338,11 @@ export class ClineProvider private recentTasksCache?: string[] public readonly taskHistoryStore: TaskHistoryStore + private readonly taskTitleService: TaskTitleService private taskHistoryStoreInitialized = false + /** Parsed legacy blob backup; undefined = not read yet, null = absent or unparsable. */ + private legacyBackupItems: HistoryItem[] | null | undefined public static readonly PENDING_OPERATION_TIMEOUT_MS = 30000 // 30 seconds private providerProfileMutationQueue = Promise.resolve() private historyTaskCreationQueue = Promise.resolve() @@ -648,6 +659,14 @@ export class ClineProvider type: "initialize", elapsedMs: Date.now() - startedAt, }) + try { + await this.sweepLegacyTaskHistoryBlob() + } catch (error) { + // Keep the legacy blob; the next startup retries the sweep. + this.log( + `[initializeTaskHistoryStore] Legacy blob sweep deferred: ${error instanceof Error ? error.message : String(error)}`, + ) + } } catch (error) { this.diagnosticsRecorder.record({ boundary: "task-history", @@ -659,6 +678,165 @@ export class ClineProvider } } + /** + * Remove the legacy globalState taskHistory blob after a verified migration. + * + * The delete runs only when the file-backed store holds every entry whose + * task directory exists and a backup file holds the full array. Orphan + * entries have no task directory; the backup preserves them. Any failure + * keeps the blob, and the next startup retries. A second window that + * already cleared the blob makes this a no-op. + */ + private async sweepLegacyTaskHistoryBlob(): Promise { + const legacyHistory = this.context.globalState.get("taskHistory") ?? [] + if (legacyHistory.length === 0) { + return + } + + const storeHeldIds = new Set() + const orphanIds = new Set() + for (const item of legacyHistory) { + if (!item?.id) { + // Migration skipped entries without an id; the backup preserves them. + continue + } + if (!(await this.taskHistoryStore.hasTaskDir(item.id))) { + orphanIds.add(item.id) + continue + } + if (this.taskHistoryStore.get(item.id)) { + storeHeldIds.add(item.id) + } + } + + const preflight = planLegacyBlobSweep(legacyHistory, storeHeldIds, orphanIds, false) + if (preflight.action === "keep" && preflight.reason === "unverified-entries") { + this.log( + `[initializeTaskHistoryStore] Keeping legacy taskHistory blob (unverified-entries: ${preflight.unverifiedIds.join(", ")})`, + ) + return + } + + const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) + + // A corrupt backup may still hold recoverable raw text, and a + // transient read error must not risk losing it; the sweep defers + // instead of writing over it. The lock-protected merge inside + // safeWriteJson re-reads the file under the advisory lock, so a + // concurrent sweep cannot merge against the same old content. + try { + const parsed: unknown = JSON.parse(await fs.readFile(backupPath, "utf8")) + if (!Array.isArray(parsed)) { + // Valid JSON that is not an array is malformed backup + // content; the merge would treat it as empty and overwrite + // possibly recoverable entries. Defer instead. + this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: backup file is malformed") + return + } + } catch (error) { + if (getErrorCode(error) !== "ENOENT" && getErrorCode(error) !== "ENOTDIR") { + throw error + } + } + + let toPersist: HistoryItem[] = legacyHistory + await safeWriteJson(backupPath, legacyHistory, { + merge: (existing, incoming) => { + toPersist = mergeLegacyBackup( + incoming as HistoryItem[], + Array.isArray(existing) ? (existing as HistoryItem[]) : [], + ) + return toPersist + }, + }) + + let backup: HistoryItem[] | null = null + try { + const raw = await fs.readFile(backupPath, "utf8") + const parsed: unknown = JSON.parse(raw) + backup = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null + } catch { + backup = null + } + if (!backup || !deepEqual(backup, toPersist)) { + this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: backup read-back did not match") + return + } + + const decision = planLegacyBlobSweep(legacyHistory, storeHeldIds, orphanIds, true) + if (decision.action !== "clear") { + this.log(`[initializeTaskHistoryStore] Keeping legacy taskHistory blob (${decision.reason})`) + return + } + + // A downgrade can append entries while the awaits above run; the + // backup does not hold them, so the sweep keeps the blob for the + // next startup when the blob changed after the read. + const current = this.context.globalState.get("taskHistory") ?? [] + if (!deepEqual(current, legacyHistory)) { + this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: it changed during the sweep") + return + } + + // VS Code defines update(key, undefined) as removal; the delete is + // idempotent across windows that run the same verified sweep. + await this.context.globalState.update("taskHistory", undefined) + this.log( + `[initializeTaskHistoryStore] Removed the legacy taskHistory blob; ${toPersist.length} entries are backed up in ${LEGACY_TASK_HISTORY_BACKUP_FILE}`, + ) + } + + /** + * Storage root for the legacy blob backup, resolved per access. + * + * getStorageBasePath re-reads the custom storage setting on every + * call, so a runtime root change is picked up instead of pinning the + * first resolution (CR 2873 thread 4816587009). + */ + private async getLegacyBackupBasePath(): Promise { + const { getStorageBasePath } = await import("../../utils/storage") + return getStorageBasePath(this.contextProxy.globalStorageUri.fsPath) + } + + /** + * Read an item from the legacy blob sweep backup, parsed once. + * + * A cached hit stays cached; a cached miss re-reads the file once, + * because a peer window can extend the shared backup after this + * window cached its snapshot. + */ + private async getLegacyBackupItem(id: string): Promise { + if (this.legacyBackupItems !== undefined) { + const hit = this.legacyBackupItems?.find((item) => item?.id === id) + if (hit !== undefined) { + return hit + } + // A cached miss can be stale: a peer window merges new entries + // into the shared backup and clears the blob after this window + // cached its snapshot. Read the backup again before confirming + // absence (CR 2873 thread 4815042571). + } + try { + const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) + // A replacement interrupted between its two renames keeps the + // committed content in a recovery file; this read retries the + // transient absence and restores it under the writer's lock + // (CR 2873 thread 4816587011). + const raw = await readFileWithMissingRetry(backupPath) + const parsed: unknown = JSON.parse(raw) + this.legacyBackupItems = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null + } catch (error) { + // A missing backup file is confirmed absence. Any other + // failure (e.g. EACCES, EIO) must stay retryable, so keep + // the unread state and let the next lookup read again. + const code = getErrorCode(error) + if (code === "ENOENT" || code === "ENOTDIR") { + this.legacyBackupItems = null + } + } + return this.legacyBackupItems?.find((item) => item?.id === id) ?? undefined + } + /** * Override EventEmitter's on method to match TaskProviderLike interface */ @@ -2117,11 +2295,22 @@ export class ClineProvider task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, newMode) try { - // Update the task history with the new mode first. - const taskHistoryItem = this.getTaskHistoryItem(task.taskId) + // Update the task history with the new mode first. A + // store-held item is updated field-only under the store + // lock, so a cost saved between the lookup and this write + // is not reverted by the older snapshot (CR 2873 thread + // 4816587015). + if (this.taskHistoryStore.get(task.taskId)) { + await this.taskHistoryStore.atomicReadAndUpdate(task.taskId, (current) => ({ + ...current, + mode: newMode, + })) + } else { + const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) - if (taskHistoryItem) { - await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) + if (taskHistoryItem) { + await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) + } } // Only update the task's mode after successful persistence. @@ -2500,10 +2689,21 @@ export class ClineProvider // been persisted into taskHistory (it will be captured on the next save). task.setTaskApiConfigName(apiConfigName) - const taskHistoryItem = this.getTaskHistoryItem(task.taskId) + // Store-held items are updated field-only under the store + // lock; a token or cost saved between the lookup and this + // write must not be reverted by the older snapshot (CR 2873 + // thread 4816587015). + if (this.taskHistoryStore.get(task.taskId)) { + await this.taskHistoryStore.atomicReadAndUpdate(task.taskId, (current) => ({ + ...current, + apiConfigName, + })) + } else { + const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) - if (taskHistoryItem) { - await this.updateTaskHistory({ ...taskHistoryItem, apiConfigName }) + if (taskHistoryItem) { + await this.updateTaskHistory({ ...taskHistoryItem, apiConfigName }) + } } } catch (error) { // If persistence fails, log the error but don't fail the profile switch. @@ -2767,7 +2967,7 @@ export class ClineProvider // Task history - private getTaskHistoryItem(id: string): HistoryItem | undefined { + private async getTaskHistoryItem(id: string): Promise { const historyItem = this.taskHistoryStore.get(id) // Once initialization and migration succeed, the file-backed store is authoritative. @@ -2776,7 +2976,21 @@ export class ClineProvider return historyItem } - return (this.getGlobalState("taskHistory") ?? []).find((item) => item.id === id) + const legacyItem = (this.getGlobalState("taskHistory") ?? []).find((item) => item.id === id) + if (legacyItem) { + return legacyItem + } + + // A peer window may have swept the blob while this provider's startup failed; + // the sweep backup keeps the fallback working in that window. + const backupItem = await this.getLegacyBackupItem(id) + // Initialization can complete while the backup read awaits; the + // file store is authoritative once it does (CR 2873 thread + // 4816587019). + if (this.taskHistoryStoreInitialized) { + return this.taskHistoryStore.get(id) + } + return backupItem } async getTaskWithId(id: string): Promise<{ @@ -2786,7 +3000,7 @@ export class ClineProvider uiMessagesFilePath: string apiConversationHistory: Anthropic.MessageParam[] }> { - const historyItem = this.getTaskHistoryItem(id) + const historyItem = await this.getTaskHistoryItem(id) if (!historyItem) { throw new Error("Task not found") @@ -2820,11 +3034,11 @@ export class ClineProvider historyItem: HistoryItem aggregatedCosts: AggregatedCosts }> { - const historyItem = this.getTaskHistoryItem(taskId) + const historyItem = await this.getTaskHistoryItem(taskId) if (!historyItem) throw new Error("Task not found") const aggregatedCosts = await aggregateTaskCostsRecursive(taskId, async (id: string) => { - const item = this.getTaskHistoryItem(id) + const item = await this.getTaskHistoryItem(id) if (!item) throw new Error("Task not found") return item }) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts index f73101d4ee..97edeb740d 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts @@ -360,11 +360,8 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to track calls - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) - + // A store-held item is updated field-only under the store lock + // (CR 2873 thread 4816587015), so assert the persisted outcome. // Add task to provider stack await provider.addClineToStack(mockTask) @@ -375,12 +372,10 @@ describe("ClineProvider - Sticky Mode", () => { expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect") // Verify task history was updated with new mode - expect(updateTaskHistorySpy).toHaveBeenCalledWith( - expect.objectContaining({ - id: taskId, - mode: "architect", - }), - ) + expect(provider.taskHistoryStore.get(taskId)).toMatchObject({ + id: taskId, + mode: "architect", + }) }) it("should update task's taskMode property when switching modes", async () => { @@ -453,24 +448,19 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to track calls - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) - + // A store-held item is updated field-only under the store lock + // (CR 2873 thread 4816587015), so assert the persisted outcome. // Add task to provider stack await provider.addClineToStack(mockTask) // Switch mode await provider.handleModeSwitch("architect") - // Verify updateTaskHistory was called with mode in the history item - expect(updateTaskHistorySpy).toHaveBeenCalledWith( - expect.objectContaining({ - id: taskId, - mode: "architect", - }), - ) + // Verify the store holds the item with the new mode + expect(provider.taskHistoryStore.get(taskId)).toMatchObject({ + id: taskId, + mode: "architect", + }) }) }) @@ -576,12 +566,10 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to capture the updated history item - let updatedHistoryItem: any - vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { - updatedHistoryItem = item - return Promise.resolve([item]) - }) + // The switch updates a store-held item field-only under the + // store lock; capture the updater and apply it to the current + // cached item (CR 2873 thread 4816587015). + const atomicSpy = vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate") // Add task to provider stack await provider.addClineToStack(mockTask) @@ -590,7 +578,9 @@ describe("ClineProvider - Sticky Mode", () => { await provider.handleModeSwitch("debug") // Verify mode was included in the updated history item - expect(updatedHistoryItem).toBeDefined() + expect(atomicSpy).toHaveBeenCalledWith(taskId, expect.any(Function)) + const [, updater] = atomicSpy.mock.calls[atomicSpy.mock.calls.length - 1] + const updatedHistoryItem = updater(provider.taskHistoryStore.get(taskId)!) expect(updatedHistoryItem.mode).toBe("debug") }) }) @@ -636,7 +626,9 @@ describe("ClineProvider - Sticky Mode", () => { } }) - // Mock updateTaskHistory to track mode changes + // Track mode changes on both write paths: store-held items go + // through atomicReadAndUpdate (CR 2873 thread 4816587015), + // fallback-only items through updateTaskHistory. const updateTaskHistoryMock = vi.spyOn(provider, "updateTaskHistory") updateTaskHistoryMock.mockImplementation((item) => { // The handleModeSwitch method updates the task history for the current task @@ -646,6 +638,17 @@ describe("ClineProvider - Sticky Mode", () => { } return Promise.resolve([]) }) + vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate").mockImplementation(async (id, updater) => { + const current = provider.taskHistoryStore.get(id) + if (!current) { + throw new Error(`[TaskHistoryStore] atomicReadAndUpdate: task ${id} not found in cache`) + } + const updated = updater(current) + if (updated.mode !== undefined) { + taskModes[updated.id] = updated.mode + } + return [updated] + }) // Add parent task to stack await provider.addClineToStack(parentTask) @@ -859,11 +862,6 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) - // Clear previous calls to globalState.update vi.mocked(mockContext.globalState.update).mockClear() @@ -883,9 +881,10 @@ describe("ClineProvider - Sticky Mode", () => { // Verify the last mode switch wins expect(lastModeCall).toEqual(["mode", "code"]) - // Verify task history was updated with final mode - const lastCall = updateTaskHistorySpy.mock.calls[updateTaskHistorySpy.mock.calls.length - 1] - expect(lastCall[0]).toMatchObject({ + // Verify task history was updated with the final mode: the + // switches serialize through the store lock, so the last one + // wins (CR 2873 thread 4816587015). + expect(provider.taskHistoryStore.get(mockTask.taskId)).toMatchObject({ id: mockTask.taskId, mode: "code", }) @@ -1073,8 +1072,10 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to throw error - vi.spyOn(provider, "updateTaskHistory").mockRejectedValue(new Error("Update failed")) + // A store-held item persists through atomicReadAndUpdate; its + // failure must propagate the same way (CR 2873 thread + // 4816587015). + vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate").mockRejectedValue(new Error("Update failed")) // Mock console.error const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 9b5996a6ea..7b8ffd436a 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -391,10 +391,8 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) - // Mock updateTaskHistory to track calls - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) + // A store-held item is updated field-only under the store + // lock (CR 2873 thread 4816587015), so assert the outcome. // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ @@ -412,12 +410,10 @@ describe("ClineProvider - Sticky Provider Profile", () => { await provider.activateProviderProfile({ name: "new-profile" }) // Verify task history was updated with new provider profile - expect(updateTaskHistorySpy).toHaveBeenCalledWith( - expect.objectContaining({ - id: mockTask.taskId, - apiConfigName: "new-profile", - }), - ) + expect(provider.taskHistoryStore.get(mockTask.taskId)).toMatchObject({ + id: mockTask.taskId, + apiConfigName: "new-profile", + }) // Verify task's setTaskApiConfigName was called expect(mockTask.setTaskApiConfigName).toHaveBeenCalledWith("new-profile") @@ -447,6 +443,7 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([]) + const atomicSpy = vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate") vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", @@ -459,9 +456,15 @@ describe("ClineProvider - Sticky Provider Profile", () => { expect(currentTask.setTaskApiConfigName).toHaveBeenCalledTimes(applies ? 1 : 0) const stickyWrite = expect.objectContaining({ id: currentTask.taskId, apiConfigName: "new-profile" }) if (applies) { - expect(updateTaskHistorySpy).toHaveBeenCalledWith(stickyWrite) + // Store-held items persist field-only under the store + // lock (CR 2873 thread 4816587015). + expect(atomicSpy).toHaveBeenCalledWith(currentTask.taskId, expect.any(Function)) + const [, updater] = atomicSpy.mock.calls[atomicSpy.mock.calls.length - 1] + expect(updater(provider.taskHistoryStore.get(currentTask.taskId)!)).toMatchObject(stickyWrite) + expect(updateTaskHistorySpy).not.toHaveBeenCalled() } else { expect(updateTaskHistorySpy).not.toHaveBeenCalled() + expect(atomicSpy).not.toHaveBeenCalled() } }, ) @@ -892,12 +895,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) - // Mock updateTaskHistory to capture the updated history item - let updatedHistoryItem: any - vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { - updatedHistoryItem = item - return Promise.resolve([item]) - }) + // The switch updates a store-held item field-only under the + // store lock; capture the updater (CR 2873 thread 4816587015). + const atomicSpy = vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate") // Add task to provider stack await provider.addClineToStack(mockTask as any) @@ -918,7 +918,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { await provider.activateProviderProfile({ name: "new-profile" }) // Verify apiConfigName was included in the updated history item - expect(updatedHistoryItem).toBeDefined() + expect(atomicSpy).toHaveBeenCalledWith(mockTask.taskId, expect.any(Function)) + const [, updater] = atomicSpy.mock.calls[atomicSpy.mock.calls.length - 1] + const updatedHistoryItem = updater(provider.taskHistoryStore.get(mockTask.taskId)!) expect(updatedHistoryItem.apiConfigName).toBe("new-profile") }) }) @@ -980,14 +982,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { await provider.taskHistoryStore.upsert(item as any) } - // Mock updateTaskHistory - vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { - const index = taskHistory.findIndex((h) => h.id === item.id) - if (index >= 0) { - taskHistory[index] = { ...taskHistory[index], ...item } - } - return Promise.resolve(taskHistory) - }) + // The store-held item persists field-only under the store lock + // (CR 2873 thread 4816587015), so the assertions below read the + // authoritative store instead of a write-path double. // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ @@ -1008,10 +1005,10 @@ describe("ClineProvider - Sticky Provider Profile", () => { // Verify task 1's profile was updated expect(task1._taskApiConfigName).toBe("profile-c") - expect(taskHistory[0].apiConfigName).toBe("profile-c") + expect(provider.taskHistoryStore.get("task-1")?.apiConfigName).toBe("profile-c") // Verify task 2's profile remains unchanged - expect(taskHistory[1].apiConfigName).toBe("profile-b") + expect(provider.taskHistoryStore.get("task-2")?.apiConfigName).toBe("profile-b") }) }) @@ -1045,8 +1042,10 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) - // Mock updateTaskHistory to throw error - vi.spyOn(provider, "updateTaskHistory").mockRejectedValue(new Error("Save failed")) + // A store-held item persists through atomicReadAndUpdate; its + // failure must stay swallowed by the profile-switch error + // handling (CR 2873 thread 4816587015). + vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate").mockRejectedValue(new Error("Save failed")) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index e16badb348..ac4f62b7c8 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1,3 +1,4 @@ +import { Writable } from "node:stream" import { WebviewFocusTracker } from "../WebviewFocusTracker" // pnpm --filter roo-cline test core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -20,16 +21,54 @@ vi.mock("p-wait-for", () => ({ default: vi.fn().mockResolvedValue(undefined), })) -vi.mock("fs/promises", () => ({ - mkdir: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(""), - readdir: vi.fn().mockResolvedValue([]), - unlink: vi.fn().mockResolvedValue(undefined), - rmdir: vi.fn().mockResolvedValue(undefined), - access: vi.fn().mockResolvedValue(undefined), - rm: vi.fn().mockResolvedValue(undefined), -})) +vi.mock("fs/promises", () => { + // The same object backs the named exports and `default`, so default + // importers (`import fs from "fs/promises"`) hit the same mocked fns. + const mock = { + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + readdir: vi.fn().mockResolvedValue([]), + stat: vi.fn(), + rename: vi.fn(), + open: vi.fn(), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + access: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), + } + return { ...mock, default: mock } +}) + +// The sweep harness runs the real safeWriteJson against the in-memory +// fs (CR 2873 thread 4814936085). Its temp-file staging writes through +// the sync createWriteStream, so only that one function is mocked here. +vi.mock("fs", async (importOriginal) => { + const actual = await importOriginal() + const createWriteStream = vi.fn() + return { + ...actual, + default: { ...actual, createWriteStream }, + createWriteStream, + } +}) + +// The advisory lock protocol crosses process boundaries with real lock +// directories; the in-memory fs has none. The real safeWriteJson keeps +// its read-merge-write sequence and commits with this no-op lock. +vi.mock("../../../utils/fileLock", async (importOriginal) => { + const actual = await importOriginal() + // withFileLock calls the module-internal acquireFileLock, which the + // export-level mock cannot intercept; mock it directly so recovery + // helpers run without proper-lockfile touching the real filesystem. + return { + ...actual, + acquireFileLock: vi.fn(async () => async () => {}), + withFileLock: vi.fn(async (filePath: string, operation: (absoluteFilePath: string) => Promise) => + operation(filePath), + ), + } +}) vi.mock("axios", () => ({ default: { @@ -1321,3 +1360,915 @@ describe("ClineProvider Task History Synchronization", () => { ) }) }) + +describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { + const STORAGE_ROOT = "/test/storage/path" + const TASKS_DIR = `${STORAGE_ROOT}/tasks` + const BACKUP_PATH = `${STORAGE_ROOT}/legacy-task-history.backup.json` + + const makeItem = (id: string, task: string): HistoryItem => ({ + number: 1, + ts: 1700000000000 + id.length, + tokensIn: 10, + tokensOut: 5, + totalCost: 0.01, + id, + task, + }) + + describe("sweep after a verified migration", () => { + let provider: ClineProvider + let context: vscode.ExtensionContext + let outputChannel: vscode.OutputChannel + let state: Record + const memFiles = new Map() + const memDirs = new Set() + + const errno = (code: string, p: string): NodeJS.ErrnoException => { + const err: NodeJS.ErrnoException = new Error(`${code}: ${p}`) + err.code = code + return err + } + + // Normalize separators and the drive anchor: production path.join + // emits backslashes on Windows, and the real safeWriteJson resolves + // fixture paths against the working drive (path.resolve in + // utils/safeWriteJson.ts), so a "/test/..." fixture arrives with a + // "D:" prefix on windows CI. The in-memory keys stay forward-slash, + // drive-less. + const toKey = (p: unknown): string => + String(p) + .replace(/\\/g, "/") + .replace(/^[A-Za-z]:/, "") + + const wireFsMocks = async () => { + renameGate = undefined + readGate = undefined + fsMockRef = await import("fs/promises") + const fsMock = fsMockRef + vi.mocked(fsMock.mkdir).mockReset().mockResolvedValue(undefined) + vi.mocked(fsMock.access) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + if (memDirs.has(key) || Array.from(memFiles.keys()).some((k) => k.startsWith(`${key}/`))) { + return undefined + } + throw errno("ENOENT", key) + }) + vi.mocked(fsMock.readFile) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + if (readGate && key === BACKUP_PATH) { + // The authority test parks the backup read here. + await readGate.promise + } + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + vi.mocked(fsMock.readdir) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + const names = new Set() + for (const k of memFiles.keys()) { + if (k.startsWith(`${key}/`)) { + const rest = k.slice(key.length + 1) + if (!rest.includes("/")) names.add(rest) + } + } + for (const d of memDirs) { + if (d.startsWith(`${key}/`)) { + const rest = d.slice(key.length + 1) + if (!rest.includes("/")) names.add(rest) + } + } + return Array.from(names) as never + }) + vi.mocked(fsMock.stat) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return { mtimeMs: content.length } as never + }) + // The sweep's temp-file staging and commit run through the + // sync stream and the fs/promises rename, so wire them onto + // the same in-memory map (CR 2873 thread 4814936085: the real + // writer runs; only the filesystem is mocked). + const fsSyncRef = await import("fs") + vi.mocked(fsSyncRef.createWriteStream) + .mockReset() + .mockImplementation(((targetPath: unknown) => { + let staged = "" + return new Writable({ + write(chunk: unknown, _enc: unknown, cb: (error?: Error | null) => void) { + staged += String(chunk) + cb() + }, + final(cb: (error?: Error | null) => void) { + memFiles.set(toKey(targetPath), staged) + cb() + }, + }) as never + }) as never) + vi.mocked(fsMock.rename) + .mockReset() + .mockImplementation(async (fromPath, toPath) => { + const from = toKey(fromPath) + const to = toKey(toPath) + const content = memFiles.get(from) + if (content === undefined) { + throw errno("ENOENT", from) + } + if (renameGate && to === BACKUP_PATH) { + // The deferred-write test parks the commit rename. + await renameGate.promise + } + memFiles.set(to, content) + memFiles.delete(from) + return undefined as never + }) + vi.mocked(fsMock.open) + .mockReset() + .mockImplementation(async () => + Promise.resolve({ + sync: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + } as never), + ) + storageUtilsRef = await import("../../../utils/storage") + vi.mocked(storageUtilsRef.getStorageBasePath) + .mockReset() + .mockImplementation(async (defaultPath: string) => defaultPath) + lockRef = await import("../../../utils/fileLock") + vi.mocked(lockRef.acquireFileLock) + .mockReset() + .mockImplementation(async () => async () => {}) + vi.mocked(lockRef.withFileLock) + .mockReset() + .mockImplementation(async (filePath: string, operation: (absoluteFilePath: string) => Promise) => + operation(filePath), + ) + const swj = (swjRef = await import("../../../utils/safeWriteJson")) + const realWriter = + await vi.importActual("../../../utils/safeWriteJson") + vi.mocked(swj.safeWriteJson).mockReset().mockImplementation(realWriter.safeWriteJson) + } + + let fsMockRef: typeof import("fs/promises") + let swjRef: typeof import("../../../utils/safeWriteJson") + let lockRef: typeof import("../../../utils/fileLock") + let storageUtilsRef: typeof import("../../../utils/storage") + let renameGate: { promise: Promise; release: () => void } | undefined + let readGate: { promise: Promise; release: () => void } | undefined + + const buildProvider = async (options: { + globalState: Record + dirs?: string[] + files?: Record + beforeFlush?: () => void + }): Promise => { + vi.clearAllMocks() + // This suite must also pass when it runs without its sibling + // suite, whose beforeEach creates the telemetry singleton. + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + memFiles.clear() + memDirs.clear() + for (const d of options.dirs ?? []) { + memDirs.add(d) + } + for (const [k, v] of Object.entries(options.files ?? {})) { + memFiles.set(k, v) + } + state = { taskHistoryMigratedToFiles: false, ...options.globalState } + + const secrets: Record = {} + context = { + extensionPath: "/test/path", + extensionUri: { fsPath: "/test/path" } as vscode.Uri, + globalState: { + get: vi.fn().mockImplementation((key: string) => state[key]), + update: vi.fn().mockImplementation((key: string, value: unknown) => { + state[key] = value + return Promise.resolve() + }), + keys: vi.fn().mockImplementation(() => Object.keys(state)), + }, + secrets: { + get: vi.fn().mockImplementation((key: string) => secrets[key]), + store: vi + .fn() + .mockImplementation((key: string, value: string | undefined) => (secrets[key] = value)), + delete: vi.fn().mockImplementation((key: string) => void delete secrets[key]), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + subscriptions: [], + extension: { packageJSON: { version: "1.0.0" } }, + globalStorageUri: { fsPath: STORAGE_ROOT }, + } as unknown as vscode.ExtensionContext + + outputChannel = { + appendLine: vi.fn(), + clear: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + await wireFsMocks() + + provider = new ClineProvider( + context, + outputChannel, + "sidebar", + new ContextProxy(context), + new WebviewFocusTracker(), + ) + // Synchronous hook: it must land before the constructor's async + // init chain resumes in the flush below. + options.beforeFlush?.() + // Long enough for reconcile's ENOENT retry path to settle. + await new Promise((resolve) => setTimeout(resolve, 250)) + + ;(provider as unknown as Record)["customModesManager"] = { + updateCustomMode: vi.fn().mockResolvedValue(undefined), + getCustomModes: vi.fn().mockResolvedValue([]), + dispose: vi.fn(), + } + provider.getMcpHub = vi.fn().mockReturnValue({ + listTools: vi.fn().mockResolvedValue([]), + callTool: vi.fn().mockResolvedValue({ content: [] }), + listResources: vi.fn().mockResolvedValue({ contents: [] }), + readResource: vi.fn().mockResolvedValue({ contents: [] }), + getAllServers: vi.fn().mockReturnValue([]), + }) + return provider + } + + it("clears the legacy blob and writes a backup after a verified migration", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemB] }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " "), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, " "), + }, + }) + + // The migration log proves the marker flow ran before the sweep. + const initLog = vi + .mocked(outputChannel.appendLine) + .mock.calls.map((call) => String(call[0])) + .join(" | ") + expect(initLog).toContain("[initializeTaskHistoryStore] Migration complete") + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // The blob must be gone from globalState, and the backup must hold + // the full array before the delete. + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup).toStrictEqual([itemA, itemB]) + }) + + it("keeps the blob when an entry with a task directory is not held by the store", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + await buildProvider({ + globalState: { taskHistory: [itemA, itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + }) + + // task-b has a task directory but no store entry: deleting the blob + // would destroy unverified history, so the sweep must keep it. + expect(provider["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA, itemB]) + expect(memFiles.has(BACKUP_PATH)).toBe(false) + }) + + it("keeps the blob when the backup write fails", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + beforeFlush: () => { + // Only the sweep's backup write fails; init-time repair writes go through. + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + if (toKey(p) === BACKUP_PATH) { + throw new Error("disk full") + } + memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + return undefined as never + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + }) + + it("clears the blob on a later startup after a failed sweep", async () => { + const itemA = makeItem("task-a", "A") + const seeds = { + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + } + const first = await buildProvider({ + ...seeds, + beforeFlush: () => { + // Only the sweep's backup write fails; init-time repair writes go through. + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + if (toKey(p) === BACKUP_PATH) { + throw new Error("disk full") + } + memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + return undefined as never + }) + }, + }) + const firstContext = context + const firstState = state + expect(first["taskHistoryStoreInitialized"]).toBe(true) + expect(firstContext.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + + const second = await buildProvider({ ...seeds, files: { ...seeds.files } }) + expect(second["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(firstState.taskHistory).toStrictEqual([itemA]) + }) + + it("sweeps the blob when only orphan entries lack task directories", async () => { + const itemA = makeItem("task-a", "A") + const itemOrphan = makeItem("task-orphan", "Orphan") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemOrphan], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + }) + + // The orphan has no task directory, so the store can never hold it. + // The backup preserves it and the sweep proceeds. + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup).toStrictEqual([itemA, itemOrphan]) + }) + + it("does nothing when a peer window already cleared the blob", async () => { + await buildProvider({ globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true } }) + + expect(provider["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(memFiles.has(BACKUP_PATH)).toBe(false) + }) + + it("failed-initialization fallback reads the sweep backup when the blob is gone", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, " ") }, + beforeFlush: () => { + // Every mkdir call fails, so TaskHistoryStore.initialize() throws. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + }, + }) + + // The store never initialized, so the provider still serves the legacy + // fallback; the blob was swept by a peer, and the backup takes over. + expect(p["taskHistoryStoreInitialized"]).toBe(false) + const item = await p["getTaskHistoryItem"]("task-a") + expect(item?.id).toBe("task-a") + }) + + it("keeps the blob when it changes during the sweep", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + const itemC = makeItem("task-c", "C") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, "\t"), + }, + beforeFlush: () => { + // A downgraded build appends task-c while the sweep + // awaits the directory check for task-a, which runs + // after the sweep's read of the blob. + let appended = false + vi.mocked(fsMockRef.access).mockImplementation(async (p) => { + const key = toKey(p) + if (key === `${TASKS_DIR}/task-a` && !appended) { + appended = true + state.taskHistory = [...(state.taskHistory as HistoryItem[]), itemC] + } + if (memDirs.has(key) || Array.from(memFiles.keys()).some((k) => k.startsWith(`${key}/`))) { + return undefined as never + } + throw errno("ENOENT", key) + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // The appended entry is not in the backup, so the sweep must + // keep the blob and let the next startup retry. Capture the + // first window's state before the second build replaces it. + const firstContext = context + const firstState = state + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(firstContext.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(firstState.taskHistory).toStrictEqual([itemA, itemB, itemC]) + expect(backup).toStrictEqual([itemA, itemB]) + + // The next startup reads all three entries and completes the + // sweep. + const second = await buildProvider({ + globalState: { taskHistory: [itemA, itemB, itemC], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`, `${TASKS_DIR}/task-c`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, "\t"), + [`${TASKS_DIR}/task-c/history_item.json`]: JSON.stringify(itemC, null, "\t"), + }, + }) + expect(second["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + }) + + it("merges the sweep backup with entries an earlier sweep backed up", async () => { + const itemA = makeItem("task-a", "A") + const itemOld = makeItem("task-old", "Old") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + // An earlier sweep backed up an orphan that has no task + // directory; the orphan exists only in the backup. + [BACKUP_PATH]: JSON.stringify([itemOld], null, "\t"), + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup).toStrictEqual([itemA, itemOld]) + }) + + it("keeps the blob when the backup file is not an array", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " "), + // Valid JSON that is not an array: the sweep must not + // treat it as empty and overwrite recoverable content. + [BACKUP_PATH]: JSON.stringify({ junk: true }, null, " "), + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + // The malformed file is preserved for recovery. + expect(memFiles.get(BACKUP_PATH)).toContain("junk") + }) + + it("keeps entries an earlier sweep backed up when a second sweep runs", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + // First window sweeps [itemA] and writes the backup. + await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " "), + }, + }) + const firstBackup = memFiles.get(BACKUP_PATH) + expect(firstBackup).toBeDefined() + + // A second window sweeps [itemB] against the same storage; its + // merge must keep the first window's entry. + const second = await buildProvider({ + globalState: { taskHistory: [itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, " "), + [BACKUP_PATH]: firstBackup!, + }, + }) + + expect(second["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup).toStrictEqual([itemB, itemA]) + }) + it("keeps ID-less backup entries stable across deferred sweeps", async () => { + const itemA = makeItem("task-a", "A") + const orphan = { number: 1, ts: 1, task: "no-id" } as unknown as HistoryItem + const providerWithOrphan = await buildProvider({ + globalState: { taskHistory: [orphan, itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + // A previous sweep wrote this backup; the blob was retained + // because that sweep's clear did not run. + [BACKUP_PATH]: JSON.stringify([orphan], null, "\t"), + }, + }) + + expect(providerWithOrphan["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + // The ID-less entry must not be appended a second time (CR 2873 + // thread 4814737822). + expect(backup).toStrictEqual([orphan, itemA]) + }) + + it("keeps the blob when the backup read-back does not match", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, "\t"), + }, + beforeFlush: () => { + // The backup write succeeds but the stored content + // loses an entry, so the read-back cannot match. + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + const content = toKey(p) === BACKUP_PATH ? [(data as HistoryItem[])[0]] : data + memFiles.set(toKey(p), JSON.stringify(content, null, "\t")) + return undefined as never + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA, itemB]) + }) + + it("keeps the blob when the backup read-back cannot be read", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + beforeFlush: () => { + // The pre-check read and the writer's locked merge read + // succeed, so the backup write lands; only the post-write + // read-back fails. + let backupReads = 0 + vi.mocked(fsMockRef.readFile).mockImplementation(async (p) => { + if (toKey(p) === BACKUP_PATH) { + backupReads += 1 + if (backupReads >= 3) { + throw errno("EIO", toKey(p)) + } + } + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // The backup was written, so this is the read-back keep branch, + // not an early defer. + expect(memFiles.has(BACKUP_PATH)).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + }) + + it("leaves the blob untouched while the backup write is pending", async () => { + const itemA = makeItem("task-a", "A") + let releaseWrite: (() => void) | undefined + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + beforeFlush: () => { + // Park the backup commit at its rename: the real writer has + // read, merged, and staged the temp file by then, and the + // assertions below run before the write lands. + let release: (() => void) | undefined + renameGate = { + promise: new Promise((resolve) => { + release = resolve + }), + release: () => release?.(), + } + releaseWrite = () => renameGate?.release() + }, + }) + + // The sweep is parked on the pending backup write: the blob + // must still be in globalState, untouched. + expect(releaseWrite).toBeInstanceOf(Function) + expect(state.taskHistory).toStrictEqual([itemA]) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + + releaseWrite!() + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + expect(p["taskHistoryStoreInitialized"]).toBe(true) + }) + + it("keeps the blob when a task directory access fails", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.access).mockImplementation(async (p) => { + const key = toKey(p) + if (key === `${TASKS_DIR}/task-a`) { + throw errno("EIO", key) + } + if (memDirs.has(key) || Array.from(memFiles.keys()).some((k) => k.startsWith(`${key}/`))) { + return undefined as never + } + throw errno("ENOENT", key) + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // An access failure is not evidence of absence: the sweep + // defers and keeps the blob. + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + expect(memFiles.has(BACKUP_PATH)).toBe(false) + const initLog = vi + .mocked(outputChannel.appendLine) + .mock.calls.map((call) => String(call[0])) + .join(" | ") + expect(initLog).toContain("Legacy blob sweep deferred") + }) + + it("retries a transient backup read error in the fallback", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + // Store init fails, so the provider keeps the legacy + // fallback path. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + // The first backup read hits a transient I/O error. + let backupReads = 0 + vi.mocked(fsMockRef.readFile).mockImplementation(async (p) => { + if (toKey(p) === BACKUP_PATH) { + backupReads += 1 + if (backupReads === 1) { + throw errno("EIO", toKey(p)) + } + } + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(false) + const first = await p["getTaskHistoryItem"]("task-a") + expect(first).toBeUndefined() + // A transient read error must not be cached as absence: the + // next lookup reads the backup again. + const second = await p["getTaskHistoryItem"]("task-a") + expect(second?.id).toBe("task-a") + }) + + it("re-reads the backup after a cached miss when a peer extends it", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + let backupReads = 0 + const pStale = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + // Store init fails, so the provider keeps the legacy + // fallback path; count the backup reads from here on. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + vi.mocked(fsMockRef.readFile).mockImplementation(async (pathArg) => { + if (toKey(pathArg) === BACKUP_PATH) { + backupReads += 1 + } + const key = toKey(pathArg) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(pStale["taskHistoryStoreInitialized"]).toBe(false) + const cached = await pStale["getTaskHistoryItem"]("task-a") + expect(cached?.id).toBe("task-a") + const readsAfterCache = backupReads + + // A peer window merges B into the shared backup and clears the + // blob while this window still holds its cached [A]. + memFiles.set(BACKUP_PATH, JSON.stringify([itemB, itemA], null, "\t")) + + // The cached miss must re-read the file and find B without a + // restart (CR 2873 thread 4815042571). + const found = await pStale["getTaskHistoryItem"]("task-b") + expect(found?.id).toBe("task-b") + expect(backupReads).toBe(readsAfterCache + 1) + + // A cached hit keeps using the cache: no further read. + const again = await pStale["getTaskHistoryItem"]("task-a") + expect(again?.id).toBe("task-a") + expect(backupReads).toBe(readsAfterCache + 1) + }) + + it("re-resolves the backup root when the storage setting changes", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + let backupReads = 0 + const pRoot = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + // Store init fails, so the provider keeps the legacy + // fallback path. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + vi.mocked(fsMockRef.readFile).mockImplementation(async (pathArg) => { + if (toKey(pathArg) === BACKUP_PATH) { + backupReads += 1 + } + const key = toKey(pathArg) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(pRoot["taskHistoryStoreInitialized"]).toBe(false) + const cached = await pRoot["getTaskHistoryItem"]("task-a") + expect(cached?.id).toBe("task-a") + + // The user moves the storage root at runtime; a peer window + // writes its backup at the new root and clears the blob. + const movedRoot = `${STORAGE_ROOT}-moved` + vi.mocked(storageUtilsRef.getStorageBasePath).mockImplementation(async (defaultPath: string) => + toKey(defaultPath) === STORAGE_ROOT ? movedRoot : toKey(defaultPath), + ) + memFiles.set(`${movedRoot}/legacy-task-history.backup.json`, JSON.stringify([itemB, itemA], null, "\t")) + + // The next miss must read at the NEW root (CR 2873 thread + // 4816587009), not stay pinned to the first resolution. + const found = await pRoot["getTaskHistoryItem"]("task-b") + expect(found?.id).toBe("task-b") + expect(backupReads).toBeGreaterThan(0) + }) + + it("recovers an interrupted backup replacement before confirming absence", async () => { + const itemA = makeItem("task-a", "A") + // The canonical backup is absent; an interrupted replacement + // left its committed content in a recovery file. + const recoveryFile = `${STORAGE_ROOT}/.legacy-task-history.backup.json.bak_1_unit.tmp` + const pRec = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [recoveryFile]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + }, + }) + + expect(pRec["taskHistoryStoreInitialized"]).toBe(false) + // The committed backup content must be restored and served + // instead of answering "Task not found" (CR 2873 thread + // 4816587011). + const found = await pRec["getTaskHistoryItem"]("task-a") + expect(found?.id).toBe("task-a") + }) + + it("returns no backup item once initialization completes during its read", async () => { + const itemA = makeItem("task-a", "A") + let releaseRead: (() => void) | undefined + const pAuth = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + // Park the backup read; initialization "completes" + // while the lookup is awaiting it. + let release: (() => void) | undefined + readGate = { + promise: new Promise((resolve) => { + release = resolve + }), + release: () => release?.(), + } + releaseRead = () => readGate?.release() + }, + }) + + expect(pAuth["taskHistoryStoreInitialized"]).toBe(false) + const lookup = pAuth["getTaskHistoryItem"]("task-a") + ;(pAuth as unknown as { taskHistoryStoreInitialized: boolean }).taskHistoryStoreInitialized = true + releaseRead!() + const result = await lookup + // The store is authoritative now and does not hold the task, + // so the stale backup item must not be delivered (CR 2873 + // thread 4816587019). + expect(result).toBeUndefined() + }) + + it.each([ + ["mode switch", "mode"], + ["profile switch", "apiConfigName"], + ])("keeps a newer cost when a %s persists field-only", async (_name, field) => { + const itemA = makeItem("task-a", "A") + const pCost = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + }) + + expect(pCost["taskHistoryStoreInitialized"]).toBe(true) + // A token save lands a newer cost after the caller's snapshot + // was taken: the cached item now holds it. + const newer = { ...itemA, totalCost: 9 } + await pCost.updateTaskHistory(newer, { broadcast: false }) + expect(pCost["taskHistoryStore"].get("task-a")?.totalCost).toBe(9) + + // The switch flow still holds the OLDER full-item snapshot: + // stub the lookup so the pre-fix full-item write replays it. + vi.spyOn( + pCost as unknown as { getTaskHistoryItem: (id: string) => Promise }, + "getTaskHistoryItem", + ).mockResolvedValue(itemA) + + const taskDouble = { taskId: "task-a", emit: vi.fn(), setTaskApiConfigName: vi.fn() } as unknown as Task + const provider = pCost as unknown as { + getTaskHistoryItem: (id: string) => Promise + getCurrentTask: () => Task | undefined + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue(taskDouble) + + if (field === "mode") { + await ( + pCost as unknown as { + handleModeSwitchUnlocked: (mode: string, task: Task | null) => Promise + } + ).handleModeSwitchUnlocked("arch", taskDouble) + const stored = pCost["taskHistoryStore"].get("task-a") + expect(stored?.totalCost).toBe(9) + expect(stored?.mode).toBe("arch") + } else { + await ( + pCost as unknown as { + persistStickyProviderProfileToCurrentTask: (name: string) => Promise + } + ).persistStickyProviderProfileToCurrentTask("sticky-profile") + const stored = pCost["taskHistoryStore"].get("task-a") + expect(stored?.totalCost).toBe(9) + expect(stored?.apiConfigName).toBe("sticky-profile") + } + }) + }) +}) diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index fd22782226..85a6121737 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -901,12 +901,12 @@ }, "core/webview/__tests__/ClineProvider.sticky-mode.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 27 + "count": 26 } }, "core/webview/__tests__/ClineProvider.sticky-profile.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 15 + "count": 14 } }, "core/webview/__tests__/ClineProvider.taskHistory.spec.ts": {