@@ -28,6 +28,10 @@ import { resolveWrapupProtectedTailBoundary } from "@magic-context/core/hooks/ma
2828import { setRawMessageProvider } from "@magic-context/core/hooks/magic-context/read-session-chunk" ;
2929import type { SubagentRunner } from "@magic-context/core/shared/subagent-runner" ;
3030import { applyDeferredPiCompactionMarker } from "../compaction-marker-manager-pi" ;
31+ import {
32+ signalPiDeferredHistoryRefresh ,
33+ signalPiDeferredMaterialization ,
34+ } from "../context-handler" ;
3135import { ensureProjectRegisteredFromPiDirectory } from "../embedding-bootstrap" ;
3236import { runPiHistorian } from "../pi-historian-runner" ;
3337import { isPiRecompInFlight } from "../pi-recomp-runner" ;
@@ -201,8 +205,32 @@ export async function runPiWrapup(
201205 ) ;
202206 }
203207
208+ let ownershipLost = false ;
209+ const ownershipLostReason =
210+ "another process took over this session's wrapup" ;
211+ const markOwnershipLost = ( ) : void => {
212+ if ( ownershipLost ) return ;
213+ ownershipLost = true ;
214+ } ;
215+ const renewWrapupMarker = (
216+ updates : Parameters < typeof updateWrapupInProgress > [ 3 ] ,
217+ ) : boolean => {
218+ const updated = updateWrapupInProgress (
219+ deps . db ,
220+ sessionId ,
221+ holderId ,
222+ updates ,
223+ ) ;
224+ if ( ! updated ) {
225+ markOwnershipLost ( ) ;
226+ return false ;
227+ }
228+ return true ;
229+ } ;
204230 const renewal = setInterval ( ( ) => {
205- updateWrapupInProgress ( deps . db , sessionId , holderId , { } ) ;
231+ renewWrapupMarker ( {
232+ lastCompartmentEnd : getLastCompartmentEndMessage ( deps . db , sessionId ) ,
233+ } ) ;
206234 } , 60_000 ) ;
207235 try {
208236 sendCtxStatusMessage ( pi , {
@@ -218,6 +246,23 @@ export async function runPiWrapup(
218246 let failure : string | null = null ;
219247
220248 for ( ; ; ) {
249+ if ( ownershipLost ) {
250+ failure = `${ ownershipLostReason } ; wrapped up through message ${ lastEnd } . Run /ctx-wrapup again to continue.` ;
251+ break ;
252+ }
253+ if (
254+ ! renewWrapupMarker ( {
255+ chunkIndex,
256+ lastCompartmentEnd : getLastCompartmentEndMessage (
257+ deps . db ,
258+ sessionId ,
259+ ) ,
260+ } )
261+ ) {
262+ failure = `${ ownershipLostReason } ; wrapped up through message ${ lastEnd } . Run /ctx-wrapup again to continue.` ;
263+ break ;
264+ }
265+
221266 const plan = resolveWrapupProtectedTailBoundary ( {
222267 db : deps . db ,
223268 sessionId,
@@ -234,18 +279,26 @@ export async function runPiWrapup(
234279 if ( plan . snapshot . eligibleEndOrdinal <= plan . snapshot . offset ) break ;
235280
236281 chunkIndex += 1 ;
237- updateWrapupInProgress ( deps . db , sessionId , holderId , {
238- chunkIndex,
239- lastCompartmentEnd : getLastCompartmentEndMessage ( deps . db , sessionId ) ,
240- targetEligibleEndOrdinal : plan . targetEligibleEndOrdinal ,
241- expectedChunks : Math . max (
282+ if (
283+ ! renewWrapupMarker ( {
242284 chunkIndex,
243- estimateChunks (
244- plan . snapshot . trueRawEligibleTokens ,
245- deps . historianChunkTokens ,
285+ lastCompartmentEnd : getLastCompartmentEndMessage (
286+ deps . db ,
287+ sessionId ,
246288 ) ,
247- ) ,
248- } ) ;
289+ targetEligibleEndOrdinal : plan . targetEligibleEndOrdinal ,
290+ expectedChunks : Math . max (
291+ chunkIndex ,
292+ estimateChunks (
293+ plan . snapshot . trueRawEligibleTokens ,
294+ deps . historianChunkTokens ,
295+ ) ,
296+ ) ,
297+ } )
298+ ) {
299+ failure = `${ ownershipLostReason } ; wrapped up through message ${ lastEnd } . Run /ctx-wrapup again to continue.` ;
300+ break ;
301+ }
249302 sendCtxStatusMessage ( pi , {
250303 title : "/ctx-wrapup" ,
251304 text : `## Magic Wrapup\n\nChunk ${ chunkIndex } : wrapping messages ${ plan . snapshot . offset } -${ plan . snapshot . eligibleEndOrdinal - 1 } (~${ plan . snapshot . trueRawEligibleTokens . toLocaleString ( ) } eligible tokens remain).` ,
@@ -255,8 +308,14 @@ export async function runPiWrapup(
255308 const leaseHolder = await acquireCompartmentLeaseEventually (
256309 deps . db ,
257310 sessionId ,
258- holderId ,
311+ renewWrapupMarker ,
259312 ) ;
313+ if ( ! leaseHolder ) {
314+ failure = ownershipLost
315+ ? `${ ownershipLostReason } ; wrapped up through message ${ lastEnd } . Run /ctx-wrapup again to continue.`
316+ : "Another Magic Context rebuild started while wrapup was waiting. Run /ctx-wrapup again to continue." ;
317+ break ;
318+ }
260319 const leaseRenewal = setInterval ( ( ) => {
261320 renewCompartmentLease ( deps . db , sessionId , leaseHolder ) ;
262321 } , COMPARTMENT_LEASE_RENEWAL_MS ) ;
@@ -303,9 +362,14 @@ export async function runPiWrapup(
303362 } ) ,
304363 ensureProjectRegistered : ensureProjectRegisteredFromPiDirectory ,
305364 forceDrainQuota : true ,
306- forceKeepLastCompartment : plan . finalChunk ,
307- onPublished : ( ) =>
308- updateStatusLine ( ctx , { db : deps . db , projectIdentity : ctx . cwd } ) ,
365+ // The runner applies this only to the actual final chunk; token-capped
366+ // chunks are downgraded based on readSessionChunk().hasMore.
367+ forceKeepLastCompartment : true ,
368+ onPublished : ( ) => {
369+ updateStatusLine ( ctx , { db : deps . db , projectIdentity : ctx . cwd } ) ;
370+ signalPiDeferredHistoryRefresh ( sessionId ) ;
371+ signalPiDeferredMaterialization ( sessionId ) ;
372+ } ,
309373 } ) ;
310374 } finally {
311375 clearInterval ( leaseRenewal ) ;
@@ -369,13 +433,15 @@ function resolvePiContextLimit(ctx: ExtensionCommandContext): number {
369433async function acquireCompartmentLeaseEventually (
370434 db : ContextDatabase ,
371435 sessionId : string ,
372- wrapupHolderId : string ,
373- ) : Promise < string > {
436+ renewWrapupMarker : (
437+ updates : Parameters < typeof updateWrapupInProgress > [ 3 ] ,
438+ ) => boolean ,
439+ ) : Promise < string | null > {
374440 for ( ; ; ) {
375441 const holderId = crypto . randomUUID ( ) ;
376442 const lease = acquireCompartmentLease ( db , sessionId , holderId ) ;
377443 if ( lease ) return holderId ;
378- updateWrapupInProgress ( db , sessionId , wrapupHolderId , { } ) ;
444+ if ( ! renewWrapupMarker ( { } ) ) return null ;
379445 await new Promise ( ( resolve ) => setTimeout ( resolve , LEASE_WAIT_MS ) ) ;
380446 }
381447}
0 commit comments