Skip to content

AI-3904: a scheduled call reads its stored money refusal - #2560

Merged
kanat merged 11 commits into
mainfrom
kanat/ai-3904-call-reads-stored-refusal
Nov 26, 2026
Merged

kanat merged 11 commits into
mainfrom
kanat/ai-3904-call-reads-stored-refusal

Conversation

@kanat

@kanat kanat commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

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.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE

@github-actions github-actions Bot added the docs label Nov 26, 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.

VERDICT: GO

[security R1] No security findings at bb6b0c4.

  • Who can produce the money code. The new forward to the conversation (Session.refusedUnanswered, consume) only fires for an agent.Error whose policy.Code is non-empty. policy.Code uses errors.Is on the in-process policy sentinels. A tool result, a remote worker reply or a model output comes back as a plain error built from text, so none of them can produce a money code. Speech and DTMF cannot either.
  • Stored fields and frames. The forwarded failure is kept only in commandRecord.Failure (json:"-", in memory). The conversation message gets the state failed, with no error text. The run row records only the refusal's code, which is what base did with the same error value. The transcript and runtime-error rows are unchanged.
  • Resources. The call's ticker is stopped on return and lasts at most callLimit. Nothing changes the stored format, so a rollback widens nothing.
  • Mutation checks. 7 checked, 0 survived: the money check, the answered check, the forward in consume, Continues inheriting the answered flag, the turnRefusal read, and the tick case in carryOutAnswered.

For the main reviewer, with no security effect: suppose the caller interrupts the typed turn before it answers, and a later turn is then refused for money. Base ended that run failed under the money code; head records it delivered. No refused work runs or is billed, and both ends are final.

@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: NO-GO

Reviewed bb6b0c4 (it already contains main b11e578). The verdict rests on R1.1 and R1.3, two rows of the path table that now end differently from main, with no test for either. The probes below ran on head and on main in TelnyxUnpaidSuite.

  • [Should fix] R1.1: a call with no transcript. A later turn's money refusal now fails the run and hangs up after the task was said. Main delivered it. Inline at scheduled_delivery.go:1316 and session.go:2055.
  • [Should fix] R1.2: a mutation of the money check survives. Inline at session.go:1796, with a test row.
  • [Should fix] R1.3: the caller interrupts the typed turn before it answers, then a later turn is refused for money. Main fails the run under the money code and hangs up. This head keeps a silent call until the user hangs up and records delivered, with or without a transcript. The refusal reaches no open reply, because the typed reply already ended cancelled. Probe: stuck/stuck-model, pick up, wait for the reply to be thinking, held.Interrupt(), spend the credit, held.Respond(...). Main: let go at once, insufficient_credits. Head: deliveredTo=phone, FollowUpFailure=nil. Fix: keep main's rule ("a money refusal before the agent answered anything on the call fails it") without the event. For example, the session records a money refusal it sees while a typed turn is unanswered (refusedUnanswered) on itself, not only on the open reply, and carryOutAnswered reads it beside turnRefusal. Add the probe as a test: expected end is failed, final, under the money code, hung up.
  • [Question] R1.4: typedTurns is never pruned (inline at session.go:1801). Ticket.

Checked and sound:

  • Suites on head: go test ./internal/session/ passes, and -tags integration -p 1 ./internal/api/ -run 'TestTelnyxUnpaidSuite|TestScheduledTasksSuite' passes.
  • go vet is clean in both tag modes. go run ./cmd/openapi gives no diff.
  • Hot path: consume adds work only for agent.Error events on a transcribed call, with no lock before the type check. Text sessions short-circuit as on main.
  • Mutations: author M1-M9 killed. M5 is killed by a nil-map panic, and M5b by TestATurnSaidOnACallAfterATypedOneStaysTheTranscripts. Two mutants survive as equivalent: reading only on ticks (≤100 ms later), and Continues inheriting true.
  • The PR is a draft, so CI go and integration were skipped on this head. They run at gh pr ready.
  • Merge order: #2556 conflicts with this PR on .claude/skills/scheduled-tasks/SKILL.md (the same row).

