Skip to content

AI-3594: a scheduled reply wait never misses how the turn ended - #2278

Merged
kanat merged 17 commits into
mainfrom
kanat/ai-3594-reply-wait-reads-the-end
Nov 25, 2026
Merged

kanat merged 17 commits into
mainfrom
kanat/ai-3594-reply-wait-reads-the-end

Conversation

@kanat

@kanat kanat commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Bundles AI-3594, AI-3596 and AI-3598 (from the review of #2191).

Why

A scheduled reply wait learned that the model refused its turn for money only from the agent.Error event that the session sends its watchers. That event can be lost:

  • A watcher drops events once its 256-event buffer is full (watcher.send, internal/session/session.go:551). The conversation channel attaches its watcher before followUpWithin waits behind a busy turn. A dropped refusal then gave a 3-minute wait and delivered (AI-3596).
  • deliverOnThread read the buffer without blocking once the conversation said failed. Session.consume records the event (persisted.Observe) before it broadcasts it, so the event could still be on its way, and the run recorded reply_failed (AI-3594).
  • An attempt cut short while its turn ran (its context cancelled) leaves the turn to end unwatched. The retry reads the reply back as failed and records reply_failed on a text channel or a thread, or delivered in the conversation, though the user got nothing.
  • A conversation retry that found that turn still running recorded delivered at once, before the turn ended (review R1.1).
  • A text channel joined every agent.Responded its watch saw. It attached the watch before followUpWithin waited behind a busy turn, so the busy turn's words were texted as the scheduled reply too (review R1.2).

The conversation recorded the state failed, but not why, so no wait could recover the money code from the state. The tick guard state != "failed" (AI-3598, M7) existed because only the event could say whether the failure was about money, and no test could hit it reliably.

How it works

agent.Error ─> Session.consume
               ├─ persisted.Observe: Commands[id].Failure = err, state = failed
               └─ broadcast ─> watchers (may drop)

reply wait (any channel)
└─ turnRefusal(found, id) = moneyError(found.FollowUpFailure(id))
   ├─ refusal for money -> unpaid: money code, final
   │                        (spend_check_unavailable: retried)
   └─ nil -> the channel's old answer
Wait Before After
followUpInConversation refusal from the event; tick ignored failed; a reply already held settled at once each event or tick reads the state; an ended reply returns turnRefusal; a reply already held is waited out the same
captureReply joined the words of every event its watch saw; refusal from the event runs the follow-up, then reads its own reply back once its turn ends (readBackReply)
readBackReply (text and thread read-back) failed -> reply_failed refusal for money -> its code, else reply_failed
deliverOnThread non-blocking drain of the watch no watch: readBackReply answers

A refusal for money that the session reports to watchers for another command (Session.Report) no longer ends the delivery's turn: only the reply's own recorded failure counts.

What a text channel texts now

captureReply carries the follow-up's reply as the conversation keeps it, the same reply its retry already read back. Against base, on a reply with no turn ahead of it:

Case Base Now
one round (TestATextReplyIsTextedAsItWasOnceItsTurnEnds, the reciting model) user: stretch same
two rounds with the same words, a run of code then the answer (TestATaskTextedBySMSCarriesTheFileItsCodeMade) Done. (the event loop dropped a repeat) Done.\n\nDone., as a thread task texts it (reportReply)
reply cut off before it was written (TestATurnCancelledBeforeItsReplyRunsAgainOnTheRetry) no_reply reply_failed (was cancelled); the retry runs the turn again, as before
non-money failure while watched (Q.2) no_reply, or the words said before it reply_failed, as its retry read it back
a turn still open at the end of a round (the model waits on a tool that never answers) the words before the tool call, after the 2 s settle gap, delivered waits to scheduledReplyWindow, then no_reply; the retry reads it back

Path table

Channels: conversation, text (sms/whatsapp/imessage), thread. "Missed" means the turn ended while no attempt watched it.

End Seen Missed
failed for money money code, final (existing tests) money code, final: TestAConversationTurnRefusedForMoneyUnwatchedFailsUnderTheMoney, TestATextTurnRefusedForMoneyUnwatchedFailsUnderTheMoney, TestAThreadTurnRefusedForMoneyUnwatchedFailsUnderTheMoney
failed, money not checkable spend_check_unavailable, retried (existing) same: TestAConversationTurnRefusedUncheckedUnwatchedIsRetried, TestATextTurnRefusedUncheckedUnwatchedIsRetried
failed, not money conversation delivered; text/thread reply_failed once read back (existing) unchanged (TestAConversationAfterATextChannelIsNotWaitedOnForTheSameTurn, TestATextTurnFailedNotForMoneyIsNotRunAgainOnItsRetry)
cancelled / interrupted / completed unchanged (existing) unchanged

On base dff7498, all six new tests fail: the conversation gives delivered, and text and thread give reply_failed. TestAConversationTurnOutlivesARefusalReportedForAnotherCommand settles on another command's refusal there.

User-facing note

A scheduled task whose turn the model refused for money could end delivered after a 3-minute wait in the conversation, or reply_failed on a text channel or in a thread. This also happened on the retry of an attempt that was cut short while the turn ran. Such a run now fails under the refusal's code (for example insufficient_credits) and is not tried again. spend_check_unavailable is still tried again.

Known gap: the retry reads why the turn failed only while the session that ran it is still open. The failure is kept in memory, so after the conversation is opened again (a router restart or drain, or the end of the session's unwatched grace) the retry still records reply_failed, or delivered in the conversation.

An SMS, WhatsApp or iMessage task now texts only its own reply. Before, a task that came due while another turn ran texted that turn's words too.

Mutations

Round 0: 16 of 22 mutants killed (mutate.py). Review round 1 showed 3 of the 6 survivors were not equivalent. Each mutant below now fails a test:

Mutant Test that kills it
followUpInConversation: if known returns at once TestAConversationRetryWaitsOutTheTurnAnEarlierAttemptBegan
followUpInConversation: followUpWithin error ignored TestAConversationFollowUpTheSessionRefusesIsNotDelivered
replyEnded without interrupted (a regenerate or an edit interrupts the turn, conversation/branches.go:454) TestAReplyEndsHoweverItsTurnEnded
captureReply: the old event loop instead of the read-back TestATextReplyCarriesOnlyItsOwnTurnsWords
captureReply: followUpWithin error ignored TestATextFollowUpTheSessionRefusesFailsWithWhy

The settle-gap and closed-watch survivors went with captureReply's event loop. Still equivalent: followUpInConversation ignoring a closed watch (a session that ends also leaves the reply cancelled, which the tick reads).

Changes

  • internal/conversation: commandRecord.Failure (memory only), set by Observe on agent.Error; Conversation.FollowUpFailure.
  • internal/session: Session.FollowUpFailure.
  • internal/api/scheduled_delivery.go, scheduled_thread_delivery.go: the waits above. spokenOf, madeBy and scheduledReplySettle went with the event loop.
  • Tests in internal/api/scheduled_unpaid_test.go and scheduled_reply_test.go. Four expectations in scheduled_tasks_test.go follow the read-back (table above). The scheduled-tasks skill row.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE

@github-actions github-actions Bot added the docs label Nov 23, 2026

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed #2278 at 1af2ee9, merged onto main 644103a. CI: the PR is a draft, so go and integration were skipped. They run at gh pr ready. Locally on the merged tree: TelnyxUnpaidSuite, ScheduledTasksSuite, and the unit tests of internal/conversation and internal/session pass. The 7 new tests pass 51 times with -race -cpu 1.

[Should fix] R1.4 internal/conversation/conversation.go:168 and commandsIn (conversation.go:1099, not in the diff): Failure lives in memory only, and commandsIn rebuilds the records from the stored messages without it. A retry that finds the conversation reopened still reads a bare failed: reply_failed on a text channel or a thread, delivered in the conversation. This happens after a router restart or drain, or after the 5-minute detached grace ended the session before the 2-minute or 10-minute retry. Yet the PR body ("User-facing note", and "a draining router" under Why) and the skill row say that the retry of a cut-short attempt now fails under the money. Shown by code reading; I did not probe a reopen. Fix: either keep the refusal's code on the stored reply so that commandsIn reads it back, or narrow the body and the skill row to "while the session that ran the turn is still open" and file a ticket for the persistence.

[Nit] R1.6 .claude/skills/scheduled-tasks/SKILL.md:204: the row this PR edits still cites scheduled_delivery.go:334 and :355. deliveryReason is at :346 and unpaid at :390.

Author questions: Q.1 is confirmed and in scope, see R1.2. Q.2 (non-money text failure: no_reply when watched, reply_failed when read back) is pre-existing and outside this PR's goal: ticket.

Checked and sound: Failure is set only when finish("failed") goes ahead (Observe returns early on stopping or a finished reply), and it is read and written under c.mu. Every new command id gets a fresh record, and no other reader of the command records changed. Report's refusal for another command no longer settles a wait. Non-money ends give the same answer as on base: the conversation now settles at once instead of after 3 min. M7 is gone, and the unwatched tests are deterministic.

Verdict: request changes, for R1.1, R1.2, R1.3 and R1.4.

if err := s.followUpWithin(ctx, found, delivery); err != nil {
return err
}
if known {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 A conversation retry that finds the earlier attempt's turn still running settles delivered at once, before the turn ends. So a turn refused for money after this point is recorded delivered, the miss this PR is meant to close. Text and thread retries do wait for a held reply (readBackReply). Probe: attempt 1 is cut short by a ctx cancel while the holding model holds st_run. The retry's deliverOn(conversation) returns nil with the reply state "thinking", on head and on base. Not verified: a real turn refused for money after it started, for example on a later LLM round. Fix: drop this early return and let the loop below wait. An ended held reply settles there on the first tick. This is your surviving mutant conv-known-ignored, and the suite passes with it. Test row (fails on head, passes with the fix): hold the turn with heldConversationTurn(ctx), call cancel(), check <-done is context.Canceled, then run deliverOn again in a goroutine, assert with s.Never for 1 s that it has not settled, call s.holding.answers(), and assert NoError within deliveryWait.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 82136ab: TestAConversationRetryWaitsOutTheTurnAnEarlierAttemptBegan (your row). With the if known return put back, it fails: "settled while the turn ran".

return "", nil, refusal
}
if text := spokenOf(event); text != "" && (len(said) == 0 || said[len(said)-1] != text) {
said = append(said, text)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 (Q.1, confirmed) The watch is attached before followUpWithin, which waits behind a busy turn. So every agent.Responded of that other turn is joined into said and texted as the scheduled reply. Probe: the holding model holds another follow-up's turn (reply "Words of the earlier turn."). A captureReply on sms for st_run2 waits behind it, and then the holding model answers "The scheduled words.". Captured text: "Words of the earlier turn.\n\nThe scheduled words.", on head and on base. This is the event loop this PR rewrites, and it has the same cause as the PR's own thesis: it reads events, not the conversation. Fix: carry only this command's reply. Once the turn has ended, read it back from the conversation (FollowUpFinished, as readBackReply does for delivery.CommandID) instead of joining every event the watch saw. Test row: s.holding.reply = "Words of the earlier turn.", then heldConversationTurn, then captureReply in a goroutine for a second delivery (CommandID: "st_run2", same user), s.Never for 1 s, set the reply to "The scheduled words.", call answers(), and assert that the text is "The scheduled words.".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 282da2c (+ d2f9523, 7c3505e): captureReply runs the follow-up, then reads its own reply back once the turn ends (readBackReply). Tests: TestATextReplyCarriesOnlyItsOwnTurnsWords (your row; the old event loop gives "Words of the earlier turn.\n\nThe scheduled words."), TestATextFollowUpTheSessionRefusesFailsWithWhy. Control TestATextReplyIsTextedAsItWasOnceItsTurnEnds: "user: stretch", the same text base sends. Two other cases now differ from base. A two-round reply texts "Done.\n\nDone.", as a thread task already does (reportReply). A reply cut off before it was written is reply_failed, where base gave no_reply. Both are in the PR body table.

case active && !found.Busy() && time.Since(last) >= scheduledReplySettle:
return captured(said, files)
}
ended = time.Now().After(deadline) || active && !found.Busy() && time.Since(last) >= scheduledReplySettle

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.3 Three of the six surviving mutants are not equivalent. Each row below was checked in a scratch copy: it passes on head and fails under its mutant.

  1. Capture with no settle gap (ended = time.Now().After(deadline) || false && ..., written so that it builds): every SMS reply waits the full 3-minute window. Row: creditedOpening("holding/holding-model"), captureReply in a goroutine, and the result must arrive within deliveryWait with text "Held.". Head passes in 2.35 s. The mutant fails at 30 s.
  2. followUpInConversation ignores followUpWithin's error (line 551): a follow-up the session refuses is recorded delivered once the window passes. Row: a conversation delivery with Text: "" and scheduledReplyWindow = 2s must give an error. Head gives "there is nothing to answer". The mutant gives nil.
  3. M12, replyEnded without interrupted, is not equivalent. A regenerate or an edit during the turn runs Session.branch, which calls s.current().Interrupt() and then persisted.Rewind. Then Conversation.switchTo calls finish("interrupted") (conversation/branches.go:454) while the session and the watch stay open. Under the mutant, the wait holds the worker for the 3-minute window. Row: a unit test that asserts replyEnded("interrupted"), or an integration row that regenerates during a held turn.
    The other three are accepted: !open ignored and closed-watch-not-ending (the same answer, at most the 2 s settle later), and if known skipped (that one is the fix for R1.1).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f8f5877. Row 2: TestAConversationFollowUpTheSessionRefusesIsNotDelivered fails under conv-err-ignored ("An error is expected but got nil"). Row 3: TestAReplyEndsHoweverItsTurnEnded fails under ended-no-interrupted. Row 1: the settle gap went away with the event loop (R1.2). TestATextReplyIsTextedAsItWasOnceItsTurnEnds still requires the reply within deliveryWait.

@@ -99,31 +99,15 @@ func (s *Server) deliverOnThread(ctx context.Context, delivery scheduledDelivery
// A retried occurrence whose turn the thread already holds is a duplicate follow-up, which
// runs nothing (Session.FollowUp); its reply is read back, and sent unless it went out.
_, _, retried := found.FollowUpReply(delivery.CommandID)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.5 Ticket. Removing Watch() here also stops the delivery from pausing and resetting the session's unwatched grace. watch() stops the timer (session.go:620), and detach restarts it for 5 min (session.go:669). A kept API session found in its last seconds of grace can now end mid-turn, and it ends sooner after the reply. An inbound thread message (answerThread) already behaves this way, so this is consistent, but it is a change in a non-money path that the PR body does not mention.

kanat and others added 10 commits November 23, 2026 20:52
…egan

R1.1: followUpInConversation returned at once for a follow-up the
conversation already held, so a retry after an attempt cut short mid-turn
recorded delivered while the turn ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
R1.2: captureReply watched the session before followUpWithin waited
behind a busy turn, so that turn's words were texted as the scheduled
reply. It now reads the follow-up's reply back from the conversation once
its turn ends (readBackReply), as a retry already did; the event-joining
helpers it alone used are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
R1.3: two of the reviewer's surviving mutants were not equivalent:
followUpInConversation ignoring followUpWithin's error, and replyEnded
without interrupted. The third (capture with no settle gap) went with the
event loop R1.2 removed; TestATextReplyIsTextedAsItWasOnceItsTurnEnds keeps
its row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
…n is open

R1.4: the reply's failure is kept in memory only, so a reopened
conversation retry still records reply_failed or delivered; say so as a
known gap. R1.6: deliveryReason and unpaid line numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
… session

R1.4: a draining router reopens the conversation elsewhere, which the
in-memory failure does not survive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
R1.2: captureReply returns followUpWithin's error rather than waiting for
a reply nobody writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
R1.2 follow-on: the text channel now reads its reply back, so a turn of two
rounds texts both rounds' words, as a thread task already does
(reportReply), and a reply cut off before it was written fails as the
reply that was cancelled (reply_failed), as its retry read it back. The
retry still runs the turn again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
R1.6: deliveryReason is at scheduled_delivery.go:355, unpaid at :399.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delta round 2: GO (head dded582, main ef6b972 already merged in). Suites TestTelnyxUnpaidSuite + TestScheduledTasksSuite pass on the merged head; new text tests also pass with -cpu 1 -count=8. CI: draft, go and integration skip, the rest pass.

Prior findings

  • R1.1 fixed. Putting the early if known { return } back fails TestAConversationRetryWaitsOutTheTurnAnEarlierAttemptBegan ("settled while the turn ran").
  • R1.2 fixed (Q.1 confirmed). The text channel now runs followUpWithin, then reads the reply back from the conversation, so another turn's words cannot reach the user. Mutants killed: readBackReply without turnRefusal (3 tests), followUpInConversation returning nil instead of turnRefusal (7 tests), Observe storing no Failure (5 tests, all three channels). The only survivor, dropping the known guard in captureReply, is equivalent: Conversation.FollowUp answers a known command id as a duplicate before its ErrResponseRunning check (conversation.go:1649-1658, then :1667).
  • R1.3 fixed. followUpWithin's error ignored: TestAConversationFollowUpTheSessionRefusesIsNotDelivered fails. replyEnded without interrupted: TestAReplyEndsHoweverItsTurnEnded fails. The settle-gap row went with the event loop.
  • R1.4 fixed as decided: skill row and PR body claim only the in-session case and name the known gap. Persistence stays a ticket (exit).
  • R1.5 stays a Nit for a ticket.
  • R1.6 fixed: deliveryReason is at scheduled_delivery.go:355 and unpaid at :399, as the skill row says.
  • Q.2 resolved by R1.2: readBackReply's failed branch (scheduled_delivery.go:643-651) gives reply_failed for a non-money failure, watched or not.

The three behaviour changes (the 4 changed expectations in scheduled_tasks_test.go)

  1. Done. becomes Done.\n\nDone. (2 expectations): accepted. The text is the conversation's own message text (finish copies m.Text, conversation.go:2215-2221), the same a thread task texts and the user sees in the app. The old "drop a repeat" was a heuristic over events. Only a model that repeats a sentence word for word in two rounds is affected.
  2. cancelled before written: no_reply becomes reply_failed (2 expectations): accepted. Both are retryable and nothing else branches on either (grep). The retry still reruns the turn under _r1 (tests at :4145 and :4182). A session that closes mid-turn no longer texts the words said so far as if they were the answer.
  3. a tool that never answers: accepted, no change needed. Tools are bounded (session/tools.go:47: 30 s default, connectors 5 s), so a "never answering" tool times out and the turn goes on to its real answer, which head now texts. Base texted the words before the tool call after the 2 s settle gap and lost the answer. Only a tool that outlasts the 3 min scheduledReplyWindow ends no_reply, as a thread task already does. No committed test pins this in either direction. Not a finding.

New findings

  • [Nit, small, fix in this PR] .claude/skills/scheduled-tasks/SKILL.md:201 — the reply_failed row says "a thread task's first cut-off also gives it". After R1.2 a text channel's first cut-off gives it too (it was no_reply). Change it to "a text channel's or a thread task's first cut-off also gives it".

Mutations: 7 checked, 1 survived (equivalent). Details: scratchpad rev2/reviewer-2.md.

@kanat
kanat marked this pull request as ready for review November 23, 2026 21:04

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: GO

Delta round 3 (review of the merge of origin/main dc88f2f into the PR). Reviewed 70d0b5c merged onto main dc88f2f (main is an ancestor of the head, so the head is the merge).

PRIOR (all fixed or settled in round 2; nothing opened by the merge)

  • R1.1-R1.4, R1.6, Q.2: still fixed. Their tests pass on the merged head and still fail under the round-1/2 mutants (below).
  • R1.4 persistence gap and R1.5 (thread delivery no longer pauses the unwatched-grace timer): tickets at exit, unchanged.
  • R2.1 nit: unchanged.

THE RESOLUTION (git show --remerge-diff 70d0b5c)

  • scheduled_delivery.go captureReply: this PR's readBackReply version kept; main's watcher loop dropped. Main's #2277 did not change captureReply apart from scheduledReplyWindow -> s.replyWindow (#2293), which readBackReply already uses (diff of the PR's own hunks before and after the merge shows only that and the two adaptations below).
  • moneyRefusal(failure error): turnRefusal(found, id) is now moneyRefusal(found.FollowUpFailure(id)). It is main's old turnRefusal(event) body (moneyError, then unpaid(turnRefused{...})) taking the error instead of the event. Same answer for the same error.
  • carryOutAnswered: keeps #2277's rule (a refusal ends the call only while nothing was answered: erred && !answered, then agent.Responded sets answered), reading agent.Error events and calling moneyRefusal(failed.Err). Behaviour equal to main's.
  • #2293 compile breaks: the reply/phone/call windows are now fields of the router; this PR's R1.3 tests and #2277's callOn use s.router.replyWindow/phoneWindow/callLimit. The tests keep the shortened windows and restore them in Cleanup.
  • scheduled_unpaid_test.go:1758 uses moneyRefusal(refusal) for the gate's refusal.
  • SKILL.md: one row merged with both texts (the call sentences of #2277 and this PR's "reads how the turn ended from the conversation ... readBackReply" text); the spend_check_unavailable row is main's, with the "placed call is rung once" sentence, plus this PR's earlier text.
  • No revert: the PR's diff against main on scheduled_delivery.go differs from its diff against the old base only by these adaptations; the file set is the same; #2277's hunks (callEnded failure.Final = true, carryOutOnCall money branch, the call tests) are all there (mutants M1-M3).

CHECKS on the merged head (test DB model_router_test_ai3594e_test, -p 1)

  • go vet ./internal/api (plain and -tags integration) clean; gofmt clean.
  • TestTelnyxUnpaidSuite pass (97 s), TestScheduled* incl. TestScheduledTasksSuite pass (105 s); unit tests of internal/api, internal/conversation, internal/session pass.
  • CI at read time (gh pr checks 2278): integration agent/api/rest/router/routers/store, CodeQL, GitGuardian, labeler pass; go pending. A run that is still pending is the orchestrator's to wait for.

MUTATIONS (each run on the merged head, restored one file at a time, 5 checked, 0 survived)

  • M1 delete failure.Final = true in callEnded: killed by 4 (TestACallWhoseSessionCannotOpenIsRungOnceWhateverTheFirstChannelFailedUnder, TestACallWhoseSessionCannotOpenWhileMoneyCannotBeCheckedFailsFinal, TestACallWhoseTurnIsRefusedIsRungOnceWhateverTheAttemptsBetweenFailedUnder, TestACallWhoseTurnIsRefusedWhileMoneyCannotBeCheckedFailsFinalAfterOneRing).
  • M2 carryOutAnswered never reads the turn refusal (&& false): killed by 3 (TestACallWhoseTurnIsRefusedForMoneyFailsUnderTheMoney, ...IsRungOnce..., ...FailsFinalAfterOneRing: "the call was never let go").
  • M3 drop the !answered guard: killed by TestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered.
  • M4 readBackReply ignores the refusal (turnRefusal result unused): killed by 10 (text, thread and open-session rows, e.g. TestATextTurnRefusedTwiceFailsUnderTheMoney, TestAThreadTurnRefusedForMoneyUnwatchedFailsUnderTheMoney, TestATurnRefusedForMoneyInAnOpenSessionIsFinal).
  • M5 the conversation stores no Failure (conversation.go record.Failure = e.Err): killed by 17 (conversation, text and thread rows).

NEW FINDINGS

  • [Nit] .claude/skills/scheduled-tasks/SKILL.md (the money row): scheduled_delivery.go:355 and :399 now point one line above deliveryReason (:356) and unpaid (:400); the merge's added import line moved them. Fix: bump both to :356 and :400 (the other refs in the file are main's and untouched by this PR).

NOTE (ticket, not blocking; the fixer reports it too)

  • carryOutAnswered reads the call's refusal from the session's lossy event stream, the same class as AI-3594, in AI-3597's path. Ticket it at exit. It cannot reuse the conversation's recorded failure as is because the rule depends on the order "refused before the agent answered anything".

UNVERIFIED

  • -race and -cpu 1 -count=50 not rerun on the call tests: the delta adds no goroutine or ordering code to them (a helper split and a window field); earlier rounds' runs stand for the reply-wait tests.
  • gh pr checks: go was pending when read.

@kanat
kanat merged commit 41bce36 into main Nov 25, 2026
13 checks passed
@kanat
kanat deleted the kanat/ai-3594-reply-wait-reads-the-end branch November 25, 2026 18:43
kanat added a commit that referenced this pull request Nov 25, 2026
#2404 made scheduledOwnerContext a Server method that returns an error;
#2278's tests, merged after it, still call the old function, so main's
internal/api integration tests do not build. They go through the suite's
ownerContext, as the other tests in the file do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
thesyncim added a commit that referenced this pull request Nov 25, 2026
…#2481)

The eleven calls of scheduledOwnerContext use the suite's owner context, so the api integration tests compile.
kanat added a commit that referenced this pull request Nov 26, 2026
## Why

A scheduled reply refused for money must end its run failed, final,
under the money code (AI-2055, AI-3183). #2278 made the wait read how
the turn ended from the conversation (`FollowUpFailure`), but the
conversation kept the failure in memory only (`commandRecord.Failure`,
"kept in memory only"). A session reopens after a router drain or
restart, or after its 5-minute unwatched grace. After a reopen,
`commandsIn` rebuilt the records from the Chat messages without the
failure. A retry of a reply refused for money then recorded
`reply_failed` (text channels) or `delivered` (conversation channel),
although the user got nothing (AI-3902, #2278 R1.4).

The placed-call path (`carryOutAnswered`, AI-3904) is a separate PR.

## How it works

```
first attempt (router A)                   retry after a reopen (router B)
──────────────────────────                 ───────────────────────────────
agent.Error{money refusal}                 carryOn: session unknown here
  └─ Conversation.Observe                    └─ conversation opened from Chat
       ├─ record.Failure = err (memory)           └─ messageFromWire
       └─ m.refusal = err                              └─ support_money_refusal
            └─ sendWith: Chat custom                        -> policy.Refusal(code, unchecked)
               support_money_refusal =                 └─ commandsIn: record.Failure
               {code, unchecked}                  └─ turnRefusal / refusedAgain
attempt cut short (drain, restart)                     -> unpaid: money code, Final
                                                          = !policy.Transient
```

What is kept, and why:

| Kept | Why | Where it is read |
|---|---|---|
| `code` (`policy.Code`) | the run records only the code |
`deliveryReason`, `scheduled_delivery.go:374`; scheduler `Error:
reason`, `scheduler.go:452` |
| `unchecked` (`policy.Transient`) | decides final or retried;
`insufficient_credits` is transient when the balance is unread
(`policy/money.go:105`) | `unpaid`, `scheduled_delivery.go:422` |
| not the text | no run field and nothing a user sees carries it; only
the worker's warn log line shows it | `scheduler.go:444` |

A message without the field (any message written before this change, or
a failure not about money) reads back with no failure, as before.

## Changes

- `policy.Refusal(code, unchecked)`: the refusal of the kind `Code`
names, for a refusal read back from where it was kept.
- `conversation`: `Observe` keeps a money refusal on the failed reply;
`sendWith` writes it as the `support_money_refusal` custom field;
`messageFromWire` reads it back; `commandsIn` restores `Failure` for a
follow-up and for a person's command. The `Message` field is unexported,
so no API or `openapi.yaml` change, and no migration.

## Validation

| Path (brief's table) | Test | Base 92fcbb8 | Head |
|---|---|---|---|
| conversation, first attempt, refused for money | existing
`TestAConversationTaskWhoseTurnIsRefusedForMoneyIsNotRetried` | pass |
pass |
| conversation, retry after a reopen, refused for money |
`TestAConversationTurnRefusedForMoneyBeforeAReopenFailsUnderTheMoney` |
fail: delivered | failed, final, `insufficient_credits` |
| text (SMS), retry after a reopen, refused for money |
`TestATextTurnRefusedForMoneyBeforeAReopenFailsUnderTheMoney` | fail:
`reply_failed` | failed, final, `insufficient_credits` |
| transient money check before a reopen |
`TestAConversationTurnRefusedUncheckedBeforeAReopenRunsAgainOnItsRetry`
| fail: delivered with no rerun | retried, then the rerun completes |
| failed not for money before a reopen (control) |
`TestATextTurnFailedNotForMoneyBeforeAReopenFailsAsAReplyThatFailed` |
`reply_failed` | `reply_failed` |
| completed before a reopen (control) |
`TestATextTurnCompletedBeforeAReopenIsTexted` | texted | texted |

- The reopen is forced: the turn runs on the suite's router and its
session is stopped. A second router with a conversation service of its
own (`restartedNode`) then carries the session on. That router holds
nothing in memory, so it reads the conversation from Chat, as after a
restart, a drain to a peer or the end of the grace. A worker that takes
the run over after the first attempt was cut short reads no reason from
the row (`Run.Error` nil), which these tests use.
- Thread delivery reads the same `readBackReply` / `refusedAgain`
(`scheduled_thread_delivery.go:93,108`) as the SMS test.
- `internal/conversation` `MoneyRefusalSuite`: each of the 7 money
kinds, checked and unchecked, reads back after a reopen. A person's
command reads back too. A failure not about money keeps no field. A
table of field shapes (none, empty, a bare code, no flag, a flag of
text, a number code, an unknown code, an empty code) reads as no
refusal.
- `internal/policy`: `Refusal` round trips every code, checked and
unchecked, and refuses unknown codes.
- Mutations: each of the 13 changed conditions, writes and reads was
mutated, and a test failed for each one.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 26, 2026
## How it works

```
typed turn starts on a call        -> Session.unanswered = true
agent.Responded                    -> Session.unanswered = false
agent.Error for money (policy.Code)
  Session.consume -> refusedUnanswered
  ├─ unanswered: kept (Session.UnansweredRefusal), given to the conversation
  │    -> typed reply ends failed under the money code
  ├─ answered: a later turn's, not kept, not written
  │    -> delivered, as on main
  └─ any other event on a call -> transcript (conversation when there is none)
carryOutAnswered, on each event AND each replyPoll tick:
  UnansweredRefusal() != nil -> fail under the money code, hang up
```

## Why

`carryOutAnswered` (`internal/api/scheduled_delivery.go:1290` on main)
learned that a call's turn was refused for money only from the
`agent.Error` event. A watcher drops events once its buffer is full
(`watcherBuffer`, `internal/session/session.go:43`; `watcher.send`,
:589). That is the loss #2278 fixed for reply waits by reading
`Session.FollowUpFailure`.

Reading the stored failure alone was not enough. On a call with a
transcript (`cmd/router/sessions.go:61`), `consume` gives the
conversation only the typed turn's events. A money refusal names no turn
(see the `refusedUnanswered` comment), so it went to the transcript and
the typed reply stayed "thinking" with no failure. The api suite's calls
had no transcript, which hid this. A probe on main with a transcript
showed it.

The rule for "answered" stays as on main. On a call the typed turn's
`Responded` has `PendingWork: true` while the agent speaks
(`internal/agent/agent.go:3868`, `pendingWork := len(calls) > 0 ||
a.Busy()`), so the reply stays "writing" for the whole call. A refusal
is therefore kept only while no `Responded` has come since the typed
turn started. A caller who cuts the turn off before it answers leaves
that open, so the next refusal still ends the run under the money code,
as on main. A round that goes on after a tool call counts as answered,
as on main.

## Changes

- `Session.consume` gives the conversation a money `agent.Error` on a
voice session only while a typed turn is unanswered
(`refusedUnanswered`), and keeps that refusal
(`Session.UnansweredRefusal`). Typed-turn bookkeeping runs with or
without a transcript. Text sessions forward every error, as before.
- `carryOutAnswered` reads `Session.UnansweredRefusal` on each event and
on each `replyPoll` tick. It no longer reads events for the refusal.
- `.claude/skills/scheduled-tasks/SKILL.md`: the answered-call row.

## Validation

| Case | Result | Test |
| --- | --- | --- |
| Money refusal before the answer, watcher lost the event | failed under
the money code | `TestACallWhoseRefusalItsWatchLostFailsUnderTheMoney`,
`TestACallWhoseWatchGetsNoEventFailsUnderTheMoney` (api, both fail on
main); `TestARefusalForMoneyOfATurnTypedIntoACallFailsItsReply`
(session, both modes) |
| Money refusal before the answer, transcribed call | failed, final,
hung up, under the money code |
`TestATranscribedCallWhoseTurnIsRefusedForMoneyFailsUnderTheMoney`;
untranscribed: `TestACallWhoseTurnIsRefusedForMoneyFailsUnderTheMoney` |
| Caller cuts the typed turn off, the next turn is refused for money |
failed, final, hung up, under the money code |
`TestACallWhoseTurnIsCutOffAndWhoseNextIsRefusedForMoneyFailsUnderTheMoney`
(api, both modes; fails on the pre-fix head bb6b0c4) |
| Typed turn answered, later turn refused for money | delivered, as on
main | `TestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered` (api, both
modes);
`TestARefusalForMoneyAfterATypedTurnOnACallAnsweredLeavesItsReply`
(session, both modes) |
| Refusal of the round after a typed turn's tool call | reply keeps no
failure |
`TestARefusalForMoneyOfTheRoundAfterATypedTurnsToolCallLeavesItsReply`
(session) |
| A cut-off typed turn, then an answered one, then a refusal | the
answered reply keeps no failure (fails on bb6b0c4 when reproduced by
probe) |
`TestARefusalForMoneyAfterATypedTurnAnsweredOneCutOffBeforeItLeavesItsReply`
(session, both modes) |
| Money cannot be checked | final after one ring (unchanged) |
`TestACallWhoseTurnIsRefusedWhileMoneyCannotBeCheckedFailsFinalAfterOneRing`
(existing) |
| Transcriber failure during a typed turn | reply not failed |
`TestATranscriberFailingDuringATypedTurnOnACallLeavesItsReplyAnswered`
(session) |
| Provider failure during a typed turn | reply not failed |
`TestAProviderFailingATypedTurnOnACallKeepsNoFailure` (session) |
| Spoken turn after a typed one | stays in the transcript |
`TestATurnSaidOnACallAfterATypedOneStaysTheTranscripts` (session) |
| Typed turn not refused for money, transcribed call | delivered |
`TestATranscribedCallWhoseTurnIsNotRefusedForMoneyIsDelivered` (api,
control) |

Each changed condition was mutated and a test fails under each mutation.
The ticker case in `carryOutAnswered` was not mutated;
`TestACallWhoseWatchGetsNoEventFailsUnderTheMoney` is the test that
covers it.

Local runs on the head: `go test -race -count=50` and `-cpu 1 -count=50`
on the session call tests pass; `TestTelnyxUnpaidSuite` and
`TestScheduledTasksSuite` pass with `-tags integration`; `go vet` is
clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 27, 2026
## Why

#2278 took the `Watch()` out of `deliverOnThread` and `captureReply`,
because a watcher's buffer drops events and the wait read the turn's end
from them. Only a watcher stops the unwatched grace of a persistent text
session (`Session.watch`, `internal/session/session.go`), and
`endUnwatched` ends the session with what it is still saying (`abandon`
calls `Interrupt`). So a scheduled turn in a kept session that nobody
watches can be cut off when that grace runs out. The inbound path (a
person's text answered in a kept session, `answerHosted`) held nothing
either; it takes the same `Hold`. `answerHosted` also serves the
chat-channel turn (`answerChatChannelTurn`, `chat_channels.go:201`), so
that path is held too. The grace is 5 minutes by default
(`defaultDetachedGrace`, `internal/session/manager.go`).

Example: the customer's backend keeps a session on an SMS thread. The
person watching it leaves, and a task comes due while the grace counts
down. On base, the grace ends the session in the middle of the task's
turn (`TestATaskKeepsTheSessionItFoundUntilItsReplyIsTexted` fails on
92fcbb8 with "the session ended in the middle of the task's turn").

## How it works

`Session.Hold()` counts a holder beside the watchers. A holder gets no
events and takes no tool seat, so the lossy buffer does not come back.

```
deliverOnThread / captureReply / answerHosted (inbound thread message and chat-channel turn)
└─ found := the session on the thread (or the task's session)
   ├─ release := found.Hold()       stops a running grace (owed back at release)
   │    watcher leaves meanwhile -> no grace (leaveUnwatched: holders > 0)
   │    voice stopped meanwhile  -> no grace (swap: holders == 0)
   │    grace fired as it held   -> ends nothing (endUnwatched re-checks)
   ├─ FollowUp, read back the reply, send it
   └─ release()                     nobody watches or holds -> grace starts
                                    somebody watches         -> nothing
                                    no grace was owed (never watched) -> nothing
                                    session ended / closed   -> nothing
```

The release starts the grace only when one is owed (`graceOwed`): the
hold stopped a counting grace, or a watcher's leaving or `swap` skipped
one because of a holder. A session nobody ever watched has none
counting, so a release leaves it as it was.

`leaveUnwatched` is the watcher detach's own check, moved out of `watch`
so that the release uses the same one.

## Path table

| Session the delivery finds | During the delivery | Expected | Test |
|---|---|---|---|
| kept, its watcher leaves mid-turn | the grace would end it mid-turn |
stays open, run `delivered`, reply texted |
`ThreadHoldSuite/TestATaskKeepsTheSessionItFoundUntilItsReplyIsTexted`
(fails on base) |
| kept, grace already counting | the hold is taken | grace stopped |
`SessionSuite/TestAHoldStopsTheGraceOfAConversationNobodyWatches` |
| kept | the delivery ends | grace starts from the end of the delivery,
then it ends | the same two tests (`endsAfter`: ended no sooner than a
grace after the turn was let go) |
| opened by the delivery | any | closed by the delivery, as before; the
release afterwards starts no grace |
`TelnyxChannelSuite/TestATaskMadeInAnSMSThreadIsTextedBackOnTheThread`
(existing),
`SessionSuite/TestAReleaseAfterTheConversationEndedStartsNoGrace` |
| watched by a person | any | stays open after the delivery |
`ThreadHoldSuite/TestATaskLeavesASessionSomebodyWatchesOpen` (passes on
base too) |
| inbound thread message (`answerHosted`) in a kept session | its
watcher leaves mid-turn | stays open for the turn, reply texted, grace
starts after |
`ThreadHoldSuite/TestATextAnsweredInAKeptSessionKeepsItOpenForTheTurn`
(fails without the hold) |
| kept, never watched (opened by `POST /sessions`) | a task or an
inbound text runs in it | unchanged from base: no grace before, none
after |
`ThreadHoldSuite/TestATaskDeliveredInANeverWatchedSessionLeavesItOpen`,
`TestATextAnsweredInANeverWatchedSessionLeavesItOpen`,
`SessionSuite/TestAReleaseInAConversationNobodyWatchedStartsNoGrace`
(fail without the owed-grace flag) |
| text channel (`captureReply`) on a kept session | its watcher leaves
mid-turn | stays open until the reply is read |
`ThreadHoldSuite/TestATextedReplyKeepsTheSessionItRunsInUntilItIsRead`
(fails on base) |

## Not changed

- `takeOver` still ends a held session that nobody watches when a person
reopens the conversation (`unwatchedFor` ignores holders). The person
who came back takes the conversation over, as before.

## Validation

- `go test ./internal/session/ -run TestSessionSuite` (hold tests,
`-count=3`) and `go test -tags integration -p 1 ./internal/api/ -run
TestThreadHoldSuite`: pass on head. On base 92fcbb8 with the head's
tests, the two "fails on base" rows fail and the watched control passes.
- Mutations: every guard the diff adds or moves, applied one at a time
by one script. Each is killed or is listed as equivalent in the PR's
ledger.
- `ThreadHoldSuite` is a new suite with its own database
(`thread_hold`). Its sessions have a grace of 200 ms
(`RouterSuite.detachedGrace`, zero elsewhere, which is the manager's
default).

Fixes AI-3903

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant