@@ -398,4 +398,313 @@ describe("commitment extraction runtime", () => {
398398 ) ;
399399 expect ( processed ) . toBe ( DEFAULT_COMMITMENT_EXTRACTION_QUEUE_MAX_ITEMS ) ;
400400 } ) ;
401+
402+ function mapBatchToCandidates ( { items } : { items : CommitmentExtractionItem [ ] } ) {
403+ return {
404+ candidates : items . map ( ( item , index ) => ( {
405+ itemId : item . itemId ,
406+ kind : "event_check_in" as const ,
407+ sensitivity : "routine" as const ,
408+ source : "inferred_user_context" as const ,
409+ reason : `Follow up ${ index + 1 } ` ,
410+ suggestedText : `How did item ${ index + 1 } go?` ,
411+ dedupeKey : `event:${ item . sourceMessageId ?? index } ` ,
412+ confidence : 0.93 ,
413+ dueWindow : {
414+ earliest : "2026-04-30T17:00:00.000Z" ,
415+ latest : "2026-04-30T23:00:00.000Z" ,
416+ timezone : "America/Los_Angeles" ,
417+ } ,
418+ } ) ) ,
419+ } ;
420+ }
421+
422+ it ( "restores and reprocesses a batch after a non-terminal extractor failure" , async ( ) => {
423+ const cfg = await createConfig ( ) ;
424+ let attempts = 0 ;
425+ const extractBatch = vi . fn ( async ( params : { items : CommitmentExtractionItem [ ] } ) => {
426+ attempts += 1 ;
427+ if ( attempts === 1 ) {
428+ throw new Error ( "transient extraction failure" ) ;
429+ }
430+ return mapBatchToCandidates ( params ) ;
431+ } ) ;
432+ configureCommitmentExtractionRuntime ( {
433+ forceInTests : true ,
434+ extractBatch,
435+ setTimer : ( ) => ( { unref ( ) { } } ) as ReturnType < typeof setTimeout > ,
436+ clearTimer : ( ) => undefined ,
437+ } ) ;
438+
439+ expect (
440+ enqueueCommitmentExtraction ( {
441+ cfg,
442+ nowMs,
443+ agentId : "main" ,
444+ sessionKey : "agent:main:telegram:user-1" ,
445+ channel : "telegram" ,
446+ sourceMessageId : "m1" ,
447+ userText : "I have an interview tomorrow." ,
448+ assistantText : "Good luck." ,
449+ } ) ,
450+ ) . toBe ( true ) ;
451+ expect (
452+ enqueueCommitmentExtraction ( {
453+ cfg,
454+ nowMs : nowMs + 1 ,
455+ agentId : "main" ,
456+ sessionKey : "agent:main:telegram:user-1" ,
457+ channel : "telegram" ,
458+ sourceMessageId : "m2" ,
459+ userText : "I have a dentist appointment tomorrow." ,
460+ assistantText : "Hope it goes smoothly." ,
461+ } ) ,
462+ ) . toBe ( true ) ;
463+
464+ // First drain: the extractor throws a non-terminal error and nothing persists.
465+ await expect ( drainCommitmentExtractionQueue ( ) ) . rejects . toThrow ( "transient extraction failure" ) ;
466+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 1 ) ;
467+ const emptyStore = await loadCommitmentStore ( ) ;
468+ expect ( emptyStore . commitments ) . toHaveLength ( 0 ) ;
469+
470+ // Retry: the restored batch is reprocessed once, in the same order, with no
471+ // duplicate persistence or extraction.
472+ await expect ( drainCommitmentExtractionQueue ( ) ) . resolves . toBe ( 2 ) ;
473+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 2 ) ;
474+
475+ const firstCallIds = extractBatch . mock . calls [ 0 ] ?. [ 0 ] . items . map ( ( item ) => item . itemId ) ;
476+ const retryCallIds = extractBatch . mock . calls [ 1 ] ?. [ 0 ] . items . map ( ( item ) => item . itemId ) ;
477+ expect ( retryCallIds ) . toEqual ( firstCallIds ) ;
478+
479+ const store = await loadCommitmentStore ( ) ;
480+ expect ( store . commitments . map ( ( commitment ) => commitment . dedupeKey ) ) . toEqual ( [
481+ "event:m1" ,
482+ "event:m2" ,
483+ ] ) ;
484+
485+ // A third drain has nothing left to do: no duplicate reprocessing.
486+ await expect ( drainCommitmentExtractionQueue ( ) ) . resolves . toBe ( 0 ) ;
487+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 2 ) ;
488+ } ) ;
489+
490+ it ( "restores a failed batch to the front, preserving order across batches" , async ( ) => {
491+ const cfg = await createConfig ( ) ;
492+ const seenOrder : string [ ] = [ ] ;
493+ let attempts = 0 ;
494+ const extractBatch = vi . fn ( async ( { items } : { items : CommitmentExtractionItem [ ] } ) => {
495+ attempts += 1 ;
496+ if ( attempts === 1 ) {
497+ // Fail the first batch only; record nothing so order reflects success runs.
498+ throw new Error ( "transient extraction failure" ) ;
499+ }
500+ for ( const item of items ) {
501+ seenOrder . push ( item . sourceMessageId ?? "" ) ;
502+ }
503+ return { candidates : [ ] } ;
504+ } ) ;
505+ configureCommitmentExtractionRuntime ( {
506+ forceInTests : true ,
507+ extractBatch,
508+ setTimer : ( ) => ( { unref ( ) { } } ) as ReturnType < typeof setTimeout > ,
509+ clearTimer : ( ) => undefined ,
510+ } ) ;
511+
512+ // Enqueue more than one batch (batchMaxItems = 8) so the restored batch must
513+ // land ahead of the tail rather than being appended.
514+ const total = 10 ;
515+ for ( let index = 0 ; index < total ; index += 1 ) {
516+ expect (
517+ enqueueCommitmentExtraction ( {
518+ cfg,
519+ nowMs : nowMs + index ,
520+ agentId : "main" ,
521+ sessionKey : "agent:main:telegram:user-1" ,
522+ channel : "telegram" ,
523+ sourceMessageId : `m${ index } ` ,
524+ userText : `Commitment candidate ${ index } ` ,
525+ assistantText : "I will follow up." ,
526+ } ) ,
527+ ) . toBe ( true ) ;
528+ }
529+
530+ await expect ( drainCommitmentExtractionQueue ( ) ) . rejects . toThrow ( "transient extraction failure" ) ;
531+ await expect ( drainCommitmentExtractionQueue ( ) ) . resolves . toBe ( total ) ;
532+
533+ const expectedOrder = Array . from ( { length : total } , ( _v , index ) => `m${ index } ` ) ;
534+ expect ( seenOrder ) . toEqual ( expectedOrder ) ;
535+ } ) ;
536+
537+ it ( "keeps the existing drop/stop behavior on terminal extraction failures" , async ( ) => {
538+ const cfg = await createConfig ( ) ;
539+ const extractBatch = vi . fn ( async ( ) => {
540+ throw new Error ( 'No API key found for provider "openai".' ) ;
541+ } ) ;
542+ configureCommitmentExtractionRuntime ( {
543+ forceInTests : true ,
544+ extractBatch,
545+ setTimer : ( ) => ( { unref ( ) { } } ) as ReturnType < typeof setTimeout > ,
546+ clearTimer : ( ) => undefined ,
547+ } ) ;
548+
549+ expect (
550+ enqueueCommitmentExtraction ( {
551+ cfg,
552+ nowMs,
553+ agentId : "main" ,
554+ sessionKey : "agent:main:telegram:user-1" ,
555+ channel : "telegram" ,
556+ sourceMessageId : "m1" ,
557+ userText : "I have an interview tomorrow." ,
558+ assistantText : "Good luck." ,
559+ } ) ,
560+ ) . toBe ( true ) ;
561+
562+ await expect ( drainCommitmentExtractionQueue ( ) ) . rejects . toThrow ( "No API key found" ) ;
563+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 1 ) ;
564+
565+ // Terminal failures drop the agent's queued work; a retry must not reprocess
566+ // the dropped batch.
567+ await expect ( drainCommitmentExtractionQueue ( ) ) . resolves . toBe ( 0 ) ;
568+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 1 ) ;
569+ } ) ;
570+
571+ it ( "schedules a retry when a non-terminal failure leaves the queue full" , async ( ) => {
572+ const cfg = await createConfig ( ) ;
573+ const scheduled : Array < ( ) => void > = [ ] ;
574+ let attempts = 0 ;
575+ const extractBatch = vi . fn (
576+ async ( _params : {
577+ items : CommitmentExtractionItem [ ] ;
578+ } ) : Promise < CommitmentExtractionBatchResult > => {
579+ attempts += 1 ;
580+ if ( attempts === 1 ) {
581+ throw new Error ( "transient extraction failure" ) ;
582+ }
583+ return { candidates : [ ] } ;
584+ } ,
585+ ) ;
586+ configureCommitmentExtractionRuntime ( {
587+ forceInTests : true ,
588+ extractBatch,
589+ setTimer : ( callback ) => {
590+ scheduled . push ( callback ) ;
591+ return { unref ( ) { } } as ReturnType < typeof setTimeout > ;
592+ } ,
593+ clearTimer : ( ) => undefined ,
594+ } ) ;
595+
596+ for ( let index = 0 ; index < DEFAULT_COMMITMENT_EXTRACTION_QUEUE_MAX_ITEMS ; index += 1 ) {
597+ expect (
598+ enqueueCommitmentExtraction ( {
599+ cfg,
600+ nowMs : nowMs + index ,
601+ agentId : "main" ,
602+ sessionKey : "agent:main:telegram:user-1" ,
603+ channel : "telegram" ,
604+ sourceMessageId : `m${ index } ` ,
605+ userText : `Commitment candidate ${ index } ` ,
606+ assistantText : "I will follow up." ,
607+ } ) ,
608+ ) . toBe ( true ) ;
609+ }
610+ // The single-slot debounce schedules exactly one drain while filling.
611+ expect ( scheduled ) . toHaveLength ( 1 ) ;
612+
613+ // Fire the scheduled drain: the first batch fails (non-terminal) and is
614+ // restored, leaving the queue full again with no pending timer.
615+ scheduled [ 0 ] ?.( ) ;
616+ await vi . waitFor ( ( ) => {
617+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 1 ) ;
618+ } ) ;
619+ await new Promise < void > ( ( resolve ) => {
620+ setTimeout ( resolve , 0 ) ;
621+ } ) ;
622+
623+ // A new request is dropped because the queue is full, but the restored batch
624+ // must still get a retry scheduled, otherwise it would be stuck forever.
625+ expect (
626+ enqueueCommitmentExtraction ( {
627+ cfg,
628+ nowMs : nowMs + DEFAULT_COMMITMENT_EXTRACTION_QUEUE_MAX_ITEMS ,
629+ agentId : "main" ,
630+ sessionKey : "agent:main:telegram:user-1" ,
631+ channel : "telegram" ,
632+ sourceMessageId : "overflow" ,
633+ userText : "Overflow candidate" ,
634+ assistantText : "I will follow up." ,
635+ } ) ,
636+ ) . toBe ( false ) ;
637+ expect ( scheduled ) . toHaveLength ( 2 ) ;
638+
639+ // The drain is healthy after the failure: the full queue reprocesses cleanly.
640+ await expect ( drainCommitmentExtractionQueue ( ) ) . resolves . toBe (
641+ DEFAULT_COMMITMENT_EXTRACTION_QUEUE_MAX_ITEMS ,
642+ ) ;
643+ } ) ;
644+
645+ it ( "re-arms the drain after a timer-fired non-terminal failure with no later enqueue" , async ( ) => {
646+ const cfg = await createConfig ( ) ;
647+ const scheduled : Array < ( ) => void > = [ ] ;
648+ let attempts = 0 ;
649+ const extractBatch = vi . fn ( async ( params : { items : CommitmentExtractionItem [ ] } ) => {
650+ attempts += 1 ;
651+ if ( attempts === 1 ) {
652+ throw new Error ( "transient extraction failure" ) ;
653+ }
654+ return mapBatchToCandidates ( params ) ;
655+ } ) ;
656+ configureCommitmentExtractionRuntime ( {
657+ forceInTests : true ,
658+ extractBatch,
659+ setTimer : ( callback ) => {
660+ scheduled . push ( callback ) ;
661+ return { unref ( ) { } } as ReturnType < typeof setTimeout > ;
662+ } ,
663+ clearTimer : ( ) => undefined ,
664+ } ) ;
665+
666+ expect (
667+ enqueueCommitmentExtraction ( {
668+ cfg,
669+ nowMs,
670+ agentId : "main" ,
671+ sessionKey : "agent:main:telegram:user-1" ,
672+ channel : "telegram" ,
673+ sourceMessageId : "m1" ,
674+ userText : "I have an interview tomorrow." ,
675+ assistantText : "Good luck." ,
676+ } ) ,
677+ ) . toBe ( true ) ;
678+ // The enqueue schedules exactly one drain via the single-slot debounce.
679+ expect ( scheduled ) . toHaveLength ( 1 ) ;
680+
681+ // Fire the scheduled drain. The timer callback clears the pending timer first,
682+ // then the extractor throws a non-terminal error and the batch is restored.
683+ scheduled [ 0 ] ?.( ) ;
684+ await vi . waitFor ( ( ) => {
685+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 1 ) ;
686+ } ) ;
687+ await new Promise < void > ( ( resolve ) => {
688+ setTimeout ( resolve , 0 ) ;
689+ } ) ;
690+
691+ // Regression guard for the timer-fired-failure path: with no later enqueue to
692+ // reschedule it, the restored batch must still have a fresh drain armed, or it
693+ // would sit only in memory and be lost on process exit.
694+ expect ( scheduled ) . toHaveLength ( 2 ) ;
695+
696+ // Firing that re-armed drain reprocesses the same batch and persists it.
697+ scheduled [ 1 ] ?.( ) ;
698+ await vi . waitFor ( ( ) => {
699+ expect ( extractBatch ) . toHaveBeenCalledTimes ( 2 ) ;
700+ } ) ;
701+ await new Promise < void > ( ( resolve ) => {
702+ setTimeout ( resolve , 0 ) ;
703+ } ) ;
704+
705+ const store = await loadCommitmentStore ( ) ;
706+ expect ( store . commitments . map ( ( commitment ) => commitment . dedupeKey ) ) . toEqual ( [ "event:m1" ] ) ;
707+ // The successful drain empties the queue, so no further retry is armed.
708+ expect ( scheduled ) . toHaveLength ( 2 ) ;
709+ } ) ;
401710} ) ;
0 commit comments