@@ -5,21 +5,24 @@ import {
55 abortActiveReplyRuns ,
66 abortReplyRunBySessionId ,
77 expireStaleReplyRunBySessionId ,
8- forceClearReplyRunBySessionId ,
8+ forceClearReplyOperation ,
99 isReplyRunEvidenceStaleBySessionId ,
1010 isReplyRunActiveForSessionId ,
1111 isReplyRunAbortableForCompaction ,
1212 isReplyRunStreamingForSessionId ,
1313 listActiveReplyRunSessionIds ,
1414 queueReplyRunMessage ,
15+ resolveActiveReplyOperationForSessionId ,
16+ resolveActiveReplyRunSessionId ,
1517 resolveReplyBackendQueueMessageMismatch ,
1618 resolveReplyRunPhaseForSessionId ,
19+ type ReplyOperation ,
1720 type ReplyOperationPhase ,
1821 waitForReplyRunEndBySessionId ,
1922} from "../../auto-reply/reply/reply-run-registry.js" ;
2023import { getRuntimeConfig } from "../../config/io.js" ;
2124import { resolveStorePath } from "../../config/sessions/paths.js" ;
22- import { updateSessionEntry } from "../../config/sessions/session-accessor.js" ;
25+ import { loadSessionEntry , updateSessionEntry } from "../../config/sessions/session-accessor.js" ;
2326import {
2427 getDiagnosticSessionActivitySnapshot ,
2528 markDiagnosticEmbeddedRunEnded ,
@@ -772,6 +775,8 @@ export async function abortAndDrainEmbeddedAgentRun(params: {
772775 reason ?: string ;
773776} ) : Promise < AbortAndDrainEmbeddedAgentRunResult > {
774777 const settleMs = params . settleMs ?? 15_000 ;
778+ const embeddedRunHandle = ACTIVE_EMBEDDED_RUNS . get ( params . sessionId ) ;
779+ const replyOperation = resolveActiveReplyOperationForSessionId ( params . sessionId ) ;
775780 // Recovery is a staleness expiry: stamp run_stalled on the reply operation
776781 // BEFORE any handle abort, or the run loop's abort handler re-enters
777782 // abortByUser and misattributes the watchdog kill to the user.
@@ -789,55 +794,90 @@ export async function abortAndDrainEmbeddedAgentRun(params: {
789794 }
790795 const aborted = abortEmbeddedAgentRun ( params . sessionId ) || expiredReplyRun ;
791796 const drained = aborted ? await waitForEmbeddedAgentRunEnd ( params . sessionId , settleMs ) : false ;
797+ const persistenceSnapshot =
798+ params . forceClear === true && params . sessionKey
799+ ? tryLoadForceClearSessionSnapshot ( params . sessionKey )
800+ : undefined ;
792801 const forceCleared =
793802 params . forceClear === true && ( ! aborted || ! drained )
794- ? forceClearEmbeddedAgentRun ( params . sessionId , params . sessionKey , params . reason )
803+ ? forceClearEmbeddedAgentRun (
804+ params . sessionId ,
805+ embeddedRunHandle ,
806+ replyOperation ,
807+ params . sessionKey ,
808+ params . reason ,
809+ )
795810 : false ;
796- if ( forceCleared && params . sessionKey ) {
811+ if ( forceCleared && params . sessionKey && persistenceSnapshot ) {
797812 await persistForceClearedEmbeddedRunTerminalState ( {
813+ ...persistenceSnapshot ,
798814 sessionId : params . sessionId ,
799815 sessionKey : params . sessionKey ,
800816 } ) ;
801817 }
802818 return { aborted, drained, forceCleared } ;
803819}
804820
805- /**
806- * Patches the session entry with terminal state after a force-clear.
807- * This keeps the in-memory registry and the persisted SQLite row consistent,
808- * so upstream recovery paths (e.g. isRecoverableTerminalSessionStatus) can
809- * recognize the session as recoverable without waiting for the next heartbeat.
810- */
821+ type ForceClearSessionSnapshot = {
822+ startedAt ?: number ;
823+ storePath : string ;
824+ updatedAt : number ;
825+ } ;
826+
827+ function tryLoadForceClearSessionSnapshot (
828+ sessionKey : string ,
829+ ) : ForceClearSessionSnapshot | undefined {
830+ try {
831+ const cfg = getRuntimeConfig ( ) ;
832+ const agentId = resolveAgentIdFromSessionKey ( sessionKey ) ;
833+ const storePath = resolveStorePath ( cfg . session ?. store , { agentId } ) ;
834+ const entry = loadSessionEntry ( { sessionKey, storePath } ) ;
835+ if ( ! entry || entry . status !== "running" ) {
836+ return undefined ;
837+ }
838+ return {
839+ ...( entry . startedAt === undefined ? { } : { startedAt : entry . startedAt } ) ,
840+ storePath,
841+ updatedAt : entry . updatedAt ,
842+ } ;
843+ } catch ( err ) {
844+ diag . warn (
845+ `load force-clear session snapshot failed: sessionKey=${ sessionKey } error=${ String ( err ) } ` ,
846+ ) ;
847+ return undefined ;
848+ }
849+ }
850+
851+ /** Persists terminal state when a forced registry clear cannot emit normal lifecycle. */
811852async function persistForceClearedEmbeddedRunTerminalState ( params : {
812853 sessionId : string ;
813854 sessionKey : string ;
855+ startedAt ?: number ;
856+ storePath : string ;
857+ updatedAt : number ;
814858} ) : Promise < void > {
815859 try {
816- const cfg = getRuntimeConfig ( ) ;
817- const agentId = resolveAgentIdFromSessionKey ( params . sessionKey ) ;
818- const storePath = resolveStorePath ( cfg . session ?. store , { agentId } ) ;
819860 await updateSessionEntry (
820- { sessionKey : params . sessionKey , storePath } ,
861+ { sessionKey : params . sessionKey , storePath : params . storePath } ,
821862 ( entry ) => {
822- // Guard: skip the write when this session key now maps to a different session.
823- // This check runs inside the store's serialized write lock, so a replacement
824- // session cannot interleave between the read and the conditional patch.
825- // A stale force-clear recovery that arrives after a new session has claimed
826- // the same key must not mark the replacement as killed.
827- if ( entry . sessionId !== params . sessionId ) {
863+ // A replacement can reuse the session id; bind this patch to both owners' exact snapshot.
864+ if (
865+ ACTIVE_EMBEDDED_RUNS . has ( params . sessionId ) ||
866+ ACTIVE_EMBEDDED_RUN_SESSION_IDS_BY_KEY . has ( params . sessionKey ) ||
867+ isReplyRunActiveForSessionId ( params . sessionId ) ||
868+ resolveActiveReplyRunSessionId ( params . sessionKey ) !== undefined ||
869+ entry . sessionId !== params . sessionId ||
870+ entry . status !== "running" ||
871+ entry . updatedAt !== params . updatedAt ||
872+ entry . startedAt !== params . startedAt
873+ ) {
828874 return null ;
829875 }
830876 const endedAt = Date . now ( ) ;
831- const startedAt = entry . startedAt ;
832- const runtimeMs =
833- typeof startedAt === "number" && startedAt > 0 && startedAt <= endedAt
834- ? endedAt - startedAt
835- : undefined ;
836877 return {
837878 status : "killed" ,
838879 abortedLastRun : true ,
839880 endedAt,
840- runtimeMs,
841881 updatedAt : endedAt ,
842882 } ;
843883 } ,
@@ -848,6 +888,7 @@ async function persistForceClearedEmbeddedRunTerminalState(params: {
848888 } ,
849889 ) ;
850890 } catch ( err ) {
891+ // Registry ownership is already gone; preserve the completed recovery result.
851892 diag . warn (
852893 `persist force-cleared terminal state failed: sessionKey=${ params . sessionKey } error=${ String ( err ) } ` ,
853894 ) ;
@@ -957,12 +998,14 @@ export function clearActiveEmbeddedRun(
957998
958999function forceClearEmbeddedAgentRun (
9591000 sessionId : string ,
1001+ expectedHandle : EmbeddedAgentQueueHandle | undefined ,
1002+ expectedReplyOperation : ReplyOperation | undefined ,
9601003 sessionKey ?: string ,
9611004 reason = "stuck_recovery" ,
9621005) : boolean {
9631006 let cleared = false ;
9641007 const handle = ACTIVE_EMBEDDED_RUNS . get ( sessionId ) ;
965- if ( handle ) {
1008+ if ( handle && handle === expectedHandle ) {
9661009 ACTIVE_EMBEDDED_RUNS . delete ( sessionId ) ;
9671010 clearEmbeddedRunAbortability ( handle ) ;
9681011 ACTIVE_EMBEDDED_RUN_SNAPSHOTS . delete ( sessionId ) ;
@@ -974,7 +1017,10 @@ function forceClearEmbeddedAgentRun(
9741017 cleared = true ;
9751018 }
9761019 const cause = new Error ( `Embedded run force-cleared by ${ reason } ` ) ;
977- return forceClearReplyRunBySessionId ( sessionId , cause ) || cleared ;
1020+ return (
1021+ ( expectedReplyOperation ? forceClearReplyOperation ( expectedReplyOperation , cause ) : false ) ||
1022+ cleared
1023+ ) ;
9781024}
9791025
9801026const testing = {
0 commit comments