@@ -1367,6 +1367,307 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
13671367 expect ( hoisted . sessionManager . branch ) . toHaveBeenCalledWith ( "parent-leaf" ) ;
13681368 } ) ;
13691369
1370+ it ( "targets the latest active prompt after orphan repair reaches the embedded provider" , async ( ) => {
1371+ const marker =
1372+ "[Queued user message from a previous active turn; preserved as context only. Continue with the active prompt below.]" ;
1373+ const olderPrompt = "OLD_TURN: answer the earlier short request" ;
1374+ const latestPrompt = "LATEST_TURN: answer only this active instruction" ;
1375+ const repairedPrompt = `${ marker } \n${ olderPrompt } \n\n${ latestPrompt } ` ;
1376+ const runBeforePromptBuild = vi . fn ( async ( ) => ( {
1377+ prependContext : "provider-side context" ,
1378+ } ) ) ;
1379+ const seen : { modelInputPrompt ?: string ; modelMessages ?: AgentMessage [ ] } = { } ;
1380+ hoisted . getGlobalHookRunnerMock . mockReturnValue ( {
1381+ hasHooks : vi . fn ( ( name : string ) => name === "before_prompt_build" ) ,
1382+ runBeforePromptBuild,
1383+ runBeforeAgentStart : vi . fn ( ) ,
1384+ } ) ;
1385+ hoisted . sessionManager . getLeafEntry . mockReturnValueOnce ( {
1386+ id : "orphan-leaf" ,
1387+ parentId : "parent-leaf" ,
1388+ type : "message" ,
1389+ message : { role : "user" , content : olderPrompt , timestamp : 1 } ,
1390+ } ) ;
1391+
1392+ const result = await createContextEngineAttemptRunner ( {
1393+ contextEngine : createContextEngineBootstrapAndAssemble ( ) ,
1394+ sessionKey,
1395+ tempPaths,
1396+ attemptOverrides : {
1397+ prompt : latestPrompt ,
1398+ } ,
1399+ sessionPrompt : async ( session , prompt ) => {
1400+ seen . modelInputPrompt = prompt ;
1401+ const transformContext = (
1402+ session . agent as {
1403+ transformContext ?: ( messages : AgentMessage [ ] ) => Promise < AgentMessage [ ] > ;
1404+ }
1405+ ) . transformContext ;
1406+ seen . modelMessages = await transformContext ?.( [
1407+ { role : "user" , content : [ { type : "text" , text : prompt } ] , timestamp : 1 } ,
1408+ ] ) ;
1409+ const activePrompt = prompt . startsWith ( `${ marker } \n${ olderPrompt } \n\n` )
1410+ ? prompt . slice ( `${ marker } \n${ olderPrompt } \n\n` . length )
1411+ : "missing-active-prompt" ;
1412+ session . messages = [
1413+ ...session . messages ,
1414+ { role : "assistant" , content : `stub-provider-target=${ activePrompt } ` , timestamp : 2 } ,
1415+ ] ;
1416+ } ,
1417+ } ) ;
1418+
1419+ expect ( result . finalPromptText ) . toBe ( repairedPrompt ) ;
1420+ expect ( seen . modelInputPrompt ) . toBe ( repairedPrompt ) ;
1421+ const serializedModelMessages = JSON . stringify ( seen . modelMessages ) ;
1422+ expect ( serializedModelMessages ) . toContain ( marker ) ;
1423+ expect ( serializedModelMessages ) . toContain ( olderPrompt ) ;
1424+ expect ( serializedModelMessages ) . toContain ( latestPrompt ) ;
1425+ const finalAssistant = findRecord (
1426+ requireRecords ( result . messagesSnapshot , "messages snapshot" ) ,
1427+ ( message ) => message . role === "assistant" ,
1428+ "final assistant" ,
1429+ ) ;
1430+ expect ( finalAssistant . content ) . toBe ( `stub-provider-target=${ latestPrompt } ` ) ;
1431+ expect ( finalAssistant . content ) . not . toContain ( "OLD_TURN" ) ;
1432+ expect ( hoisted . sessionManager . branch ) . toHaveBeenCalledWith ( "parent-leaf" ) ;
1433+ } ) ;
1434+
1435+ it ( "repairs an orphaned user message behind non-message session metadata before the provider" , async ( ) => {
1436+ const marker =
1437+ "[Queued user message from a previous active turn; preserved as context only. Continue with the active prompt below.]" ;
1438+ const olderPrompt = "OLD_TURN_76888: answer the orphaned queued turn" ;
1439+ const latestPrompt = "LATEST_TURN_76888: answer only the active channel prompt" ;
1440+ const repairedPrompt = `${ marker } \n${ olderPrompt } \n\n${ latestPrompt } ` ;
1441+ const modelSnapshotData = { provider : "deepseek" , modelId : "deepseek-chat" } ;
1442+ const orphanLeaf = {
1443+ id : "orphan-leaf" ,
1444+ parentId : "parent-leaf" ,
1445+ type : "message" ,
1446+ message : { role : "user" , content : olderPrompt , timestamp : 1 } ,
1447+ } ;
1448+ const thinkingEntry = {
1449+ id : "thinking-leaf" ,
1450+ parentId : "orphan-leaf" ,
1451+ type : "thinking_level_change" ,
1452+ thinkingLevel : "high" ,
1453+ } ;
1454+ const modelEntry = {
1455+ id : "model-leaf" ,
1456+ parentId : "thinking-leaf" ,
1457+ type : "model_change" ,
1458+ provider : "deepseek" ,
1459+ modelId : "deepseek-chat" ,
1460+ } ;
1461+ const modelSnapshotEntry = {
1462+ id : "model-snapshot-leaf" ,
1463+ parentId : "model-leaf" ,
1464+ type : "custom" ,
1465+ customType : "model-snapshot" ,
1466+ data : modelSnapshotData ,
1467+ } ;
1468+ const labelEntry = {
1469+ id : "label-leaf" ,
1470+ parentId : "model-snapshot-leaf" ,
1471+ type : "label" ,
1472+ targetId : "model-snapshot-leaf" ,
1473+ label : "model snapshot" ,
1474+ } ;
1475+ hoisted . sessionManager . getLeafEntry . mockReturnValueOnce ( labelEntry ) ;
1476+ hoisted . sessionManager . getEntry . mockImplementation ( ( id : unknown ) => {
1477+ if ( id === "model-snapshot-leaf" ) {
1478+ return modelSnapshotEntry ;
1479+ }
1480+ if ( id === "model-leaf" ) {
1481+ return modelEntry ;
1482+ }
1483+ if ( id === "thinking-leaf" ) {
1484+ return thinkingEntry ;
1485+ }
1486+ return id === "orphan-leaf" ? orphanLeaf : undefined ;
1487+ } ) ;
1488+ const replayedEntries : string [ ] = [ ] ;
1489+ hoisted . sessionManager . appendThinkingLevelChange . mockImplementation ( ( ...args : unknown [ ] ) => {
1490+ replayedEntries . push ( `thinking:${ String ( args [ 0 ] ) } ` ) ;
1491+ return "replayed-thinking" ;
1492+ } ) ;
1493+ hoisted . sessionManager . appendModelChange . mockImplementation ( ( ...args : unknown [ ] ) => {
1494+ replayedEntries . push ( `model:${ String ( args [ 0 ] ) } /${ String ( args [ 1 ] ) } ` ) ;
1495+ return "replayed-model" ;
1496+ } ) ;
1497+ hoisted . sessionManager . appendCustomEntry . mockImplementation ( ( ...args : unknown [ ] ) => {
1498+ if ( args [ 0 ] === "model-snapshot" ) {
1499+ replayedEntries . push ( `custom:${ args [ 0 ] } :${ JSON . stringify ( args [ 1 ] ) } ` ) ;
1500+ }
1501+ return "replayed-custom" ;
1502+ } ) ;
1503+ hoisted . sessionManager . appendLabelChange . mockImplementation ( ( ...args : unknown [ ] ) => {
1504+ replayedEntries . push ( `label:${ String ( args [ 0 ] ) } /${ String ( args [ 1 ] ) } ` ) ;
1505+ return "replayed-label" ;
1506+ } ) ;
1507+ const seen : { modelInputPrompt ?: string } = { } ;
1508+
1509+ const result = await createContextEngineAttemptRunner ( {
1510+ contextEngine : createContextEngineBootstrapAndAssemble ( ) ,
1511+ sessionKey,
1512+ tempPaths,
1513+ attemptOverrides : {
1514+ prompt : latestPrompt ,
1515+ } ,
1516+ sessionPrompt : async ( session , prompt ) => {
1517+ seen . modelInputPrompt = prompt ;
1518+ const activePrompt = prompt . startsWith ( `${ marker } \n${ olderPrompt } \n\n` )
1519+ ? prompt . slice ( `${ marker } \n${ olderPrompt } \n\n` . length )
1520+ : "missing-active-prompt" ;
1521+ session . messages = [
1522+ ...session . messages ,
1523+ { role : "assistant" , content : `stub-provider-target=${ activePrompt } ` , timestamp : 2 } ,
1524+ ] ;
1525+ } ,
1526+ } ) ;
1527+
1528+ expect ( result . finalPromptText ) . toBe ( repairedPrompt ) ;
1529+ expect ( seen . modelInputPrompt ) . toBe ( repairedPrompt ) ;
1530+ const finalAssistant = findRecord (
1531+ requireRecords ( result . messagesSnapshot , "messages snapshot" ) ,
1532+ ( message ) => message . role === "assistant" ,
1533+ "final assistant" ,
1534+ ) ;
1535+ expect ( finalAssistant . content ) . toBe ( `stub-provider-target=${ latestPrompt } ` ) ;
1536+ expect ( hoisted . sessionManager . branch ) . toHaveBeenCalledWith ( "parent-leaf" ) ;
1537+ expect ( replayedEntries ) . toEqual ( [
1538+ "thinking:high" ,
1539+ "model:deepseek/deepseek-chat" ,
1540+ `custom:model-snapshot:${ JSON . stringify ( modelSnapshotData ) } ` ,
1541+ "label:replayed-custom/model snapshot" ,
1542+ ] ) ;
1543+ } ) ;
1544+
1545+ it ( "does not abort orphan repair for a dangling trailing label" , async ( ) => {
1546+ const marker =
1547+ "[Queued user message from a previous active turn; preserved as context only. Continue with the active prompt below.]" ;
1548+ const olderPrompt = "OLD_TURN_76888: dangling label repair" ;
1549+ const latestPrompt = "LATEST_TURN_76888: answer after dangling label" ;
1550+ const orphanLeaf = {
1551+ id : "orphan-leaf" ,
1552+ parentId : "parent-leaf" ,
1553+ type : "message" ,
1554+ message : { role : "user" , content : olderPrompt , timestamp : 1 } ,
1555+ } ;
1556+ const thinkingEntry = {
1557+ id : "thinking-leaf" ,
1558+ parentId : "orphan-leaf" ,
1559+ type : "thinking_level_change" ,
1560+ thinkingLevel : "high" ,
1561+ } ;
1562+ const labelEntry = {
1563+ id : "label-leaf" ,
1564+ parentId : "thinking-leaf" ,
1565+ type : "label" ,
1566+ targetId : "missing-entry" ,
1567+ label : "stale label" ,
1568+ } ;
1569+ hoisted . sessionManager . getLeafEntry . mockReturnValueOnce ( labelEntry ) ;
1570+ hoisted . sessionManager . getEntry . mockImplementation ( ( id : unknown ) => {
1571+ if ( id === "thinking-leaf" ) {
1572+ return thinkingEntry ;
1573+ }
1574+ return id === "orphan-leaf" ? orphanLeaf : undefined ;
1575+ } ) ;
1576+ hoisted . sessionManager . appendThinkingLevelChange . mockReturnValue ( "replayed-thinking" ) ;
1577+ hoisted . sessionManager . appendLabelChange . mockImplementation ( ( targetId : unknown ) => {
1578+ throw new Error ( `Entry ${ String ( targetId ) } not found` ) ;
1579+ } ) ;
1580+ const seen : { modelInputPrompt ?: string } = { } ;
1581+
1582+ const result = await createContextEngineAttemptRunner ( {
1583+ contextEngine : createContextEngineBootstrapAndAssemble ( ) ,
1584+ sessionKey,
1585+ tempPaths,
1586+ attemptOverrides : {
1587+ prompt : latestPrompt ,
1588+ } ,
1589+ sessionPrompt : async ( session , prompt ) => {
1590+ seen . modelInputPrompt = prompt ;
1591+ const activePrompt = prompt . startsWith ( `${ marker } \n${ olderPrompt } \n\n` )
1592+ ? prompt . slice ( `${ marker } \n${ olderPrompt } \n\n` . length )
1593+ : "missing-active-prompt" ;
1594+ session . messages = [
1595+ ...session . messages ,
1596+ { role : "assistant" , content : `stub-provider-target=${ activePrompt } ` , timestamp : 2 } ,
1597+ ] ;
1598+ } ,
1599+ } ) ;
1600+
1601+ expect ( result . finalPromptText ) . toBe ( `${ marker } \n${ olderPrompt } \n\n${ latestPrompt } ` ) ;
1602+ expect ( seen . modelInputPrompt ) . toBe ( result . finalPromptText ) ;
1603+ const finalAssistant = findRecord (
1604+ requireRecords ( result . messagesSnapshot , "messages snapshot" ) ,
1605+ ( message ) => message . role === "assistant" ,
1606+ "final assistant" ,
1607+ ) ;
1608+ expect ( finalAssistant . content ) . toBe ( `stub-provider-target=${ latestPrompt } ` ) ;
1609+ expect ( hoisted . sessionManager . branch ) . toHaveBeenCalledWith ( "parent-leaf" ) ;
1610+ expect ( hoisted . sessionManager . appendLabelChange ) . not . toHaveBeenCalled ( ) ;
1611+ } ) ;
1612+
1613+ it ( "removes the repaired orphan from assembled history when the context engine appends the active prompt" , async ( ) => {
1614+ const marker =
1615+ "[Queued user message from a previous active turn; preserved as context only. Continue with the active prompt below.]" ;
1616+ const olderPrompt = "OLD_TURN_76888: stale assembled history" ;
1617+ const latestPrompt = "LATEST_TURN_76888: active assembled prompt" ;
1618+ hoisted . sessionManager . getLeafEntry . mockReturnValueOnce ( {
1619+ id : "orphan-leaf" ,
1620+ parentId : "parent-leaf" ,
1621+ type : "message" ,
1622+ message : { role : "user" , content : olderPrompt , timestamp : 1 } ,
1623+ } ) ;
1624+ const seen : {
1625+ prompt ?: string ;
1626+ assembledPrompt ?: string ;
1627+ assembledMessages ?: AgentMessage [ ] ;
1628+ messages ?: AgentMessage [ ] ;
1629+ } = { } ;
1630+
1631+ await createContextEngineAttemptRunner ( {
1632+ contextEngine : createTestContextEngine ( {
1633+ bootstrap : async ( ) => ( { bootstrapped : true } ) ,
1634+ assemble : async ( { messages, prompt } : { messages : AgentMessage [ ] ; prompt ?: string } ) => {
1635+ seen . assembledPrompt = prompt ;
1636+ seen . assembledMessages = [ ...messages ] ;
1637+ return {
1638+ messages : [
1639+ ...messages ,
1640+ { role : "user" , content : latestPrompt , timestamp : 2 } as AgentMessage ,
1641+ ] ,
1642+ estimatedTokens : 1 ,
1643+ } ;
1644+ } ,
1645+ } ) ,
1646+ sessionKey,
1647+ tempPaths,
1648+ sessionMessages : [ { role : "user" , content : olderPrompt , timestamp : 1 } as AgentMessage ] ,
1649+ sessionMessagesAfterRepair : [ ] ,
1650+ attemptOverrides : {
1651+ prompt : latestPrompt ,
1652+ } ,
1653+ sessionPrompt : async ( session , prompt ) => {
1654+ seen . prompt = prompt ;
1655+ seen . messages = [ ...session . messages ] as AgentMessage [ ] ;
1656+ session . messages = [
1657+ ...session . messages ,
1658+ { role : "assistant" , content : "done" , timestamp : 3 } ,
1659+ ] ;
1660+ } ,
1661+ } ) ;
1662+
1663+ expect ( seen . prompt ) . toBe ( `${ marker } \n${ olderPrompt } \n\n${ latestPrompt } ` ) ;
1664+ expect ( seen . assembledPrompt ) . toBe ( seen . prompt ) ;
1665+ expect ( JSON . stringify ( seen . assembledMessages ) ) . not . toContain ( olderPrompt ) ;
1666+ expect ( JSON . stringify ( seen . messages ) ) . not . toContain ( olderPrompt ) ;
1667+ expect ( JSON . stringify ( seen . messages ) ) . toContain ( latestPrompt ) ;
1668+ expect ( hoisted . sessionManager . branch ) . toHaveBeenCalledWith ( "parent-leaf" ) ;
1669+ } ) ;
1670+
13701671 it ( "keeps hidden runtime context hidden when orphan repair merges a transcript prompt" , async ( ) => {
13711672 hoisted . sessionManager . getLeafEntry . mockReturnValueOnce ( {
13721673 id : "orphan-leaf" ,
0 commit comments