@@ -14,6 +14,7 @@ import {
1414 isPrimaryBootstrapRun ,
1515 mergeOrphanedTrailingUserPrompt ,
1616 normalizeMessagesForLlmBoundary ,
17+ removeSessionManagerLeafEntry ,
1718 prependSystemPromptAddition ,
1819 remapInjectedContextFilesToWorkspace ,
1920 resetEmbeddedAgentBaseStreamFnCacheForTest ,
@@ -479,6 +480,54 @@ describe("remapInjectedContextFilesToWorkspace", () => {
479480 } ) ;
480481} ) ;
481482
483+ describe ( "removeSessionManagerLeafEntry" , ( ) => {
484+ it ( "removes the persisted leaf entry before rebuilding context" , ( ) => {
485+ const orphan = { type : "message" , id : "orphan-user" , parentId : "assistant-1" } ;
486+ const fileEntries = [
487+ { type : "session" , id : "session-1" } ,
488+ { type : "message" , id : "user-1" , parentId : null } ,
489+ { type : "message" , id : "assistant-1" , parentId : "user-1" } ,
490+ orphan ,
491+ ] ;
492+ const manager = {
493+ fileEntries,
494+ byId : new Map ( fileEntries . map ( ( entry ) => [ entry . id , entry ] ) ) ,
495+ leafId : "orphan-user" as string | null ,
496+ branch : vi . fn ( ) ,
497+ resetLeaf : vi . fn ( ) ,
498+ _rewriteFile : vi . fn ( ) ,
499+ } ;
500+
501+ removeSessionManagerLeafEntry ( { sessionManager : manager , leafEntry : orphan } ) ;
502+
503+ expect ( manager . fileEntries . map ( ( entry ) => entry . id ) ) . toEqual ( [
504+ "session-1" ,
505+ "user-1" ,
506+ "assistant-1" ,
507+ ] ) ;
508+ expect ( manager . byId . has ( "orphan-user" ) ) . toBe ( false ) ;
509+ expect ( manager . leafId ) . toBe ( "assistant-1" ) ;
510+ expect ( manager . _rewriteFile ) . toHaveBeenCalledTimes ( 1 ) ;
511+ expect ( manager . branch ) . not . toHaveBeenCalled ( ) ;
512+ expect ( manager . resetLeaf ) . not . toHaveBeenCalled ( ) ;
513+ } ) ;
514+
515+ it ( "falls back to in-memory branching when the manager cannot rewrite" , ( ) => {
516+ const manager = {
517+ branch : vi . fn ( ) ,
518+ resetLeaf : vi . fn ( ) ,
519+ } ;
520+
521+ removeSessionManagerLeafEntry ( {
522+ sessionManager : manager ,
523+ leafEntry : { id : "orphan-user" , parentId : "assistant-1" } ,
524+ } ) ;
525+
526+ expect ( manager . branch ) . toHaveBeenCalledWith ( "assistant-1" ) ;
527+ expect ( manager . resetLeaf ) . not . toHaveBeenCalled ( ) ;
528+ } ) ;
529+ } ) ;
530+
482531describe ( "shouldWarnOnOrphanedUserRepair" , ( ) => {
483532 it ( "warns for user and manual runs" , ( ) => {
484533 expect ( shouldWarnOnOrphanedUserRepair ( "user" ) ) . toBe ( true ) ;
0 commit comments