case <-limit.C:
return nil
}
if refusal := turnRefusal(created, delivery.CommandID); refusal != nil {

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 This changes the "later turn refused" row on a call with no transcript. The transcript can fail to open (manager.go:995/999); transcript == nil then sends every event to the conversation. The typed reply stays writing after its Responded (PendingWork), so a later turn's money refusal fails it and stores the refusal. Main stored it too, but its answered flag ignored it. Here turnRefusal reads it, and the run fails under the money code, final, and hangs up on the user after the task was said.

Probe in TelnyxUnpaidSuite, with transcribing off: ringingOn("noted/noted-model"), pick up, answeredOn, spend the credit, held.Respond(ctx, "and what else", nil, options.LLM{}).

  • Main b11e578: deliveredTo=phone.
  • Head: insufficient_credits, and the call is let go before the user hangs up. With transcribing on, head delivers.

The existing TestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered no longer pins this row. It uses Session.Report, which only broadcasts (session.go:1232), and this function no longer reads events.

Fix: on every voice session (!s.spec.Text), run typedEvent's bookkeeping, and give the conversation a money agent.Error with no turn only while refusedUnanswered holds, with or without a transcript. I tried this in a scratch copy: the probe passes both ways, and TestTelnyxUnpaidSuite and the session suite still pass. Then drive the later-turn test through the agent (held.Respond with the credit spent), with transcribing off and on.

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 771301b: carryOutAnswered now reads Session.UnansweredRefusal, which the session keeps only while the agent has not answered since the task's turn was typed, transcript or not. Test: TestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered (scheduled_call_stored_test.go), now going through the agent (held.Respond, credit spent), transcribed=true/false. It fails on bb6b0c4 for transcribed=false. The Session.Report version in scheduled_unpaid_test.go is replaced.

for event := range held.Events() {
typed := transcript == nil || s.typedEvent(event)
if s.persisted != nil && typed {
if s.persisted != nil && (typed || s.refusedUnanswered(event)) {

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 (call site) transcript == nil skips typedEvent, so a call without a transcript has no record of whether its typed turn answered. Every money refusal then reaches the conversation, including a later turn's (see the comment on scheduled_delivery.go:1316).

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 771301b: consume runs typedEvent on every event (typed := s.typedEvent(event) || transcript == nil). On a call, a money agent.Error goes to the conversation only while refusedUnanswered holds, transcript or not. Tests: TestARefusalForMoneyAfterATypedTurnOnACallAnsweredLeavesItsReply and TestARefusalForMoneyOfATurnTypedIntoACallFailsItsReply, both transcribed=true/false. Mutating the gate back to written || refused fails the first one for transcribed=false. Reverting the order fails the second one for transcribed=false.

// failure, such as the transcriber's, is not the reply's.
func (s *Session) refusedUnanswered(event Event) bool {
failed, ok := event.(agent.Error)
if !ok || policy.Code(failed.Err) == "" {

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 A mutant survives: if !ok || failed.Context == "stt" {, which forwards every non-STT error, such as a provider's. Only the transcriber false positive is pinned. The api control with failing/failing-model still delivers, because moneyRefusal drops failures that are not about money.

Test row for call_refusal_test.go. I checked it: it passes 3/3 on head and fails under the mutant.

func (s *SessionSuite) TestAProviderFailingATypedTurnOnACallKeepsNoFailure() {
	running := s.transcribedCall()
	events, detach := running.Watch()
	defer detach()
	down := errors.New("the provider is down")
	s.model.refuses = down
	s.Require().NoError(running.FollowUp(s.ctx, "task_call", "Remind them to stretch", nil))
	s.Require().True(sawError(events, down), "the provider's failure never reached the session")
	s.NoError(running.FollowUpFailure("task_call"))
}

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 cd53c7c: TestAProviderFailingATypedTurnOnACallKeepsNoFailure (call_refusal_test.go). It passes 3/3, and your M18 mutant fails it.

}
s.typedMu.Lock()
defer s.typedMu.Unlock()
for _, answered := range s.typedTurns {

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.

[Question] R1.4 typedTurns is never pruned, and this loop fires on any entry that is still false. A typed turn that ends without a Responded stays false for the life of the session; the R1.3 probe shows an interrupted turn does. A later spoken turn's money refusal could then fail whichever typed reply is open at the time, such as a chat message typed during the call. Not reproduced. To settle it: interrupt typed turn A, let typed turn B answer, refuse a spoken turn for money, and check that B keeps no failure. Ticket.

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.

Probed: it reproduced. On bb6b0c4, typed A was interrupted before it answered, typed B answered, and then a money refusal came: B ended state=failed with the refusal. Fixed in 771301b: the session tracks one flag, unanswered. A typed turn's start sets it and any Responded clears it, so A's stale entry is gone (the typedTurns map is back to struct{}). Test: TestARefusalForMoneyAfterATypedTurnAnsweredOneCutOffBeforeItLeavesItsReply, transcribed=true/false. If Responded no longer clears the flag, both modes fail.

kanat and others added 3 commits November 26, 2026 13:51
The session keeps the refusal for money the agent fails on while it has
not answered since a turn was typed into the call, transcript or not,
and carryOutAnswered reads that: a later turn's refusal no longer fails
an answered call without a transcript (R1.1), a turn cut off by the
caller and then refused still fails the run (R1.3), and a turn cut off
earlier no longer leaves a later typed reply open to a refusal (R1.4).

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

kanat commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

R1.3 (review body, no inline thread): Fixed in 771301b. The session keeps a money refusal the agent gets before it answered (Session.UnansweredRefusal), and carryOutAnswered reads that refusal. A turn the caller cut off and a refused next turn now fail the run again: money code, final, and the agent hangs up without waiting for the user, as on base. Test: TestACallWhoseTurnIsCutOffAndWhoseNextIsRefusedForMoneyFailsUnderTheMoney, transcribed=true/false. It fails on bb6b0c4 in both modes, and it also fails with the read mutated back to turnRefusal.

@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 2 on 6e1ab67 (was bb6b0c4), merged onto main e4e11b6 in a scratch tree.

  • R1.1 fixed. My probe (credit spent, a later turn through the agent) is delivered by phone with and without a transcript. TestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered now runs through the agent in both modes.
  • R1.2 fixed. The mutant that forwards a non-money error is killed by TestAProviderFailingATypedTurnOnACallKeepsNoFailure.
  • R1.3 fixed. My probe (caller interrupts the typed turn, then a later turn is refused) fails the run under the money code and lets the call go at once, in both modes, as base did.
  • R1.4 fixed. TestARefusalForMoneyAfterATypedTurnAnsweredOneCutOffBeforeItLeavesItsReply kills the mutants that drop the clear on Responded, forward after an answer, or keep unconditionally.

Mutations: 14 checked, 0 survived. Session: drop the set or the clear of unanswered, written = written || refused, the transcript order, no keep, keep unconditionally, return true/false, forward any error. API: drop the Voicing check, drop the ticker, read turnRefusal instead of UnansweredRefusal, read nothing.

Suites on head merged onto main: session unit ok; the call tests pass with -race -count=50 and -cpu 1 -count=50; api integration TestTelnyxUnpaidSuite and TestScheduledTasksSuite ok; the new api tests pass with -race and -cpu 1. I found no added production line that the four findings or the stored read do not need.

Nit: the unanswered/refused field comment at session.go:207 reads "and refused the refusal for money the agent failed on meanwhile"; reword it.

CI: a draft runs no integration here (analyze and CodeQL pass).

@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

R2.1 fixed, comment-only delta: the unanswered/refused field comment in acceleration/internal/session/session.go now matches the code (set :1779/:1782, refused :1807, read by UnansweredRefusal :1819). go build and go vet ./internal/session/ pass; gofmt clean.

@kanat
kanat marked this pull request as ready for review November 26, 2026 20:13
@kanat
kanat merged commit 889ef40 into main Nov 26, 2026
13 checks passed
@kanat
kanat deleted the kanat/ai-3904-call-reads-stored-refusal branch November 26, 2026 23:20
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