@@ -3,15 +3,17 @@ import fs from "node:fs/promises";
33import os from "node:os" ;
44import path from "node:path" ;
55import { afterEach , beforeAll , beforeEach , describe , expect , it , vi } from "vitest" ;
6- import type { SessionEntry } from "../config/sessions.js" ;
6+ import type { InternalSessionEntry , SessionEntry } from "../config/sessions.js" ;
77import { formatSqliteSessionFileMarker } from "../config/sessions/legacy-sqlite-marker.js" ;
8+ import { SessionWorkStartInvalidatedError } from "../config/sessions/lifecycle.js" ;
89import {
910 appendTranscriptEvent ,
1011 appendTranscriptMessage ,
1112 listSessionEntriesCore ,
1213 loadTranscriptEvents ,
1314 replaceSessionEntry ,
1415} from "../config/sessions/session-accessor.js" ;
16+ import { createSessionDiffBaselineCaptureClaim } from "../config/sessions/session-diff-baseline-capture.js" ;
1517import type { OpenClawConfig } from "../config/types.openclaw.js" ;
1618import { rotateAgentEventLifecycleGeneration } from "../infra/agent-events.js" ;
1719import { defaultRuntime } from "../runtime.js" ;
@@ -23,6 +25,8 @@ import { createAgentRunRestartAbortError } from "./run-termination.js";
2325type ProviderModelNormalizationParams = { provider : string ; context : { modelId : string } } ;
2426type LoadManifestModelCatalogParams = Parameters < typeof loadManifestModelCatalog > [ 0 ] ;
2527type RunAgentAttempt = typeof runAgentAttempt ;
28+ type CaptureSessionDiffBaseline =
29+ ( typeof import ( "../sessions/session-diff.js" ) ) [ "captureSessionDiffBaseline" ] ;
2630type CliCompactionParams = {
2731 sessionId : string ;
2832 sessionEntry ?: SessionEntry ;
@@ -50,6 +54,13 @@ const state = vi.hoisted(() => ({
5054 deliverAgentCommandResultMock : vi . fn ( ) ,
5155 emitAgentEventMock : vi . fn ( ) ,
5256 deliveryFreshEntries : [ ] as Array < SessionEntry | undefined > ,
57+ captureSessionDiffBaselineMock : vi . fn < CaptureSessionDiffBaseline > ( ) ,
58+ } ) ) ;
59+
60+ vi . mock ( "../sessions/session-diff.js" , async ( importOriginal ) => ( {
61+ ...( await importOriginal < typeof import ( "../sessions/session-diff.js" ) > ( ) ) ,
62+ captureSessionDiffBaseline : ( params : Parameters < CaptureSessionDiffBaseline > [ 0 ] ) =>
63+ state . captureSessionDiffBaselineMock ( params ) ,
5364} ) ) ;
5465
5566vi . mock ( "../config/io.js" , ( ) => ( {
@@ -336,6 +347,46 @@ const COMPACTION_ERROR =
336347 "CLI transcript compaction failed for openai/gpt-5.5: Summarization failed: Connection error." ;
337348
338349describe ( "agentCommand compaction transcript rotation" , ( ) => {
350+ it . each ( [
351+ [ "settles a precreated baseline claim before embedded execution" , false ] ,
352+ [ "does not execute after baseline work-start invalidation" , true ] ,
353+ ] as const ) ( "%s" , async ( _name , invalidated ) => {
354+ const sessionId = invalidated ? "invalidated-agent-command" : "precreated-agent-command" ,
355+ sessionKey = `agent:main:explicit:${ sessionId } ` ;
356+ await replaceSessionEntry ( { sessionKey, storePath : requireStorePath ( ) } , {
357+ sessionId,
358+ sessionDiffBaselineCapture : createSessionDiffBaselineCaptureClaim ( ) ,
359+ updatedAt : Date . now ( ) ,
360+ } as InternalSessionEntry ) ;
361+ if ( invalidated ) {
362+ const error = new SessionWorkStartInvalidatedError (
363+ "session changed during baseline settlement" ,
364+ ) ;
365+ state . captureSessionDiffBaselineMock . mockRejectedValueOnce ( error ) ;
366+ await expect (
367+ agentCommand ( { message : "must not execute" , sessionId, sessionKey } ) ,
368+ ) . rejects . toBe ( error ) ;
369+ expect ( state . runAgentAttemptMock ) . not . toHaveBeenCalled ( ) ;
370+ return ;
371+ }
372+ state . captureSessionDiffBaselineMock . mockResolvedValueOnce ( {
373+ version : 1 ,
374+ sessionId,
375+ root : "/workspace" ,
376+ files : [ ] ,
377+ } ) ;
378+ state . runAgentAttemptMock . mockImplementationOnce ( async ( ) => {
379+ expect ( findStoredSessionEntry ( sessionKey ) ?. sessionDiffBaseline ) . toMatchObject ( {
380+ version : 1 ,
381+ sessionId,
382+ } ) ;
383+ return makeResult ( { sessionId, text : "captured before execution" } ) ;
384+ } ) ;
385+
386+ await agentCommand ( { message : "write after capture" , sessionId, sessionKey } ) ;
387+ expect ( state . captureSessionDiffBaselineMock ) . toHaveBeenCalledOnce ( ) ;
388+ } ) ;
389+
339390 it ( "does not re-normalize an exact configured custom provider through plugin runtime" , async ( ) => {
340391 state . normalizeProviderModelIdWithRuntimeMock . mockImplementation (
341392 ( { provider } : ProviderModelNormalizationParams ) => {
@@ -776,17 +827,27 @@ describe("agentCommand compaction transcript rotation", () => {
776827 } ) ;
777828 } ) ;
778829
779- it ( "does not deliver or clear the pending final when restart aborts compaction" , async ( ) => {
780- const sessionId = "restart-during-compaction" ;
830+ it . each ( [
831+ [ "restart-during-compaction" , "reply owned by restart recovery" ] ,
832+ [ "restart-after-successful-compaction" , "reply owned by restart recovery after compaction" ] ,
833+ [ "stale-during-compaction" , "reply owned by the next gateway lifecycle" ] ,
834+ ] as const ) ( "does not deliver or clear the pending final for %s" , async ( sessionId , text ) => {
835+ const restart = sessionId !== "stale-during-compaction" ;
781836 const sessionKey = `agent:main:explicit:${ sessionId } ` ;
782- const text = "reply owned by restart recovery" ;
783837 const abortController = new AbortController ( ) ;
784838 state . runAgentAttemptMock . mockResolvedValueOnce ( makeResult ( { sessionId, text } ) ) ;
785839 state . runCliTurnCompactionLifecycleMock . mockImplementationOnce ( async ( params ) => {
786840 expect ( params . sessionEntry ) . toMatchObject ( {
787841 pendingFinalDelivery : { kind : "replayable" , text } ,
788842 } ) ;
789- abortController . abort ( createAgentRunRestartAbortError ( ) ) ;
843+ if ( restart ) {
844+ abortController . abort ( createAgentRunRestartAbortError ( ) ) ;
845+ } else {
846+ rotateAgentEventLifecycleGeneration ( ) ;
847+ }
848+ if ( sessionId === "restart-after-successful-compaction" ) {
849+ return params . sessionEntry ;
850+ }
790851 throw new Error ( COMPACTION_ERROR ) ;
791852 } ) ;
792853
@@ -802,73 +863,9 @@ describe("agentCommand compaction transcript rotation", () => {
802863 deliver : true ,
803864 abortSignal : abortController . signal ,
804865 } ) ,
805- ) . rejects . toThrow ( "agent run aborted for restart" ) ;
806-
807- expect ( state . deliverAgentCommandResultMock ) . not . toHaveBeenCalled ( ) ;
808- expect ( findStoredSessionEntry ( sessionKey ) ) . toMatchObject ( {
809- pendingFinalDelivery : { kind : "replayable" , text } ,
810- } ) ;
811- } ) ;
812-
813- it ( "does not deliver or clear the pending final when restart wins after successful compaction" , async ( ) => {
814- const sessionId = "restart-after-successful-compaction" ;
815- const sessionKey = `agent:main:explicit:${ sessionId } ` ;
816- const text = "reply owned by restart recovery after compaction" ;
817- const abortController = new AbortController ( ) ;
818- state . runAgentAttemptMock . mockResolvedValueOnce ( makeResult ( { sessionId, text } ) ) ;
819- state . runCliTurnCompactionLifecycleMock . mockImplementationOnce ( async ( params ) => {
820- expect ( params . sessionEntry ) . toMatchObject ( {
821- pendingFinalDelivery : { kind : "replayable" , text } ,
822- } ) ;
823- abortController . abort ( createAgentRunRestartAbortError ( ) ) ;
824- return params . sessionEntry ;
825- } ) ;
826-
827- await expect (
828- agentCommand ( {
829- message : "room message" ,
830- sessionId,
831- sessionKey,
832- cwd : state . workspaceDir ,
833- channel : "discord" ,
834- to : "discord:dm:123" ,
835- accountId : "main" ,
836- deliver : true ,
837- abortSignal : abortController . signal ,
838- } ) ,
839- ) . rejects . toThrow ( "agent run aborted for restart" ) ;
840-
841- expect ( state . deliverAgentCommandResultMock ) . not . toHaveBeenCalled ( ) ;
842- expect ( findStoredSessionEntry ( sessionKey ) ) . toMatchObject ( {
843- pendingFinalDelivery : { kind : "replayable" , text } ,
844- } ) ;
845- } ) ;
846-
847- it ( "does not deliver or clear the pending final after lifecycle ownership turns stale" , async ( ) => {
848- const sessionId = "stale-during-compaction" ;
849- const sessionKey = `agent:main:explicit:${ sessionId } ` ;
850- const text = "reply owned by the next gateway lifecycle" ;
851- state . runAgentAttemptMock . mockResolvedValueOnce ( makeResult ( { sessionId, text } ) ) ;
852- state . runCliTurnCompactionLifecycleMock . mockImplementationOnce ( async ( params ) => {
853- expect ( params . sessionEntry ) . toMatchObject ( {
854- pendingFinalDelivery : { kind : "replayable" , text } ,
855- } ) ;
856- rotateAgentEventLifecycleGeneration ( ) ;
857- throw new Error ( COMPACTION_ERROR ) ;
858- } ) ;
859-
860- await expect (
861- agentCommand ( {
862- message : "room message" ,
863- sessionId,
864- sessionKey,
865- cwd : state . workspaceDir ,
866- channel : "discord" ,
867- to : "discord:dm:123" ,
868- accountId : "main" ,
869- deliver : true ,
870- } ) ,
871- ) . rejects . toThrow ( "Agent run belongs to a stale gateway lifecycle" ) ;
866+ ) . rejects . toThrow (
867+ restart ? "agent run aborted for restart" : "Agent run belongs to a stale gateway lifecycle" ,
868+ ) ;
872869
873870 expect ( state . deliverAgentCommandResultMock ) . not . toHaveBeenCalled ( ) ;
874871 expect ( findStoredSessionEntry ( sessionKey ) ) . toMatchObject ( {
0 commit comments