@@ -223,7 +223,7 @@ async function resolveTranscriptLeafIdFromTrailingControls(
223223 return { appendMode : "active" } ;
224224}
225225
226- async function readTranscriptLeafInfo ( transcriptPath : string ) : Promise < TranscriptLeafInfo > {
226+ async function readTranscriptLeafInfoForward ( transcriptPath : string ) : Promise < TranscriptLeafInfo > {
227227 let leafId : string | undefined ;
228228 let hasParentLinkedEntries = false ;
229229 let nonSessionEntryCount = 0 ;
@@ -266,6 +266,57 @@ async function readTranscriptLeafInfo(transcriptPath: string): Promise<Transcrip
266266 } ;
267267}
268268
269+ async function readTranscriptLeafInfo ( transcriptPath : string ) : Promise < TranscriptLeafInfo > {
270+ let latestEntryId : string | undefined ;
271+ for await ( const line of streamSessionTranscriptLinesReverse ( transcriptPath ) ) {
272+ const lineInfo = readTranscriptLineInfo ( line ) ;
273+ if ( ! lineInfo . entryId ) {
274+ continue ;
275+ }
276+ if ( lineInfo . invalidLeafControl ) {
277+ break ;
278+ }
279+ if ( lineInfo . leafControl ) {
280+ if ( latestEntryId ) {
281+ const valid = await validateTranscriptLeafControlReferences ( {
282+ transcriptPath,
283+ leafControlId : lineInfo . entryId ,
284+ leafControl : lineInfo . leafControl ,
285+ } ) ;
286+ if ( ! valid ) {
287+ break ;
288+ }
289+ return {
290+ leafId : latestEntryId ,
291+ appendMode : lineInfo . leafControl . appendMode === "side" ? "side" : "active" ,
292+ hasParentLinkedEntries : true ,
293+ nonSessionEntryCount : 0 ,
294+ } ;
295+ }
296+ const resolvedLeaf = await resolveTranscriptLeafIdFromTrailingControls ( transcriptPath ) ;
297+ return {
298+ ...( resolvedLeaf . leafId ? { leafId : resolvedLeaf . leafId } : { } ) ,
299+ appendMode : resolvedLeaf . appendMode ,
300+ hasParentLinkedEntries : true ,
301+ nonSessionEntryCount : 0 ,
302+ } ;
303+ }
304+ latestEntryId ??= lineInfo . entryId ;
305+ if ( lineInfo . isCanonicalEntry && lineInfo . hasParentLinkedEntry ) {
306+ return {
307+ leafId : latestEntryId ,
308+ appendMode : lineInfo . appendMode === "side" ? "side" : "active" ,
309+ hasParentLinkedEntries : true ,
310+ nonSessionEntryCount : 0 ,
311+ } ;
312+ }
313+ // A latest entry without parent linkage may be a legacy linear transcript.
314+ // Fall back to the full scan only when migration detection needs it.
315+ break ;
316+ }
317+ return await readTranscriptLeafInfoForward ( transcriptPath ) ;
318+ }
319+
269320async function migrateLinearTranscriptToParentLinked ( transcriptPath : string ) : Promise < {
270321 leafId ?: string ;
271322} > {
0 commit comments