@@ -6,7 +6,7 @@ import * as os from "os"
66
77import type { HistoryItem } from "@roo-code/types"
88
9- import { TaskHistoryStore } from "../TaskHistoryStore"
9+ import { TaskHistoryStore , DeltaRejectedError } from "../TaskHistoryStore"
1010import { GlobalFileNames } from "../../../shared/globalFileNames"
1111
1212vi . mock ( "../../../utils/storage" , ( ) => ( {
@@ -15,12 +15,30 @@ vi.mock("../../../utils/storage", () => ({
1515 } ) ,
1616} ) )
1717
18- // Mock safeWriteJson to use plain fs writes in tests (avoids proper-lockfile issues)
18+ // Mock safeWriteJson to use plain fs writes but honor the merge callback.
1919vi . mock ( "../../../utils/safeWriteJson" , ( ) => ( {
20- safeWriteJson : vi . fn ( ) . mockImplementation ( async ( filePath : string , data : any ) => {
21- await fs . mkdir ( path . dirname ( filePath ) , { recursive : true } )
22- await fs . writeFile ( filePath , JSON . stringify ( data , null , "\t" ) , "utf8" )
23- } ) ,
20+ safeWriteJson : vi
21+ . fn ( )
22+ . mockImplementation (
23+ async (
24+ filePath : string ,
25+ data : unknown ,
26+ options ?: { merge ?: ( existing : unknown , incoming : unknown ) => unknown } ,
27+ ) => {
28+ await fs . mkdir ( path . dirname ( filePath ) , { recursive : true } )
29+ if ( options ?. merge ) {
30+ let existing : unknown = null
31+ try {
32+ const raw = await fs . readFile ( filePath , "utf8" )
33+ existing = JSON . parse ( raw )
34+ } catch {
35+ // File does not exist or is corrupt
36+ }
37+ data = options . merge ( existing , data )
38+ }
39+ await fs . writeFile ( filePath , JSON . stringify ( data , null , "\t" ) , "utf8" )
40+ } ,
41+ ) ,
2442} ) )
2543
2644function makeHistoryItem ( overrides : Partial < HistoryItem > = { } ) : HistoryItem {
@@ -124,6 +142,27 @@ describe("TaskHistoryStore cross-instance safety", () => {
124142 expect ( storeB . get ( "shared-task" ) ) . toBeUndefined ( )
125143 } )
126144
145+ it ( "delete by instance A is detected even when the task directory remains" , async ( ) => {
146+ await storeA . initialize ( )
147+ await storeB . initialize ( )
148+
149+ const item = makeHistoryItem ( { id : "file-only-delete" } )
150+ await storeA . upsert ( item )
151+ await storeB . reconcile ( )
152+
153+ expect ( storeB . get ( "file-only-delete" ) ) . toBeDefined ( )
154+
155+ // delete() unlinks history_item.json but leaves the task directory.
156+ await storeA . delete ( "file-only-delete" )
157+
158+ // Directory still exists (other files like ui_messages.json may remain).
159+ const taskDir = path . join ( tmpDir , "tasks" , "file-only-delete" )
160+ await expect ( fs . access ( taskDir ) ) . resolves . toBeUndefined ( )
161+
162+ await storeB . reconcile ( )
163+ expect ( storeB . get ( "file-only-delete" ) ) . toBeUndefined ( )
164+ } )
165+
127166 it ( "per-task file updates by one instance are visible to another after invalidation" , async ( ) => {
128167 await storeA . initialize ( )
129168 await storeB . initialize ( )
@@ -164,4 +203,107 @@ describe("TaskHistoryStore cross-instance safety", () => {
164203 expect ( storeA . getAll ( ) . length ) . toBe ( 10 )
165204 expect ( storeB . getAll ( ) . length ) . toBe ( 10 )
166205 } )
206+
207+ /**
208+ * Host B completes a task on disk while host A's cache still has it
209+ * active. Host A's next save updates only totalCost (a full-object
210+ * upsert — the realistic production shape). The diff-delta merge
211+ * preserves B's status because status did not change in A's cache.
212+ */
213+ it ( "per-task diff-delta preserves a peer's status change on full-object upsert" , async ( ) => {
214+ await storeA . initialize ( )
215+
216+ // Base item with an explicit status — mirrors real production items.
217+ const base = makeHistoryItem ( { id : "shared-task" , status : "active" , totalCost : 0.01 , ts : 1000 } )
218+ await storeA . upsert ( base )
219+
220+ // Host B completes the task on disk; A's cache still has "active".
221+ const filePath = path . join ( tmpDir , "tasks" , "shared-task" , GlobalFileNames . historyItem )
222+ const onDisk = JSON . parse ( await fs . readFile ( filePath , "utf8" ) )
223+ onDisk . status = "completed"
224+ onDisk . completionResultSummary = "done by host B"
225+ await fs . writeFile ( filePath , JSON . stringify ( onDisk ) , "utf8" )
226+
227+ // Host A does a full-object upsert (the realistic path — spread the
228+ // cached item and change one field). The cached item has status: "active".
229+ await storeA . upsert ( { ...storeA . get ( "shared-task" ) ! , totalCost : 9.99 } )
230+
231+ const final = JSON . parse ( await fs . readFile ( filePath , "utf8" ) ) as HistoryItem
232+ expect ( final . totalCost ) . toBe ( 9.99 )
233+ // Status is preserved from disk because A's delta does not include
234+ // status — it was unchanged relative to A's cache.
235+ expect ( final . status ) . toBe ( "completed" )
236+ expect ( final . completionResultSummary ) . toBe ( "done by host B" )
237+
238+ // Cache reflects the caller's totalCost change and the peer's status.
239+ expect ( storeA . get ( "shared-task" ) ! . totalCost ) . toBe ( 9.99 )
240+ expect ( storeA . get ( "shared-task" ) ! . status ) . toBe ( "completed" )
241+ expect ( storeA . get ( "shared-task" ) ! . completionResultSummary ) . toBe ( "done by host B" )
242+ } )
243+
244+ /**
245+ * Regression: a stale host whose cache says "active" tries to write
246+ * status: "delegated" after a peer already wrote "completed" to disk.
247+ * The merge must reject the entire delta (including companion fields)
248+ * to prevent an internally-inconsistent record.
249+ */
250+ it ( "merge rejects an invalid status transition against disk and throws DeltaRejectedError" , async ( ) => {
251+ await storeA . initialize ( )
252+
253+ const base = makeHistoryItem ( { id : "guarded-task" , status : "active" , totalCost : 0.01 , ts : 1000 } )
254+ await storeA . upsert ( base )
255+
256+ // Peer writes terminal "completed" directly to disk.
257+ const filePath = path . join ( tmpDir , "tasks" , "guarded-task" , GlobalFileNames . historyItem )
258+ const onDisk = JSON . parse ( await fs . readFile ( filePath , "utf8" ) )
259+ onDisk . status = "completed"
260+ onDisk . completionResultSummary = "done by peer"
261+ await fs . writeFile ( filePath , JSON . stringify ( onDisk ) , "utf8" )
262+
263+ // Host A's cache still has "active". It tries to delegate (active → delegated
264+ // passes the cache check, but completed → delegated is invalid on disk).
265+ const staleItem = storeA . get ( "guarded-task" ) !
266+ await expect (
267+ storeA . upsert ( {
268+ ...staleItem ,
269+ status : "delegated" ,
270+ awaitingChildId : "child-99" ,
271+ delegatedToId : "child-99" ,
272+ } ) ,
273+ ) . rejects . toThrow ( DeltaRejectedError )
274+
275+ const final = JSON . parse ( await fs . readFile ( filePath , "utf8" ) ) as HistoryItem
276+ // Terminal status must survive — disk is untouched.
277+ expect ( final . status ) . toBe ( "completed" )
278+ expect ( final . completionResultSummary ) . toBe ( "done by peer" )
279+ // Companion fields from the rejected delta must NOT be applied.
280+ expect ( final . awaitingChildId ) . toBeUndefined ( )
281+ expect ( final . delegatedToId ) . toBeUndefined ( )
282+
283+ // Cache must reflect the disk state, not the stale delta.
284+ expect ( storeA . get ( "guarded-task" ) ! . status ) . toBe ( "completed" )
285+ } )
286+
287+ /**
288+ * When both hosts change the same field, the last writer wins.
289+ * This is expected — true conflict resolution requires application
290+ * semantics that a generic merge cannot provide.
291+ */
292+ it ( "same-field changes from both hosts are last-writer-wins" , async ( ) => {
293+ await storeA . initialize ( )
294+ await storeB . initialize ( )
295+
296+ const base = makeHistoryItem ( { id : "shared-task" , status : "active" , totalCost : 0.01 , ts : 1000 } )
297+ await storeA . upsert ( base )
298+ await storeB . reconcile ( )
299+
300+ // Both hosts change totalCost.
301+ await storeA . upsert ( { ...storeA . get ( "shared-task" ) ! , totalCost : 1.0 } )
302+ await storeB . upsert ( { ...storeB . get ( "shared-task" ) ! , totalCost : 2.0 } )
303+
304+ const filePath = path . join ( tmpDir , "tasks" , "shared-task" , GlobalFileNames . historyItem )
305+ const final = JSON . parse ( await fs . readFile ( filePath , "utf8" ) ) as HistoryItem
306+ // B wrote last, so B's value wins.
307+ expect ( final . totalCost ) . toBe ( 2.0 )
308+ } )
167309} )
0 commit comments